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
|
---|---|---|---|---|---|---|
Thomas-Bergmann/Tournament | de.hatoka.tournament/src/main/java/de/hatoka/tournament/internal/app/actions/PlayerAction.java | // Path: de.hatoka.tournament/src/main/java/de/hatoka/tournament/capi/business/TournamentBusinessFactory.java
// public interface TournamentBusinessFactory
// {
// CashGameCompetitorBO getCompetitorBO(CompetitorPO competitorPO, CashGameBO cashGameBO);
//
// CompetitorBO getCompetitorBO(CompetitorPO competitorPO, TournamentBO tournamentBO);
//
// PlayerBO getPlayerBO(PlayerPO playerPO);
//
// PlayerBORepository getPlayerBORepository(String accountRef);
//
// CashGameBO getCashGameBO(TournamentPO tournamentPO);
//
// TournamentBO getTournamentBO(TournamentPO tournamentPO);
//
// TournamentBORepository getTournamentBORepository(String accountRef);
//
// HistoryEntryBO getHistoryBO(HistoryPO historyPO);
//
// BlindLevelBO getBlindLevelBO(BlindLevelPO blindLevelPO, ITournamentBO tournament);
//
// PauseBO getPauseBO(BlindLevelPO blindLevelPO, ITournamentBO tournament);
//
// RankBO getRankBO(RankPO rankPO, TournamentBO tournamentBO);
//
// ITableBO getTableBO(int tableNo);
// }
| import java.util.List;
import java.util.stream.Collectors;
import de.hatoka.tournament.capi.business.PlayerBO;
import de.hatoka.tournament.capi.business.PlayerBORepository;
import de.hatoka.tournament.capi.business.TournamentBusinessFactory;
import de.hatoka.tournament.internal.app.models.PlayerListModel;
import de.hatoka.tournament.internal.app.models.PlayerVO; | package de.hatoka.tournament.internal.app.actions;
public class PlayerAction
{ | // Path: de.hatoka.tournament/src/main/java/de/hatoka/tournament/capi/business/TournamentBusinessFactory.java
// public interface TournamentBusinessFactory
// {
// CashGameCompetitorBO getCompetitorBO(CompetitorPO competitorPO, CashGameBO cashGameBO);
//
// CompetitorBO getCompetitorBO(CompetitorPO competitorPO, TournamentBO tournamentBO);
//
// PlayerBO getPlayerBO(PlayerPO playerPO);
//
// PlayerBORepository getPlayerBORepository(String accountRef);
//
// CashGameBO getCashGameBO(TournamentPO tournamentPO);
//
// TournamentBO getTournamentBO(TournamentPO tournamentPO);
//
// TournamentBORepository getTournamentBORepository(String accountRef);
//
// HistoryEntryBO getHistoryBO(HistoryPO historyPO);
//
// BlindLevelBO getBlindLevelBO(BlindLevelPO blindLevelPO, ITournamentBO tournament);
//
// PauseBO getPauseBO(BlindLevelPO blindLevelPO, ITournamentBO tournament);
//
// RankBO getRankBO(RankPO rankPO, TournamentBO tournamentBO);
//
// ITableBO getTableBO(int tableNo);
// }
// Path: de.hatoka.tournament/src/main/java/de/hatoka/tournament/internal/app/actions/PlayerAction.java
import java.util.List;
import java.util.stream.Collectors;
import de.hatoka.tournament.capi.business.PlayerBO;
import de.hatoka.tournament.capi.business.PlayerBORepository;
import de.hatoka.tournament.capi.business.TournamentBusinessFactory;
import de.hatoka.tournament.internal.app.models.PlayerListModel;
import de.hatoka.tournament.internal.app.models.PlayerVO;
package de.hatoka.tournament.internal.app.actions;
public class PlayerAction
{ | private final TournamentBusinessFactory factory; |
Thomas-Bergmann/Tournament | de.hatoka.common/src/main/java/de/hatoka/common/capi/app/servlet/ResourceService.java | // Path: de.hatoka.common/src/main/java/de/hatoka/common/capi/dao/UUIDGenerator.java
// public interface UUIDGenerator
// {
// public String generate();
// }
| import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import javax.servlet.ServletContext;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.core.Application;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.Response;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.inject.Injector;
import de.hatoka.common.capi.dao.UUIDGenerator; | String realPath = context.getRealPath("/" + relative);
if (realPath == null)
{
// web application without context
realPath = relative;
}
LOGGER.warn("Resource '{}' translated to '{}'.", filename, realPath);
java.nio.file.Path path = Paths.get(realPath);
if (!path.toFile().exists())
{
LOGGER.warn("Resource '{}' not found. Resource translated to '{}'.", filename, path);
return Response.status(404).entity("404 - resource not found: " + filename).build();
}
return Response.status(200).type(Files.probeContentType(path)).entity(Files.readAllBytes(path)).build();
}
catch(IOException | NullPointerException e)
{
String errorID = getUUID(application);
LOGGER.error("Error-Identifier: '" + errorID + "' - Load resource '"+filename+"' failed.", e);
return Response.status(404).entity("Load resource failed: " + errorID).build();
}
}
private static Injector getInjector(Application application)
{
return (Injector)application.getProperties().get(ServletConstants.PROPERTY_INJECTOR);
}
private static String getUUID(Application application)
{ | // Path: de.hatoka.common/src/main/java/de/hatoka/common/capi/dao/UUIDGenerator.java
// public interface UUIDGenerator
// {
// public String generate();
// }
// Path: de.hatoka.common/src/main/java/de/hatoka/common/capi/app/servlet/ResourceService.java
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import javax.servlet.ServletContext;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.core.Application;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.Response;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.inject.Injector;
import de.hatoka.common.capi.dao.UUIDGenerator;
String realPath = context.getRealPath("/" + relative);
if (realPath == null)
{
// web application without context
realPath = relative;
}
LOGGER.warn("Resource '{}' translated to '{}'.", filename, realPath);
java.nio.file.Path path = Paths.get(realPath);
if (!path.toFile().exists())
{
LOGGER.warn("Resource '{}' not found. Resource translated to '{}'.", filename, path);
return Response.status(404).entity("404 - resource not found: " + filename).build();
}
return Response.status(200).type(Files.probeContentType(path)).entity(Files.readAllBytes(path)).build();
}
catch(IOException | NullPointerException e)
{
String errorID = getUUID(application);
LOGGER.error("Error-Identifier: '" + errorID + "' - Load resource '"+filename+"' failed.", e);
return Response.status(404).entity("Load resource failed: " + errorID).build();
}
}
private static Injector getInjector(Application application)
{
return (Injector)application.getProperties().get(ServletConstants.PROPERTY_INJECTOR);
}
private static String getUUID(Application application)
{ | return getInjector(application).getInstance(UUIDGenerator.class).generate(); |
Thomas-Bergmann/Tournament | de.hatoka.common/src/main/java/de/hatoka/common/capi/app/xslt/XSLTRenderer.java | // Path: de.hatoka.common/src/main/java/de/hatoka/common/capi/resource/LocalizationBundle.java
// public class LocalizationBundle
// {
// private static final Logger LOGGER = LoggerFactory.getLogger(LocalizationBundle.class);
//
// private final ResourceBundle resourceBundle;
// private final Locale locale;
// private final String resourceBundleName;
// private final Set<String> unkownKeys = new HashSet<>();
// private final TimeZone timezone;
//
// @Deprecated
// public LocalizationBundle(String resourceBundleName, Locale locale)
// {
// this(resourceBundleName, locale, CountryHelper.UTC);
// }
//
// public LocalizationBundle(String resourceBundleName, Locale locale, TimeZone timeZone)
// {
// resourceBundle = PropertyResourceBundle.getBundle(resourceBundleName, locale);
// this.resourceBundleName = resourceBundleName;
// this.locale = locale;
// this.timezone = timeZone;
// }
//
// public Locale getLocal()
// {
// return locale;
// }
//
// public TimeZone getTimeZone()
// {
// return timezone;
// }
//
// public String getText(String key)
// {
// return getText(key, "{" + key + "}");
// }
//
// public String getText(String key, String defaultText)
// {
// if (unkownKeys.contains(key))
// {
// return defaultText;
// }
// try
// {
// return resourceBundle.getString(key);
// }
// catch(MissingResourceException ex)
// {
// if (!unkownKeys.contains(key))
// {
// LOGGER.warn("Can't resolve key '" + key + "' inside of resource '" + resourceBundleName
// + "' and locale '" + locale + "'.", ex);
// unkownKeys.add(key);
// }
// }
// return defaultText;
// }
//
// }
| import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.StringWriter;
import java.io.Writer;
import java.net.URL;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.Map.Entry;
import java.util.TimeZone;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.util.JAXBSource;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import de.hatoka.common.capi.business.CountryHelper;
import de.hatoka.common.capi.resource.LocalizationBundle;
import de.hatoka.common.capi.resource.ResourceLocalizer; | package de.hatoka.common.capi.app.xslt;
public class XSLTRenderer
{
private final TransformerFactory transformerFactory = TransformerFactory.newInstance();
public XSLTRenderer()
{
transformerFactory.setURIResolver(new ClassPathURIResolver());
}
@Deprecated
public Map<String, Object> getParameter(String localizationResource, Locale locale)
{
return getParameter(localizationResource, locale, CountryHelper.UTC);
}
public Map<String, Object> getParameter(String localizationResource, Locale locale, TimeZone timeZone)
{
Map<String, Object> result = new HashMap<>(); | // Path: de.hatoka.common/src/main/java/de/hatoka/common/capi/resource/LocalizationBundle.java
// public class LocalizationBundle
// {
// private static final Logger LOGGER = LoggerFactory.getLogger(LocalizationBundle.class);
//
// private final ResourceBundle resourceBundle;
// private final Locale locale;
// private final String resourceBundleName;
// private final Set<String> unkownKeys = new HashSet<>();
// private final TimeZone timezone;
//
// @Deprecated
// public LocalizationBundle(String resourceBundleName, Locale locale)
// {
// this(resourceBundleName, locale, CountryHelper.UTC);
// }
//
// public LocalizationBundle(String resourceBundleName, Locale locale, TimeZone timeZone)
// {
// resourceBundle = PropertyResourceBundle.getBundle(resourceBundleName, locale);
// this.resourceBundleName = resourceBundleName;
// this.locale = locale;
// this.timezone = timeZone;
// }
//
// public Locale getLocal()
// {
// return locale;
// }
//
// public TimeZone getTimeZone()
// {
// return timezone;
// }
//
// public String getText(String key)
// {
// return getText(key, "{" + key + "}");
// }
//
// public String getText(String key, String defaultText)
// {
// if (unkownKeys.contains(key))
// {
// return defaultText;
// }
// try
// {
// return resourceBundle.getString(key);
// }
// catch(MissingResourceException ex)
// {
// if (!unkownKeys.contains(key))
// {
// LOGGER.warn("Can't resolve key '" + key + "' inside of resource '" + resourceBundleName
// + "' and locale '" + locale + "'.", ex);
// unkownKeys.add(key);
// }
// }
// return defaultText;
// }
//
// }
// Path: de.hatoka.common/src/main/java/de/hatoka/common/capi/app/xslt/XSLTRenderer.java
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.StringWriter;
import java.io.Writer;
import java.net.URL;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.Map.Entry;
import java.util.TimeZone;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.util.JAXBSource;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import de.hatoka.common.capi.business.CountryHelper;
import de.hatoka.common.capi.resource.LocalizationBundle;
import de.hatoka.common.capi.resource.ResourceLocalizer;
package de.hatoka.common.capi.app.xslt;
public class XSLTRenderer
{
private final TransformerFactory transformerFactory = TransformerFactory.newInstance();
public XSLTRenderer()
{
transformerFactory.setURIResolver(new ClassPathURIResolver());
}
@Deprecated
public Map<String, Object> getParameter(String localizationResource, Locale locale)
{
return getParameter(localizationResource, locale, CountryHelper.UTC);
}
public Map<String, Object> getParameter(String localizationResource, Locale locale, TimeZone timeZone)
{
Map<String, Object> result = new HashMap<>(); | result.put(Lib.XSLT_LOCALIZER, new ResourceLocalizer(new LocalizationBundle(localizationResource, |
Thomas-Bergmann/Tournament | de.hatoka.user/src/test/java/de/hatoka/user/internal/templates/app/LoginTemplateTest.java | // Path: de.hatoka.common/src/main/java/de/hatoka/common/capi/app/xslt/XSLTRenderer.java
// public class XSLTRenderer
// {
// private final TransformerFactory transformerFactory = TransformerFactory.newInstance();
//
// public XSLTRenderer()
// {
// transformerFactory.setURIResolver(new ClassPathURIResolver());
// }
//
// @Deprecated
// public Map<String, Object> getParameter(String localizationResource, Locale locale)
// {
// return getParameter(localizationResource, locale, CountryHelper.UTC);
// }
//
// public Map<String, Object> getParameter(String localizationResource, Locale locale, TimeZone timeZone)
// {
// Map<String, Object> result = new HashMap<>();
// result.put(Lib.XSLT_LOCALIZER, new ResourceLocalizer(new LocalizationBundle(localizationResource,
// locale, timeZone)));
// return result;
// }
//
// private StreamSource getStreamSource(String resource) throws FileNotFoundException
// {
// URL url = getClass().getClassLoader().getResource(resource);
// if (url == null)
// {
// throw new FileNotFoundException(resource);
// }
// return new StreamSource(url.toString());
// }
//
// /**
// * Render a jaxbElement with given xslt resource and
// * @param jaxbElement
// * @param stylesheet
// * @param parameters
// * @return
// * @throws IOException
// */
// public String render(Object jaxbModel, String stylesheet, Map<String, Object> parameters) throws IOException
// {
// StringWriter writer = new StringWriter();
// render(writer, jaxbModel, stylesheet, parameters);
// return writer.toString();
// }
//
// /**
// * Render a jaxbElement with given xslt resource and
// * @param writer write result to this writer
// * @param jaxbModel date to render
// * @param stylesheet xslt stylesheet resource
// * @param parameters parameter for style sheet, like localizer, uriInfo (depends on stylesheet)
// * @throws IOException
// */
// public void render(Writer writer, Object jaxbModel, String stylesheet, Map<String, Object> parameters) throws IOException
// {
// try
// {
// // Create Transformer
// Transformer transformer = transformerFactory.newTransformer(getStreamSource(stylesheet));
// for(Entry<String, Object> entry : parameters.entrySet())
// {
// transformer.setParameter(entry.getKey(), entry.getValue());
// }
// // Source
// JAXBContext jc = JAXBContext.newInstance(jaxbModel.getClass());
//
// // Transform
// transformer.transform(new JAXBSource(jc, jaxbModel), new StreamResult(writer));
// }
// catch(JAXBException | TransformerException e)
// {
// throw new IOException("Can't process stylesheet: " + stylesheet, e);
// }
// }
// }
| import java.io.IOException;
import java.util.Locale;
import org.custommonkey.xmlunit.XMLAssert;
import org.custommonkey.xmlunit.XMLUnit;
import org.junit.BeforeClass;
import org.junit.Test;
import org.xml.sax.SAXException;
import de.hatoka.common.capi.app.xslt.XSLTRenderer;
import de.hatoka.common.capi.business.CountryHelper;
import de.hatoka.common.capi.resource.ResourceLoader;
import de.hatoka.user.internal.app.forms.LoginForm; | package de.hatoka.user.internal.templates.app;
public class LoginTemplateTest
{
private static final String ORIGIN = "http://testdomain.de/origin";
private static final String RESOURCE_PREFIX = "de/hatoka/user/internal/templates/app/"; | // Path: de.hatoka.common/src/main/java/de/hatoka/common/capi/app/xslt/XSLTRenderer.java
// public class XSLTRenderer
// {
// private final TransformerFactory transformerFactory = TransformerFactory.newInstance();
//
// public XSLTRenderer()
// {
// transformerFactory.setURIResolver(new ClassPathURIResolver());
// }
//
// @Deprecated
// public Map<String, Object> getParameter(String localizationResource, Locale locale)
// {
// return getParameter(localizationResource, locale, CountryHelper.UTC);
// }
//
// public Map<String, Object> getParameter(String localizationResource, Locale locale, TimeZone timeZone)
// {
// Map<String, Object> result = new HashMap<>();
// result.put(Lib.XSLT_LOCALIZER, new ResourceLocalizer(new LocalizationBundle(localizationResource,
// locale, timeZone)));
// return result;
// }
//
// private StreamSource getStreamSource(String resource) throws FileNotFoundException
// {
// URL url = getClass().getClassLoader().getResource(resource);
// if (url == null)
// {
// throw new FileNotFoundException(resource);
// }
// return new StreamSource(url.toString());
// }
//
// /**
// * Render a jaxbElement with given xslt resource and
// * @param jaxbElement
// * @param stylesheet
// * @param parameters
// * @return
// * @throws IOException
// */
// public String render(Object jaxbModel, String stylesheet, Map<String, Object> parameters) throws IOException
// {
// StringWriter writer = new StringWriter();
// render(writer, jaxbModel, stylesheet, parameters);
// return writer.toString();
// }
//
// /**
// * Render a jaxbElement with given xslt resource and
// * @param writer write result to this writer
// * @param jaxbModel date to render
// * @param stylesheet xslt stylesheet resource
// * @param parameters parameter for style sheet, like localizer, uriInfo (depends on stylesheet)
// * @throws IOException
// */
// public void render(Writer writer, Object jaxbModel, String stylesheet, Map<String, Object> parameters) throws IOException
// {
// try
// {
// // Create Transformer
// Transformer transformer = transformerFactory.newTransformer(getStreamSource(stylesheet));
// for(Entry<String, Object> entry : parameters.entrySet())
// {
// transformer.setParameter(entry.getKey(), entry.getValue());
// }
// // Source
// JAXBContext jc = JAXBContext.newInstance(jaxbModel.getClass());
//
// // Transform
// transformer.transform(new JAXBSource(jc, jaxbModel), new StreamResult(writer));
// }
// catch(JAXBException | TransformerException e)
// {
// throw new IOException("Can't process stylesheet: " + stylesheet, e);
// }
// }
// }
// Path: de.hatoka.user/src/test/java/de/hatoka/user/internal/templates/app/LoginTemplateTest.java
import java.io.IOException;
import java.util.Locale;
import org.custommonkey.xmlunit.XMLAssert;
import org.custommonkey.xmlunit.XMLUnit;
import org.junit.BeforeClass;
import org.junit.Test;
import org.xml.sax.SAXException;
import de.hatoka.common.capi.app.xslt.XSLTRenderer;
import de.hatoka.common.capi.business.CountryHelper;
import de.hatoka.common.capi.resource.ResourceLoader;
import de.hatoka.user.internal.app.forms.LoginForm;
package de.hatoka.user.internal.templates.app;
public class LoginTemplateTest
{
private static final String ORIGIN = "http://testdomain.de/origin";
private static final String RESOURCE_PREFIX = "de/hatoka/user/internal/templates/app/"; | private static final XSLTRenderer RENDERER = new XSLTRenderer(); |
Thomas-Bergmann/Tournament | de.hatoka.tournament/src/main/java/de/hatoka/tournament/capi/entities/HistoryPO.java | // Path: de.hatoka.common/src/main/java/de/hatoka/common/capi/app/xslt/DateXmlAdapter.java
// public class DateXmlAdapter extends XmlAdapter<String, Date>
// {
// private final SimpleDateFormat dateFormat;
//
// public DateXmlAdapter()
// {
// dateFormat = new SimpleDateFormat(LocalizationConstants.XML_DATEFORMAT_SECONDS);
// dateFormat.setTimeZone(CountryHelper.UTC);
// }
//
// @Override
// public String marshal(Date v) throws Exception
// {
// if (v == null)
// {
// return null;
// }
// return dateFormat.format(v);
// }
//
// @Override
// public Date unmarshal(String v) throws Exception
// {
// if (v == null)
// {
// return null;
// }
// return dateFormat.parse(v);
// }
//
// }
//
// Path: de.hatoka.common/src/main/java/de/hatoka/common/capi/dao/IdentifiableEntity.java
// public interface IdentifiableEntity
// {
// String getId();
//
// void setId(String id);
// }
| import java.io.Serializable;
import java.util.Date;
import javax.persistence.AttributeOverride;
import javax.persistence.AttributeOverrides;
import javax.persistence.Column;
import javax.persistence.Embedded;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.validation.constraints.NotNull;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlTransient;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
import de.hatoka.common.capi.app.xslt.DateXmlAdapter;
import de.hatoka.common.capi.dao.IdentifiableEntity;
import de.hatoka.common.capi.entities.MoneyPO; | package de.hatoka.tournament.capi.entities;
@Entity
public class HistoryPO implements Serializable, IdentifiableEntity
{
private static final long serialVersionUID = 1L;
@Id
@XmlTransient
private String id;
@NotNull
@XmlAttribute(name="player")
private String player;
@NotNull
@ManyToOne
@JoinColumn(name = "tournament", updatable = false)
@XmlTransient
private TournamentPO tournament;
/**
* The player is in play
*/
@XmlAttribute
private String actionKey;
/**
* The player is out and was placed at position
*/
@NotNull
@Temporal(TemporalType.TIMESTAMP)
@XmlAttribute | // Path: de.hatoka.common/src/main/java/de/hatoka/common/capi/app/xslt/DateXmlAdapter.java
// public class DateXmlAdapter extends XmlAdapter<String, Date>
// {
// private final SimpleDateFormat dateFormat;
//
// public DateXmlAdapter()
// {
// dateFormat = new SimpleDateFormat(LocalizationConstants.XML_DATEFORMAT_SECONDS);
// dateFormat.setTimeZone(CountryHelper.UTC);
// }
//
// @Override
// public String marshal(Date v) throws Exception
// {
// if (v == null)
// {
// return null;
// }
// return dateFormat.format(v);
// }
//
// @Override
// public Date unmarshal(String v) throws Exception
// {
// if (v == null)
// {
// return null;
// }
// return dateFormat.parse(v);
// }
//
// }
//
// Path: de.hatoka.common/src/main/java/de/hatoka/common/capi/dao/IdentifiableEntity.java
// public interface IdentifiableEntity
// {
// String getId();
//
// void setId(String id);
// }
// Path: de.hatoka.tournament/src/main/java/de/hatoka/tournament/capi/entities/HistoryPO.java
import java.io.Serializable;
import java.util.Date;
import javax.persistence.AttributeOverride;
import javax.persistence.AttributeOverrides;
import javax.persistence.Column;
import javax.persistence.Embedded;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.validation.constraints.NotNull;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlTransient;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
import de.hatoka.common.capi.app.xslt.DateXmlAdapter;
import de.hatoka.common.capi.dao.IdentifiableEntity;
import de.hatoka.common.capi.entities.MoneyPO;
package de.hatoka.tournament.capi.entities;
@Entity
public class HistoryPO implements Serializable, IdentifiableEntity
{
private static final long serialVersionUID = 1L;
@Id
@XmlTransient
private String id;
@NotNull
@XmlAttribute(name="player")
private String player;
@NotNull
@ManyToOne
@JoinColumn(name = "tournament", updatable = false)
@XmlTransient
private TournamentPO tournament;
/**
* The player is in play
*/
@XmlAttribute
private String actionKey;
/**
* The player is out and was placed at position
*/
@NotNull
@Temporal(TemporalType.TIMESTAMP)
@XmlAttribute | @XmlJavaTypeAdapter(DateXmlAdapter.class) |
Thomas-Bergmann/Tournament | de.hatoka.group/src/main/java/de/hatoka/group/capi/dao/MemberDao.java | // Path: de.hatoka.group/src/main/java/de/hatoka/group/capi/entities/GroupPO.java
// @Entity
// @NamedQueries(value = {
// @NamedQuery(name = "GroupPO.findByName", query = "select a from GroupPO a where a.name = :name"),
// @NamedQuery(name = "GroupPO.findByOwnerRef", query = "select a from GroupPO a where a.ownerRef = :ownerRef")
// })
// public class GroupPO implements Serializable, IdentifiableEntity
// {
// private static final long serialVersionUID = 1L;
//
// @Id
// @XmlTransient
// private String id;
//
// @NotNull
// private String name;
//
// @NotNull
// private String ownerRef;
//
// @OneToMany(mappedBy = "groupPO", cascade = CascadeType.ALL)
// @XmlElement(name = "member")
// private List<MemberPO> members = new ArrayList<>();
//
// public GroupPO()
// {
// }
//
// @Override
// public boolean equals(Object obj)
// {
// if (this == obj)
// return true;
// if (obj == null)
// return false;
// if (getClass() != obj.getClass())
// return false;
// GroupPO other = (GroupPO)obj;
// if (id == null)
// {
// if (other.id != null)
// return false;
// }
// else if (!id.equals(other.id))
// return false;
// return true;
// }
//
// @Override
// public String getId()
// {
// return id;
// }
//
// @Override
// public void setId(String id)
// {
// this.id = id;
// }
//
// public String getName()
// {
// return name;
// }
//
// public void setName(String name)
// {
// this.name = name;
// }
//
// public List<MemberPO> getMembers()
// {
// return members;
// }
//
// public void setMembers(List<MemberPO> members)
// {
// this.members = members;
// }
//
// public String getOwnerRef()
// {
// return ownerRef;
// }
//
// public void setOwnerRef(String ownerRef)
// {
// this.ownerRef = ownerRef;
// }
// }
//
// Path: de.hatoka.group/src/main/java/de/hatoka/group/capi/entities/MemberPO.java
// @Entity
// @NamedQueries(value = {
// @NamedQuery(name = "MemberPO.findByUserRef", query = "select a from MemberPO a where a.userRef = :userRef")
// })
// public class MemberPO implements Serializable, IdentifiableEntity
// {
// private static final long serialVersionUID = 1L;
//
// @Id
// @XmlTransient
// private String id;
//
// @NotNull
// @ManyToOne
// @JoinColumn(name = "groupPO", updatable = false)
// private GroupPO groupPO;
//
// /**
// * user reference of member
// */
// @NotNull
// @XmlAttribute
// private String userRef;
//
// /**
// * name of user inside of the group
// */
// @NotNull
// @XmlAttribute
// private String name;
//
// public MemberPO()
// {
//
// }
//
// @Override
// public boolean equals(Object obj)
// {
// if (this == obj)
// return true;
// if (obj == null)
// return false;
// if (getClass() != obj.getClass())
// return false;
// MemberPO other = (MemberPO)obj;
// if (id == null)
// {
// if (other.id != null)
// return false;
// }
// else if (!id.equals(other.id))
// return false;
// return true;
// }
//
// @Override
// @XmlTransient
// public String getId()
// {
// return id;
// }
//
// @XmlTransient
// public GroupPO getGroup()
// {
// return groupPO;
// }
//
// public void setGroup(GroupPO groupPO)
// {
// this.groupPO = groupPO;
// }
//
// @XmlTransient
// public String getUserRef()
// {
// return userRef;
// }
//
// public void setUserRef(String userRef)
// {
// this.userRef = userRef;
// }
//
// @Override
// public void setId(String id)
// {
// this.id = id;
// }
//
// @XmlTransient
// public String getName()
// {
// return name;
// }
//
// public void setName(String name)
// {
// this.name = name;
// }
// }
| import java.util.List;
import de.hatoka.common.capi.dao.Dao;
import de.hatoka.group.capi.entities.GroupPO;
import de.hatoka.group.capi.entities.MemberPO; | package de.hatoka.group.capi.dao;
public interface MemberDao extends Dao<MemberPO>
{
/**
* Add member to group
* @param groupPO
* @param userRef
* @return
*/ | // Path: de.hatoka.group/src/main/java/de/hatoka/group/capi/entities/GroupPO.java
// @Entity
// @NamedQueries(value = {
// @NamedQuery(name = "GroupPO.findByName", query = "select a from GroupPO a where a.name = :name"),
// @NamedQuery(name = "GroupPO.findByOwnerRef", query = "select a from GroupPO a where a.ownerRef = :ownerRef")
// })
// public class GroupPO implements Serializable, IdentifiableEntity
// {
// private static final long serialVersionUID = 1L;
//
// @Id
// @XmlTransient
// private String id;
//
// @NotNull
// private String name;
//
// @NotNull
// private String ownerRef;
//
// @OneToMany(mappedBy = "groupPO", cascade = CascadeType.ALL)
// @XmlElement(name = "member")
// private List<MemberPO> members = new ArrayList<>();
//
// public GroupPO()
// {
// }
//
// @Override
// public boolean equals(Object obj)
// {
// if (this == obj)
// return true;
// if (obj == null)
// return false;
// if (getClass() != obj.getClass())
// return false;
// GroupPO other = (GroupPO)obj;
// if (id == null)
// {
// if (other.id != null)
// return false;
// }
// else if (!id.equals(other.id))
// return false;
// return true;
// }
//
// @Override
// public String getId()
// {
// return id;
// }
//
// @Override
// public void setId(String id)
// {
// this.id = id;
// }
//
// public String getName()
// {
// return name;
// }
//
// public void setName(String name)
// {
// this.name = name;
// }
//
// public List<MemberPO> getMembers()
// {
// return members;
// }
//
// public void setMembers(List<MemberPO> members)
// {
// this.members = members;
// }
//
// public String getOwnerRef()
// {
// return ownerRef;
// }
//
// public void setOwnerRef(String ownerRef)
// {
// this.ownerRef = ownerRef;
// }
// }
//
// Path: de.hatoka.group/src/main/java/de/hatoka/group/capi/entities/MemberPO.java
// @Entity
// @NamedQueries(value = {
// @NamedQuery(name = "MemberPO.findByUserRef", query = "select a from MemberPO a where a.userRef = :userRef")
// })
// public class MemberPO implements Serializable, IdentifiableEntity
// {
// private static final long serialVersionUID = 1L;
//
// @Id
// @XmlTransient
// private String id;
//
// @NotNull
// @ManyToOne
// @JoinColumn(name = "groupPO", updatable = false)
// private GroupPO groupPO;
//
// /**
// * user reference of member
// */
// @NotNull
// @XmlAttribute
// private String userRef;
//
// /**
// * name of user inside of the group
// */
// @NotNull
// @XmlAttribute
// private String name;
//
// public MemberPO()
// {
//
// }
//
// @Override
// public boolean equals(Object obj)
// {
// if (this == obj)
// return true;
// if (obj == null)
// return false;
// if (getClass() != obj.getClass())
// return false;
// MemberPO other = (MemberPO)obj;
// if (id == null)
// {
// if (other.id != null)
// return false;
// }
// else if (!id.equals(other.id))
// return false;
// return true;
// }
//
// @Override
// @XmlTransient
// public String getId()
// {
// return id;
// }
//
// @XmlTransient
// public GroupPO getGroup()
// {
// return groupPO;
// }
//
// public void setGroup(GroupPO groupPO)
// {
// this.groupPO = groupPO;
// }
//
// @XmlTransient
// public String getUserRef()
// {
// return userRef;
// }
//
// public void setUserRef(String userRef)
// {
// this.userRef = userRef;
// }
//
// @Override
// public void setId(String id)
// {
// this.id = id;
// }
//
// @XmlTransient
// public String getName()
// {
// return name;
// }
//
// public void setName(String name)
// {
// this.name = name;
// }
// }
// Path: de.hatoka.group/src/main/java/de/hatoka/group/capi/dao/MemberDao.java
import java.util.List;
import de.hatoka.common.capi.dao.Dao;
import de.hatoka.group.capi.entities.GroupPO;
import de.hatoka.group.capi.entities.MemberPO;
package de.hatoka.group.capi.dao;
public interface MemberDao extends Dao<MemberPO>
{
/**
* Add member to group
* @param groupPO
* @param userRef
* @return
*/ | public MemberPO createAndInsert(GroupPO groupPO, String userRef, String name); |
Thomas-Bergmann/Tournament | de.hatoka.tournament/src/main/java/de/hatoka/tournament/internal/app/models/RankVO.java | // Path: de.hatoka.tournament/src/main/java/de/hatoka/tournament/capi/business/RankBO.java
// public interface RankBO
// {
// /**
// * @return the identifier (artificial key)
// */
// String getID();
//
// Integer getFirstPosition();
//
// Integer getLastPosition();
//
// BigDecimal getPercentage();
//
// Money getAmountPerPlayer();
//
// Money getAmount();
// }
| import java.math.BigDecimal;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlTransient;
import de.hatoka.common.capi.app.model.MoneyVO;
import de.hatoka.tournament.capi.business.RankBO; | package de.hatoka.tournament.internal.app.models;
public class RankVO
{
@XmlAttribute
private String id;
@XmlAttribute
private int firstPosition;
@XmlAttribute
private Integer lastPosition;
@XmlAttribute
private BigDecimal percentage; // 0.5 for 50%
private MoneyVO amountPerPlayer;
private MoneyVO amount;
public RankVO()
{
}
| // Path: de.hatoka.tournament/src/main/java/de/hatoka/tournament/capi/business/RankBO.java
// public interface RankBO
// {
// /**
// * @return the identifier (artificial key)
// */
// String getID();
//
// Integer getFirstPosition();
//
// Integer getLastPosition();
//
// BigDecimal getPercentage();
//
// Money getAmountPerPlayer();
//
// Money getAmount();
// }
// Path: de.hatoka.tournament/src/main/java/de/hatoka/tournament/internal/app/models/RankVO.java
import java.math.BigDecimal;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlTransient;
import de.hatoka.common.capi.app.model.MoneyVO;
import de.hatoka.tournament.capi.business.RankBO;
package de.hatoka.tournament.internal.app.models;
public class RankVO
{
@XmlAttribute
private String id;
@XmlAttribute
private int firstPosition;
@XmlAttribute
private Integer lastPosition;
@XmlAttribute
private BigDecimal percentage; // 0.5 for 50%
private MoneyVO amountPerPlayer;
private MoneyVO amount;
public RankVO()
{
}
| public RankVO(RankBO rank) |
Thomas-Bergmann/Tournament | de.hatoka.user/src/test/java/de/hatoka/user/capi/business/TestBusinessInjectorProvider.java | // Path: de.hatoka.common/src/main/java/de/hatoka/common/capi/modules/CommonDaoModule.java
// public class CommonDaoModule implements Module
// {
// private long start;
//
// public CommonDaoModule()
// {
// this(0);
// }
//
// public CommonDaoModule(long sequenceStartPosition)
// {
// start = sequenceStartPosition;
// }
//
// @Override
// public void configure(Binder binder)
// {
// binder.bind(UUIDGenerator.class).to(UUIDGeneratorImpl.class).asEagerSingleton();
// binder.bind(EncryptionUtils.class).to(EncryptionUtilsImpl.class).asEagerSingleton();
// binder.bind(SequenceProvider.class).toInstance(new SequenceProviderImpl(start));
// }
//
// }
//
// Path: de.hatoka.mail/src/main/java/de/hatoka/mail/capi/config/SmtpConfiguration.java
// public interface SmtpConfiguration
// {
// Session getSession();
// }
//
// Path: de.hatoka.mail/src/main/java/de/hatoka/mail/internal/modules/MailDaoJpaModule.java
// public class MailDaoJpaModule implements Module
// {
// @Override
// public void configure(Binder binder)
// {
// binder.bind(MessageIDGenerator.class).to(MessageIDGeneratorImpl.class).asEagerSingleton();
// binder.bind(MailDao.class).to(MailDaoJpa.class).asEagerSingleton();
// }
//
// }
//
// Path: de.hatoka.user/src/test/java/de/hatoka/user/internal/config/SmtpTestConfiguration.java
// public class SmtpTestConfiguration implements SmtpConfiguration
// {
//
// @Override
// public Session getSession()
// {
// return null;
// }
// }
//
// Path: de.hatoka.user/src/main/java/de/hatoka/user/internal/modules/UserDaoJpaModule.java
// public class UserDaoJpaModule implements Module
// {
// @Override
// public void configure(Binder binder)
// {
// binder.bind(UserDao.class).to(UserDaoJpa.class).asEagerSingleton();
// }
// }
| import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import com.google.inject.Guice;
import com.google.inject.Injector;
import com.google.inject.Module;
import de.hatoka.common.capi.modules.CommonDaoModule;
import de.hatoka.mail.capi.config.SmtpConfiguration;
import de.hatoka.mail.internal.modules.MailDaoJpaModule;
import de.hatoka.mail.internal.modules.MailServiceModule;
import de.hatoka.user.capi.config.UserConfiguration;
import de.hatoka.user.internal.config.SmtpTestConfiguration;
import de.hatoka.user.internal.config.UserTestConfiguration;
import de.hatoka.user.internal.modules.UserBusinessModule;
import de.hatoka.user.internal.modules.UserDaoJpaModule; | package de.hatoka.user.capi.business;
public final class TestBusinessInjectorProvider
{
public static Injector get(Module... modules)
{
List<Module> list = new ArrayList<>(Arrays.asList(modules)); | // Path: de.hatoka.common/src/main/java/de/hatoka/common/capi/modules/CommonDaoModule.java
// public class CommonDaoModule implements Module
// {
// private long start;
//
// public CommonDaoModule()
// {
// this(0);
// }
//
// public CommonDaoModule(long sequenceStartPosition)
// {
// start = sequenceStartPosition;
// }
//
// @Override
// public void configure(Binder binder)
// {
// binder.bind(UUIDGenerator.class).to(UUIDGeneratorImpl.class).asEagerSingleton();
// binder.bind(EncryptionUtils.class).to(EncryptionUtilsImpl.class).asEagerSingleton();
// binder.bind(SequenceProvider.class).toInstance(new SequenceProviderImpl(start));
// }
//
// }
//
// Path: de.hatoka.mail/src/main/java/de/hatoka/mail/capi/config/SmtpConfiguration.java
// public interface SmtpConfiguration
// {
// Session getSession();
// }
//
// Path: de.hatoka.mail/src/main/java/de/hatoka/mail/internal/modules/MailDaoJpaModule.java
// public class MailDaoJpaModule implements Module
// {
// @Override
// public void configure(Binder binder)
// {
// binder.bind(MessageIDGenerator.class).to(MessageIDGeneratorImpl.class).asEagerSingleton();
// binder.bind(MailDao.class).to(MailDaoJpa.class).asEagerSingleton();
// }
//
// }
//
// Path: de.hatoka.user/src/test/java/de/hatoka/user/internal/config/SmtpTestConfiguration.java
// public class SmtpTestConfiguration implements SmtpConfiguration
// {
//
// @Override
// public Session getSession()
// {
// return null;
// }
// }
//
// Path: de.hatoka.user/src/main/java/de/hatoka/user/internal/modules/UserDaoJpaModule.java
// public class UserDaoJpaModule implements Module
// {
// @Override
// public void configure(Binder binder)
// {
// binder.bind(UserDao.class).to(UserDaoJpa.class).asEagerSingleton();
// }
// }
// Path: de.hatoka.user/src/test/java/de/hatoka/user/capi/business/TestBusinessInjectorProvider.java
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import com.google.inject.Guice;
import com.google.inject.Injector;
import com.google.inject.Module;
import de.hatoka.common.capi.modules.CommonDaoModule;
import de.hatoka.mail.capi.config.SmtpConfiguration;
import de.hatoka.mail.internal.modules.MailDaoJpaModule;
import de.hatoka.mail.internal.modules.MailServiceModule;
import de.hatoka.user.capi.config.UserConfiguration;
import de.hatoka.user.internal.config.SmtpTestConfiguration;
import de.hatoka.user.internal.config.UserTestConfiguration;
import de.hatoka.user.internal.modules.UserBusinessModule;
import de.hatoka.user.internal.modules.UserDaoJpaModule;
package de.hatoka.user.capi.business;
public final class TestBusinessInjectorProvider
{
public static Injector get(Module... modules)
{
List<Module> list = new ArrayList<>(Arrays.asList(modules)); | list.addAll(Arrays.asList(new CommonDaoModule(), new UserDaoJpaModule(), new UserBusinessModule(), |
Thomas-Bergmann/Tournament | de.hatoka.user/src/test/java/de/hatoka/user/capi/business/TestBusinessInjectorProvider.java | // Path: de.hatoka.common/src/main/java/de/hatoka/common/capi/modules/CommonDaoModule.java
// public class CommonDaoModule implements Module
// {
// private long start;
//
// public CommonDaoModule()
// {
// this(0);
// }
//
// public CommonDaoModule(long sequenceStartPosition)
// {
// start = sequenceStartPosition;
// }
//
// @Override
// public void configure(Binder binder)
// {
// binder.bind(UUIDGenerator.class).to(UUIDGeneratorImpl.class).asEagerSingleton();
// binder.bind(EncryptionUtils.class).to(EncryptionUtilsImpl.class).asEagerSingleton();
// binder.bind(SequenceProvider.class).toInstance(new SequenceProviderImpl(start));
// }
//
// }
//
// Path: de.hatoka.mail/src/main/java/de/hatoka/mail/capi/config/SmtpConfiguration.java
// public interface SmtpConfiguration
// {
// Session getSession();
// }
//
// Path: de.hatoka.mail/src/main/java/de/hatoka/mail/internal/modules/MailDaoJpaModule.java
// public class MailDaoJpaModule implements Module
// {
// @Override
// public void configure(Binder binder)
// {
// binder.bind(MessageIDGenerator.class).to(MessageIDGeneratorImpl.class).asEagerSingleton();
// binder.bind(MailDao.class).to(MailDaoJpa.class).asEagerSingleton();
// }
//
// }
//
// Path: de.hatoka.user/src/test/java/de/hatoka/user/internal/config/SmtpTestConfiguration.java
// public class SmtpTestConfiguration implements SmtpConfiguration
// {
//
// @Override
// public Session getSession()
// {
// return null;
// }
// }
//
// Path: de.hatoka.user/src/main/java/de/hatoka/user/internal/modules/UserDaoJpaModule.java
// public class UserDaoJpaModule implements Module
// {
// @Override
// public void configure(Binder binder)
// {
// binder.bind(UserDao.class).to(UserDaoJpa.class).asEagerSingleton();
// }
// }
| import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import com.google.inject.Guice;
import com.google.inject.Injector;
import com.google.inject.Module;
import de.hatoka.common.capi.modules.CommonDaoModule;
import de.hatoka.mail.capi.config.SmtpConfiguration;
import de.hatoka.mail.internal.modules.MailDaoJpaModule;
import de.hatoka.mail.internal.modules.MailServiceModule;
import de.hatoka.user.capi.config.UserConfiguration;
import de.hatoka.user.internal.config.SmtpTestConfiguration;
import de.hatoka.user.internal.config.UserTestConfiguration;
import de.hatoka.user.internal.modules.UserBusinessModule;
import de.hatoka.user.internal.modules.UserDaoJpaModule; | package de.hatoka.user.capi.business;
public final class TestBusinessInjectorProvider
{
public static Injector get(Module... modules)
{
List<Module> list = new ArrayList<>(Arrays.asList(modules)); | // Path: de.hatoka.common/src/main/java/de/hatoka/common/capi/modules/CommonDaoModule.java
// public class CommonDaoModule implements Module
// {
// private long start;
//
// public CommonDaoModule()
// {
// this(0);
// }
//
// public CommonDaoModule(long sequenceStartPosition)
// {
// start = sequenceStartPosition;
// }
//
// @Override
// public void configure(Binder binder)
// {
// binder.bind(UUIDGenerator.class).to(UUIDGeneratorImpl.class).asEagerSingleton();
// binder.bind(EncryptionUtils.class).to(EncryptionUtilsImpl.class).asEagerSingleton();
// binder.bind(SequenceProvider.class).toInstance(new SequenceProviderImpl(start));
// }
//
// }
//
// Path: de.hatoka.mail/src/main/java/de/hatoka/mail/capi/config/SmtpConfiguration.java
// public interface SmtpConfiguration
// {
// Session getSession();
// }
//
// Path: de.hatoka.mail/src/main/java/de/hatoka/mail/internal/modules/MailDaoJpaModule.java
// public class MailDaoJpaModule implements Module
// {
// @Override
// public void configure(Binder binder)
// {
// binder.bind(MessageIDGenerator.class).to(MessageIDGeneratorImpl.class).asEagerSingleton();
// binder.bind(MailDao.class).to(MailDaoJpa.class).asEagerSingleton();
// }
//
// }
//
// Path: de.hatoka.user/src/test/java/de/hatoka/user/internal/config/SmtpTestConfiguration.java
// public class SmtpTestConfiguration implements SmtpConfiguration
// {
//
// @Override
// public Session getSession()
// {
// return null;
// }
// }
//
// Path: de.hatoka.user/src/main/java/de/hatoka/user/internal/modules/UserDaoJpaModule.java
// public class UserDaoJpaModule implements Module
// {
// @Override
// public void configure(Binder binder)
// {
// binder.bind(UserDao.class).to(UserDaoJpa.class).asEagerSingleton();
// }
// }
// Path: de.hatoka.user/src/test/java/de/hatoka/user/capi/business/TestBusinessInjectorProvider.java
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import com.google.inject.Guice;
import com.google.inject.Injector;
import com.google.inject.Module;
import de.hatoka.common.capi.modules.CommonDaoModule;
import de.hatoka.mail.capi.config.SmtpConfiguration;
import de.hatoka.mail.internal.modules.MailDaoJpaModule;
import de.hatoka.mail.internal.modules.MailServiceModule;
import de.hatoka.user.capi.config.UserConfiguration;
import de.hatoka.user.internal.config.SmtpTestConfiguration;
import de.hatoka.user.internal.config.UserTestConfiguration;
import de.hatoka.user.internal.modules.UserBusinessModule;
import de.hatoka.user.internal.modules.UserDaoJpaModule;
package de.hatoka.user.capi.business;
public final class TestBusinessInjectorProvider
{
public static Injector get(Module... modules)
{
List<Module> list = new ArrayList<>(Arrays.asList(modules)); | list.addAll(Arrays.asList(new CommonDaoModule(), new UserDaoJpaModule(), new UserBusinessModule(), |
Thomas-Bergmann/Tournament | de.hatoka.user/src/test/java/de/hatoka/user/capi/business/TestBusinessInjectorProvider.java | // Path: de.hatoka.common/src/main/java/de/hatoka/common/capi/modules/CommonDaoModule.java
// public class CommonDaoModule implements Module
// {
// private long start;
//
// public CommonDaoModule()
// {
// this(0);
// }
//
// public CommonDaoModule(long sequenceStartPosition)
// {
// start = sequenceStartPosition;
// }
//
// @Override
// public void configure(Binder binder)
// {
// binder.bind(UUIDGenerator.class).to(UUIDGeneratorImpl.class).asEagerSingleton();
// binder.bind(EncryptionUtils.class).to(EncryptionUtilsImpl.class).asEagerSingleton();
// binder.bind(SequenceProvider.class).toInstance(new SequenceProviderImpl(start));
// }
//
// }
//
// Path: de.hatoka.mail/src/main/java/de/hatoka/mail/capi/config/SmtpConfiguration.java
// public interface SmtpConfiguration
// {
// Session getSession();
// }
//
// Path: de.hatoka.mail/src/main/java/de/hatoka/mail/internal/modules/MailDaoJpaModule.java
// public class MailDaoJpaModule implements Module
// {
// @Override
// public void configure(Binder binder)
// {
// binder.bind(MessageIDGenerator.class).to(MessageIDGeneratorImpl.class).asEagerSingleton();
// binder.bind(MailDao.class).to(MailDaoJpa.class).asEagerSingleton();
// }
//
// }
//
// Path: de.hatoka.user/src/test/java/de/hatoka/user/internal/config/SmtpTestConfiguration.java
// public class SmtpTestConfiguration implements SmtpConfiguration
// {
//
// @Override
// public Session getSession()
// {
// return null;
// }
// }
//
// Path: de.hatoka.user/src/main/java/de/hatoka/user/internal/modules/UserDaoJpaModule.java
// public class UserDaoJpaModule implements Module
// {
// @Override
// public void configure(Binder binder)
// {
// binder.bind(UserDao.class).to(UserDaoJpa.class).asEagerSingleton();
// }
// }
| import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import com.google.inject.Guice;
import com.google.inject.Injector;
import com.google.inject.Module;
import de.hatoka.common.capi.modules.CommonDaoModule;
import de.hatoka.mail.capi.config.SmtpConfiguration;
import de.hatoka.mail.internal.modules.MailDaoJpaModule;
import de.hatoka.mail.internal.modules.MailServiceModule;
import de.hatoka.user.capi.config.UserConfiguration;
import de.hatoka.user.internal.config.SmtpTestConfiguration;
import de.hatoka.user.internal.config.UserTestConfiguration;
import de.hatoka.user.internal.modules.UserBusinessModule;
import de.hatoka.user.internal.modules.UserDaoJpaModule; | package de.hatoka.user.capi.business;
public final class TestBusinessInjectorProvider
{
public static Injector get(Module... modules)
{
List<Module> list = new ArrayList<>(Arrays.asList(modules));
list.addAll(Arrays.asList(new CommonDaoModule(), new UserDaoJpaModule(), new UserBusinessModule(), | // Path: de.hatoka.common/src/main/java/de/hatoka/common/capi/modules/CommonDaoModule.java
// public class CommonDaoModule implements Module
// {
// private long start;
//
// public CommonDaoModule()
// {
// this(0);
// }
//
// public CommonDaoModule(long sequenceStartPosition)
// {
// start = sequenceStartPosition;
// }
//
// @Override
// public void configure(Binder binder)
// {
// binder.bind(UUIDGenerator.class).to(UUIDGeneratorImpl.class).asEagerSingleton();
// binder.bind(EncryptionUtils.class).to(EncryptionUtilsImpl.class).asEagerSingleton();
// binder.bind(SequenceProvider.class).toInstance(new SequenceProviderImpl(start));
// }
//
// }
//
// Path: de.hatoka.mail/src/main/java/de/hatoka/mail/capi/config/SmtpConfiguration.java
// public interface SmtpConfiguration
// {
// Session getSession();
// }
//
// Path: de.hatoka.mail/src/main/java/de/hatoka/mail/internal/modules/MailDaoJpaModule.java
// public class MailDaoJpaModule implements Module
// {
// @Override
// public void configure(Binder binder)
// {
// binder.bind(MessageIDGenerator.class).to(MessageIDGeneratorImpl.class).asEagerSingleton();
// binder.bind(MailDao.class).to(MailDaoJpa.class).asEagerSingleton();
// }
//
// }
//
// Path: de.hatoka.user/src/test/java/de/hatoka/user/internal/config/SmtpTestConfiguration.java
// public class SmtpTestConfiguration implements SmtpConfiguration
// {
//
// @Override
// public Session getSession()
// {
// return null;
// }
// }
//
// Path: de.hatoka.user/src/main/java/de/hatoka/user/internal/modules/UserDaoJpaModule.java
// public class UserDaoJpaModule implements Module
// {
// @Override
// public void configure(Binder binder)
// {
// binder.bind(UserDao.class).to(UserDaoJpa.class).asEagerSingleton();
// }
// }
// Path: de.hatoka.user/src/test/java/de/hatoka/user/capi/business/TestBusinessInjectorProvider.java
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import com.google.inject.Guice;
import com.google.inject.Injector;
import com.google.inject.Module;
import de.hatoka.common.capi.modules.CommonDaoModule;
import de.hatoka.mail.capi.config.SmtpConfiguration;
import de.hatoka.mail.internal.modules.MailDaoJpaModule;
import de.hatoka.mail.internal.modules.MailServiceModule;
import de.hatoka.user.capi.config.UserConfiguration;
import de.hatoka.user.internal.config.SmtpTestConfiguration;
import de.hatoka.user.internal.config.UserTestConfiguration;
import de.hatoka.user.internal.modules.UserBusinessModule;
import de.hatoka.user.internal.modules.UserDaoJpaModule;
package de.hatoka.user.capi.business;
public final class TestBusinessInjectorProvider
{
public static Injector get(Module... modules)
{
List<Module> list = new ArrayList<>(Arrays.asList(modules));
list.addAll(Arrays.asList(new CommonDaoModule(), new UserDaoJpaModule(), new UserBusinessModule(), | new MailDaoJpaModule(), new MailServiceModule(), |
Thomas-Bergmann/Tournament | de.hatoka.user/src/test/java/de/hatoka/user/capi/business/TestBusinessInjectorProvider.java | // Path: de.hatoka.common/src/main/java/de/hatoka/common/capi/modules/CommonDaoModule.java
// public class CommonDaoModule implements Module
// {
// private long start;
//
// public CommonDaoModule()
// {
// this(0);
// }
//
// public CommonDaoModule(long sequenceStartPosition)
// {
// start = sequenceStartPosition;
// }
//
// @Override
// public void configure(Binder binder)
// {
// binder.bind(UUIDGenerator.class).to(UUIDGeneratorImpl.class).asEagerSingleton();
// binder.bind(EncryptionUtils.class).to(EncryptionUtilsImpl.class).asEagerSingleton();
// binder.bind(SequenceProvider.class).toInstance(new SequenceProviderImpl(start));
// }
//
// }
//
// Path: de.hatoka.mail/src/main/java/de/hatoka/mail/capi/config/SmtpConfiguration.java
// public interface SmtpConfiguration
// {
// Session getSession();
// }
//
// Path: de.hatoka.mail/src/main/java/de/hatoka/mail/internal/modules/MailDaoJpaModule.java
// public class MailDaoJpaModule implements Module
// {
// @Override
// public void configure(Binder binder)
// {
// binder.bind(MessageIDGenerator.class).to(MessageIDGeneratorImpl.class).asEagerSingleton();
// binder.bind(MailDao.class).to(MailDaoJpa.class).asEagerSingleton();
// }
//
// }
//
// Path: de.hatoka.user/src/test/java/de/hatoka/user/internal/config/SmtpTestConfiguration.java
// public class SmtpTestConfiguration implements SmtpConfiguration
// {
//
// @Override
// public Session getSession()
// {
// return null;
// }
// }
//
// Path: de.hatoka.user/src/main/java/de/hatoka/user/internal/modules/UserDaoJpaModule.java
// public class UserDaoJpaModule implements Module
// {
// @Override
// public void configure(Binder binder)
// {
// binder.bind(UserDao.class).to(UserDaoJpa.class).asEagerSingleton();
// }
// }
| import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import com.google.inject.Guice;
import com.google.inject.Injector;
import com.google.inject.Module;
import de.hatoka.common.capi.modules.CommonDaoModule;
import de.hatoka.mail.capi.config.SmtpConfiguration;
import de.hatoka.mail.internal.modules.MailDaoJpaModule;
import de.hatoka.mail.internal.modules.MailServiceModule;
import de.hatoka.user.capi.config.UserConfiguration;
import de.hatoka.user.internal.config.SmtpTestConfiguration;
import de.hatoka.user.internal.config.UserTestConfiguration;
import de.hatoka.user.internal.modules.UserBusinessModule;
import de.hatoka.user.internal.modules.UserDaoJpaModule; | package de.hatoka.user.capi.business;
public final class TestBusinessInjectorProvider
{
public static Injector get(Module... modules)
{
List<Module> list = new ArrayList<>(Arrays.asList(modules));
list.addAll(Arrays.asList(new CommonDaoModule(), new UserDaoJpaModule(), new UserBusinessModule(),
new MailDaoJpaModule(), new MailServiceModule(),
binder -> binder.bind(UserConfiguration.class).to(UserTestConfiguration.class).asEagerSingleton(), | // Path: de.hatoka.common/src/main/java/de/hatoka/common/capi/modules/CommonDaoModule.java
// public class CommonDaoModule implements Module
// {
// private long start;
//
// public CommonDaoModule()
// {
// this(0);
// }
//
// public CommonDaoModule(long sequenceStartPosition)
// {
// start = sequenceStartPosition;
// }
//
// @Override
// public void configure(Binder binder)
// {
// binder.bind(UUIDGenerator.class).to(UUIDGeneratorImpl.class).asEagerSingleton();
// binder.bind(EncryptionUtils.class).to(EncryptionUtilsImpl.class).asEagerSingleton();
// binder.bind(SequenceProvider.class).toInstance(new SequenceProviderImpl(start));
// }
//
// }
//
// Path: de.hatoka.mail/src/main/java/de/hatoka/mail/capi/config/SmtpConfiguration.java
// public interface SmtpConfiguration
// {
// Session getSession();
// }
//
// Path: de.hatoka.mail/src/main/java/de/hatoka/mail/internal/modules/MailDaoJpaModule.java
// public class MailDaoJpaModule implements Module
// {
// @Override
// public void configure(Binder binder)
// {
// binder.bind(MessageIDGenerator.class).to(MessageIDGeneratorImpl.class).asEagerSingleton();
// binder.bind(MailDao.class).to(MailDaoJpa.class).asEagerSingleton();
// }
//
// }
//
// Path: de.hatoka.user/src/test/java/de/hatoka/user/internal/config/SmtpTestConfiguration.java
// public class SmtpTestConfiguration implements SmtpConfiguration
// {
//
// @Override
// public Session getSession()
// {
// return null;
// }
// }
//
// Path: de.hatoka.user/src/main/java/de/hatoka/user/internal/modules/UserDaoJpaModule.java
// public class UserDaoJpaModule implements Module
// {
// @Override
// public void configure(Binder binder)
// {
// binder.bind(UserDao.class).to(UserDaoJpa.class).asEagerSingleton();
// }
// }
// Path: de.hatoka.user/src/test/java/de/hatoka/user/capi/business/TestBusinessInjectorProvider.java
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import com.google.inject.Guice;
import com.google.inject.Injector;
import com.google.inject.Module;
import de.hatoka.common.capi.modules.CommonDaoModule;
import de.hatoka.mail.capi.config.SmtpConfiguration;
import de.hatoka.mail.internal.modules.MailDaoJpaModule;
import de.hatoka.mail.internal.modules.MailServiceModule;
import de.hatoka.user.capi.config.UserConfiguration;
import de.hatoka.user.internal.config.SmtpTestConfiguration;
import de.hatoka.user.internal.config.UserTestConfiguration;
import de.hatoka.user.internal.modules.UserBusinessModule;
import de.hatoka.user.internal.modules.UserDaoJpaModule;
package de.hatoka.user.capi.business;
public final class TestBusinessInjectorProvider
{
public static Injector get(Module... modules)
{
List<Module> list = new ArrayList<>(Arrays.asList(modules));
list.addAll(Arrays.asList(new CommonDaoModule(), new UserDaoJpaModule(), new UserBusinessModule(),
new MailDaoJpaModule(), new MailServiceModule(),
binder -> binder.bind(UserConfiguration.class).to(UserTestConfiguration.class).asEagerSingleton(), | binder -> binder.bind(SmtpConfiguration.class).to(SmtpTestConfiguration.class).asEagerSingleton() |
Thomas-Bergmann/Tournament | de.hatoka.user/src/test/java/de/hatoka/user/capi/business/TestBusinessInjectorProvider.java | // Path: de.hatoka.common/src/main/java/de/hatoka/common/capi/modules/CommonDaoModule.java
// public class CommonDaoModule implements Module
// {
// private long start;
//
// public CommonDaoModule()
// {
// this(0);
// }
//
// public CommonDaoModule(long sequenceStartPosition)
// {
// start = sequenceStartPosition;
// }
//
// @Override
// public void configure(Binder binder)
// {
// binder.bind(UUIDGenerator.class).to(UUIDGeneratorImpl.class).asEagerSingleton();
// binder.bind(EncryptionUtils.class).to(EncryptionUtilsImpl.class).asEagerSingleton();
// binder.bind(SequenceProvider.class).toInstance(new SequenceProviderImpl(start));
// }
//
// }
//
// Path: de.hatoka.mail/src/main/java/de/hatoka/mail/capi/config/SmtpConfiguration.java
// public interface SmtpConfiguration
// {
// Session getSession();
// }
//
// Path: de.hatoka.mail/src/main/java/de/hatoka/mail/internal/modules/MailDaoJpaModule.java
// public class MailDaoJpaModule implements Module
// {
// @Override
// public void configure(Binder binder)
// {
// binder.bind(MessageIDGenerator.class).to(MessageIDGeneratorImpl.class).asEagerSingleton();
// binder.bind(MailDao.class).to(MailDaoJpa.class).asEagerSingleton();
// }
//
// }
//
// Path: de.hatoka.user/src/test/java/de/hatoka/user/internal/config/SmtpTestConfiguration.java
// public class SmtpTestConfiguration implements SmtpConfiguration
// {
//
// @Override
// public Session getSession()
// {
// return null;
// }
// }
//
// Path: de.hatoka.user/src/main/java/de/hatoka/user/internal/modules/UserDaoJpaModule.java
// public class UserDaoJpaModule implements Module
// {
// @Override
// public void configure(Binder binder)
// {
// binder.bind(UserDao.class).to(UserDaoJpa.class).asEagerSingleton();
// }
// }
| import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import com.google.inject.Guice;
import com.google.inject.Injector;
import com.google.inject.Module;
import de.hatoka.common.capi.modules.CommonDaoModule;
import de.hatoka.mail.capi.config.SmtpConfiguration;
import de.hatoka.mail.internal.modules.MailDaoJpaModule;
import de.hatoka.mail.internal.modules.MailServiceModule;
import de.hatoka.user.capi.config.UserConfiguration;
import de.hatoka.user.internal.config.SmtpTestConfiguration;
import de.hatoka.user.internal.config.UserTestConfiguration;
import de.hatoka.user.internal.modules.UserBusinessModule;
import de.hatoka.user.internal.modules.UserDaoJpaModule; | package de.hatoka.user.capi.business;
public final class TestBusinessInjectorProvider
{
public static Injector get(Module... modules)
{
List<Module> list = new ArrayList<>(Arrays.asList(modules));
list.addAll(Arrays.asList(new CommonDaoModule(), new UserDaoJpaModule(), new UserBusinessModule(),
new MailDaoJpaModule(), new MailServiceModule(),
binder -> binder.bind(UserConfiguration.class).to(UserTestConfiguration.class).asEagerSingleton(), | // Path: de.hatoka.common/src/main/java/de/hatoka/common/capi/modules/CommonDaoModule.java
// public class CommonDaoModule implements Module
// {
// private long start;
//
// public CommonDaoModule()
// {
// this(0);
// }
//
// public CommonDaoModule(long sequenceStartPosition)
// {
// start = sequenceStartPosition;
// }
//
// @Override
// public void configure(Binder binder)
// {
// binder.bind(UUIDGenerator.class).to(UUIDGeneratorImpl.class).asEagerSingleton();
// binder.bind(EncryptionUtils.class).to(EncryptionUtilsImpl.class).asEagerSingleton();
// binder.bind(SequenceProvider.class).toInstance(new SequenceProviderImpl(start));
// }
//
// }
//
// Path: de.hatoka.mail/src/main/java/de/hatoka/mail/capi/config/SmtpConfiguration.java
// public interface SmtpConfiguration
// {
// Session getSession();
// }
//
// Path: de.hatoka.mail/src/main/java/de/hatoka/mail/internal/modules/MailDaoJpaModule.java
// public class MailDaoJpaModule implements Module
// {
// @Override
// public void configure(Binder binder)
// {
// binder.bind(MessageIDGenerator.class).to(MessageIDGeneratorImpl.class).asEagerSingleton();
// binder.bind(MailDao.class).to(MailDaoJpa.class).asEagerSingleton();
// }
//
// }
//
// Path: de.hatoka.user/src/test/java/de/hatoka/user/internal/config/SmtpTestConfiguration.java
// public class SmtpTestConfiguration implements SmtpConfiguration
// {
//
// @Override
// public Session getSession()
// {
// return null;
// }
// }
//
// Path: de.hatoka.user/src/main/java/de/hatoka/user/internal/modules/UserDaoJpaModule.java
// public class UserDaoJpaModule implements Module
// {
// @Override
// public void configure(Binder binder)
// {
// binder.bind(UserDao.class).to(UserDaoJpa.class).asEagerSingleton();
// }
// }
// Path: de.hatoka.user/src/test/java/de/hatoka/user/capi/business/TestBusinessInjectorProvider.java
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import com.google.inject.Guice;
import com.google.inject.Injector;
import com.google.inject.Module;
import de.hatoka.common.capi.modules.CommonDaoModule;
import de.hatoka.mail.capi.config.SmtpConfiguration;
import de.hatoka.mail.internal.modules.MailDaoJpaModule;
import de.hatoka.mail.internal.modules.MailServiceModule;
import de.hatoka.user.capi.config.UserConfiguration;
import de.hatoka.user.internal.config.SmtpTestConfiguration;
import de.hatoka.user.internal.config.UserTestConfiguration;
import de.hatoka.user.internal.modules.UserBusinessModule;
import de.hatoka.user.internal.modules.UserDaoJpaModule;
package de.hatoka.user.capi.business;
public final class TestBusinessInjectorProvider
{
public static Injector get(Module... modules)
{
List<Module> list = new ArrayList<>(Arrays.asList(modules));
list.addAll(Arrays.asList(new CommonDaoModule(), new UserDaoJpaModule(), new UserBusinessModule(),
new MailDaoJpaModule(), new MailServiceModule(),
binder -> binder.bind(UserConfiguration.class).to(UserTestConfiguration.class).asEagerSingleton(), | binder -> binder.bind(SmtpConfiguration.class).to(SmtpTestConfiguration.class).asEagerSingleton() |
Thomas-Bergmann/Tournament | de.hatoka.tournament/src/main/java/de/hatoka/tournament/internal/business/HistoryEntryBOImpl.java | // Path: de.hatoka.tournament/src/main/java/de/hatoka/tournament/capi/entities/HistoryPO.java
// @Entity
// public class HistoryPO implements Serializable, IdentifiableEntity
// {
// private static final long serialVersionUID = 1L;
//
// @Id
// @XmlTransient
// private String id;
//
// @NotNull
// @XmlAttribute(name="player")
// private String player;
//
// @NotNull
// @ManyToOne
// @JoinColumn(name = "tournament", updatable = false)
// @XmlTransient
// private TournamentPO tournament;
//
// /**
// * The player is in play
// */
// @XmlAttribute
// private String actionKey;
//
// /**
// * The player is out and was placed at position
// */
// @NotNull
// @Temporal(TemporalType.TIMESTAMP)
// @XmlAttribute
// @XmlJavaTypeAdapter(DateXmlAdapter.class)
// private Date date;
//
// @Embedded
// @AttributeOverrides({ @AttributeOverride(name = "currencyCode", column = @Column(name = "amountCur")),
// @AttributeOverride(name = "amount", column = @Column(name = "amount")) })
// @XmlElement(name="amount")
// private MoneyPO amount;
//
// public HistoryPO()
// {
//
// }
//
// @Override
// public boolean equals(Object obj)
// {
// if (this == obj)
// return true;
// if (obj == null)
// return false;
// if (getClass() != obj.getClass())
// return false;
// HistoryPO other = (HistoryPO)obj;
// if (id == null)
// {
// if (other.id != null)
// return false;
// }
// else if (!id.equals(other.id))
// return false;
// return true;
// }
//
// @Override
// @XmlTransient
// public String getId()
// {
// return id;
// }
//
// @XmlTransient
// public MoneyPO getAmount()
// {
// return amount;
// }
//
// @XmlTransient
// public String getPlayer()
// {
// return player;
// }
//
// @XmlTransient
// public TournamentPO getTournamentPO()
// {
// return tournament;
// }
//
// @Override
// public int hashCode()
// {
// final int prime = 31;
// int result = 1;
// result = prime * result + ((id == null) ? 0 : id.hashCode());
// return result;
// }
//
// @Override
// public void setId(String id)
// {
// this.id = id;
// }
//
// public void setAmount(MoneyPO moneyAmount)
// {
// this.amount = moneyAmount;
// }
//
// public void setPlayer(String player)
// {
// this.player = player;
// }
//
// public void setTournamentPO(TournamentPO tournamentPO)
// {
// this.tournament = tournamentPO;
// }
//
// @XmlTransient
// public String getActionKey()
// {
// return actionKey;
// }
//
// public void setActionKey(String actionKey)
// {
// this.actionKey = actionKey;
// }
//
// @XmlTransient
// public Date getDate()
// {
// return date;
// }
//
// public void setDate(Date date)
// {
// this.date = date;
// }
// }
| import java.util.Date;
import de.hatoka.common.capi.business.Money;
import de.hatoka.tournament.capi.business.HistoryEntryBO;
import de.hatoka.tournament.capi.entities.HistoryPO;
import de.hatoka.tournament.capi.types.HistoryEntryType; | package de.hatoka.tournament.internal.business;
public class HistoryEntryBOImpl implements HistoryEntryBO
{ | // Path: de.hatoka.tournament/src/main/java/de/hatoka/tournament/capi/entities/HistoryPO.java
// @Entity
// public class HistoryPO implements Serializable, IdentifiableEntity
// {
// private static final long serialVersionUID = 1L;
//
// @Id
// @XmlTransient
// private String id;
//
// @NotNull
// @XmlAttribute(name="player")
// private String player;
//
// @NotNull
// @ManyToOne
// @JoinColumn(name = "tournament", updatable = false)
// @XmlTransient
// private TournamentPO tournament;
//
// /**
// * The player is in play
// */
// @XmlAttribute
// private String actionKey;
//
// /**
// * The player is out and was placed at position
// */
// @NotNull
// @Temporal(TemporalType.TIMESTAMP)
// @XmlAttribute
// @XmlJavaTypeAdapter(DateXmlAdapter.class)
// private Date date;
//
// @Embedded
// @AttributeOverrides({ @AttributeOverride(name = "currencyCode", column = @Column(name = "amountCur")),
// @AttributeOverride(name = "amount", column = @Column(name = "amount")) })
// @XmlElement(name="amount")
// private MoneyPO amount;
//
// public HistoryPO()
// {
//
// }
//
// @Override
// public boolean equals(Object obj)
// {
// if (this == obj)
// return true;
// if (obj == null)
// return false;
// if (getClass() != obj.getClass())
// return false;
// HistoryPO other = (HistoryPO)obj;
// if (id == null)
// {
// if (other.id != null)
// return false;
// }
// else if (!id.equals(other.id))
// return false;
// return true;
// }
//
// @Override
// @XmlTransient
// public String getId()
// {
// return id;
// }
//
// @XmlTransient
// public MoneyPO getAmount()
// {
// return amount;
// }
//
// @XmlTransient
// public String getPlayer()
// {
// return player;
// }
//
// @XmlTransient
// public TournamentPO getTournamentPO()
// {
// return tournament;
// }
//
// @Override
// public int hashCode()
// {
// final int prime = 31;
// int result = 1;
// result = prime * result + ((id == null) ? 0 : id.hashCode());
// return result;
// }
//
// @Override
// public void setId(String id)
// {
// this.id = id;
// }
//
// public void setAmount(MoneyPO moneyAmount)
// {
// this.amount = moneyAmount;
// }
//
// public void setPlayer(String player)
// {
// this.player = player;
// }
//
// public void setTournamentPO(TournamentPO tournamentPO)
// {
// this.tournament = tournamentPO;
// }
//
// @XmlTransient
// public String getActionKey()
// {
// return actionKey;
// }
//
// public void setActionKey(String actionKey)
// {
// this.actionKey = actionKey;
// }
//
// @XmlTransient
// public Date getDate()
// {
// return date;
// }
//
// public void setDate(Date date)
// {
// this.date = date;
// }
// }
// Path: de.hatoka.tournament/src/main/java/de/hatoka/tournament/internal/business/HistoryEntryBOImpl.java
import java.util.Date;
import de.hatoka.common.capi.business.Money;
import de.hatoka.tournament.capi.business.HistoryEntryBO;
import de.hatoka.tournament.capi.entities.HistoryPO;
import de.hatoka.tournament.capi.types.HistoryEntryType;
package de.hatoka.tournament.internal.business;
public class HistoryEntryBOImpl implements HistoryEntryBO
{ | private final HistoryPO historyPO; |
Thomas-Bergmann/Tournament | de.hatoka.tournament/src/main/java/de/hatoka/tournament/internal/app/models/BlindLevelVO.java | // Path: de.hatoka.tournament/src/main/java/de/hatoka/tournament/capi/business/BlindLevelBO.java
// public interface BlindLevelBO extends TournamentRoundBO
// {
// Integer getSmallBlind();
//
// Integer getBigBlind();
//
// Integer getAnte();
// }
| import java.util.Date;
import de.hatoka.tournament.capi.business.BlindLevelBO;
import de.hatoka.tournament.capi.business.TournamentRoundBO; | package de.hatoka.tournament.internal.app.models;
public class BlindLevelVO
{
private String id = null;
private int smallBlind = 0;
private int bigBlind = 0;
private int ante = 0;
private boolean isPause = false;
private boolean isRebuy = false;
private boolean isActive = false;
/**
* Duration in minutes
*/
private int duration;
private Date estStartDateTime;
private Date estEndDateTime;
public BlindLevelVO()
{
}
public BlindLevelVO(TournamentRoundBO round)
{ | // Path: de.hatoka.tournament/src/main/java/de/hatoka/tournament/capi/business/BlindLevelBO.java
// public interface BlindLevelBO extends TournamentRoundBO
// {
// Integer getSmallBlind();
//
// Integer getBigBlind();
//
// Integer getAnte();
// }
// Path: de.hatoka.tournament/src/main/java/de/hatoka/tournament/internal/app/models/BlindLevelVO.java
import java.util.Date;
import de.hatoka.tournament.capi.business.BlindLevelBO;
import de.hatoka.tournament.capi.business.TournamentRoundBO;
package de.hatoka.tournament.internal.app.models;
public class BlindLevelVO
{
private String id = null;
private int smallBlind = 0;
private int bigBlind = 0;
private int ante = 0;
private boolean isPause = false;
private boolean isRebuy = false;
private boolean isActive = false;
/**
* Duration in minutes
*/
private int duration;
private Date estStartDateTime;
private Date estEndDateTime;
public BlindLevelVO()
{
}
public BlindLevelVO(TournamentRoundBO round)
{ | BlindLevelBO blindLevelBO = round.getBlindLevel(); |
Thomas-Bergmann/Tournament | de.hatoka.common/src/main/java/de/hatoka/common/capi/app/xslt/Lib.java | // Path: de.hatoka.common/src/main/java/de/hatoka/common/capi/app/servlet/ResourceService.java
// @Path("/resources")
// public class ResourceService
// {
// private static final Logger LOGGER = LoggerFactory.getLogger(ResourceService.class);
//
// @GET
// @Path("/{filename: [-a-zA-Z_0-9\\.\\/]*}")
// public Response getResource(@Context ServletContext context, @Context Application application,
// @PathParam("filename") String filename)
// {
// try
// {
// String relative = "WEB-INF/resources/" + filename;
// String realPath = context.getRealPath("/" + relative);
// if (realPath == null)
// {
// // web application without context
// realPath = relative;
// }
// LOGGER.warn("Resource '{}' translated to '{}'.", filename, realPath);
// java.nio.file.Path path = Paths.get(realPath);
// if (!path.toFile().exists())
// {
// LOGGER.warn("Resource '{}' not found. Resource translated to '{}'.", filename, path);
// return Response.status(404).entity("404 - resource not found: " + filename).build();
// }
// return Response.status(200).type(Files.probeContentType(path)).entity(Files.readAllBytes(path)).build();
// }
// catch(IOException | NullPointerException e)
// {
// String errorID = getUUID(application);
// LOGGER.error("Error-Identifier: '" + errorID + "' - Load resource '"+filename+"' failed.", e);
// return Response.status(404).entity("Load resource failed: " + errorID).build();
// }
// }
//
// private static Injector getInjector(Application application)
// {
// return (Injector)application.getProperties().get(ServletConstants.PROPERTY_INJECTOR);
// }
//
// private static String getUUID(Application application)
// {
// return getInjector(application).getInstance(UUIDGenerator.class).generate();
// }
// }
| import javax.ws.rs.core.UriInfo;
import de.hatoka.common.capi.app.servlet.ResourceService; | return localizer.formatMoney(amountString, currencyCode);
}
public static String formatDate(Localizer localizer, String dateString)
{
return localizer.formatDate(dateString);
}
public static String formatDateTime(Localizer localizer, String dateString)
{
return localizer.formatDateTime(dateString);
}
public static String formatTime(Localizer localizer, String dateString)
{
return localizer.formatTime(dateString);
}
public static String formatDuration(Localizer localizer, String duration)
{
return localizer.formatDuration(duration);
}
public static String getResourceURI(String info, String resourceName)
{
return "../resources/" + resourceName;
}
public static String getResourceURI(UriInfo info, String resourceName)
{ | // Path: de.hatoka.common/src/main/java/de/hatoka/common/capi/app/servlet/ResourceService.java
// @Path("/resources")
// public class ResourceService
// {
// private static final Logger LOGGER = LoggerFactory.getLogger(ResourceService.class);
//
// @GET
// @Path("/{filename: [-a-zA-Z_0-9\\.\\/]*}")
// public Response getResource(@Context ServletContext context, @Context Application application,
// @PathParam("filename") String filename)
// {
// try
// {
// String relative = "WEB-INF/resources/" + filename;
// String realPath = context.getRealPath("/" + relative);
// if (realPath == null)
// {
// // web application without context
// realPath = relative;
// }
// LOGGER.warn("Resource '{}' translated to '{}'.", filename, realPath);
// java.nio.file.Path path = Paths.get(realPath);
// if (!path.toFile().exists())
// {
// LOGGER.warn("Resource '{}' not found. Resource translated to '{}'.", filename, path);
// return Response.status(404).entity("404 - resource not found: " + filename).build();
// }
// return Response.status(200).type(Files.probeContentType(path)).entity(Files.readAllBytes(path)).build();
// }
// catch(IOException | NullPointerException e)
// {
// String errorID = getUUID(application);
// LOGGER.error("Error-Identifier: '" + errorID + "' - Load resource '"+filename+"' failed.", e);
// return Response.status(404).entity("Load resource failed: " + errorID).build();
// }
// }
//
// private static Injector getInjector(Application application)
// {
// return (Injector)application.getProperties().get(ServletConstants.PROPERTY_INJECTOR);
// }
//
// private static String getUUID(Application application)
// {
// return getInjector(application).getInstance(UUIDGenerator.class).generate();
// }
// }
// Path: de.hatoka.common/src/main/java/de/hatoka/common/capi/app/xslt/Lib.java
import javax.ws.rs.core.UriInfo;
import de.hatoka.common.capi.app.servlet.ResourceService;
return localizer.formatMoney(amountString, currencyCode);
}
public static String formatDate(Localizer localizer, String dateString)
{
return localizer.formatDate(dateString);
}
public static String formatDateTime(Localizer localizer, String dateString)
{
return localizer.formatDateTime(dateString);
}
public static String formatTime(Localizer localizer, String dateString)
{
return localizer.formatTime(dateString);
}
public static String formatDuration(Localizer localizer, String duration)
{
return localizer.formatDuration(duration);
}
public static String getResourceURI(String info, String resourceName)
{
return "../resources/" + resourceName;
}
public static String getResourceURI(UriInfo info, String resourceName)
{ | return info.getBaseUriBuilder().path(ResourceService.class, "getResource").buildFromEncoded("resources/" + resourceName).toString(); |
Thomas-Bergmann/Tournament | de.hatoka.common/src/main/java/de/hatoka/common/capi/app/xslt/DurationXmlAdapter.java | // Path: de.hatoka.common/src/main/java/de/hatoka/common/capi/resource/LocalizationConstants.java
// public class LocalizationConstants
// {
// public static final String XML_DATEFORMAT_MILLIS = "yyyy-MM-dd'T'HH:mm:ss.SSSXXX";
// public static final String XML_DATEFORMAT_SECONDS = "yyyy-MM-dd'T'HH:mm:ssXXX";
// public static final String XML_DATEFORMAT_MINUTES = "yyyy-MM-dd'T'HH:mm";
// }
| import java.text.SimpleDateFormat;
import java.time.Duration;
import javax.xml.bind.annotation.adapters.XmlAdapter;
import de.hatoka.common.capi.business.CountryHelper;
import de.hatoka.common.capi.resource.LocalizationConstants; | package de.hatoka.common.capi.app.xslt;
public class DurationXmlAdapter extends XmlAdapter<String, Duration>
{
private final SimpleDateFormat dateFormat;
public DurationXmlAdapter()
{ | // Path: de.hatoka.common/src/main/java/de/hatoka/common/capi/resource/LocalizationConstants.java
// public class LocalizationConstants
// {
// public static final String XML_DATEFORMAT_MILLIS = "yyyy-MM-dd'T'HH:mm:ss.SSSXXX";
// public static final String XML_DATEFORMAT_SECONDS = "yyyy-MM-dd'T'HH:mm:ssXXX";
// public static final String XML_DATEFORMAT_MINUTES = "yyyy-MM-dd'T'HH:mm";
// }
// Path: de.hatoka.common/src/main/java/de/hatoka/common/capi/app/xslt/DurationXmlAdapter.java
import java.text.SimpleDateFormat;
import java.time.Duration;
import javax.xml.bind.annotation.adapters.XmlAdapter;
import de.hatoka.common.capi.business.CountryHelper;
import de.hatoka.common.capi.resource.LocalizationConstants;
package de.hatoka.common.capi.app.xslt;
public class DurationXmlAdapter extends XmlAdapter<String, Duration>
{
private final SimpleDateFormat dateFormat;
public DurationXmlAdapter()
{ | dateFormat = new SimpleDateFormat(LocalizationConstants.XML_DATEFORMAT_SECONDS); |
Thomas-Bergmann/Tournament | de.hatoka.group/src/main/java/de/hatoka/group/internal/dao/GroupDaoJpa.java | // Path: de.hatoka.common/src/main/java/de/hatoka/common/capi/dao/UUIDGenerator.java
// public interface UUIDGenerator
// {
// public String generate();
// }
//
// Path: de.hatoka.group/src/main/java/de/hatoka/group/capi/dao/MemberDao.java
// public interface MemberDao extends Dao<MemberPO>
// {
// /**
// * Add member to group
// * @param groupPO
// * @param userRef
// * @return
// */
// public MemberPO createAndInsert(GroupPO groupPO, String userRef, String name);
//
// /**
// * @param userRef
// * any userRef
// * @return list of members
// */
// List<MemberPO> getByUser(String userRef);
// }
//
// Path: de.hatoka.group/src/main/java/de/hatoka/group/capi/entities/GroupPO.java
// @Entity
// @NamedQueries(value = {
// @NamedQuery(name = "GroupPO.findByName", query = "select a from GroupPO a where a.name = :name"),
// @NamedQuery(name = "GroupPO.findByOwnerRef", query = "select a from GroupPO a where a.ownerRef = :ownerRef")
// })
// public class GroupPO implements Serializable, IdentifiableEntity
// {
// private static final long serialVersionUID = 1L;
//
// @Id
// @XmlTransient
// private String id;
//
// @NotNull
// private String name;
//
// @NotNull
// private String ownerRef;
//
// @OneToMany(mappedBy = "groupPO", cascade = CascadeType.ALL)
// @XmlElement(name = "member")
// private List<MemberPO> members = new ArrayList<>();
//
// public GroupPO()
// {
// }
//
// @Override
// public boolean equals(Object obj)
// {
// if (this == obj)
// return true;
// if (obj == null)
// return false;
// if (getClass() != obj.getClass())
// return false;
// GroupPO other = (GroupPO)obj;
// if (id == null)
// {
// if (other.id != null)
// return false;
// }
// else if (!id.equals(other.id))
// return false;
// return true;
// }
//
// @Override
// public String getId()
// {
// return id;
// }
//
// @Override
// public void setId(String id)
// {
// this.id = id;
// }
//
// public String getName()
// {
// return name;
// }
//
// public void setName(String name)
// {
// this.name = name;
// }
//
// public List<MemberPO> getMembers()
// {
// return members;
// }
//
// public void setMembers(List<MemberPO> members)
// {
// this.members = members;
// }
//
// public String getOwnerRef()
// {
// return ownerRef;
// }
//
// public void setOwnerRef(String ownerRef)
// {
// this.ownerRef = ownerRef;
// }
// }
| import java.util.ArrayList;
import java.util.List;
import javax.inject.Inject;
import de.hatoka.common.capi.dao.GenericJPADao;
import de.hatoka.common.capi.dao.UUIDGenerator;
import de.hatoka.group.capi.dao.GroupDao;
import de.hatoka.group.capi.dao.MemberDao;
import de.hatoka.group.capi.entities.GroupPO; | package de.hatoka.group.internal.dao;
public class GroupDaoJpa extends GenericJPADao<GroupPO> implements GroupDao
{
@Inject | // Path: de.hatoka.common/src/main/java/de/hatoka/common/capi/dao/UUIDGenerator.java
// public interface UUIDGenerator
// {
// public String generate();
// }
//
// Path: de.hatoka.group/src/main/java/de/hatoka/group/capi/dao/MemberDao.java
// public interface MemberDao extends Dao<MemberPO>
// {
// /**
// * Add member to group
// * @param groupPO
// * @param userRef
// * @return
// */
// public MemberPO createAndInsert(GroupPO groupPO, String userRef, String name);
//
// /**
// * @param userRef
// * any userRef
// * @return list of members
// */
// List<MemberPO> getByUser(String userRef);
// }
//
// Path: de.hatoka.group/src/main/java/de/hatoka/group/capi/entities/GroupPO.java
// @Entity
// @NamedQueries(value = {
// @NamedQuery(name = "GroupPO.findByName", query = "select a from GroupPO a where a.name = :name"),
// @NamedQuery(name = "GroupPO.findByOwnerRef", query = "select a from GroupPO a where a.ownerRef = :ownerRef")
// })
// public class GroupPO implements Serializable, IdentifiableEntity
// {
// private static final long serialVersionUID = 1L;
//
// @Id
// @XmlTransient
// private String id;
//
// @NotNull
// private String name;
//
// @NotNull
// private String ownerRef;
//
// @OneToMany(mappedBy = "groupPO", cascade = CascadeType.ALL)
// @XmlElement(name = "member")
// private List<MemberPO> members = new ArrayList<>();
//
// public GroupPO()
// {
// }
//
// @Override
// public boolean equals(Object obj)
// {
// if (this == obj)
// return true;
// if (obj == null)
// return false;
// if (getClass() != obj.getClass())
// return false;
// GroupPO other = (GroupPO)obj;
// if (id == null)
// {
// if (other.id != null)
// return false;
// }
// else if (!id.equals(other.id))
// return false;
// return true;
// }
//
// @Override
// public String getId()
// {
// return id;
// }
//
// @Override
// public void setId(String id)
// {
// this.id = id;
// }
//
// public String getName()
// {
// return name;
// }
//
// public void setName(String name)
// {
// this.name = name;
// }
//
// public List<MemberPO> getMembers()
// {
// return members;
// }
//
// public void setMembers(List<MemberPO> members)
// {
// this.members = members;
// }
//
// public String getOwnerRef()
// {
// return ownerRef;
// }
//
// public void setOwnerRef(String ownerRef)
// {
// this.ownerRef = ownerRef;
// }
// }
// Path: de.hatoka.group/src/main/java/de/hatoka/group/internal/dao/GroupDaoJpa.java
import java.util.ArrayList;
import java.util.List;
import javax.inject.Inject;
import de.hatoka.common.capi.dao.GenericJPADao;
import de.hatoka.common.capi.dao.UUIDGenerator;
import de.hatoka.group.capi.dao.GroupDao;
import de.hatoka.group.capi.dao.MemberDao;
import de.hatoka.group.capi.entities.GroupPO;
package de.hatoka.group.internal.dao;
public class GroupDaoJpa extends GenericJPADao<GroupPO> implements GroupDao
{
@Inject | private UUIDGenerator uuidGenerator; |
Thomas-Bergmann/Tournament | de.hatoka.group/src/main/java/de/hatoka/group/internal/dao/GroupDaoJpa.java | // Path: de.hatoka.common/src/main/java/de/hatoka/common/capi/dao/UUIDGenerator.java
// public interface UUIDGenerator
// {
// public String generate();
// }
//
// Path: de.hatoka.group/src/main/java/de/hatoka/group/capi/dao/MemberDao.java
// public interface MemberDao extends Dao<MemberPO>
// {
// /**
// * Add member to group
// * @param groupPO
// * @param userRef
// * @return
// */
// public MemberPO createAndInsert(GroupPO groupPO, String userRef, String name);
//
// /**
// * @param userRef
// * any userRef
// * @return list of members
// */
// List<MemberPO> getByUser(String userRef);
// }
//
// Path: de.hatoka.group/src/main/java/de/hatoka/group/capi/entities/GroupPO.java
// @Entity
// @NamedQueries(value = {
// @NamedQuery(name = "GroupPO.findByName", query = "select a from GroupPO a where a.name = :name"),
// @NamedQuery(name = "GroupPO.findByOwnerRef", query = "select a from GroupPO a where a.ownerRef = :ownerRef")
// })
// public class GroupPO implements Serializable, IdentifiableEntity
// {
// private static final long serialVersionUID = 1L;
//
// @Id
// @XmlTransient
// private String id;
//
// @NotNull
// private String name;
//
// @NotNull
// private String ownerRef;
//
// @OneToMany(mappedBy = "groupPO", cascade = CascadeType.ALL)
// @XmlElement(name = "member")
// private List<MemberPO> members = new ArrayList<>();
//
// public GroupPO()
// {
// }
//
// @Override
// public boolean equals(Object obj)
// {
// if (this == obj)
// return true;
// if (obj == null)
// return false;
// if (getClass() != obj.getClass())
// return false;
// GroupPO other = (GroupPO)obj;
// if (id == null)
// {
// if (other.id != null)
// return false;
// }
// else if (!id.equals(other.id))
// return false;
// return true;
// }
//
// @Override
// public String getId()
// {
// return id;
// }
//
// @Override
// public void setId(String id)
// {
// this.id = id;
// }
//
// public String getName()
// {
// return name;
// }
//
// public void setName(String name)
// {
// this.name = name;
// }
//
// public List<MemberPO> getMembers()
// {
// return members;
// }
//
// public void setMembers(List<MemberPO> members)
// {
// this.members = members;
// }
//
// public String getOwnerRef()
// {
// return ownerRef;
// }
//
// public void setOwnerRef(String ownerRef)
// {
// this.ownerRef = ownerRef;
// }
// }
| import java.util.ArrayList;
import java.util.List;
import javax.inject.Inject;
import de.hatoka.common.capi.dao.GenericJPADao;
import de.hatoka.common.capi.dao.UUIDGenerator;
import de.hatoka.group.capi.dao.GroupDao;
import de.hatoka.group.capi.dao.MemberDao;
import de.hatoka.group.capi.entities.GroupPO; | package de.hatoka.group.internal.dao;
public class GroupDaoJpa extends GenericJPADao<GroupPO> implements GroupDao
{
@Inject
private UUIDGenerator uuidGenerator;
@Inject | // Path: de.hatoka.common/src/main/java/de/hatoka/common/capi/dao/UUIDGenerator.java
// public interface UUIDGenerator
// {
// public String generate();
// }
//
// Path: de.hatoka.group/src/main/java/de/hatoka/group/capi/dao/MemberDao.java
// public interface MemberDao extends Dao<MemberPO>
// {
// /**
// * Add member to group
// * @param groupPO
// * @param userRef
// * @return
// */
// public MemberPO createAndInsert(GroupPO groupPO, String userRef, String name);
//
// /**
// * @param userRef
// * any userRef
// * @return list of members
// */
// List<MemberPO> getByUser(String userRef);
// }
//
// Path: de.hatoka.group/src/main/java/de/hatoka/group/capi/entities/GroupPO.java
// @Entity
// @NamedQueries(value = {
// @NamedQuery(name = "GroupPO.findByName", query = "select a from GroupPO a where a.name = :name"),
// @NamedQuery(name = "GroupPO.findByOwnerRef", query = "select a from GroupPO a where a.ownerRef = :ownerRef")
// })
// public class GroupPO implements Serializable, IdentifiableEntity
// {
// private static final long serialVersionUID = 1L;
//
// @Id
// @XmlTransient
// private String id;
//
// @NotNull
// private String name;
//
// @NotNull
// private String ownerRef;
//
// @OneToMany(mappedBy = "groupPO", cascade = CascadeType.ALL)
// @XmlElement(name = "member")
// private List<MemberPO> members = new ArrayList<>();
//
// public GroupPO()
// {
// }
//
// @Override
// public boolean equals(Object obj)
// {
// if (this == obj)
// return true;
// if (obj == null)
// return false;
// if (getClass() != obj.getClass())
// return false;
// GroupPO other = (GroupPO)obj;
// if (id == null)
// {
// if (other.id != null)
// return false;
// }
// else if (!id.equals(other.id))
// return false;
// return true;
// }
//
// @Override
// public String getId()
// {
// return id;
// }
//
// @Override
// public void setId(String id)
// {
// this.id = id;
// }
//
// public String getName()
// {
// return name;
// }
//
// public void setName(String name)
// {
// this.name = name;
// }
//
// public List<MemberPO> getMembers()
// {
// return members;
// }
//
// public void setMembers(List<MemberPO> members)
// {
// this.members = members;
// }
//
// public String getOwnerRef()
// {
// return ownerRef;
// }
//
// public void setOwnerRef(String ownerRef)
// {
// this.ownerRef = ownerRef;
// }
// }
// Path: de.hatoka.group/src/main/java/de/hatoka/group/internal/dao/GroupDaoJpa.java
import java.util.ArrayList;
import java.util.List;
import javax.inject.Inject;
import de.hatoka.common.capi.dao.GenericJPADao;
import de.hatoka.common.capi.dao.UUIDGenerator;
import de.hatoka.group.capi.dao.GroupDao;
import de.hatoka.group.capi.dao.MemberDao;
import de.hatoka.group.capi.entities.GroupPO;
package de.hatoka.group.internal.dao;
public class GroupDaoJpa extends GenericJPADao<GroupPO> implements GroupDao
{
@Inject
private UUIDGenerator uuidGenerator;
@Inject | private MemberDao memberDao; |
Thomas-Bergmann/Tournament | de.hatoka.group/src/main/java/de/hatoka/group/internal/app/member/GroupMemberAction.java | // Path: de.hatoka.group/src/main/java/de/hatoka/group/capi/business/GroupBO.java
// public interface GroupBO
// {
// /**
// * @return userRef of owner
// */
// String getOwner();
//
// /**
// * Removes the group
// */
// void remove();
//
// /**
// * @return name of group
// */
// String getName();
//
// /**
// * Create member for given user
// * @param userRef
// * @param name of member in side of the group
// * @return
// */
// MemberBO createMember(String userRef, String name);
//
// /**
// * @return members of the group (owner is one member)
// */
// Collection<MemberBO> getMembers();
//
// /**
// * @return identifier of group
// */
// String getID();
//
// /**
// * @param userRef
// * @return the member instance of the given user.
// */
// MemberBO getMember(String userRef);
//
// /**
// * @param userRef
// * @return true in case user is member of this group
// */
// boolean isMember(String userRef);
// }
//
// Path: de.hatoka.group/src/main/java/de/hatoka/group/capi/business/GroupBusinessFactory.java
// public interface GroupBusinessFactory
// {
// GroupBO findGroupBOByName(String name);
//
// GroupBO getGroupBO(GroupPO groupPO);
//
// GroupBORepository getGroupBORepository(String ownerRef);
//
// MemberBO getMemberBO(MemberPO memberPO);
//
// List<GroupBO> getGroupBOsByUser(String userRef);
//
// GroupBO getGroupBOByID(String groupID);
// }
| import java.util.List;
import java.util.stream.Collectors;
import javax.inject.Inject;
import de.hatoka.common.capi.app.servlet.RequestUserRefProvider;
import de.hatoka.group.capi.business.GroupBO;
import de.hatoka.group.capi.business.GroupBusinessFactory;
import de.hatoka.group.capi.business.MemberBO; | package de.hatoka.group.internal.app.member;
public class GroupMemberAction
{
@Inject | // Path: de.hatoka.group/src/main/java/de/hatoka/group/capi/business/GroupBO.java
// public interface GroupBO
// {
// /**
// * @return userRef of owner
// */
// String getOwner();
//
// /**
// * Removes the group
// */
// void remove();
//
// /**
// * @return name of group
// */
// String getName();
//
// /**
// * Create member for given user
// * @param userRef
// * @param name of member in side of the group
// * @return
// */
// MemberBO createMember(String userRef, String name);
//
// /**
// * @return members of the group (owner is one member)
// */
// Collection<MemberBO> getMembers();
//
// /**
// * @return identifier of group
// */
// String getID();
//
// /**
// * @param userRef
// * @return the member instance of the given user.
// */
// MemberBO getMember(String userRef);
//
// /**
// * @param userRef
// * @return true in case user is member of this group
// */
// boolean isMember(String userRef);
// }
//
// Path: de.hatoka.group/src/main/java/de/hatoka/group/capi/business/GroupBusinessFactory.java
// public interface GroupBusinessFactory
// {
// GroupBO findGroupBOByName(String name);
//
// GroupBO getGroupBO(GroupPO groupPO);
//
// GroupBORepository getGroupBORepository(String ownerRef);
//
// MemberBO getMemberBO(MemberPO memberPO);
//
// List<GroupBO> getGroupBOsByUser(String userRef);
//
// GroupBO getGroupBOByID(String groupID);
// }
// Path: de.hatoka.group/src/main/java/de/hatoka/group/internal/app/member/GroupMemberAction.java
import java.util.List;
import java.util.stream.Collectors;
import javax.inject.Inject;
import de.hatoka.common.capi.app.servlet.RequestUserRefProvider;
import de.hatoka.group.capi.business.GroupBO;
import de.hatoka.group.capi.business.GroupBusinessFactory;
import de.hatoka.group.capi.business.MemberBO;
package de.hatoka.group.internal.app.member;
public class GroupMemberAction
{
@Inject | private GroupBusinessFactory factory; |
Thomas-Bergmann/Tournament | de.hatoka.group/src/main/java/de/hatoka/group/internal/app/member/GroupMemberAction.java | // Path: de.hatoka.group/src/main/java/de/hatoka/group/capi/business/GroupBO.java
// public interface GroupBO
// {
// /**
// * @return userRef of owner
// */
// String getOwner();
//
// /**
// * Removes the group
// */
// void remove();
//
// /**
// * @return name of group
// */
// String getName();
//
// /**
// * Create member for given user
// * @param userRef
// * @param name of member in side of the group
// * @return
// */
// MemberBO createMember(String userRef, String name);
//
// /**
// * @return members of the group (owner is one member)
// */
// Collection<MemberBO> getMembers();
//
// /**
// * @return identifier of group
// */
// String getID();
//
// /**
// * @param userRef
// * @return the member instance of the given user.
// */
// MemberBO getMember(String userRef);
//
// /**
// * @param userRef
// * @return true in case user is member of this group
// */
// boolean isMember(String userRef);
// }
//
// Path: de.hatoka.group/src/main/java/de/hatoka/group/capi/business/GroupBusinessFactory.java
// public interface GroupBusinessFactory
// {
// GroupBO findGroupBOByName(String name);
//
// GroupBO getGroupBO(GroupPO groupPO);
//
// GroupBORepository getGroupBORepository(String ownerRef);
//
// MemberBO getMemberBO(MemberPO memberPO);
//
// List<GroupBO> getGroupBOsByUser(String userRef);
//
// GroupBO getGroupBOByID(String groupID);
// }
| import java.util.List;
import java.util.stream.Collectors;
import javax.inject.Inject;
import de.hatoka.common.capi.app.servlet.RequestUserRefProvider;
import de.hatoka.group.capi.business.GroupBO;
import de.hatoka.group.capi.business.GroupBusinessFactory;
import de.hatoka.group.capi.business.MemberBO; | package de.hatoka.group.internal.app.member;
public class GroupMemberAction
{
@Inject
private GroupBusinessFactory factory;
@Inject
private RequestUserRefProvider userRefProvider;
private final String groupID;
public GroupMemberAction(String groupID)
{
this.groupID = groupID;
}
public GroupMemberModel getGroupModel()
{
return new GroupMemberModel(groupID, getAccessableGroup().getName());
}
| // Path: de.hatoka.group/src/main/java/de/hatoka/group/capi/business/GroupBO.java
// public interface GroupBO
// {
// /**
// * @return userRef of owner
// */
// String getOwner();
//
// /**
// * Removes the group
// */
// void remove();
//
// /**
// * @return name of group
// */
// String getName();
//
// /**
// * Create member for given user
// * @param userRef
// * @param name of member in side of the group
// * @return
// */
// MemberBO createMember(String userRef, String name);
//
// /**
// * @return members of the group (owner is one member)
// */
// Collection<MemberBO> getMembers();
//
// /**
// * @return identifier of group
// */
// String getID();
//
// /**
// * @param userRef
// * @return the member instance of the given user.
// */
// MemberBO getMember(String userRef);
//
// /**
// * @param userRef
// * @return true in case user is member of this group
// */
// boolean isMember(String userRef);
// }
//
// Path: de.hatoka.group/src/main/java/de/hatoka/group/capi/business/GroupBusinessFactory.java
// public interface GroupBusinessFactory
// {
// GroupBO findGroupBOByName(String name);
//
// GroupBO getGroupBO(GroupPO groupPO);
//
// GroupBORepository getGroupBORepository(String ownerRef);
//
// MemberBO getMemberBO(MemberPO memberPO);
//
// List<GroupBO> getGroupBOsByUser(String userRef);
//
// GroupBO getGroupBOByID(String groupID);
// }
// Path: de.hatoka.group/src/main/java/de/hatoka/group/internal/app/member/GroupMemberAction.java
import java.util.List;
import java.util.stream.Collectors;
import javax.inject.Inject;
import de.hatoka.common.capi.app.servlet.RequestUserRefProvider;
import de.hatoka.group.capi.business.GroupBO;
import de.hatoka.group.capi.business.GroupBusinessFactory;
import de.hatoka.group.capi.business.MemberBO;
package de.hatoka.group.internal.app.member;
public class GroupMemberAction
{
@Inject
private GroupBusinessFactory factory;
@Inject
private RequestUserRefProvider userRefProvider;
private final String groupID;
public GroupMemberAction(String groupID)
{
this.groupID = groupID;
}
public GroupMemberModel getGroupModel()
{
return new GroupMemberModel(groupID, getAccessableGroup().getName());
}
| private GroupBO getAccessableGroup() |
Thomas-Bergmann/Tournament | de.hatoka.group/src/main/java/de/hatoka/group/capi/business/GroupBusinessFactory.java | // Path: de.hatoka.group/src/main/java/de/hatoka/group/capi/entities/GroupPO.java
// @Entity
// @NamedQueries(value = {
// @NamedQuery(name = "GroupPO.findByName", query = "select a from GroupPO a where a.name = :name"),
// @NamedQuery(name = "GroupPO.findByOwnerRef", query = "select a from GroupPO a where a.ownerRef = :ownerRef")
// })
// public class GroupPO implements Serializable, IdentifiableEntity
// {
// private static final long serialVersionUID = 1L;
//
// @Id
// @XmlTransient
// private String id;
//
// @NotNull
// private String name;
//
// @NotNull
// private String ownerRef;
//
// @OneToMany(mappedBy = "groupPO", cascade = CascadeType.ALL)
// @XmlElement(name = "member")
// private List<MemberPO> members = new ArrayList<>();
//
// public GroupPO()
// {
// }
//
// @Override
// public boolean equals(Object obj)
// {
// if (this == obj)
// return true;
// if (obj == null)
// return false;
// if (getClass() != obj.getClass())
// return false;
// GroupPO other = (GroupPO)obj;
// if (id == null)
// {
// if (other.id != null)
// return false;
// }
// else if (!id.equals(other.id))
// return false;
// return true;
// }
//
// @Override
// public String getId()
// {
// return id;
// }
//
// @Override
// public void setId(String id)
// {
// this.id = id;
// }
//
// public String getName()
// {
// return name;
// }
//
// public void setName(String name)
// {
// this.name = name;
// }
//
// public List<MemberPO> getMembers()
// {
// return members;
// }
//
// public void setMembers(List<MemberPO> members)
// {
// this.members = members;
// }
//
// public String getOwnerRef()
// {
// return ownerRef;
// }
//
// public void setOwnerRef(String ownerRef)
// {
// this.ownerRef = ownerRef;
// }
// }
//
// Path: de.hatoka.group/src/main/java/de/hatoka/group/capi/entities/MemberPO.java
// @Entity
// @NamedQueries(value = {
// @NamedQuery(name = "MemberPO.findByUserRef", query = "select a from MemberPO a where a.userRef = :userRef")
// })
// public class MemberPO implements Serializable, IdentifiableEntity
// {
// private static final long serialVersionUID = 1L;
//
// @Id
// @XmlTransient
// private String id;
//
// @NotNull
// @ManyToOne
// @JoinColumn(name = "groupPO", updatable = false)
// private GroupPO groupPO;
//
// /**
// * user reference of member
// */
// @NotNull
// @XmlAttribute
// private String userRef;
//
// /**
// * name of user inside of the group
// */
// @NotNull
// @XmlAttribute
// private String name;
//
// public MemberPO()
// {
//
// }
//
// @Override
// public boolean equals(Object obj)
// {
// if (this == obj)
// return true;
// if (obj == null)
// return false;
// if (getClass() != obj.getClass())
// return false;
// MemberPO other = (MemberPO)obj;
// if (id == null)
// {
// if (other.id != null)
// return false;
// }
// else if (!id.equals(other.id))
// return false;
// return true;
// }
//
// @Override
// @XmlTransient
// public String getId()
// {
// return id;
// }
//
// @XmlTransient
// public GroupPO getGroup()
// {
// return groupPO;
// }
//
// public void setGroup(GroupPO groupPO)
// {
// this.groupPO = groupPO;
// }
//
// @XmlTransient
// public String getUserRef()
// {
// return userRef;
// }
//
// public void setUserRef(String userRef)
// {
// this.userRef = userRef;
// }
//
// @Override
// public void setId(String id)
// {
// this.id = id;
// }
//
// @XmlTransient
// public String getName()
// {
// return name;
// }
//
// public void setName(String name)
// {
// this.name = name;
// }
// }
| import java.util.List;
import de.hatoka.group.capi.entities.GroupPO;
import de.hatoka.group.capi.entities.MemberPO; | package de.hatoka.group.capi.business;
public interface GroupBusinessFactory
{
GroupBO findGroupBOByName(String name);
| // Path: de.hatoka.group/src/main/java/de/hatoka/group/capi/entities/GroupPO.java
// @Entity
// @NamedQueries(value = {
// @NamedQuery(name = "GroupPO.findByName", query = "select a from GroupPO a where a.name = :name"),
// @NamedQuery(name = "GroupPO.findByOwnerRef", query = "select a from GroupPO a where a.ownerRef = :ownerRef")
// })
// public class GroupPO implements Serializable, IdentifiableEntity
// {
// private static final long serialVersionUID = 1L;
//
// @Id
// @XmlTransient
// private String id;
//
// @NotNull
// private String name;
//
// @NotNull
// private String ownerRef;
//
// @OneToMany(mappedBy = "groupPO", cascade = CascadeType.ALL)
// @XmlElement(name = "member")
// private List<MemberPO> members = new ArrayList<>();
//
// public GroupPO()
// {
// }
//
// @Override
// public boolean equals(Object obj)
// {
// if (this == obj)
// return true;
// if (obj == null)
// return false;
// if (getClass() != obj.getClass())
// return false;
// GroupPO other = (GroupPO)obj;
// if (id == null)
// {
// if (other.id != null)
// return false;
// }
// else if (!id.equals(other.id))
// return false;
// return true;
// }
//
// @Override
// public String getId()
// {
// return id;
// }
//
// @Override
// public void setId(String id)
// {
// this.id = id;
// }
//
// public String getName()
// {
// return name;
// }
//
// public void setName(String name)
// {
// this.name = name;
// }
//
// public List<MemberPO> getMembers()
// {
// return members;
// }
//
// public void setMembers(List<MemberPO> members)
// {
// this.members = members;
// }
//
// public String getOwnerRef()
// {
// return ownerRef;
// }
//
// public void setOwnerRef(String ownerRef)
// {
// this.ownerRef = ownerRef;
// }
// }
//
// Path: de.hatoka.group/src/main/java/de/hatoka/group/capi/entities/MemberPO.java
// @Entity
// @NamedQueries(value = {
// @NamedQuery(name = "MemberPO.findByUserRef", query = "select a from MemberPO a where a.userRef = :userRef")
// })
// public class MemberPO implements Serializable, IdentifiableEntity
// {
// private static final long serialVersionUID = 1L;
//
// @Id
// @XmlTransient
// private String id;
//
// @NotNull
// @ManyToOne
// @JoinColumn(name = "groupPO", updatable = false)
// private GroupPO groupPO;
//
// /**
// * user reference of member
// */
// @NotNull
// @XmlAttribute
// private String userRef;
//
// /**
// * name of user inside of the group
// */
// @NotNull
// @XmlAttribute
// private String name;
//
// public MemberPO()
// {
//
// }
//
// @Override
// public boolean equals(Object obj)
// {
// if (this == obj)
// return true;
// if (obj == null)
// return false;
// if (getClass() != obj.getClass())
// return false;
// MemberPO other = (MemberPO)obj;
// if (id == null)
// {
// if (other.id != null)
// return false;
// }
// else if (!id.equals(other.id))
// return false;
// return true;
// }
//
// @Override
// @XmlTransient
// public String getId()
// {
// return id;
// }
//
// @XmlTransient
// public GroupPO getGroup()
// {
// return groupPO;
// }
//
// public void setGroup(GroupPO groupPO)
// {
// this.groupPO = groupPO;
// }
//
// @XmlTransient
// public String getUserRef()
// {
// return userRef;
// }
//
// public void setUserRef(String userRef)
// {
// this.userRef = userRef;
// }
//
// @Override
// public void setId(String id)
// {
// this.id = id;
// }
//
// @XmlTransient
// public String getName()
// {
// return name;
// }
//
// public void setName(String name)
// {
// this.name = name;
// }
// }
// Path: de.hatoka.group/src/main/java/de/hatoka/group/capi/business/GroupBusinessFactory.java
import java.util.List;
import de.hatoka.group.capi.entities.GroupPO;
import de.hatoka.group.capi.entities.MemberPO;
package de.hatoka.group.capi.business;
public interface GroupBusinessFactory
{
GroupBO findGroupBOByName(String name);
| GroupBO getGroupBO(GroupPO groupPO); |
Thomas-Bergmann/Tournament | de.hatoka.group/src/main/java/de/hatoka/group/capi/business/GroupBusinessFactory.java | // Path: de.hatoka.group/src/main/java/de/hatoka/group/capi/entities/GroupPO.java
// @Entity
// @NamedQueries(value = {
// @NamedQuery(name = "GroupPO.findByName", query = "select a from GroupPO a where a.name = :name"),
// @NamedQuery(name = "GroupPO.findByOwnerRef", query = "select a from GroupPO a where a.ownerRef = :ownerRef")
// })
// public class GroupPO implements Serializable, IdentifiableEntity
// {
// private static final long serialVersionUID = 1L;
//
// @Id
// @XmlTransient
// private String id;
//
// @NotNull
// private String name;
//
// @NotNull
// private String ownerRef;
//
// @OneToMany(mappedBy = "groupPO", cascade = CascadeType.ALL)
// @XmlElement(name = "member")
// private List<MemberPO> members = new ArrayList<>();
//
// public GroupPO()
// {
// }
//
// @Override
// public boolean equals(Object obj)
// {
// if (this == obj)
// return true;
// if (obj == null)
// return false;
// if (getClass() != obj.getClass())
// return false;
// GroupPO other = (GroupPO)obj;
// if (id == null)
// {
// if (other.id != null)
// return false;
// }
// else if (!id.equals(other.id))
// return false;
// return true;
// }
//
// @Override
// public String getId()
// {
// return id;
// }
//
// @Override
// public void setId(String id)
// {
// this.id = id;
// }
//
// public String getName()
// {
// return name;
// }
//
// public void setName(String name)
// {
// this.name = name;
// }
//
// public List<MemberPO> getMembers()
// {
// return members;
// }
//
// public void setMembers(List<MemberPO> members)
// {
// this.members = members;
// }
//
// public String getOwnerRef()
// {
// return ownerRef;
// }
//
// public void setOwnerRef(String ownerRef)
// {
// this.ownerRef = ownerRef;
// }
// }
//
// Path: de.hatoka.group/src/main/java/de/hatoka/group/capi/entities/MemberPO.java
// @Entity
// @NamedQueries(value = {
// @NamedQuery(name = "MemberPO.findByUserRef", query = "select a from MemberPO a where a.userRef = :userRef")
// })
// public class MemberPO implements Serializable, IdentifiableEntity
// {
// private static final long serialVersionUID = 1L;
//
// @Id
// @XmlTransient
// private String id;
//
// @NotNull
// @ManyToOne
// @JoinColumn(name = "groupPO", updatable = false)
// private GroupPO groupPO;
//
// /**
// * user reference of member
// */
// @NotNull
// @XmlAttribute
// private String userRef;
//
// /**
// * name of user inside of the group
// */
// @NotNull
// @XmlAttribute
// private String name;
//
// public MemberPO()
// {
//
// }
//
// @Override
// public boolean equals(Object obj)
// {
// if (this == obj)
// return true;
// if (obj == null)
// return false;
// if (getClass() != obj.getClass())
// return false;
// MemberPO other = (MemberPO)obj;
// if (id == null)
// {
// if (other.id != null)
// return false;
// }
// else if (!id.equals(other.id))
// return false;
// return true;
// }
//
// @Override
// @XmlTransient
// public String getId()
// {
// return id;
// }
//
// @XmlTransient
// public GroupPO getGroup()
// {
// return groupPO;
// }
//
// public void setGroup(GroupPO groupPO)
// {
// this.groupPO = groupPO;
// }
//
// @XmlTransient
// public String getUserRef()
// {
// return userRef;
// }
//
// public void setUserRef(String userRef)
// {
// this.userRef = userRef;
// }
//
// @Override
// public void setId(String id)
// {
// this.id = id;
// }
//
// @XmlTransient
// public String getName()
// {
// return name;
// }
//
// public void setName(String name)
// {
// this.name = name;
// }
// }
| import java.util.List;
import de.hatoka.group.capi.entities.GroupPO;
import de.hatoka.group.capi.entities.MemberPO; | package de.hatoka.group.capi.business;
public interface GroupBusinessFactory
{
GroupBO findGroupBOByName(String name);
GroupBO getGroupBO(GroupPO groupPO);
GroupBORepository getGroupBORepository(String ownerRef);
| // Path: de.hatoka.group/src/main/java/de/hatoka/group/capi/entities/GroupPO.java
// @Entity
// @NamedQueries(value = {
// @NamedQuery(name = "GroupPO.findByName", query = "select a from GroupPO a where a.name = :name"),
// @NamedQuery(name = "GroupPO.findByOwnerRef", query = "select a from GroupPO a where a.ownerRef = :ownerRef")
// })
// public class GroupPO implements Serializable, IdentifiableEntity
// {
// private static final long serialVersionUID = 1L;
//
// @Id
// @XmlTransient
// private String id;
//
// @NotNull
// private String name;
//
// @NotNull
// private String ownerRef;
//
// @OneToMany(mappedBy = "groupPO", cascade = CascadeType.ALL)
// @XmlElement(name = "member")
// private List<MemberPO> members = new ArrayList<>();
//
// public GroupPO()
// {
// }
//
// @Override
// public boolean equals(Object obj)
// {
// if (this == obj)
// return true;
// if (obj == null)
// return false;
// if (getClass() != obj.getClass())
// return false;
// GroupPO other = (GroupPO)obj;
// if (id == null)
// {
// if (other.id != null)
// return false;
// }
// else if (!id.equals(other.id))
// return false;
// return true;
// }
//
// @Override
// public String getId()
// {
// return id;
// }
//
// @Override
// public void setId(String id)
// {
// this.id = id;
// }
//
// public String getName()
// {
// return name;
// }
//
// public void setName(String name)
// {
// this.name = name;
// }
//
// public List<MemberPO> getMembers()
// {
// return members;
// }
//
// public void setMembers(List<MemberPO> members)
// {
// this.members = members;
// }
//
// public String getOwnerRef()
// {
// return ownerRef;
// }
//
// public void setOwnerRef(String ownerRef)
// {
// this.ownerRef = ownerRef;
// }
// }
//
// Path: de.hatoka.group/src/main/java/de/hatoka/group/capi/entities/MemberPO.java
// @Entity
// @NamedQueries(value = {
// @NamedQuery(name = "MemberPO.findByUserRef", query = "select a from MemberPO a where a.userRef = :userRef")
// })
// public class MemberPO implements Serializable, IdentifiableEntity
// {
// private static final long serialVersionUID = 1L;
//
// @Id
// @XmlTransient
// private String id;
//
// @NotNull
// @ManyToOne
// @JoinColumn(name = "groupPO", updatable = false)
// private GroupPO groupPO;
//
// /**
// * user reference of member
// */
// @NotNull
// @XmlAttribute
// private String userRef;
//
// /**
// * name of user inside of the group
// */
// @NotNull
// @XmlAttribute
// private String name;
//
// public MemberPO()
// {
//
// }
//
// @Override
// public boolean equals(Object obj)
// {
// if (this == obj)
// return true;
// if (obj == null)
// return false;
// if (getClass() != obj.getClass())
// return false;
// MemberPO other = (MemberPO)obj;
// if (id == null)
// {
// if (other.id != null)
// return false;
// }
// else if (!id.equals(other.id))
// return false;
// return true;
// }
//
// @Override
// @XmlTransient
// public String getId()
// {
// return id;
// }
//
// @XmlTransient
// public GroupPO getGroup()
// {
// return groupPO;
// }
//
// public void setGroup(GroupPO groupPO)
// {
// this.groupPO = groupPO;
// }
//
// @XmlTransient
// public String getUserRef()
// {
// return userRef;
// }
//
// public void setUserRef(String userRef)
// {
// this.userRef = userRef;
// }
//
// @Override
// public void setId(String id)
// {
// this.id = id;
// }
//
// @XmlTransient
// public String getName()
// {
// return name;
// }
//
// public void setName(String name)
// {
// this.name = name;
// }
// }
// Path: de.hatoka.group/src/main/java/de/hatoka/group/capi/business/GroupBusinessFactory.java
import java.util.List;
import de.hatoka.group.capi.entities.GroupPO;
import de.hatoka.group.capi.entities.MemberPO;
package de.hatoka.group.capi.business;
public interface GroupBusinessFactory
{
GroupBO findGroupBOByName(String name);
GroupBO getGroupBO(GroupPO groupPO);
GroupBORepository getGroupBORepository(String ownerRef);
| MemberBO getMemberBO(MemberPO memberPO); |
Thomas-Bergmann/Tournament | de.hatoka.tournament/src/main/java/de/hatoka/tournament/internal/app/models/HistoryEntryVO.java | // Path: de.hatoka.tournament/src/main/java/de/hatoka/tournament/capi/entities/HistoryPO.java
// @Entity
// public class HistoryPO implements Serializable, IdentifiableEntity
// {
// private static final long serialVersionUID = 1L;
//
// @Id
// @XmlTransient
// private String id;
//
// @NotNull
// @XmlAttribute(name="player")
// private String player;
//
// @NotNull
// @ManyToOne
// @JoinColumn(name = "tournament", updatable = false)
// @XmlTransient
// private TournamentPO tournament;
//
// /**
// * The player is in play
// */
// @XmlAttribute
// private String actionKey;
//
// /**
// * The player is out and was placed at position
// */
// @NotNull
// @Temporal(TemporalType.TIMESTAMP)
// @XmlAttribute
// @XmlJavaTypeAdapter(DateXmlAdapter.class)
// private Date date;
//
// @Embedded
// @AttributeOverrides({ @AttributeOverride(name = "currencyCode", column = @Column(name = "amountCur")),
// @AttributeOverride(name = "amount", column = @Column(name = "amount")) })
// @XmlElement(name="amount")
// private MoneyPO amount;
//
// public HistoryPO()
// {
//
// }
//
// @Override
// public boolean equals(Object obj)
// {
// if (this == obj)
// return true;
// if (obj == null)
// return false;
// if (getClass() != obj.getClass())
// return false;
// HistoryPO other = (HistoryPO)obj;
// if (id == null)
// {
// if (other.id != null)
// return false;
// }
// else if (!id.equals(other.id))
// return false;
// return true;
// }
//
// @Override
// @XmlTransient
// public String getId()
// {
// return id;
// }
//
// @XmlTransient
// public MoneyPO getAmount()
// {
// return amount;
// }
//
// @XmlTransient
// public String getPlayer()
// {
// return player;
// }
//
// @XmlTransient
// public TournamentPO getTournamentPO()
// {
// return tournament;
// }
//
// @Override
// public int hashCode()
// {
// final int prime = 31;
// int result = 1;
// result = prime * result + ((id == null) ? 0 : id.hashCode());
// return result;
// }
//
// @Override
// public void setId(String id)
// {
// this.id = id;
// }
//
// public void setAmount(MoneyPO moneyAmount)
// {
// this.amount = moneyAmount;
// }
//
// public void setPlayer(String player)
// {
// this.player = player;
// }
//
// public void setTournamentPO(TournamentPO tournamentPO)
// {
// this.tournament = tournamentPO;
// }
//
// @XmlTransient
// public String getActionKey()
// {
// return actionKey;
// }
//
// public void setActionKey(String actionKey)
// {
// this.actionKey = actionKey;
// }
//
// @XmlTransient
// public Date getDate()
// {
// return date;
// }
//
// public void setDate(Date date)
// {
// this.date = date;
// }
// }
| import java.util.Date;
import javax.xml.bind.annotation.XmlAttribute;
import de.hatoka.common.capi.app.model.MoneyVO;
import de.hatoka.common.capi.business.Money;
import de.hatoka.tournament.capi.business.HistoryEntryBO;
import de.hatoka.tournament.capi.entities.HistoryPO;
import de.hatoka.tournament.capi.types.HistoryEntryType; | package de.hatoka.tournament.internal.app.models;
public class HistoryEntryVO
{
private String playerName;
private HistoryEntryType entryType;
private Date date;
private MoneyVO amount;
public HistoryEntryVO()
{
}
| // Path: de.hatoka.tournament/src/main/java/de/hatoka/tournament/capi/entities/HistoryPO.java
// @Entity
// public class HistoryPO implements Serializable, IdentifiableEntity
// {
// private static final long serialVersionUID = 1L;
//
// @Id
// @XmlTransient
// private String id;
//
// @NotNull
// @XmlAttribute(name="player")
// private String player;
//
// @NotNull
// @ManyToOne
// @JoinColumn(name = "tournament", updatable = false)
// @XmlTransient
// private TournamentPO tournament;
//
// /**
// * The player is in play
// */
// @XmlAttribute
// private String actionKey;
//
// /**
// * The player is out and was placed at position
// */
// @NotNull
// @Temporal(TemporalType.TIMESTAMP)
// @XmlAttribute
// @XmlJavaTypeAdapter(DateXmlAdapter.class)
// private Date date;
//
// @Embedded
// @AttributeOverrides({ @AttributeOverride(name = "currencyCode", column = @Column(name = "amountCur")),
// @AttributeOverride(name = "amount", column = @Column(name = "amount")) })
// @XmlElement(name="amount")
// private MoneyPO amount;
//
// public HistoryPO()
// {
//
// }
//
// @Override
// public boolean equals(Object obj)
// {
// if (this == obj)
// return true;
// if (obj == null)
// return false;
// if (getClass() != obj.getClass())
// return false;
// HistoryPO other = (HistoryPO)obj;
// if (id == null)
// {
// if (other.id != null)
// return false;
// }
// else if (!id.equals(other.id))
// return false;
// return true;
// }
//
// @Override
// @XmlTransient
// public String getId()
// {
// return id;
// }
//
// @XmlTransient
// public MoneyPO getAmount()
// {
// return amount;
// }
//
// @XmlTransient
// public String getPlayer()
// {
// return player;
// }
//
// @XmlTransient
// public TournamentPO getTournamentPO()
// {
// return tournament;
// }
//
// @Override
// public int hashCode()
// {
// final int prime = 31;
// int result = 1;
// result = prime * result + ((id == null) ? 0 : id.hashCode());
// return result;
// }
//
// @Override
// public void setId(String id)
// {
// this.id = id;
// }
//
// public void setAmount(MoneyPO moneyAmount)
// {
// this.amount = moneyAmount;
// }
//
// public void setPlayer(String player)
// {
// this.player = player;
// }
//
// public void setTournamentPO(TournamentPO tournamentPO)
// {
// this.tournament = tournamentPO;
// }
//
// @XmlTransient
// public String getActionKey()
// {
// return actionKey;
// }
//
// public void setActionKey(String actionKey)
// {
// this.actionKey = actionKey;
// }
//
// @XmlTransient
// public Date getDate()
// {
// return date;
// }
//
// public void setDate(Date date)
// {
// this.date = date;
// }
// }
// Path: de.hatoka.tournament/src/main/java/de/hatoka/tournament/internal/app/models/HistoryEntryVO.java
import java.util.Date;
import javax.xml.bind.annotation.XmlAttribute;
import de.hatoka.common.capi.app.model.MoneyVO;
import de.hatoka.common.capi.business.Money;
import de.hatoka.tournament.capi.business.HistoryEntryBO;
import de.hatoka.tournament.capi.entities.HistoryPO;
import de.hatoka.tournament.capi.types.HistoryEntryType;
package de.hatoka.tournament.internal.app.models;
public class HistoryEntryVO
{
private String playerName;
private HistoryEntryType entryType;
private Date date;
private MoneyVO amount;
public HistoryEntryVO()
{
}
| public HistoryEntryVO(HistoryPO historyPO) |
Thomas-Bergmann/Tournament | de.hatoka.tournament/src/main/java/de/hatoka/tournament/capi/entities/PlayerPO.java | // Path: de.hatoka.common/src/main/java/de/hatoka/common/capi/dao/IdentifiableEntity.java
// public interface IdentifiableEntity
// {
// String getId();
//
// void setId(String id);
// }
| import java.io.Serializable;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;
import javax.validation.constraints.NotNull;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlID;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlTransient;
import de.hatoka.common.capi.dao.IdentifiableEntity; | package de.hatoka.tournament.capi.entities;
@Entity
@NamedQueries(value = {
@NamedQuery(name = "PlayerPO.findByAccountRef", query = "select a from PlayerPO a where a.accountRef = :accountRef"),
@NamedQuery(name = "PlayerPO.findByName", query = "select a from PlayerPO a where a.accountRef = :accountRef and a.name = :name"),
@NamedQuery(name = "PlayerPO.findByExternalRef", query = "select a from PlayerPO a where a.accountRef = :accountRef and a.externalRef = :externalRef")
})
@XmlRootElement(name="player") | // Path: de.hatoka.common/src/main/java/de/hatoka/common/capi/dao/IdentifiableEntity.java
// public interface IdentifiableEntity
// {
// String getId();
//
// void setId(String id);
// }
// Path: de.hatoka.tournament/src/main/java/de/hatoka/tournament/capi/entities/PlayerPO.java
import java.io.Serializable;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;
import javax.validation.constraints.NotNull;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlID;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlTransient;
import de.hatoka.common.capi.dao.IdentifiableEntity;
package de.hatoka.tournament.capi.entities;
@Entity
@NamedQueries(value = {
@NamedQuery(name = "PlayerPO.findByAccountRef", query = "select a from PlayerPO a where a.accountRef = :accountRef"),
@NamedQuery(name = "PlayerPO.findByName", query = "select a from PlayerPO a where a.accountRef = :accountRef and a.name = :name"),
@NamedQuery(name = "PlayerPO.findByExternalRef", query = "select a from PlayerPO a where a.accountRef = :accountRef and a.externalRef = :externalRef")
})
@XmlRootElement(name="player") | public class PlayerPO implements Serializable, IdentifiableEntity |
Thomas-Bergmann/Tournament | de.hatoka.group/src/main/java/de/hatoka/group/internal/business/GroupBORepositoryImpl.java | // Path: de.hatoka.group/src/main/java/de/hatoka/group/capi/business/GroupBO.java
// public interface GroupBO
// {
// /**
// * @return userRef of owner
// */
// String getOwner();
//
// /**
// * Removes the group
// */
// void remove();
//
// /**
// * @return name of group
// */
// String getName();
//
// /**
// * Create member for given user
// * @param userRef
// * @param name of member in side of the group
// * @return
// */
// MemberBO createMember(String userRef, String name);
//
// /**
// * @return members of the group (owner is one member)
// */
// Collection<MemberBO> getMembers();
//
// /**
// * @return identifier of group
// */
// String getID();
//
// /**
// * @param userRef
// * @return the member instance of the given user.
// */
// MemberBO getMember(String userRef);
//
// /**
// * @param userRef
// * @return true in case user is member of this group
// */
// boolean isMember(String userRef);
// }
//
// Path: de.hatoka.group/src/main/java/de/hatoka/group/capi/business/GroupBORepository.java
// public interface GroupBORepository
// {
// /**
// * Creates a new group
// * @param name of group
// * @param ownerName member name of owner for this group
// * @return created group
// */
// GroupBO createGroup(String name, String ownerName);
//
// /**
// * @return list of owned groups
// */
// List<GroupBO> getGroups();
//
// /**
// * Removes all groups of this repository
// */
// void clear();
// }
//
// Path: de.hatoka.group/src/main/java/de/hatoka/group/capi/business/GroupBusinessFactory.java
// public interface GroupBusinessFactory
// {
// GroupBO findGroupBOByName(String name);
//
// GroupBO getGroupBO(GroupPO groupPO);
//
// GroupBORepository getGroupBORepository(String ownerRef);
//
// MemberBO getMemberBO(MemberPO memberPO);
//
// List<GroupBO> getGroupBOsByUser(String userRef);
//
// GroupBO getGroupBOByID(String groupID);
// }
//
// Path: de.hatoka.group/src/main/java/de/hatoka/group/capi/dao/MemberDao.java
// public interface MemberDao extends Dao<MemberPO>
// {
// /**
// * Add member to group
// * @param groupPO
// * @param userRef
// * @return
// */
// public MemberPO createAndInsert(GroupPO groupPO, String userRef, String name);
//
// /**
// * @param userRef
// * any userRef
// * @return list of members
// */
// List<MemberPO> getByUser(String userRef);
// }
//
// Path: de.hatoka.group/src/main/java/de/hatoka/group/capi/entities/GroupPO.java
// @Entity
// @NamedQueries(value = {
// @NamedQuery(name = "GroupPO.findByName", query = "select a from GroupPO a where a.name = :name"),
// @NamedQuery(name = "GroupPO.findByOwnerRef", query = "select a from GroupPO a where a.ownerRef = :ownerRef")
// })
// public class GroupPO implements Serializable, IdentifiableEntity
// {
// private static final long serialVersionUID = 1L;
//
// @Id
// @XmlTransient
// private String id;
//
// @NotNull
// private String name;
//
// @NotNull
// private String ownerRef;
//
// @OneToMany(mappedBy = "groupPO", cascade = CascadeType.ALL)
// @XmlElement(name = "member")
// private List<MemberPO> members = new ArrayList<>();
//
// public GroupPO()
// {
// }
//
// @Override
// public boolean equals(Object obj)
// {
// if (this == obj)
// return true;
// if (obj == null)
// return false;
// if (getClass() != obj.getClass())
// return false;
// GroupPO other = (GroupPO)obj;
// if (id == null)
// {
// if (other.id != null)
// return false;
// }
// else if (!id.equals(other.id))
// return false;
// return true;
// }
//
// @Override
// public String getId()
// {
// return id;
// }
//
// @Override
// public void setId(String id)
// {
// this.id = id;
// }
//
// public String getName()
// {
// return name;
// }
//
// public void setName(String name)
// {
// this.name = name;
// }
//
// public List<MemberPO> getMembers()
// {
// return members;
// }
//
// public void setMembers(List<MemberPO> members)
// {
// this.members = members;
// }
//
// public String getOwnerRef()
// {
// return ownerRef;
// }
//
// public void setOwnerRef(String ownerRef)
// {
// this.ownerRef = ownerRef;
// }
// }
| import java.util.List;
import java.util.stream.Collectors;
import de.hatoka.group.capi.business.GroupBO;
import de.hatoka.group.capi.business.GroupBORepository;
import de.hatoka.group.capi.business.GroupBusinessFactory;
import de.hatoka.group.capi.dao.GroupDao;
import de.hatoka.group.capi.dao.MemberDao;
import de.hatoka.group.capi.entities.GroupPO; | package de.hatoka.group.internal.business;
public class GroupBORepositoryImpl implements GroupBORepository
{
private final String ownerRef;
| // Path: de.hatoka.group/src/main/java/de/hatoka/group/capi/business/GroupBO.java
// public interface GroupBO
// {
// /**
// * @return userRef of owner
// */
// String getOwner();
//
// /**
// * Removes the group
// */
// void remove();
//
// /**
// * @return name of group
// */
// String getName();
//
// /**
// * Create member for given user
// * @param userRef
// * @param name of member in side of the group
// * @return
// */
// MemberBO createMember(String userRef, String name);
//
// /**
// * @return members of the group (owner is one member)
// */
// Collection<MemberBO> getMembers();
//
// /**
// * @return identifier of group
// */
// String getID();
//
// /**
// * @param userRef
// * @return the member instance of the given user.
// */
// MemberBO getMember(String userRef);
//
// /**
// * @param userRef
// * @return true in case user is member of this group
// */
// boolean isMember(String userRef);
// }
//
// Path: de.hatoka.group/src/main/java/de/hatoka/group/capi/business/GroupBORepository.java
// public interface GroupBORepository
// {
// /**
// * Creates a new group
// * @param name of group
// * @param ownerName member name of owner for this group
// * @return created group
// */
// GroupBO createGroup(String name, String ownerName);
//
// /**
// * @return list of owned groups
// */
// List<GroupBO> getGroups();
//
// /**
// * Removes all groups of this repository
// */
// void clear();
// }
//
// Path: de.hatoka.group/src/main/java/de/hatoka/group/capi/business/GroupBusinessFactory.java
// public interface GroupBusinessFactory
// {
// GroupBO findGroupBOByName(String name);
//
// GroupBO getGroupBO(GroupPO groupPO);
//
// GroupBORepository getGroupBORepository(String ownerRef);
//
// MemberBO getMemberBO(MemberPO memberPO);
//
// List<GroupBO> getGroupBOsByUser(String userRef);
//
// GroupBO getGroupBOByID(String groupID);
// }
//
// Path: de.hatoka.group/src/main/java/de/hatoka/group/capi/dao/MemberDao.java
// public interface MemberDao extends Dao<MemberPO>
// {
// /**
// * Add member to group
// * @param groupPO
// * @param userRef
// * @return
// */
// public MemberPO createAndInsert(GroupPO groupPO, String userRef, String name);
//
// /**
// * @param userRef
// * any userRef
// * @return list of members
// */
// List<MemberPO> getByUser(String userRef);
// }
//
// Path: de.hatoka.group/src/main/java/de/hatoka/group/capi/entities/GroupPO.java
// @Entity
// @NamedQueries(value = {
// @NamedQuery(name = "GroupPO.findByName", query = "select a from GroupPO a where a.name = :name"),
// @NamedQuery(name = "GroupPO.findByOwnerRef", query = "select a from GroupPO a where a.ownerRef = :ownerRef")
// })
// public class GroupPO implements Serializable, IdentifiableEntity
// {
// private static final long serialVersionUID = 1L;
//
// @Id
// @XmlTransient
// private String id;
//
// @NotNull
// private String name;
//
// @NotNull
// private String ownerRef;
//
// @OneToMany(mappedBy = "groupPO", cascade = CascadeType.ALL)
// @XmlElement(name = "member")
// private List<MemberPO> members = new ArrayList<>();
//
// public GroupPO()
// {
// }
//
// @Override
// public boolean equals(Object obj)
// {
// if (this == obj)
// return true;
// if (obj == null)
// return false;
// if (getClass() != obj.getClass())
// return false;
// GroupPO other = (GroupPO)obj;
// if (id == null)
// {
// if (other.id != null)
// return false;
// }
// else if (!id.equals(other.id))
// return false;
// return true;
// }
//
// @Override
// public String getId()
// {
// return id;
// }
//
// @Override
// public void setId(String id)
// {
// this.id = id;
// }
//
// public String getName()
// {
// return name;
// }
//
// public void setName(String name)
// {
// this.name = name;
// }
//
// public List<MemberPO> getMembers()
// {
// return members;
// }
//
// public void setMembers(List<MemberPO> members)
// {
// this.members = members;
// }
//
// public String getOwnerRef()
// {
// return ownerRef;
// }
//
// public void setOwnerRef(String ownerRef)
// {
// this.ownerRef = ownerRef;
// }
// }
// Path: de.hatoka.group/src/main/java/de/hatoka/group/internal/business/GroupBORepositoryImpl.java
import java.util.List;
import java.util.stream.Collectors;
import de.hatoka.group.capi.business.GroupBO;
import de.hatoka.group.capi.business.GroupBORepository;
import de.hatoka.group.capi.business.GroupBusinessFactory;
import de.hatoka.group.capi.dao.GroupDao;
import de.hatoka.group.capi.dao.MemberDao;
import de.hatoka.group.capi.entities.GroupPO;
package de.hatoka.group.internal.business;
public class GroupBORepositoryImpl implements GroupBORepository
{
private final String ownerRef;
| private final GroupBusinessFactory factory; |
Thomas-Bergmann/Tournament | de.hatoka.group/src/main/java/de/hatoka/group/internal/business/GroupBORepositoryImpl.java | // Path: de.hatoka.group/src/main/java/de/hatoka/group/capi/business/GroupBO.java
// public interface GroupBO
// {
// /**
// * @return userRef of owner
// */
// String getOwner();
//
// /**
// * Removes the group
// */
// void remove();
//
// /**
// * @return name of group
// */
// String getName();
//
// /**
// * Create member for given user
// * @param userRef
// * @param name of member in side of the group
// * @return
// */
// MemberBO createMember(String userRef, String name);
//
// /**
// * @return members of the group (owner is one member)
// */
// Collection<MemberBO> getMembers();
//
// /**
// * @return identifier of group
// */
// String getID();
//
// /**
// * @param userRef
// * @return the member instance of the given user.
// */
// MemberBO getMember(String userRef);
//
// /**
// * @param userRef
// * @return true in case user is member of this group
// */
// boolean isMember(String userRef);
// }
//
// Path: de.hatoka.group/src/main/java/de/hatoka/group/capi/business/GroupBORepository.java
// public interface GroupBORepository
// {
// /**
// * Creates a new group
// * @param name of group
// * @param ownerName member name of owner for this group
// * @return created group
// */
// GroupBO createGroup(String name, String ownerName);
//
// /**
// * @return list of owned groups
// */
// List<GroupBO> getGroups();
//
// /**
// * Removes all groups of this repository
// */
// void clear();
// }
//
// Path: de.hatoka.group/src/main/java/de/hatoka/group/capi/business/GroupBusinessFactory.java
// public interface GroupBusinessFactory
// {
// GroupBO findGroupBOByName(String name);
//
// GroupBO getGroupBO(GroupPO groupPO);
//
// GroupBORepository getGroupBORepository(String ownerRef);
//
// MemberBO getMemberBO(MemberPO memberPO);
//
// List<GroupBO> getGroupBOsByUser(String userRef);
//
// GroupBO getGroupBOByID(String groupID);
// }
//
// Path: de.hatoka.group/src/main/java/de/hatoka/group/capi/dao/MemberDao.java
// public interface MemberDao extends Dao<MemberPO>
// {
// /**
// * Add member to group
// * @param groupPO
// * @param userRef
// * @return
// */
// public MemberPO createAndInsert(GroupPO groupPO, String userRef, String name);
//
// /**
// * @param userRef
// * any userRef
// * @return list of members
// */
// List<MemberPO> getByUser(String userRef);
// }
//
// Path: de.hatoka.group/src/main/java/de/hatoka/group/capi/entities/GroupPO.java
// @Entity
// @NamedQueries(value = {
// @NamedQuery(name = "GroupPO.findByName", query = "select a from GroupPO a where a.name = :name"),
// @NamedQuery(name = "GroupPO.findByOwnerRef", query = "select a from GroupPO a where a.ownerRef = :ownerRef")
// })
// public class GroupPO implements Serializable, IdentifiableEntity
// {
// private static final long serialVersionUID = 1L;
//
// @Id
// @XmlTransient
// private String id;
//
// @NotNull
// private String name;
//
// @NotNull
// private String ownerRef;
//
// @OneToMany(mappedBy = "groupPO", cascade = CascadeType.ALL)
// @XmlElement(name = "member")
// private List<MemberPO> members = new ArrayList<>();
//
// public GroupPO()
// {
// }
//
// @Override
// public boolean equals(Object obj)
// {
// if (this == obj)
// return true;
// if (obj == null)
// return false;
// if (getClass() != obj.getClass())
// return false;
// GroupPO other = (GroupPO)obj;
// if (id == null)
// {
// if (other.id != null)
// return false;
// }
// else if (!id.equals(other.id))
// return false;
// return true;
// }
//
// @Override
// public String getId()
// {
// return id;
// }
//
// @Override
// public void setId(String id)
// {
// this.id = id;
// }
//
// public String getName()
// {
// return name;
// }
//
// public void setName(String name)
// {
// this.name = name;
// }
//
// public List<MemberPO> getMembers()
// {
// return members;
// }
//
// public void setMembers(List<MemberPO> members)
// {
// this.members = members;
// }
//
// public String getOwnerRef()
// {
// return ownerRef;
// }
//
// public void setOwnerRef(String ownerRef)
// {
// this.ownerRef = ownerRef;
// }
// }
| import java.util.List;
import java.util.stream.Collectors;
import de.hatoka.group.capi.business.GroupBO;
import de.hatoka.group.capi.business.GroupBORepository;
import de.hatoka.group.capi.business.GroupBusinessFactory;
import de.hatoka.group.capi.dao.GroupDao;
import de.hatoka.group.capi.dao.MemberDao;
import de.hatoka.group.capi.entities.GroupPO; | package de.hatoka.group.internal.business;
public class GroupBORepositoryImpl implements GroupBORepository
{
private final String ownerRef;
private final GroupBusinessFactory factory;
private final GroupDao groupDao;
| // Path: de.hatoka.group/src/main/java/de/hatoka/group/capi/business/GroupBO.java
// public interface GroupBO
// {
// /**
// * @return userRef of owner
// */
// String getOwner();
//
// /**
// * Removes the group
// */
// void remove();
//
// /**
// * @return name of group
// */
// String getName();
//
// /**
// * Create member for given user
// * @param userRef
// * @param name of member in side of the group
// * @return
// */
// MemberBO createMember(String userRef, String name);
//
// /**
// * @return members of the group (owner is one member)
// */
// Collection<MemberBO> getMembers();
//
// /**
// * @return identifier of group
// */
// String getID();
//
// /**
// * @param userRef
// * @return the member instance of the given user.
// */
// MemberBO getMember(String userRef);
//
// /**
// * @param userRef
// * @return true in case user is member of this group
// */
// boolean isMember(String userRef);
// }
//
// Path: de.hatoka.group/src/main/java/de/hatoka/group/capi/business/GroupBORepository.java
// public interface GroupBORepository
// {
// /**
// * Creates a new group
// * @param name of group
// * @param ownerName member name of owner for this group
// * @return created group
// */
// GroupBO createGroup(String name, String ownerName);
//
// /**
// * @return list of owned groups
// */
// List<GroupBO> getGroups();
//
// /**
// * Removes all groups of this repository
// */
// void clear();
// }
//
// Path: de.hatoka.group/src/main/java/de/hatoka/group/capi/business/GroupBusinessFactory.java
// public interface GroupBusinessFactory
// {
// GroupBO findGroupBOByName(String name);
//
// GroupBO getGroupBO(GroupPO groupPO);
//
// GroupBORepository getGroupBORepository(String ownerRef);
//
// MemberBO getMemberBO(MemberPO memberPO);
//
// List<GroupBO> getGroupBOsByUser(String userRef);
//
// GroupBO getGroupBOByID(String groupID);
// }
//
// Path: de.hatoka.group/src/main/java/de/hatoka/group/capi/dao/MemberDao.java
// public interface MemberDao extends Dao<MemberPO>
// {
// /**
// * Add member to group
// * @param groupPO
// * @param userRef
// * @return
// */
// public MemberPO createAndInsert(GroupPO groupPO, String userRef, String name);
//
// /**
// * @param userRef
// * any userRef
// * @return list of members
// */
// List<MemberPO> getByUser(String userRef);
// }
//
// Path: de.hatoka.group/src/main/java/de/hatoka/group/capi/entities/GroupPO.java
// @Entity
// @NamedQueries(value = {
// @NamedQuery(name = "GroupPO.findByName", query = "select a from GroupPO a where a.name = :name"),
// @NamedQuery(name = "GroupPO.findByOwnerRef", query = "select a from GroupPO a where a.ownerRef = :ownerRef")
// })
// public class GroupPO implements Serializable, IdentifiableEntity
// {
// private static final long serialVersionUID = 1L;
//
// @Id
// @XmlTransient
// private String id;
//
// @NotNull
// private String name;
//
// @NotNull
// private String ownerRef;
//
// @OneToMany(mappedBy = "groupPO", cascade = CascadeType.ALL)
// @XmlElement(name = "member")
// private List<MemberPO> members = new ArrayList<>();
//
// public GroupPO()
// {
// }
//
// @Override
// public boolean equals(Object obj)
// {
// if (this == obj)
// return true;
// if (obj == null)
// return false;
// if (getClass() != obj.getClass())
// return false;
// GroupPO other = (GroupPO)obj;
// if (id == null)
// {
// if (other.id != null)
// return false;
// }
// else if (!id.equals(other.id))
// return false;
// return true;
// }
//
// @Override
// public String getId()
// {
// return id;
// }
//
// @Override
// public void setId(String id)
// {
// this.id = id;
// }
//
// public String getName()
// {
// return name;
// }
//
// public void setName(String name)
// {
// this.name = name;
// }
//
// public List<MemberPO> getMembers()
// {
// return members;
// }
//
// public void setMembers(List<MemberPO> members)
// {
// this.members = members;
// }
//
// public String getOwnerRef()
// {
// return ownerRef;
// }
//
// public void setOwnerRef(String ownerRef)
// {
// this.ownerRef = ownerRef;
// }
// }
// Path: de.hatoka.group/src/main/java/de/hatoka/group/internal/business/GroupBORepositoryImpl.java
import java.util.List;
import java.util.stream.Collectors;
import de.hatoka.group.capi.business.GroupBO;
import de.hatoka.group.capi.business.GroupBORepository;
import de.hatoka.group.capi.business.GroupBusinessFactory;
import de.hatoka.group.capi.dao.GroupDao;
import de.hatoka.group.capi.dao.MemberDao;
import de.hatoka.group.capi.entities.GroupPO;
package de.hatoka.group.internal.business;
public class GroupBORepositoryImpl implements GroupBORepository
{
private final String ownerRef;
private final GroupBusinessFactory factory;
private final GroupDao groupDao;
| public GroupBORepositoryImpl(String ownerRef, GroupDao groupDao, MemberDao memberDao, GroupBusinessFactory factory) |
Thomas-Bergmann/Tournament | de.hatoka.group/src/main/java/de/hatoka/group/internal/business/GroupBORepositoryImpl.java | // Path: de.hatoka.group/src/main/java/de/hatoka/group/capi/business/GroupBO.java
// public interface GroupBO
// {
// /**
// * @return userRef of owner
// */
// String getOwner();
//
// /**
// * Removes the group
// */
// void remove();
//
// /**
// * @return name of group
// */
// String getName();
//
// /**
// * Create member for given user
// * @param userRef
// * @param name of member in side of the group
// * @return
// */
// MemberBO createMember(String userRef, String name);
//
// /**
// * @return members of the group (owner is one member)
// */
// Collection<MemberBO> getMembers();
//
// /**
// * @return identifier of group
// */
// String getID();
//
// /**
// * @param userRef
// * @return the member instance of the given user.
// */
// MemberBO getMember(String userRef);
//
// /**
// * @param userRef
// * @return true in case user is member of this group
// */
// boolean isMember(String userRef);
// }
//
// Path: de.hatoka.group/src/main/java/de/hatoka/group/capi/business/GroupBORepository.java
// public interface GroupBORepository
// {
// /**
// * Creates a new group
// * @param name of group
// * @param ownerName member name of owner for this group
// * @return created group
// */
// GroupBO createGroup(String name, String ownerName);
//
// /**
// * @return list of owned groups
// */
// List<GroupBO> getGroups();
//
// /**
// * Removes all groups of this repository
// */
// void clear();
// }
//
// Path: de.hatoka.group/src/main/java/de/hatoka/group/capi/business/GroupBusinessFactory.java
// public interface GroupBusinessFactory
// {
// GroupBO findGroupBOByName(String name);
//
// GroupBO getGroupBO(GroupPO groupPO);
//
// GroupBORepository getGroupBORepository(String ownerRef);
//
// MemberBO getMemberBO(MemberPO memberPO);
//
// List<GroupBO> getGroupBOsByUser(String userRef);
//
// GroupBO getGroupBOByID(String groupID);
// }
//
// Path: de.hatoka.group/src/main/java/de/hatoka/group/capi/dao/MemberDao.java
// public interface MemberDao extends Dao<MemberPO>
// {
// /**
// * Add member to group
// * @param groupPO
// * @param userRef
// * @return
// */
// public MemberPO createAndInsert(GroupPO groupPO, String userRef, String name);
//
// /**
// * @param userRef
// * any userRef
// * @return list of members
// */
// List<MemberPO> getByUser(String userRef);
// }
//
// Path: de.hatoka.group/src/main/java/de/hatoka/group/capi/entities/GroupPO.java
// @Entity
// @NamedQueries(value = {
// @NamedQuery(name = "GroupPO.findByName", query = "select a from GroupPO a where a.name = :name"),
// @NamedQuery(name = "GroupPO.findByOwnerRef", query = "select a from GroupPO a where a.ownerRef = :ownerRef")
// })
// public class GroupPO implements Serializable, IdentifiableEntity
// {
// private static final long serialVersionUID = 1L;
//
// @Id
// @XmlTransient
// private String id;
//
// @NotNull
// private String name;
//
// @NotNull
// private String ownerRef;
//
// @OneToMany(mappedBy = "groupPO", cascade = CascadeType.ALL)
// @XmlElement(name = "member")
// private List<MemberPO> members = new ArrayList<>();
//
// public GroupPO()
// {
// }
//
// @Override
// public boolean equals(Object obj)
// {
// if (this == obj)
// return true;
// if (obj == null)
// return false;
// if (getClass() != obj.getClass())
// return false;
// GroupPO other = (GroupPO)obj;
// if (id == null)
// {
// if (other.id != null)
// return false;
// }
// else if (!id.equals(other.id))
// return false;
// return true;
// }
//
// @Override
// public String getId()
// {
// return id;
// }
//
// @Override
// public void setId(String id)
// {
// this.id = id;
// }
//
// public String getName()
// {
// return name;
// }
//
// public void setName(String name)
// {
// this.name = name;
// }
//
// public List<MemberPO> getMembers()
// {
// return members;
// }
//
// public void setMembers(List<MemberPO> members)
// {
// this.members = members;
// }
//
// public String getOwnerRef()
// {
// return ownerRef;
// }
//
// public void setOwnerRef(String ownerRef)
// {
// this.ownerRef = ownerRef;
// }
// }
| import java.util.List;
import java.util.stream.Collectors;
import de.hatoka.group.capi.business.GroupBO;
import de.hatoka.group.capi.business.GroupBORepository;
import de.hatoka.group.capi.business.GroupBusinessFactory;
import de.hatoka.group.capi.dao.GroupDao;
import de.hatoka.group.capi.dao.MemberDao;
import de.hatoka.group.capi.entities.GroupPO; | package de.hatoka.group.internal.business;
public class GroupBORepositoryImpl implements GroupBORepository
{
private final String ownerRef;
private final GroupBusinessFactory factory;
private final GroupDao groupDao;
public GroupBORepositoryImpl(String ownerRef, GroupDao groupDao, MemberDao memberDao, GroupBusinessFactory factory)
{
this.ownerRef = ownerRef;
this.factory = factory;
this.groupDao = groupDao;
}
@Override | // Path: de.hatoka.group/src/main/java/de/hatoka/group/capi/business/GroupBO.java
// public interface GroupBO
// {
// /**
// * @return userRef of owner
// */
// String getOwner();
//
// /**
// * Removes the group
// */
// void remove();
//
// /**
// * @return name of group
// */
// String getName();
//
// /**
// * Create member for given user
// * @param userRef
// * @param name of member in side of the group
// * @return
// */
// MemberBO createMember(String userRef, String name);
//
// /**
// * @return members of the group (owner is one member)
// */
// Collection<MemberBO> getMembers();
//
// /**
// * @return identifier of group
// */
// String getID();
//
// /**
// * @param userRef
// * @return the member instance of the given user.
// */
// MemberBO getMember(String userRef);
//
// /**
// * @param userRef
// * @return true in case user is member of this group
// */
// boolean isMember(String userRef);
// }
//
// Path: de.hatoka.group/src/main/java/de/hatoka/group/capi/business/GroupBORepository.java
// public interface GroupBORepository
// {
// /**
// * Creates a new group
// * @param name of group
// * @param ownerName member name of owner for this group
// * @return created group
// */
// GroupBO createGroup(String name, String ownerName);
//
// /**
// * @return list of owned groups
// */
// List<GroupBO> getGroups();
//
// /**
// * Removes all groups of this repository
// */
// void clear();
// }
//
// Path: de.hatoka.group/src/main/java/de/hatoka/group/capi/business/GroupBusinessFactory.java
// public interface GroupBusinessFactory
// {
// GroupBO findGroupBOByName(String name);
//
// GroupBO getGroupBO(GroupPO groupPO);
//
// GroupBORepository getGroupBORepository(String ownerRef);
//
// MemberBO getMemberBO(MemberPO memberPO);
//
// List<GroupBO> getGroupBOsByUser(String userRef);
//
// GroupBO getGroupBOByID(String groupID);
// }
//
// Path: de.hatoka.group/src/main/java/de/hatoka/group/capi/dao/MemberDao.java
// public interface MemberDao extends Dao<MemberPO>
// {
// /**
// * Add member to group
// * @param groupPO
// * @param userRef
// * @return
// */
// public MemberPO createAndInsert(GroupPO groupPO, String userRef, String name);
//
// /**
// * @param userRef
// * any userRef
// * @return list of members
// */
// List<MemberPO> getByUser(String userRef);
// }
//
// Path: de.hatoka.group/src/main/java/de/hatoka/group/capi/entities/GroupPO.java
// @Entity
// @NamedQueries(value = {
// @NamedQuery(name = "GroupPO.findByName", query = "select a from GroupPO a where a.name = :name"),
// @NamedQuery(name = "GroupPO.findByOwnerRef", query = "select a from GroupPO a where a.ownerRef = :ownerRef")
// })
// public class GroupPO implements Serializable, IdentifiableEntity
// {
// private static final long serialVersionUID = 1L;
//
// @Id
// @XmlTransient
// private String id;
//
// @NotNull
// private String name;
//
// @NotNull
// private String ownerRef;
//
// @OneToMany(mappedBy = "groupPO", cascade = CascadeType.ALL)
// @XmlElement(name = "member")
// private List<MemberPO> members = new ArrayList<>();
//
// public GroupPO()
// {
// }
//
// @Override
// public boolean equals(Object obj)
// {
// if (this == obj)
// return true;
// if (obj == null)
// return false;
// if (getClass() != obj.getClass())
// return false;
// GroupPO other = (GroupPO)obj;
// if (id == null)
// {
// if (other.id != null)
// return false;
// }
// else if (!id.equals(other.id))
// return false;
// return true;
// }
//
// @Override
// public String getId()
// {
// return id;
// }
//
// @Override
// public void setId(String id)
// {
// this.id = id;
// }
//
// public String getName()
// {
// return name;
// }
//
// public void setName(String name)
// {
// this.name = name;
// }
//
// public List<MemberPO> getMembers()
// {
// return members;
// }
//
// public void setMembers(List<MemberPO> members)
// {
// this.members = members;
// }
//
// public String getOwnerRef()
// {
// return ownerRef;
// }
//
// public void setOwnerRef(String ownerRef)
// {
// this.ownerRef = ownerRef;
// }
// }
// Path: de.hatoka.group/src/main/java/de/hatoka/group/internal/business/GroupBORepositoryImpl.java
import java.util.List;
import java.util.stream.Collectors;
import de.hatoka.group.capi.business.GroupBO;
import de.hatoka.group.capi.business.GroupBORepository;
import de.hatoka.group.capi.business.GroupBusinessFactory;
import de.hatoka.group.capi.dao.GroupDao;
import de.hatoka.group.capi.dao.MemberDao;
import de.hatoka.group.capi.entities.GroupPO;
package de.hatoka.group.internal.business;
public class GroupBORepositoryImpl implements GroupBORepository
{
private final String ownerRef;
private final GroupBusinessFactory factory;
private final GroupDao groupDao;
public GroupBORepositoryImpl(String ownerRef, GroupDao groupDao, MemberDao memberDao, GroupBusinessFactory factory)
{
this.ownerRef = ownerRef;
this.factory = factory;
this.groupDao = groupDao;
}
@Override | public GroupBO createGroup(String name, String ownerName) |
Thomas-Bergmann/Tournament | de.hatoka.group/src/main/java/de/hatoka/group/internal/business/GroupBORepositoryImpl.java | // Path: de.hatoka.group/src/main/java/de/hatoka/group/capi/business/GroupBO.java
// public interface GroupBO
// {
// /**
// * @return userRef of owner
// */
// String getOwner();
//
// /**
// * Removes the group
// */
// void remove();
//
// /**
// * @return name of group
// */
// String getName();
//
// /**
// * Create member for given user
// * @param userRef
// * @param name of member in side of the group
// * @return
// */
// MemberBO createMember(String userRef, String name);
//
// /**
// * @return members of the group (owner is one member)
// */
// Collection<MemberBO> getMembers();
//
// /**
// * @return identifier of group
// */
// String getID();
//
// /**
// * @param userRef
// * @return the member instance of the given user.
// */
// MemberBO getMember(String userRef);
//
// /**
// * @param userRef
// * @return true in case user is member of this group
// */
// boolean isMember(String userRef);
// }
//
// Path: de.hatoka.group/src/main/java/de/hatoka/group/capi/business/GroupBORepository.java
// public interface GroupBORepository
// {
// /**
// * Creates a new group
// * @param name of group
// * @param ownerName member name of owner for this group
// * @return created group
// */
// GroupBO createGroup(String name, String ownerName);
//
// /**
// * @return list of owned groups
// */
// List<GroupBO> getGroups();
//
// /**
// * Removes all groups of this repository
// */
// void clear();
// }
//
// Path: de.hatoka.group/src/main/java/de/hatoka/group/capi/business/GroupBusinessFactory.java
// public interface GroupBusinessFactory
// {
// GroupBO findGroupBOByName(String name);
//
// GroupBO getGroupBO(GroupPO groupPO);
//
// GroupBORepository getGroupBORepository(String ownerRef);
//
// MemberBO getMemberBO(MemberPO memberPO);
//
// List<GroupBO> getGroupBOsByUser(String userRef);
//
// GroupBO getGroupBOByID(String groupID);
// }
//
// Path: de.hatoka.group/src/main/java/de/hatoka/group/capi/dao/MemberDao.java
// public interface MemberDao extends Dao<MemberPO>
// {
// /**
// * Add member to group
// * @param groupPO
// * @param userRef
// * @return
// */
// public MemberPO createAndInsert(GroupPO groupPO, String userRef, String name);
//
// /**
// * @param userRef
// * any userRef
// * @return list of members
// */
// List<MemberPO> getByUser(String userRef);
// }
//
// Path: de.hatoka.group/src/main/java/de/hatoka/group/capi/entities/GroupPO.java
// @Entity
// @NamedQueries(value = {
// @NamedQuery(name = "GroupPO.findByName", query = "select a from GroupPO a where a.name = :name"),
// @NamedQuery(name = "GroupPO.findByOwnerRef", query = "select a from GroupPO a where a.ownerRef = :ownerRef")
// })
// public class GroupPO implements Serializable, IdentifiableEntity
// {
// private static final long serialVersionUID = 1L;
//
// @Id
// @XmlTransient
// private String id;
//
// @NotNull
// private String name;
//
// @NotNull
// private String ownerRef;
//
// @OneToMany(mappedBy = "groupPO", cascade = CascadeType.ALL)
// @XmlElement(name = "member")
// private List<MemberPO> members = new ArrayList<>();
//
// public GroupPO()
// {
// }
//
// @Override
// public boolean equals(Object obj)
// {
// if (this == obj)
// return true;
// if (obj == null)
// return false;
// if (getClass() != obj.getClass())
// return false;
// GroupPO other = (GroupPO)obj;
// if (id == null)
// {
// if (other.id != null)
// return false;
// }
// else if (!id.equals(other.id))
// return false;
// return true;
// }
//
// @Override
// public String getId()
// {
// return id;
// }
//
// @Override
// public void setId(String id)
// {
// this.id = id;
// }
//
// public String getName()
// {
// return name;
// }
//
// public void setName(String name)
// {
// this.name = name;
// }
//
// public List<MemberPO> getMembers()
// {
// return members;
// }
//
// public void setMembers(List<MemberPO> members)
// {
// this.members = members;
// }
//
// public String getOwnerRef()
// {
// return ownerRef;
// }
//
// public void setOwnerRef(String ownerRef)
// {
// this.ownerRef = ownerRef;
// }
// }
| import java.util.List;
import java.util.stream.Collectors;
import de.hatoka.group.capi.business.GroupBO;
import de.hatoka.group.capi.business.GroupBORepository;
import de.hatoka.group.capi.business.GroupBusinessFactory;
import de.hatoka.group.capi.dao.GroupDao;
import de.hatoka.group.capi.dao.MemberDao;
import de.hatoka.group.capi.entities.GroupPO; | package de.hatoka.group.internal.business;
public class GroupBORepositoryImpl implements GroupBORepository
{
private final String ownerRef;
private final GroupBusinessFactory factory;
private final GroupDao groupDao;
public GroupBORepositoryImpl(String ownerRef, GroupDao groupDao, MemberDao memberDao, GroupBusinessFactory factory)
{
this.ownerRef = ownerRef;
this.factory = factory;
this.groupDao = groupDao;
}
@Override
public GroupBO createGroup(String name, String ownerName)
{ | // Path: de.hatoka.group/src/main/java/de/hatoka/group/capi/business/GroupBO.java
// public interface GroupBO
// {
// /**
// * @return userRef of owner
// */
// String getOwner();
//
// /**
// * Removes the group
// */
// void remove();
//
// /**
// * @return name of group
// */
// String getName();
//
// /**
// * Create member for given user
// * @param userRef
// * @param name of member in side of the group
// * @return
// */
// MemberBO createMember(String userRef, String name);
//
// /**
// * @return members of the group (owner is one member)
// */
// Collection<MemberBO> getMembers();
//
// /**
// * @return identifier of group
// */
// String getID();
//
// /**
// * @param userRef
// * @return the member instance of the given user.
// */
// MemberBO getMember(String userRef);
//
// /**
// * @param userRef
// * @return true in case user is member of this group
// */
// boolean isMember(String userRef);
// }
//
// Path: de.hatoka.group/src/main/java/de/hatoka/group/capi/business/GroupBORepository.java
// public interface GroupBORepository
// {
// /**
// * Creates a new group
// * @param name of group
// * @param ownerName member name of owner for this group
// * @return created group
// */
// GroupBO createGroup(String name, String ownerName);
//
// /**
// * @return list of owned groups
// */
// List<GroupBO> getGroups();
//
// /**
// * Removes all groups of this repository
// */
// void clear();
// }
//
// Path: de.hatoka.group/src/main/java/de/hatoka/group/capi/business/GroupBusinessFactory.java
// public interface GroupBusinessFactory
// {
// GroupBO findGroupBOByName(String name);
//
// GroupBO getGroupBO(GroupPO groupPO);
//
// GroupBORepository getGroupBORepository(String ownerRef);
//
// MemberBO getMemberBO(MemberPO memberPO);
//
// List<GroupBO> getGroupBOsByUser(String userRef);
//
// GroupBO getGroupBOByID(String groupID);
// }
//
// Path: de.hatoka.group/src/main/java/de/hatoka/group/capi/dao/MemberDao.java
// public interface MemberDao extends Dao<MemberPO>
// {
// /**
// * Add member to group
// * @param groupPO
// * @param userRef
// * @return
// */
// public MemberPO createAndInsert(GroupPO groupPO, String userRef, String name);
//
// /**
// * @param userRef
// * any userRef
// * @return list of members
// */
// List<MemberPO> getByUser(String userRef);
// }
//
// Path: de.hatoka.group/src/main/java/de/hatoka/group/capi/entities/GroupPO.java
// @Entity
// @NamedQueries(value = {
// @NamedQuery(name = "GroupPO.findByName", query = "select a from GroupPO a where a.name = :name"),
// @NamedQuery(name = "GroupPO.findByOwnerRef", query = "select a from GroupPO a where a.ownerRef = :ownerRef")
// })
// public class GroupPO implements Serializable, IdentifiableEntity
// {
// private static final long serialVersionUID = 1L;
//
// @Id
// @XmlTransient
// private String id;
//
// @NotNull
// private String name;
//
// @NotNull
// private String ownerRef;
//
// @OneToMany(mappedBy = "groupPO", cascade = CascadeType.ALL)
// @XmlElement(name = "member")
// private List<MemberPO> members = new ArrayList<>();
//
// public GroupPO()
// {
// }
//
// @Override
// public boolean equals(Object obj)
// {
// if (this == obj)
// return true;
// if (obj == null)
// return false;
// if (getClass() != obj.getClass())
// return false;
// GroupPO other = (GroupPO)obj;
// if (id == null)
// {
// if (other.id != null)
// return false;
// }
// else if (!id.equals(other.id))
// return false;
// return true;
// }
//
// @Override
// public String getId()
// {
// return id;
// }
//
// @Override
// public void setId(String id)
// {
// this.id = id;
// }
//
// public String getName()
// {
// return name;
// }
//
// public void setName(String name)
// {
// this.name = name;
// }
//
// public List<MemberPO> getMembers()
// {
// return members;
// }
//
// public void setMembers(List<MemberPO> members)
// {
// this.members = members;
// }
//
// public String getOwnerRef()
// {
// return ownerRef;
// }
//
// public void setOwnerRef(String ownerRef)
// {
// this.ownerRef = ownerRef;
// }
// }
// Path: de.hatoka.group/src/main/java/de/hatoka/group/internal/business/GroupBORepositoryImpl.java
import java.util.List;
import java.util.stream.Collectors;
import de.hatoka.group.capi.business.GroupBO;
import de.hatoka.group.capi.business.GroupBORepository;
import de.hatoka.group.capi.business.GroupBusinessFactory;
import de.hatoka.group.capi.dao.GroupDao;
import de.hatoka.group.capi.dao.MemberDao;
import de.hatoka.group.capi.entities.GroupPO;
package de.hatoka.group.internal.business;
public class GroupBORepositoryImpl implements GroupBORepository
{
private final String ownerRef;
private final GroupBusinessFactory factory;
private final GroupDao groupDao;
public GroupBORepositoryImpl(String ownerRef, GroupDao groupDao, MemberDao memberDao, GroupBusinessFactory factory)
{
this.ownerRef = ownerRef;
this.factory = factory;
this.groupDao = groupDao;
}
@Override
public GroupBO createGroup(String name, String ownerName)
{ | GroupPO groupPO = groupDao.createAndInsert(ownerRef, name); |
Thomas-Bergmann/Tournament | de.hatoka.tournament/src/main/java/de/hatoka/tournament/capi/entities/BlindLevelPO.java | // Path: de.hatoka.common/src/main/java/de/hatoka/common/capi/app/xslt/DateXmlAdapter.java
// public class DateXmlAdapter extends XmlAdapter<String, Date>
// {
// private final SimpleDateFormat dateFormat;
//
// public DateXmlAdapter()
// {
// dateFormat = new SimpleDateFormat(LocalizationConstants.XML_DATEFORMAT_SECONDS);
// dateFormat.setTimeZone(CountryHelper.UTC);
// }
//
// @Override
// public String marshal(Date v) throws Exception
// {
// if (v == null)
// {
// return null;
// }
// return dateFormat.format(v);
// }
//
// @Override
// public Date unmarshal(String v) throws Exception
// {
// if (v == null)
// {
// return null;
// }
// return dateFormat.parse(v);
// }
//
// }
//
// Path: de.hatoka.common/src/main/java/de/hatoka/common/capi/dao/IdentifiableEntity.java
// public interface IdentifiableEntity
// {
// String getId();
//
// void setId(String id);
// }
| import java.io.Serializable;
import java.util.Date;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.validation.constraints.NotNull;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlTransient;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
import de.hatoka.common.capi.app.xslt.DateXmlAdapter;
import de.hatoka.common.capi.dao.IdentifiableEntity; |
@XmlAttribute
private Integer smallBlind;
@XmlAttribute
private Integer bigBlind;
@XmlTransient
private int position;
@XmlAttribute
private Integer ante;
@NotNull
@XmlAttribute
private boolean isReBuy= false;
@NotNull
@XmlAttribute
private boolean isPause = false;
/**
* Duration in minutes
*/
@NotNull
@XmlAttribute
private Integer duration;
@Temporal(TemporalType.TIMESTAMP)
@XmlAttribute | // Path: de.hatoka.common/src/main/java/de/hatoka/common/capi/app/xslt/DateXmlAdapter.java
// public class DateXmlAdapter extends XmlAdapter<String, Date>
// {
// private final SimpleDateFormat dateFormat;
//
// public DateXmlAdapter()
// {
// dateFormat = new SimpleDateFormat(LocalizationConstants.XML_DATEFORMAT_SECONDS);
// dateFormat.setTimeZone(CountryHelper.UTC);
// }
//
// @Override
// public String marshal(Date v) throws Exception
// {
// if (v == null)
// {
// return null;
// }
// return dateFormat.format(v);
// }
//
// @Override
// public Date unmarshal(String v) throws Exception
// {
// if (v == null)
// {
// return null;
// }
// return dateFormat.parse(v);
// }
//
// }
//
// Path: de.hatoka.common/src/main/java/de/hatoka/common/capi/dao/IdentifiableEntity.java
// public interface IdentifiableEntity
// {
// String getId();
//
// void setId(String id);
// }
// Path: de.hatoka.tournament/src/main/java/de/hatoka/tournament/capi/entities/BlindLevelPO.java
import java.io.Serializable;
import java.util.Date;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.validation.constraints.NotNull;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlTransient;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
import de.hatoka.common.capi.app.xslt.DateXmlAdapter;
import de.hatoka.common.capi.dao.IdentifiableEntity;
@XmlAttribute
private Integer smallBlind;
@XmlAttribute
private Integer bigBlind;
@XmlTransient
private int position;
@XmlAttribute
private Integer ante;
@NotNull
@XmlAttribute
private boolean isReBuy= false;
@NotNull
@XmlAttribute
private boolean isPause = false;
/**
* Duration in minutes
*/
@NotNull
@XmlAttribute
private Integer duration;
@Temporal(TemporalType.TIMESTAMP)
@XmlAttribute | @XmlJavaTypeAdapter(DateXmlAdapter.class) |
Thomas-Bergmann/Tournament | de.hatoka.common/src/test/java/de/hatoka/common/capi/business/DateTest.java | // Path: de.hatoka.common/src/main/java/de/hatoka/common/capi/resource/LocalizationConstants.java
// public class LocalizationConstants
// {
// public static final String XML_DATEFORMAT_MILLIS = "yyyy-MM-dd'T'HH:mm:ss.SSSXXX";
// public static final String XML_DATEFORMAT_SECONDS = "yyyy-MM-dd'T'HH:mm:ssXXX";
// public static final String XML_DATEFORMAT_MINUTES = "yyyy-MM-dd'T'HH:mm";
// }
| import java.text.SimpleDateFormat;
import java.util.Date;
import org.junit.Assert;
import org.junit.Test;
import de.hatoka.common.capi.resource.LocalizationConstants; | package de.hatoka.common.capi.business;
public class DateTest
{
private static final long DATE_LONG = 1353829555000L;
@Test
public void testDateFormat() throws Exception
{ | // Path: de.hatoka.common/src/main/java/de/hatoka/common/capi/resource/LocalizationConstants.java
// public class LocalizationConstants
// {
// public static final String XML_DATEFORMAT_MILLIS = "yyyy-MM-dd'T'HH:mm:ss.SSSXXX";
// public static final String XML_DATEFORMAT_SECONDS = "yyyy-MM-dd'T'HH:mm:ssXXX";
// public static final String XML_DATEFORMAT_MINUTES = "yyyy-MM-dd'T'HH:mm";
// }
// Path: de.hatoka.common/src/test/java/de/hatoka/common/capi/business/DateTest.java
import java.text.SimpleDateFormat;
import java.util.Date;
import org.junit.Assert;
import org.junit.Test;
import de.hatoka.common.capi.resource.LocalizationConstants;
package de.hatoka.common.capi.business;
public class DateTest
{
private static final long DATE_LONG = 1353829555000L;
@Test
public void testDateFormat() throws Exception
{ | Date date = new SimpleDateFormat(LocalizationConstants.XML_DATEFORMAT_SECONDS).parse("2012-11-25T07:45:55Z"); |
Thomas-Bergmann/Tournament | de.hatoka.tournament/src/main/java/de/hatoka/tournament/modules/TournamentBusinessModule.java | // Path: de.hatoka.tournament/src/main/java/de/hatoka/tournament/capi/business/TournamentBusinessFactory.java
// public interface TournamentBusinessFactory
// {
// CashGameCompetitorBO getCompetitorBO(CompetitorPO competitorPO, CashGameBO cashGameBO);
//
// CompetitorBO getCompetitorBO(CompetitorPO competitorPO, TournamentBO tournamentBO);
//
// PlayerBO getPlayerBO(PlayerPO playerPO);
//
// PlayerBORepository getPlayerBORepository(String accountRef);
//
// CashGameBO getCashGameBO(TournamentPO tournamentPO);
//
// TournamentBO getTournamentBO(TournamentPO tournamentPO);
//
// TournamentBORepository getTournamentBORepository(String accountRef);
//
// HistoryEntryBO getHistoryBO(HistoryPO historyPO);
//
// BlindLevelBO getBlindLevelBO(BlindLevelPO blindLevelPO, ITournamentBO tournament);
//
// PauseBO getPauseBO(BlindLevelPO blindLevelPO, ITournamentBO tournament);
//
// RankBO getRankBO(RankPO rankPO, TournamentBO tournamentBO);
//
// ITableBO getTableBO(int tableNo);
// }
//
// Path: de.hatoka.tournament/src/main/java/de/hatoka/tournament/internal/business/TournamentBusinessFactoryImpl.java
// public class TournamentBusinessFactoryImpl implements TournamentBusinessFactory
// {
// @Inject
// private TournamentDao tournamentDao;
//
// @Inject
// private PlayerDao playerDao;
//
// @Inject
// private CompetitorDao competitorDao;
//
// @Inject
// private HistoryDao historyDao;
//
// @Inject
// private BlindLevelDao blindLevelDao;
//
// @Inject
// private RankDao rankDao;
//
// @Inject
// private Provider<Date> dateProvider;
//
// @Inject
// private UUIDGenerator uuidGenerator;
//
// @Inject
// private SequenceProvider sequenceProvider;
//
// @Inject
// private TransactionProvider transactionProvider;
//
// @Override
// public CashGameCompetitorBO getCompetitorBO(CompetitorPO competitorPO, CashGameBO cashGameBO)
// {
// return new CompetitorBOImpl(competitorPO, cashGameBO, historyDao, dateProvider, this);
// }
//
// @Override
// public CompetitorBO getCompetitorBO(CompetitorPO competitorPO, TournamentBO tournamentBO)
// {
// return new CompetitorBOImpl(competitorPO, tournamentBO, historyDao, dateProvider, this);
// }
//
// @Override
// public PlayerBO getPlayerBO(PlayerPO playerPO)
// {
// return new PlayerBOImpl(playerPO, playerDao, this);
// }
//
// @Override
// public PlayerBORepository getPlayerBORepository(String accountRef)
// {
// return new PlayerBORepositoryImpl(accountRef, playerDao, sequenceProvider.create(accountRef), this);
// }
//
// @Override
// public CashGameBO getCashGameBO(TournamentPO tournamentPO)
// {
// return new CashGameBOImpl(tournamentPO, tournamentDao, competitorDao, playerDao, this);
// }
//
// @Override
// public TournamentBO getTournamentBO(TournamentPO tournamentPO)
// {
// return new TournamentBOImpl(tournamentPO, tournamentDao, competitorDao, playerDao, blindLevelDao, rankDao, dateProvider, this);
// }
//
// @Override
// public TournamentBORepository getTournamentBORepository(String accountRef)
// {
// return new TournamentBORepositoryImpl(accountRef, tournamentDao, playerDao, competitorDao, blindLevelDao, historyDao, rankDao, sequenceProvider.create(accountRef), uuidGenerator, transactionProvider, this);
// }
//
// @Override
// public HistoryEntryBO getHistoryBO(HistoryPO historyPO)
// {
// return new HistoryEntryBOImpl(historyPO);
// }
//
// @Override
// public BlindLevelBO getBlindLevelBO(BlindLevelPO blindLevelPO, ITournamentBO tournament)
// {
// return new BlindLevelBOImpl(blindLevelPO, tournament, dateProvider);
// }
//
// @Override
// public PauseBO getPauseBO(BlindLevelPO blindLevelPO, ITournamentBO tournament)
// {
// return new PauseBOImpl(blindLevelPO, tournament, dateProvider);
// }
//
// @Override
// public RankBO getRankBO(RankPO rankPO, TournamentBO tournamentBO)
// {
// return new RankBOImpl(rankPO, tournamentBO);
// }
//
// @Override
// public ITableBO getTableBO(int tableNo)
// {
// return new TableBOImpl(tableNo);
// }
// }
| import com.google.inject.Binder;
import com.google.inject.Module;
import de.hatoka.tournament.capi.business.TournamentBusinessFactory;
import de.hatoka.tournament.internal.business.TournamentBusinessFactoryImpl; | package de.hatoka.tournament.modules;
public class TournamentBusinessModule implements Module
{
@Override
public void configure(Binder binder)
{ | // Path: de.hatoka.tournament/src/main/java/de/hatoka/tournament/capi/business/TournamentBusinessFactory.java
// public interface TournamentBusinessFactory
// {
// CashGameCompetitorBO getCompetitorBO(CompetitorPO competitorPO, CashGameBO cashGameBO);
//
// CompetitorBO getCompetitorBO(CompetitorPO competitorPO, TournamentBO tournamentBO);
//
// PlayerBO getPlayerBO(PlayerPO playerPO);
//
// PlayerBORepository getPlayerBORepository(String accountRef);
//
// CashGameBO getCashGameBO(TournamentPO tournamentPO);
//
// TournamentBO getTournamentBO(TournamentPO tournamentPO);
//
// TournamentBORepository getTournamentBORepository(String accountRef);
//
// HistoryEntryBO getHistoryBO(HistoryPO historyPO);
//
// BlindLevelBO getBlindLevelBO(BlindLevelPO blindLevelPO, ITournamentBO tournament);
//
// PauseBO getPauseBO(BlindLevelPO blindLevelPO, ITournamentBO tournament);
//
// RankBO getRankBO(RankPO rankPO, TournamentBO tournamentBO);
//
// ITableBO getTableBO(int tableNo);
// }
//
// Path: de.hatoka.tournament/src/main/java/de/hatoka/tournament/internal/business/TournamentBusinessFactoryImpl.java
// public class TournamentBusinessFactoryImpl implements TournamentBusinessFactory
// {
// @Inject
// private TournamentDao tournamentDao;
//
// @Inject
// private PlayerDao playerDao;
//
// @Inject
// private CompetitorDao competitorDao;
//
// @Inject
// private HistoryDao historyDao;
//
// @Inject
// private BlindLevelDao blindLevelDao;
//
// @Inject
// private RankDao rankDao;
//
// @Inject
// private Provider<Date> dateProvider;
//
// @Inject
// private UUIDGenerator uuidGenerator;
//
// @Inject
// private SequenceProvider sequenceProvider;
//
// @Inject
// private TransactionProvider transactionProvider;
//
// @Override
// public CashGameCompetitorBO getCompetitorBO(CompetitorPO competitorPO, CashGameBO cashGameBO)
// {
// return new CompetitorBOImpl(competitorPO, cashGameBO, historyDao, dateProvider, this);
// }
//
// @Override
// public CompetitorBO getCompetitorBO(CompetitorPO competitorPO, TournamentBO tournamentBO)
// {
// return new CompetitorBOImpl(competitorPO, tournamentBO, historyDao, dateProvider, this);
// }
//
// @Override
// public PlayerBO getPlayerBO(PlayerPO playerPO)
// {
// return new PlayerBOImpl(playerPO, playerDao, this);
// }
//
// @Override
// public PlayerBORepository getPlayerBORepository(String accountRef)
// {
// return new PlayerBORepositoryImpl(accountRef, playerDao, sequenceProvider.create(accountRef), this);
// }
//
// @Override
// public CashGameBO getCashGameBO(TournamentPO tournamentPO)
// {
// return new CashGameBOImpl(tournamentPO, tournamentDao, competitorDao, playerDao, this);
// }
//
// @Override
// public TournamentBO getTournamentBO(TournamentPO tournamentPO)
// {
// return new TournamentBOImpl(tournamentPO, tournamentDao, competitorDao, playerDao, blindLevelDao, rankDao, dateProvider, this);
// }
//
// @Override
// public TournamentBORepository getTournamentBORepository(String accountRef)
// {
// return new TournamentBORepositoryImpl(accountRef, tournamentDao, playerDao, competitorDao, blindLevelDao, historyDao, rankDao, sequenceProvider.create(accountRef), uuidGenerator, transactionProvider, this);
// }
//
// @Override
// public HistoryEntryBO getHistoryBO(HistoryPO historyPO)
// {
// return new HistoryEntryBOImpl(historyPO);
// }
//
// @Override
// public BlindLevelBO getBlindLevelBO(BlindLevelPO blindLevelPO, ITournamentBO tournament)
// {
// return new BlindLevelBOImpl(blindLevelPO, tournament, dateProvider);
// }
//
// @Override
// public PauseBO getPauseBO(BlindLevelPO blindLevelPO, ITournamentBO tournament)
// {
// return new PauseBOImpl(blindLevelPO, tournament, dateProvider);
// }
//
// @Override
// public RankBO getRankBO(RankPO rankPO, TournamentBO tournamentBO)
// {
// return new RankBOImpl(rankPO, tournamentBO);
// }
//
// @Override
// public ITableBO getTableBO(int tableNo)
// {
// return new TableBOImpl(tableNo);
// }
// }
// Path: de.hatoka.tournament/src/main/java/de/hatoka/tournament/modules/TournamentBusinessModule.java
import com.google.inject.Binder;
import com.google.inject.Module;
import de.hatoka.tournament.capi.business.TournamentBusinessFactory;
import de.hatoka.tournament.internal.business.TournamentBusinessFactoryImpl;
package de.hatoka.tournament.modules;
public class TournamentBusinessModule implements Module
{
@Override
public void configure(Binder binder)
{ | binder.bind(TournamentBusinessFactory.class).to(TournamentBusinessFactoryImpl.class).asEagerSingleton(); |
Thomas-Bergmann/Tournament | de.hatoka.tournament/src/main/java/de/hatoka/tournament/modules/TournamentBusinessModule.java | // Path: de.hatoka.tournament/src/main/java/de/hatoka/tournament/capi/business/TournamentBusinessFactory.java
// public interface TournamentBusinessFactory
// {
// CashGameCompetitorBO getCompetitorBO(CompetitorPO competitorPO, CashGameBO cashGameBO);
//
// CompetitorBO getCompetitorBO(CompetitorPO competitorPO, TournamentBO tournamentBO);
//
// PlayerBO getPlayerBO(PlayerPO playerPO);
//
// PlayerBORepository getPlayerBORepository(String accountRef);
//
// CashGameBO getCashGameBO(TournamentPO tournamentPO);
//
// TournamentBO getTournamentBO(TournamentPO tournamentPO);
//
// TournamentBORepository getTournamentBORepository(String accountRef);
//
// HistoryEntryBO getHistoryBO(HistoryPO historyPO);
//
// BlindLevelBO getBlindLevelBO(BlindLevelPO blindLevelPO, ITournamentBO tournament);
//
// PauseBO getPauseBO(BlindLevelPO blindLevelPO, ITournamentBO tournament);
//
// RankBO getRankBO(RankPO rankPO, TournamentBO tournamentBO);
//
// ITableBO getTableBO(int tableNo);
// }
//
// Path: de.hatoka.tournament/src/main/java/de/hatoka/tournament/internal/business/TournamentBusinessFactoryImpl.java
// public class TournamentBusinessFactoryImpl implements TournamentBusinessFactory
// {
// @Inject
// private TournamentDao tournamentDao;
//
// @Inject
// private PlayerDao playerDao;
//
// @Inject
// private CompetitorDao competitorDao;
//
// @Inject
// private HistoryDao historyDao;
//
// @Inject
// private BlindLevelDao blindLevelDao;
//
// @Inject
// private RankDao rankDao;
//
// @Inject
// private Provider<Date> dateProvider;
//
// @Inject
// private UUIDGenerator uuidGenerator;
//
// @Inject
// private SequenceProvider sequenceProvider;
//
// @Inject
// private TransactionProvider transactionProvider;
//
// @Override
// public CashGameCompetitorBO getCompetitorBO(CompetitorPO competitorPO, CashGameBO cashGameBO)
// {
// return new CompetitorBOImpl(competitorPO, cashGameBO, historyDao, dateProvider, this);
// }
//
// @Override
// public CompetitorBO getCompetitorBO(CompetitorPO competitorPO, TournamentBO tournamentBO)
// {
// return new CompetitorBOImpl(competitorPO, tournamentBO, historyDao, dateProvider, this);
// }
//
// @Override
// public PlayerBO getPlayerBO(PlayerPO playerPO)
// {
// return new PlayerBOImpl(playerPO, playerDao, this);
// }
//
// @Override
// public PlayerBORepository getPlayerBORepository(String accountRef)
// {
// return new PlayerBORepositoryImpl(accountRef, playerDao, sequenceProvider.create(accountRef), this);
// }
//
// @Override
// public CashGameBO getCashGameBO(TournamentPO tournamentPO)
// {
// return new CashGameBOImpl(tournamentPO, tournamentDao, competitorDao, playerDao, this);
// }
//
// @Override
// public TournamentBO getTournamentBO(TournamentPO tournamentPO)
// {
// return new TournamentBOImpl(tournamentPO, tournamentDao, competitorDao, playerDao, blindLevelDao, rankDao, dateProvider, this);
// }
//
// @Override
// public TournamentBORepository getTournamentBORepository(String accountRef)
// {
// return new TournamentBORepositoryImpl(accountRef, tournamentDao, playerDao, competitorDao, blindLevelDao, historyDao, rankDao, sequenceProvider.create(accountRef), uuidGenerator, transactionProvider, this);
// }
//
// @Override
// public HistoryEntryBO getHistoryBO(HistoryPO historyPO)
// {
// return new HistoryEntryBOImpl(historyPO);
// }
//
// @Override
// public BlindLevelBO getBlindLevelBO(BlindLevelPO blindLevelPO, ITournamentBO tournament)
// {
// return new BlindLevelBOImpl(blindLevelPO, tournament, dateProvider);
// }
//
// @Override
// public PauseBO getPauseBO(BlindLevelPO blindLevelPO, ITournamentBO tournament)
// {
// return new PauseBOImpl(blindLevelPO, tournament, dateProvider);
// }
//
// @Override
// public RankBO getRankBO(RankPO rankPO, TournamentBO tournamentBO)
// {
// return new RankBOImpl(rankPO, tournamentBO);
// }
//
// @Override
// public ITableBO getTableBO(int tableNo)
// {
// return new TableBOImpl(tableNo);
// }
// }
| import com.google.inject.Binder;
import com.google.inject.Module;
import de.hatoka.tournament.capi.business.TournamentBusinessFactory;
import de.hatoka.tournament.internal.business.TournamentBusinessFactoryImpl; | package de.hatoka.tournament.modules;
public class TournamentBusinessModule implements Module
{
@Override
public void configure(Binder binder)
{ | // Path: de.hatoka.tournament/src/main/java/de/hatoka/tournament/capi/business/TournamentBusinessFactory.java
// public interface TournamentBusinessFactory
// {
// CashGameCompetitorBO getCompetitorBO(CompetitorPO competitorPO, CashGameBO cashGameBO);
//
// CompetitorBO getCompetitorBO(CompetitorPO competitorPO, TournamentBO tournamentBO);
//
// PlayerBO getPlayerBO(PlayerPO playerPO);
//
// PlayerBORepository getPlayerBORepository(String accountRef);
//
// CashGameBO getCashGameBO(TournamentPO tournamentPO);
//
// TournamentBO getTournamentBO(TournamentPO tournamentPO);
//
// TournamentBORepository getTournamentBORepository(String accountRef);
//
// HistoryEntryBO getHistoryBO(HistoryPO historyPO);
//
// BlindLevelBO getBlindLevelBO(BlindLevelPO blindLevelPO, ITournamentBO tournament);
//
// PauseBO getPauseBO(BlindLevelPO blindLevelPO, ITournamentBO tournament);
//
// RankBO getRankBO(RankPO rankPO, TournamentBO tournamentBO);
//
// ITableBO getTableBO(int tableNo);
// }
//
// Path: de.hatoka.tournament/src/main/java/de/hatoka/tournament/internal/business/TournamentBusinessFactoryImpl.java
// public class TournamentBusinessFactoryImpl implements TournamentBusinessFactory
// {
// @Inject
// private TournamentDao tournamentDao;
//
// @Inject
// private PlayerDao playerDao;
//
// @Inject
// private CompetitorDao competitorDao;
//
// @Inject
// private HistoryDao historyDao;
//
// @Inject
// private BlindLevelDao blindLevelDao;
//
// @Inject
// private RankDao rankDao;
//
// @Inject
// private Provider<Date> dateProvider;
//
// @Inject
// private UUIDGenerator uuidGenerator;
//
// @Inject
// private SequenceProvider sequenceProvider;
//
// @Inject
// private TransactionProvider transactionProvider;
//
// @Override
// public CashGameCompetitorBO getCompetitorBO(CompetitorPO competitorPO, CashGameBO cashGameBO)
// {
// return new CompetitorBOImpl(competitorPO, cashGameBO, historyDao, dateProvider, this);
// }
//
// @Override
// public CompetitorBO getCompetitorBO(CompetitorPO competitorPO, TournamentBO tournamentBO)
// {
// return new CompetitorBOImpl(competitorPO, tournamentBO, historyDao, dateProvider, this);
// }
//
// @Override
// public PlayerBO getPlayerBO(PlayerPO playerPO)
// {
// return new PlayerBOImpl(playerPO, playerDao, this);
// }
//
// @Override
// public PlayerBORepository getPlayerBORepository(String accountRef)
// {
// return new PlayerBORepositoryImpl(accountRef, playerDao, sequenceProvider.create(accountRef), this);
// }
//
// @Override
// public CashGameBO getCashGameBO(TournamentPO tournamentPO)
// {
// return new CashGameBOImpl(tournamentPO, tournamentDao, competitorDao, playerDao, this);
// }
//
// @Override
// public TournamentBO getTournamentBO(TournamentPO tournamentPO)
// {
// return new TournamentBOImpl(tournamentPO, tournamentDao, competitorDao, playerDao, blindLevelDao, rankDao, dateProvider, this);
// }
//
// @Override
// public TournamentBORepository getTournamentBORepository(String accountRef)
// {
// return new TournamentBORepositoryImpl(accountRef, tournamentDao, playerDao, competitorDao, blindLevelDao, historyDao, rankDao, sequenceProvider.create(accountRef), uuidGenerator, transactionProvider, this);
// }
//
// @Override
// public HistoryEntryBO getHistoryBO(HistoryPO historyPO)
// {
// return new HistoryEntryBOImpl(historyPO);
// }
//
// @Override
// public BlindLevelBO getBlindLevelBO(BlindLevelPO blindLevelPO, ITournamentBO tournament)
// {
// return new BlindLevelBOImpl(blindLevelPO, tournament, dateProvider);
// }
//
// @Override
// public PauseBO getPauseBO(BlindLevelPO blindLevelPO, ITournamentBO tournament)
// {
// return new PauseBOImpl(blindLevelPO, tournament, dateProvider);
// }
//
// @Override
// public RankBO getRankBO(RankPO rankPO, TournamentBO tournamentBO)
// {
// return new RankBOImpl(rankPO, tournamentBO);
// }
//
// @Override
// public ITableBO getTableBO(int tableNo)
// {
// return new TableBOImpl(tableNo);
// }
// }
// Path: de.hatoka.tournament/src/main/java/de/hatoka/tournament/modules/TournamentBusinessModule.java
import com.google.inject.Binder;
import com.google.inject.Module;
import de.hatoka.tournament.capi.business.TournamentBusinessFactory;
import de.hatoka.tournament.internal.business.TournamentBusinessFactoryImpl;
package de.hatoka.tournament.modules;
public class TournamentBusinessModule implements Module
{
@Override
public void configure(Binder binder)
{ | binder.bind(TournamentBusinessFactory.class).to(TournamentBusinessFactoryImpl.class).asEagerSingleton(); |
Thomas-Bergmann/Tournament | de.hatoka.group/src/main/java/de/hatoka/group/capi/entities/GroupPO.java | // Path: de.hatoka.common/src/main/java/de/hatoka/common/capi/dao/IdentifiableEntity.java
// public interface IdentifiableEntity
// {
// String getId();
//
// void setId(String id);
// }
| import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;
import javax.validation.constraints.NotNull;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlTransient;
import de.hatoka.common.capi.dao.IdentifiableEntity; | package de.hatoka.group.capi.entities;
@Entity
@NamedQueries(value = {
@NamedQuery(name = "GroupPO.findByName", query = "select a from GroupPO a where a.name = :name"),
@NamedQuery(name = "GroupPO.findByOwnerRef", query = "select a from GroupPO a where a.ownerRef = :ownerRef")
}) | // Path: de.hatoka.common/src/main/java/de/hatoka/common/capi/dao/IdentifiableEntity.java
// public interface IdentifiableEntity
// {
// String getId();
//
// void setId(String id);
// }
// Path: de.hatoka.group/src/main/java/de/hatoka/group/capi/entities/GroupPO.java
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;
import javax.validation.constraints.NotNull;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlTransient;
import de.hatoka.common.capi.dao.IdentifiableEntity;
package de.hatoka.group.capi.entities;
@Entity
@NamedQueries(value = {
@NamedQuery(name = "GroupPO.findByName", query = "select a from GroupPO a where a.name = :name"),
@NamedQuery(name = "GroupPO.findByOwnerRef", query = "select a from GroupPO a where a.ownerRef = :ownerRef")
}) | public class GroupPO implements Serializable, IdentifiableEntity |
Thomas-Bergmann/Tournament | de.hatoka.user/src/main/java/de/hatoka/user/capi/business/UserBusinessFactory.java | // Path: de.hatoka.user/src/main/java/de/hatoka/user/capi/entities/UserPO.java
// @Entity
// @NamedQuery(name = "UserPO.findByLogin", query = "select a from UserPO a where a.login = :login")
// public class UserPO implements Serializable, IdentifiableEntity
// {
// private static final long serialVersionUID = 1L;
// @Id
// private String id;
// @NotNull
// private String login;
//
// /**
// * email is same as login for front end created users.
// */
// private String email;
//
// /**
// * is email verified during sign up or later email change? In that case a
// * user can be active, but the email could not be verified.
// */
// private boolean emailIsVerified = false;
//
// /**
// * User is active and can login with password
// */
// private boolean isActive = false;
//
// /**
// * User must provide this token to activate his account
// */
// private String signInToken;
//
// private String password;
// private String nickName;
// private String firstName;
// private String lastName;
// private String locale;
// private String timeZone;
//
// public UserPO()
// {
// }
//
// @Override
// public boolean equals(Object obj)
// {
// if (this == obj)
// return true;
// if (obj == null)
// return false;
// if (getClass() != obj.getClass())
// return false;
// UserPO other = (UserPO)obj;
// if (id == null)
// {
// if (other.id != null)
// return false;
// }
// else if (!id.equals(other.id))
// return false;
// return true;
// }
//
// public String getEmail()
// {
// return email;
// }
//
// public String getFirstName()
// {
// return firstName;
// }
//
// @Override
// public String getId()
// {
// return id;
// }
//
// public String getLastName()
// {
// return lastName;
// }
//
// public String getLocale()
// {
// return locale;
// }
//
// public String getLogin()
// {
// return login;
// }
//
// public String getNickName()
// {
// return nickName;
// }
//
// public String getPassword()
// {
// return password;
// }
//
// public String getSignInToken()
// {
// return signInToken;
// }
//
// @Override
// public int hashCode()
// {
// final int prime = 31;
// int result = 1;
// result = prime * result + ((id == null) ? 0 : id.hashCode());
// return result;
// }
//
// public boolean isActive()
// {
// return isActive;
// }
//
// public boolean isEmailIsVerified()
// {
// return emailIsVerified;
// }
//
// public void setActive(boolean isActive)
// {
// this.isActive = isActive;
// }
//
// public void setEmail(String email)
// {
// this.email = email;
// }
//
// public void setEmailIsVerified(boolean emailIsVerified)
// {
// this.emailIsVerified = emailIsVerified;
// }
//
// public void setFirstName(String firstName)
// {
// this.firstName = firstName;
// }
//
// @Override
// public void setId(String id)
// {
// this.id = id;
// }
//
// public void setLastName(String lastName)
// {
// this.lastName = lastName;
// }
//
// public void setLocale(String locale)
// {
// this.locale = locale;
// }
//
// public void setLogin(String login)
// {
// this.login = login;
// }
//
// public void setNickName(String nickName)
// {
// this.nickName = nickName;
// }
//
// public void setPassword(String password)
// {
// this.password = password;
// }
//
// public void setSignInToken(String signInToken)
// {
// this.signInToken = signInToken;
// }
//
// public String getTimeZone()
// {
// return timeZone;
// }
//
// public void setTimeZone(String timeZone)
// {
// this.timeZone = timeZone;
// }
//
// }
| import de.hatoka.user.capi.entities.UserPO; | package de.hatoka.user.capi.business;
public interface UserBusinessFactory
{ | // Path: de.hatoka.user/src/main/java/de/hatoka/user/capi/entities/UserPO.java
// @Entity
// @NamedQuery(name = "UserPO.findByLogin", query = "select a from UserPO a where a.login = :login")
// public class UserPO implements Serializable, IdentifiableEntity
// {
// private static final long serialVersionUID = 1L;
// @Id
// private String id;
// @NotNull
// private String login;
//
// /**
// * email is same as login for front end created users.
// */
// private String email;
//
// /**
// * is email verified during sign up or later email change? In that case a
// * user can be active, but the email could not be verified.
// */
// private boolean emailIsVerified = false;
//
// /**
// * User is active and can login with password
// */
// private boolean isActive = false;
//
// /**
// * User must provide this token to activate his account
// */
// private String signInToken;
//
// private String password;
// private String nickName;
// private String firstName;
// private String lastName;
// private String locale;
// private String timeZone;
//
// public UserPO()
// {
// }
//
// @Override
// public boolean equals(Object obj)
// {
// if (this == obj)
// return true;
// if (obj == null)
// return false;
// if (getClass() != obj.getClass())
// return false;
// UserPO other = (UserPO)obj;
// if (id == null)
// {
// if (other.id != null)
// return false;
// }
// else if (!id.equals(other.id))
// return false;
// return true;
// }
//
// public String getEmail()
// {
// return email;
// }
//
// public String getFirstName()
// {
// return firstName;
// }
//
// @Override
// public String getId()
// {
// return id;
// }
//
// public String getLastName()
// {
// return lastName;
// }
//
// public String getLocale()
// {
// return locale;
// }
//
// public String getLogin()
// {
// return login;
// }
//
// public String getNickName()
// {
// return nickName;
// }
//
// public String getPassword()
// {
// return password;
// }
//
// public String getSignInToken()
// {
// return signInToken;
// }
//
// @Override
// public int hashCode()
// {
// final int prime = 31;
// int result = 1;
// result = prime * result + ((id == null) ? 0 : id.hashCode());
// return result;
// }
//
// public boolean isActive()
// {
// return isActive;
// }
//
// public boolean isEmailIsVerified()
// {
// return emailIsVerified;
// }
//
// public void setActive(boolean isActive)
// {
// this.isActive = isActive;
// }
//
// public void setEmail(String email)
// {
// this.email = email;
// }
//
// public void setEmailIsVerified(boolean emailIsVerified)
// {
// this.emailIsVerified = emailIsVerified;
// }
//
// public void setFirstName(String firstName)
// {
// this.firstName = firstName;
// }
//
// @Override
// public void setId(String id)
// {
// this.id = id;
// }
//
// public void setLastName(String lastName)
// {
// this.lastName = lastName;
// }
//
// public void setLocale(String locale)
// {
// this.locale = locale;
// }
//
// public void setLogin(String login)
// {
// this.login = login;
// }
//
// public void setNickName(String nickName)
// {
// this.nickName = nickName;
// }
//
// public void setPassword(String password)
// {
// this.password = password;
// }
//
// public void setSignInToken(String signInToken)
// {
// this.signInToken = signInToken;
// }
//
// public String getTimeZone()
// {
// return timeZone;
// }
//
// public void setTimeZone(String timeZone)
// {
// this.timeZone = timeZone;
// }
//
// }
// Path: de.hatoka.user/src/main/java/de/hatoka/user/capi/business/UserBusinessFactory.java
import de.hatoka.user.capi.entities.UserPO;
package de.hatoka.user.capi.business;
public interface UserBusinessFactory
{ | public UserBO getUserBO(UserPO userPO); |
Thomas-Bergmann/Tournament | de.hatoka.group/src/main/java/de/hatoka/group/internal/business/GroupBOComparators.java | // Path: de.hatoka.group/src/main/java/de/hatoka/group/capi/business/GroupBO.java
// public interface GroupBO
// {
// /**
// * @return userRef of owner
// */
// String getOwner();
//
// /**
// * Removes the group
// */
// void remove();
//
// /**
// * @return name of group
// */
// String getName();
//
// /**
// * Create member for given user
// * @param userRef
// * @param name of member in side of the group
// * @return
// */
// MemberBO createMember(String userRef, String name);
//
// /**
// * @return members of the group (owner is one member)
// */
// Collection<MemberBO> getMembers();
//
// /**
// * @return identifier of group
// */
// String getID();
//
// /**
// * @param userRef
// * @return the member instance of the given user.
// */
// MemberBO getMember(String userRef);
//
// /**
// * @param userRef
// * @return true in case user is member of this group
// */
// boolean isMember(String userRef);
// }
| import java.util.Comparator;
import de.hatoka.group.capi.business.GroupBO; | package de.hatoka.group.internal.business;
public final class GroupBOComparators
{
private GroupBOComparators()
{
}
| // Path: de.hatoka.group/src/main/java/de/hatoka/group/capi/business/GroupBO.java
// public interface GroupBO
// {
// /**
// * @return userRef of owner
// */
// String getOwner();
//
// /**
// * Removes the group
// */
// void remove();
//
// /**
// * @return name of group
// */
// String getName();
//
// /**
// * Create member for given user
// * @param userRef
// * @param name of member in side of the group
// * @return
// */
// MemberBO createMember(String userRef, String name);
//
// /**
// * @return members of the group (owner is one member)
// */
// Collection<MemberBO> getMembers();
//
// /**
// * @return identifier of group
// */
// String getID();
//
// /**
// * @param userRef
// * @return the member instance of the given user.
// */
// MemberBO getMember(String userRef);
//
// /**
// * @param userRef
// * @return true in case user is member of this group
// */
// boolean isMember(String userRef);
// }
// Path: de.hatoka.group/src/main/java/de/hatoka/group/internal/business/GroupBOComparators.java
import java.util.Comparator;
import de.hatoka.group.capi.business.GroupBO;
package de.hatoka.group.internal.business;
public final class GroupBOComparators
{
private GroupBOComparators()
{
}
| public static final Comparator<GroupBO> DEFAULT_GROUP= (a, b) -> a.getName().compareTo(b.getName()); |
Thomas-Bergmann/Tournament | de.hatoka.tournament/src/main/java/de/hatoka/tournament/capi/entities/TournamentPO.java | // Path: de.hatoka.common/src/main/java/de/hatoka/common/capi/app/xslt/DateXmlAdapter.java
// public class DateXmlAdapter extends XmlAdapter<String, Date>
// {
// private final SimpleDateFormat dateFormat;
//
// public DateXmlAdapter()
// {
// dateFormat = new SimpleDateFormat(LocalizationConstants.XML_DATEFORMAT_SECONDS);
// dateFormat.setTimeZone(CountryHelper.UTC);
// }
//
// @Override
// public String marshal(Date v) throws Exception
// {
// if (v == null)
// {
// return null;
// }
// return dateFormat.format(v);
// }
//
// @Override
// public Date unmarshal(String v) throws Exception
// {
// if (v == null)
// {
// return null;
// }
// return dateFormat.parse(v);
// }
//
// }
//
// Path: de.hatoka.common/src/main/java/de/hatoka/common/capi/dao/IdentifiableEntity.java
// public interface IdentifiableEntity
// {
// String getId();
//
// void setId(String id);
// }
| import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javax.persistence.AttributeOverride;
import javax.persistence.AttributeOverrides;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Embedded;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.validation.constraints.NotNull;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlID;
import javax.xml.bind.annotation.XmlTransient;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
import de.hatoka.common.capi.app.xslt.DateXmlAdapter;
import de.hatoka.common.capi.dao.IdentifiableEntity;
import de.hatoka.common.capi.entities.MoneyPO; | package de.hatoka.tournament.capi.entities;
@Entity
@NamedQueries(value = {
@NamedQuery(name = "TournamentPO.findByAccountRef", query = "select a from TournamentPO a where a.accountRef = :accountRef"),
@NamedQuery(name = "TournamentPO.findByExternalRef", query = "select a from TournamentPO a where a.accountRef = :accountRef and a.externalRef = :externalRef") }) | // Path: de.hatoka.common/src/main/java/de/hatoka/common/capi/app/xslt/DateXmlAdapter.java
// public class DateXmlAdapter extends XmlAdapter<String, Date>
// {
// private final SimpleDateFormat dateFormat;
//
// public DateXmlAdapter()
// {
// dateFormat = new SimpleDateFormat(LocalizationConstants.XML_DATEFORMAT_SECONDS);
// dateFormat.setTimeZone(CountryHelper.UTC);
// }
//
// @Override
// public String marshal(Date v) throws Exception
// {
// if (v == null)
// {
// return null;
// }
// return dateFormat.format(v);
// }
//
// @Override
// public Date unmarshal(String v) throws Exception
// {
// if (v == null)
// {
// return null;
// }
// return dateFormat.parse(v);
// }
//
// }
//
// Path: de.hatoka.common/src/main/java/de/hatoka/common/capi/dao/IdentifiableEntity.java
// public interface IdentifiableEntity
// {
// String getId();
//
// void setId(String id);
// }
// Path: de.hatoka.tournament/src/main/java/de/hatoka/tournament/capi/entities/TournamentPO.java
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javax.persistence.AttributeOverride;
import javax.persistence.AttributeOverrides;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Embedded;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.validation.constraints.NotNull;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlID;
import javax.xml.bind.annotation.XmlTransient;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
import de.hatoka.common.capi.app.xslt.DateXmlAdapter;
import de.hatoka.common.capi.dao.IdentifiableEntity;
import de.hatoka.common.capi.entities.MoneyPO;
package de.hatoka.tournament.capi.entities;
@Entity
@NamedQueries(value = {
@NamedQuery(name = "TournamentPO.findByAccountRef", query = "select a from TournamentPO a where a.accountRef = :accountRef"),
@NamedQuery(name = "TournamentPO.findByExternalRef", query = "select a from TournamentPO a where a.accountRef = :accountRef and a.externalRef = :externalRef") }) | public class TournamentPO implements Serializable, IdentifiableEntity |
Thomas-Bergmann/Tournament | de.hatoka.tournament/src/main/java/de/hatoka/tournament/capi/entities/TournamentPO.java | // Path: de.hatoka.common/src/main/java/de/hatoka/common/capi/app/xslt/DateXmlAdapter.java
// public class DateXmlAdapter extends XmlAdapter<String, Date>
// {
// private final SimpleDateFormat dateFormat;
//
// public DateXmlAdapter()
// {
// dateFormat = new SimpleDateFormat(LocalizationConstants.XML_DATEFORMAT_SECONDS);
// dateFormat.setTimeZone(CountryHelper.UTC);
// }
//
// @Override
// public String marshal(Date v) throws Exception
// {
// if (v == null)
// {
// return null;
// }
// return dateFormat.format(v);
// }
//
// @Override
// public Date unmarshal(String v) throws Exception
// {
// if (v == null)
// {
// return null;
// }
// return dateFormat.parse(v);
// }
//
// }
//
// Path: de.hatoka.common/src/main/java/de/hatoka/common/capi/dao/IdentifiableEntity.java
// public interface IdentifiableEntity
// {
// String getId();
//
// void setId(String id);
// }
| import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javax.persistence.AttributeOverride;
import javax.persistence.AttributeOverrides;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Embedded;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.validation.constraints.NotNull;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlID;
import javax.xml.bind.annotation.XmlTransient;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
import de.hatoka.common.capi.app.xslt.DateXmlAdapter;
import de.hatoka.common.capi.dao.IdentifiableEntity;
import de.hatoka.common.capi.entities.MoneyPO; | package de.hatoka.tournament.capi.entities;
@Entity
@NamedQueries(value = {
@NamedQuery(name = "TournamentPO.findByAccountRef", query = "select a from TournamentPO a where a.accountRef = :accountRef"),
@NamedQuery(name = "TournamentPO.findByExternalRef", query = "select a from TournamentPO a where a.accountRef = :accountRef and a.externalRef = :externalRef") })
public class TournamentPO implements Serializable, IdentifiableEntity
{
private static final long serialVersionUID = 1L;
@Id
@XmlTransient
private String id;
@NotNull
@XmlID
@XmlAttribute(name = "id")
private String externalRef;
@NotNull
private String accountRef;
@NotNull
@XmlAttribute
private boolean isCashGame;
@NotNull
private String name;
@NotNull
@Temporal(TemporalType.TIMESTAMP)
@XmlAttribute | // Path: de.hatoka.common/src/main/java/de/hatoka/common/capi/app/xslt/DateXmlAdapter.java
// public class DateXmlAdapter extends XmlAdapter<String, Date>
// {
// private final SimpleDateFormat dateFormat;
//
// public DateXmlAdapter()
// {
// dateFormat = new SimpleDateFormat(LocalizationConstants.XML_DATEFORMAT_SECONDS);
// dateFormat.setTimeZone(CountryHelper.UTC);
// }
//
// @Override
// public String marshal(Date v) throws Exception
// {
// if (v == null)
// {
// return null;
// }
// return dateFormat.format(v);
// }
//
// @Override
// public Date unmarshal(String v) throws Exception
// {
// if (v == null)
// {
// return null;
// }
// return dateFormat.parse(v);
// }
//
// }
//
// Path: de.hatoka.common/src/main/java/de/hatoka/common/capi/dao/IdentifiableEntity.java
// public interface IdentifiableEntity
// {
// String getId();
//
// void setId(String id);
// }
// Path: de.hatoka.tournament/src/main/java/de/hatoka/tournament/capi/entities/TournamentPO.java
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javax.persistence.AttributeOverride;
import javax.persistence.AttributeOverrides;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Embedded;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.validation.constraints.NotNull;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlID;
import javax.xml.bind.annotation.XmlTransient;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
import de.hatoka.common.capi.app.xslt.DateXmlAdapter;
import de.hatoka.common.capi.dao.IdentifiableEntity;
import de.hatoka.common.capi.entities.MoneyPO;
package de.hatoka.tournament.capi.entities;
@Entity
@NamedQueries(value = {
@NamedQuery(name = "TournamentPO.findByAccountRef", query = "select a from TournamentPO a where a.accountRef = :accountRef"),
@NamedQuery(name = "TournamentPO.findByExternalRef", query = "select a from TournamentPO a where a.accountRef = :accountRef and a.externalRef = :externalRef") })
public class TournamentPO implements Serializable, IdentifiableEntity
{
private static final long serialVersionUID = 1L;
@Id
@XmlTransient
private String id;
@NotNull
@XmlID
@XmlAttribute(name = "id")
private String externalRef;
@NotNull
private String accountRef;
@NotNull
@XmlAttribute
private boolean isCashGame;
@NotNull
private String name;
@NotNull
@Temporal(TemporalType.TIMESTAMP)
@XmlAttribute | @XmlJavaTypeAdapter(DateXmlAdapter.class) |
Thomas-Bergmann/Tournament | de.hatoka.common/src/main/java/de/hatoka/common/capi/modules/CommonDaoModule.java | // Path: de.hatoka.common/src/main/java/de/hatoka/common/capi/dao/SequenceProvider.java
// public interface SequenceProvider
// {
// /**
// * Creates new sequence for a given name
// *
// * @param name
// * of sequence
// * @return next number of sequence
// */
// public UUIDGenerator create(String name);
//
// /**
// * Create a new sequence for a given name and last number, so the sequence can
// * start with the next number
// *
// * @param name
// * @param number
// */
// public UUIDGenerator create(String name, long number);
// }
//
// Path: de.hatoka.common/src/main/java/de/hatoka/common/capi/dao/UUIDGenerator.java
// public interface UUIDGenerator
// {
// public String generate();
// }
| import com.google.inject.Binder;
import com.google.inject.Module;
import de.hatoka.common.capi.dao.EncryptionUtils;
import de.hatoka.common.capi.dao.SequenceProvider;
import de.hatoka.common.capi.dao.UUIDGenerator;
import de.hatoka.common.internal.dao.EncryptionUtilsImpl;
import de.hatoka.common.internal.dao.SequenceProviderImpl;
import de.hatoka.common.internal.dao.UUIDGeneratorImpl; | package de.hatoka.common.capi.modules;
public class CommonDaoModule implements Module
{
private long start;
public CommonDaoModule()
{
this(0);
}
public CommonDaoModule(long sequenceStartPosition)
{
start = sequenceStartPosition;
}
@Override
public void configure(Binder binder)
{ | // Path: de.hatoka.common/src/main/java/de/hatoka/common/capi/dao/SequenceProvider.java
// public interface SequenceProvider
// {
// /**
// * Creates new sequence for a given name
// *
// * @param name
// * of sequence
// * @return next number of sequence
// */
// public UUIDGenerator create(String name);
//
// /**
// * Create a new sequence for a given name and last number, so the sequence can
// * start with the next number
// *
// * @param name
// * @param number
// */
// public UUIDGenerator create(String name, long number);
// }
//
// Path: de.hatoka.common/src/main/java/de/hatoka/common/capi/dao/UUIDGenerator.java
// public interface UUIDGenerator
// {
// public String generate();
// }
// Path: de.hatoka.common/src/main/java/de/hatoka/common/capi/modules/CommonDaoModule.java
import com.google.inject.Binder;
import com.google.inject.Module;
import de.hatoka.common.capi.dao.EncryptionUtils;
import de.hatoka.common.capi.dao.SequenceProvider;
import de.hatoka.common.capi.dao.UUIDGenerator;
import de.hatoka.common.internal.dao.EncryptionUtilsImpl;
import de.hatoka.common.internal.dao.SequenceProviderImpl;
import de.hatoka.common.internal.dao.UUIDGeneratorImpl;
package de.hatoka.common.capi.modules;
public class CommonDaoModule implements Module
{
private long start;
public CommonDaoModule()
{
this(0);
}
public CommonDaoModule(long sequenceStartPosition)
{
start = sequenceStartPosition;
}
@Override
public void configure(Binder binder)
{ | binder.bind(UUIDGenerator.class).to(UUIDGeneratorImpl.class).asEagerSingleton(); |
Thomas-Bergmann/Tournament | de.hatoka.common/src/main/java/de/hatoka/common/capi/modules/CommonDaoModule.java | // Path: de.hatoka.common/src/main/java/de/hatoka/common/capi/dao/SequenceProvider.java
// public interface SequenceProvider
// {
// /**
// * Creates new sequence for a given name
// *
// * @param name
// * of sequence
// * @return next number of sequence
// */
// public UUIDGenerator create(String name);
//
// /**
// * Create a new sequence for a given name and last number, so the sequence can
// * start with the next number
// *
// * @param name
// * @param number
// */
// public UUIDGenerator create(String name, long number);
// }
//
// Path: de.hatoka.common/src/main/java/de/hatoka/common/capi/dao/UUIDGenerator.java
// public interface UUIDGenerator
// {
// public String generate();
// }
| import com.google.inject.Binder;
import com.google.inject.Module;
import de.hatoka.common.capi.dao.EncryptionUtils;
import de.hatoka.common.capi.dao.SequenceProvider;
import de.hatoka.common.capi.dao.UUIDGenerator;
import de.hatoka.common.internal.dao.EncryptionUtilsImpl;
import de.hatoka.common.internal.dao.SequenceProviderImpl;
import de.hatoka.common.internal.dao.UUIDGeneratorImpl; | package de.hatoka.common.capi.modules;
public class CommonDaoModule implements Module
{
private long start;
public CommonDaoModule()
{
this(0);
}
public CommonDaoModule(long sequenceStartPosition)
{
start = sequenceStartPosition;
}
@Override
public void configure(Binder binder)
{
binder.bind(UUIDGenerator.class).to(UUIDGeneratorImpl.class).asEagerSingleton();
binder.bind(EncryptionUtils.class).to(EncryptionUtilsImpl.class).asEagerSingleton(); | // Path: de.hatoka.common/src/main/java/de/hatoka/common/capi/dao/SequenceProvider.java
// public interface SequenceProvider
// {
// /**
// * Creates new sequence for a given name
// *
// * @param name
// * of sequence
// * @return next number of sequence
// */
// public UUIDGenerator create(String name);
//
// /**
// * Create a new sequence for a given name and last number, so the sequence can
// * start with the next number
// *
// * @param name
// * @param number
// */
// public UUIDGenerator create(String name, long number);
// }
//
// Path: de.hatoka.common/src/main/java/de/hatoka/common/capi/dao/UUIDGenerator.java
// public interface UUIDGenerator
// {
// public String generate();
// }
// Path: de.hatoka.common/src/main/java/de/hatoka/common/capi/modules/CommonDaoModule.java
import com.google.inject.Binder;
import com.google.inject.Module;
import de.hatoka.common.capi.dao.EncryptionUtils;
import de.hatoka.common.capi.dao.SequenceProvider;
import de.hatoka.common.capi.dao.UUIDGenerator;
import de.hatoka.common.internal.dao.EncryptionUtilsImpl;
import de.hatoka.common.internal.dao.SequenceProviderImpl;
import de.hatoka.common.internal.dao.UUIDGeneratorImpl;
package de.hatoka.common.capi.modules;
public class CommonDaoModule implements Module
{
private long start;
public CommonDaoModule()
{
this(0);
}
public CommonDaoModule(long sequenceStartPosition)
{
start = sequenceStartPosition;
}
@Override
public void configure(Binder binder)
{
binder.bind(UUIDGenerator.class).to(UUIDGeneratorImpl.class).asEagerSingleton();
binder.bind(EncryptionUtils.class).to(EncryptionUtilsImpl.class).asEagerSingleton(); | binder.bind(SequenceProvider.class).toInstance(new SequenceProviderImpl(start)); |
mike10004/xvfb-manager-java | xvfb-testing/src/test/java/com/github/mike10004/xvfbtesting/XvfbRule_ForceWindowsTest.java | // Path: xvfb-manager/src/main/java/com/github/mike10004/xvfbmanager/XvfbController.java
// public interface XvfbController extends Closeable {
//
// String ENV_DISPLAY = "DISPLAY";
//
// /**
// * Waits until the display is ready, using default values for the polling
// * interval and maximum polls. Implementations may select the defaults
// * to use.
// * @throws InterruptedException if waiting is interrupted
// * @see #waitUntilReady(long, int)
// */
// void waitUntilReady() throws InterruptedException;
//
// /**
// * Waits until the X display is ready, polling at a given interval until the
// * display is ready or the given number of polls has been executed.
// * @param pollIntervalMs interval between polls in milliseconds
// * @param maxNumPolls maximum number of polls to execute
// * @throws InterruptedException if waiting is interrupted
// */
// void waitUntilReady(long pollIntervalMs, int maxNumPolls) throws InterruptedException;
//
// /**
// * Stops the virtual framebuffer process.
// */
// void stop();
//
// /**
// * Gets the display number in the format {@code :N} where {@code N} is the display number.
// * @return the display
// */
// String getDisplay();
//
// /**
// * Sets the display environment variable in the given environment.
// * @param environment map of environment variables in which display is to be set
// * @return the argument environment object
// * @see #ENV_DISPLAY
// */
// Map<String, String> configureEnvironment(Map<String, String> environment);
//
// /**
// * Creates a new, mutable environment variable map with the display variable set.
// * @return the new environment map
// * @see #configureEnvironment(Map)
// */
// @SuppressWarnings("unused")
// Map<String, String> newEnvironment();
//
// /**
// * Captures a screenshot of the virtual framebuffer.
// * @return the screenshot
// * @throws XvfbException if screenshooting goes awry
// */
// Screenshooter<?> getScreenshooter() throws XvfbException;
//
// /**
// * Class representing information about a window rendered by an X server.
// */
// class XWindow {
//
// /**
// * Window ID. This is commonly an integer in hexadecimal format, for example {@code 0x38ab0e}.
// */
// public final String id;
//
// /**
// * Window title. Null means the window has no title. The title may also
// * be empty, though that is not common.
// */
// public final @Nullable String title;
//
// /**
// * The line of output from which this window instance was parsed. This is a
// * line from {@code }
// */
// public final String line;
//
// /**
// * Constructs a new instance of the class.
// * @param id window id
// * @param title window title
// * @param line line of output from which this window information was parsed
// */
// public XWindow(String id, @Nullable String title, String line) {
// this.id = id;
// this.title = title;
// this.line = line;
// }
//
// @Override
// public String toString() {
// return "XWindow{" +
// "id=" + id +
// ", title='" + title + '\'' +
// ", length=" + (line == null ? -1 : line.length()) +
// '}';
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// XWindow xWindow = (XWindow) o;
//
// if (id != null ? !id.equals(xWindow.id) : xWindow.id != null) return false;
// if (title != null ? !title.equals(xWindow.title) : xWindow.title != null) return false;
// return line != null ? line.equals(xWindow.line) : xWindow.line == null;
// }
//
// @Override
// public int hashCode() {
// int result = id != null ? id.hashCode() : 0;
// result = 31 * result + (title != null ? title.hashCode() : 0);
// result = 31 * result + (line != null ? line.hashCode() : 0);
// return result;
// }
// }
//
// Optional<TreeNode<XWindow>> pollForWindow(Predicate<XWindow> windowFinder, long intervalMs, int maxPollAttempts) throws InterruptedException;
//
// }
| import com.github.mike10004.nativehelper.Platforms;
import io.github.mike10004.subprocess.SubprocessLaunchException;
import com.github.mike10004.xvfbmanager.XvfbController;
import org.junit.Assume;
import org.junit.BeforeClass;
import org.junit.ClassRule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;
import static org.junit.Assert.*; | public void testDisablingOnWindows() throws Exception {
System.out.format("testCase = %s%n", testCase);
AtomicBoolean reachedPreBefore = new AtomicBoolean(false);
RuleUser ruleUser = new RuleUser(testCase.rule) {
@Override
protected void getControllerAndUse(XvfbRule rule) throws Exception {
if (testCase.invokeGetController) {
super.getControllerAndUse(rule);
}
}
@Override
protected void preBefore() throws Exception {
reachedPreBefore.set(true);
}
@Override
protected void postBefore() throws Exception {
assertFalse("made it past before() with eager start", testCase.eagerStart);
}
@Override
protected void preAfter() throws Exception {
}
@Override
protected void postAfter() throws Exception {
}
@Override | // Path: xvfb-manager/src/main/java/com/github/mike10004/xvfbmanager/XvfbController.java
// public interface XvfbController extends Closeable {
//
// String ENV_DISPLAY = "DISPLAY";
//
// /**
// * Waits until the display is ready, using default values for the polling
// * interval and maximum polls. Implementations may select the defaults
// * to use.
// * @throws InterruptedException if waiting is interrupted
// * @see #waitUntilReady(long, int)
// */
// void waitUntilReady() throws InterruptedException;
//
// /**
// * Waits until the X display is ready, polling at a given interval until the
// * display is ready or the given number of polls has been executed.
// * @param pollIntervalMs interval between polls in milliseconds
// * @param maxNumPolls maximum number of polls to execute
// * @throws InterruptedException if waiting is interrupted
// */
// void waitUntilReady(long pollIntervalMs, int maxNumPolls) throws InterruptedException;
//
// /**
// * Stops the virtual framebuffer process.
// */
// void stop();
//
// /**
// * Gets the display number in the format {@code :N} where {@code N} is the display number.
// * @return the display
// */
// String getDisplay();
//
// /**
// * Sets the display environment variable in the given environment.
// * @param environment map of environment variables in which display is to be set
// * @return the argument environment object
// * @see #ENV_DISPLAY
// */
// Map<String, String> configureEnvironment(Map<String, String> environment);
//
// /**
// * Creates a new, mutable environment variable map with the display variable set.
// * @return the new environment map
// * @see #configureEnvironment(Map)
// */
// @SuppressWarnings("unused")
// Map<String, String> newEnvironment();
//
// /**
// * Captures a screenshot of the virtual framebuffer.
// * @return the screenshot
// * @throws XvfbException if screenshooting goes awry
// */
// Screenshooter<?> getScreenshooter() throws XvfbException;
//
// /**
// * Class representing information about a window rendered by an X server.
// */
// class XWindow {
//
// /**
// * Window ID. This is commonly an integer in hexadecimal format, for example {@code 0x38ab0e}.
// */
// public final String id;
//
// /**
// * Window title. Null means the window has no title. The title may also
// * be empty, though that is not common.
// */
// public final @Nullable String title;
//
// /**
// * The line of output from which this window instance was parsed. This is a
// * line from {@code }
// */
// public final String line;
//
// /**
// * Constructs a new instance of the class.
// * @param id window id
// * @param title window title
// * @param line line of output from which this window information was parsed
// */
// public XWindow(String id, @Nullable String title, String line) {
// this.id = id;
// this.title = title;
// this.line = line;
// }
//
// @Override
// public String toString() {
// return "XWindow{" +
// "id=" + id +
// ", title='" + title + '\'' +
// ", length=" + (line == null ? -1 : line.length()) +
// '}';
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// XWindow xWindow = (XWindow) o;
//
// if (id != null ? !id.equals(xWindow.id) : xWindow.id != null) return false;
// if (title != null ? !title.equals(xWindow.title) : xWindow.title != null) return false;
// return line != null ? line.equals(xWindow.line) : xWindow.line == null;
// }
//
// @Override
// public int hashCode() {
// int result = id != null ? id.hashCode() : 0;
// result = 31 * result + (title != null ? title.hashCode() : 0);
// result = 31 * result + (line != null ? line.hashCode() : 0);
// return result;
// }
// }
//
// Optional<TreeNode<XWindow>> pollForWindow(Predicate<XWindow> windowFinder, long intervalMs, int maxPollAttempts) throws InterruptedException;
//
// }
// Path: xvfb-testing/src/test/java/com/github/mike10004/xvfbtesting/XvfbRule_ForceWindowsTest.java
import com.github.mike10004.nativehelper.Platforms;
import io.github.mike10004.subprocess.SubprocessLaunchException;
import com.github.mike10004.xvfbmanager.XvfbController;
import org.junit.Assume;
import org.junit.BeforeClass;
import org.junit.ClassRule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;
import static org.junit.Assert.*;
public void testDisablingOnWindows() throws Exception {
System.out.format("testCase = %s%n", testCase);
AtomicBoolean reachedPreBefore = new AtomicBoolean(false);
RuleUser ruleUser = new RuleUser(testCase.rule) {
@Override
protected void getControllerAndUse(XvfbRule rule) throws Exception {
if (testCase.invokeGetController) {
super.getControllerAndUse(rule);
}
}
@Override
protected void preBefore() throws Exception {
reachedPreBefore.set(true);
}
@Override
protected void postBefore() throws Exception {
assertFalse("made it past before() with eager start", testCase.eagerStart);
}
@Override
protected void preAfter() throws Exception {
}
@Override
protected void postAfter() throws Exception {
}
@Override | protected void use(XvfbController ctrl) throws Exception { |
mike10004/xvfb-manager-java | xvfb-testing/src/test/java/com/github/mike10004/xvfbtesting/RuleUser.java | // Path: xvfb-manager/src/main/java/com/github/mike10004/xvfbmanager/XvfbController.java
// public interface XvfbController extends Closeable {
//
// String ENV_DISPLAY = "DISPLAY";
//
// /**
// * Waits until the display is ready, using default values for the polling
// * interval and maximum polls. Implementations may select the defaults
// * to use.
// * @throws InterruptedException if waiting is interrupted
// * @see #waitUntilReady(long, int)
// */
// void waitUntilReady() throws InterruptedException;
//
// /**
// * Waits until the X display is ready, polling at a given interval until the
// * display is ready or the given number of polls has been executed.
// * @param pollIntervalMs interval between polls in milliseconds
// * @param maxNumPolls maximum number of polls to execute
// * @throws InterruptedException if waiting is interrupted
// */
// void waitUntilReady(long pollIntervalMs, int maxNumPolls) throws InterruptedException;
//
// /**
// * Stops the virtual framebuffer process.
// */
// void stop();
//
// /**
// * Gets the display number in the format {@code :N} where {@code N} is the display number.
// * @return the display
// */
// String getDisplay();
//
// /**
// * Sets the display environment variable in the given environment.
// * @param environment map of environment variables in which display is to be set
// * @return the argument environment object
// * @see #ENV_DISPLAY
// */
// Map<String, String> configureEnvironment(Map<String, String> environment);
//
// /**
// * Creates a new, mutable environment variable map with the display variable set.
// * @return the new environment map
// * @see #configureEnvironment(Map)
// */
// @SuppressWarnings("unused")
// Map<String, String> newEnvironment();
//
// /**
// * Captures a screenshot of the virtual framebuffer.
// * @return the screenshot
// * @throws XvfbException if screenshooting goes awry
// */
// Screenshooter<?> getScreenshooter() throws XvfbException;
//
// /**
// * Class representing information about a window rendered by an X server.
// */
// class XWindow {
//
// /**
// * Window ID. This is commonly an integer in hexadecimal format, for example {@code 0x38ab0e}.
// */
// public final String id;
//
// /**
// * Window title. Null means the window has no title. The title may also
// * be empty, though that is not common.
// */
// public final @Nullable String title;
//
// /**
// * The line of output from which this window instance was parsed. This is a
// * line from {@code }
// */
// public final String line;
//
// /**
// * Constructs a new instance of the class.
// * @param id window id
// * @param title window title
// * @param line line of output from which this window information was parsed
// */
// public XWindow(String id, @Nullable String title, String line) {
// this.id = id;
// this.title = title;
// this.line = line;
// }
//
// @Override
// public String toString() {
// return "XWindow{" +
// "id=" + id +
// ", title='" + title + '\'' +
// ", length=" + (line == null ? -1 : line.length()) +
// '}';
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// XWindow xWindow = (XWindow) o;
//
// if (id != null ? !id.equals(xWindow.id) : xWindow.id != null) return false;
// if (title != null ? !title.equals(xWindow.title) : xWindow.title != null) return false;
// return line != null ? line.equals(xWindow.line) : xWindow.line == null;
// }
//
// @Override
// public int hashCode() {
// int result = id != null ? id.hashCode() : 0;
// result = 31 * result + (title != null ? title.hashCode() : 0);
// result = 31 * result + (line != null ? line.hashCode() : 0);
// return result;
// }
// }
//
// Optional<TreeNode<XWindow>> pollForWindow(Predicate<XWindow> windowFinder, long intervalMs, int maxPollAttempts) throws InterruptedException;
//
// }
| import com.github.mike10004.xvfbmanager.XvfbController;
import javax.annotation.Nullable;
import static com.google.common.base.Preconditions.checkNotNull; | package com.github.mike10004.xvfbtesting;
abstract class RuleUser {
private final XvfbRule xvfb;
public RuleUser(@Nullable Integer displayNumber) {
this(buildDefaultRule(displayNumber));
}
private static XvfbRule buildDefaultRule(@Nullable Integer displayNumber) {
if (displayNumber == null) {
return new XvfbRule();
} else {
return XvfbRule.builder().onDisplay(displayNumber.intValue()).build();
}
}
public RuleUser(XvfbRule xvfb) {
this.xvfb = checkNotNull(xvfb);
}
| // Path: xvfb-manager/src/main/java/com/github/mike10004/xvfbmanager/XvfbController.java
// public interface XvfbController extends Closeable {
//
// String ENV_DISPLAY = "DISPLAY";
//
// /**
// * Waits until the display is ready, using default values for the polling
// * interval and maximum polls. Implementations may select the defaults
// * to use.
// * @throws InterruptedException if waiting is interrupted
// * @see #waitUntilReady(long, int)
// */
// void waitUntilReady() throws InterruptedException;
//
// /**
// * Waits until the X display is ready, polling at a given interval until the
// * display is ready or the given number of polls has been executed.
// * @param pollIntervalMs interval between polls in milliseconds
// * @param maxNumPolls maximum number of polls to execute
// * @throws InterruptedException if waiting is interrupted
// */
// void waitUntilReady(long pollIntervalMs, int maxNumPolls) throws InterruptedException;
//
// /**
// * Stops the virtual framebuffer process.
// */
// void stop();
//
// /**
// * Gets the display number in the format {@code :N} where {@code N} is the display number.
// * @return the display
// */
// String getDisplay();
//
// /**
// * Sets the display environment variable in the given environment.
// * @param environment map of environment variables in which display is to be set
// * @return the argument environment object
// * @see #ENV_DISPLAY
// */
// Map<String, String> configureEnvironment(Map<String, String> environment);
//
// /**
// * Creates a new, mutable environment variable map with the display variable set.
// * @return the new environment map
// * @see #configureEnvironment(Map)
// */
// @SuppressWarnings("unused")
// Map<String, String> newEnvironment();
//
// /**
// * Captures a screenshot of the virtual framebuffer.
// * @return the screenshot
// * @throws XvfbException if screenshooting goes awry
// */
// Screenshooter<?> getScreenshooter() throws XvfbException;
//
// /**
// * Class representing information about a window rendered by an X server.
// */
// class XWindow {
//
// /**
// * Window ID. This is commonly an integer in hexadecimal format, for example {@code 0x38ab0e}.
// */
// public final String id;
//
// /**
// * Window title. Null means the window has no title. The title may also
// * be empty, though that is not common.
// */
// public final @Nullable String title;
//
// /**
// * The line of output from which this window instance was parsed. This is a
// * line from {@code }
// */
// public final String line;
//
// /**
// * Constructs a new instance of the class.
// * @param id window id
// * @param title window title
// * @param line line of output from which this window information was parsed
// */
// public XWindow(String id, @Nullable String title, String line) {
// this.id = id;
// this.title = title;
// this.line = line;
// }
//
// @Override
// public String toString() {
// return "XWindow{" +
// "id=" + id +
// ", title='" + title + '\'' +
// ", length=" + (line == null ? -1 : line.length()) +
// '}';
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// XWindow xWindow = (XWindow) o;
//
// if (id != null ? !id.equals(xWindow.id) : xWindow.id != null) return false;
// if (title != null ? !title.equals(xWindow.title) : xWindow.title != null) return false;
// return line != null ? line.equals(xWindow.line) : xWindow.line == null;
// }
//
// @Override
// public int hashCode() {
// int result = id != null ? id.hashCode() : 0;
// result = 31 * result + (title != null ? title.hashCode() : 0);
// result = 31 * result + (line != null ? line.hashCode() : 0);
// return result;
// }
// }
//
// Optional<TreeNode<XWindow>> pollForWindow(Predicate<XWindow> windowFinder, long intervalMs, int maxPollAttempts) throws InterruptedException;
//
// }
// Path: xvfb-testing/src/test/java/com/github/mike10004/xvfbtesting/RuleUser.java
import com.github.mike10004.xvfbmanager.XvfbController;
import javax.annotation.Nullable;
import static com.google.common.base.Preconditions.checkNotNull;
package com.github.mike10004.xvfbtesting;
abstract class RuleUser {
private final XvfbRule xvfb;
public RuleUser(@Nullable Integer displayNumber) {
this(buildDefaultRule(displayNumber));
}
private static XvfbRule buildDefaultRule(@Nullable Integer displayNumber) {
if (displayNumber == null) {
return new XvfbRule();
} else {
return XvfbRule.builder().onDisplay(displayNumber.intValue()).build();
}
}
public RuleUser(XvfbRule xvfb) {
this.xvfb = checkNotNull(xvfb);
}
| protected abstract void use(XvfbController ctrl) throws Exception; |
mike10004/xvfb-manager-java | xvfb-testing/src/test/java/com/github/mike10004/xvfbtesting/EagerNoInvocationTest.java | // Path: xvfb-testing/src/test/java/com/github/mike10004/xvfbtesting/LazyRuleTest.java
// static class ControllerCreationCountingManager extends XvfbManager {
// public final AtomicInteger controllerCreationCounter;
//
// public ControllerCreationCountingManager(AtomicInteger controllerCreationCounter) {
// this.controllerCreationCounter = controllerCreationCounter;
// }
//
// @Override
// protected DefaultXvfbController createController(ProcessMonitor<File, File> future, String display, File framebufferDir) {
// controllerCreationCounter.incrementAndGet();
// return super.createController(future, display, framebufferDir);
// }
// }
| import com.github.mike10004.xvfbtesting.LazyRuleTest.ControllerCreationCountingManager;
import org.junit.After;
import org.junit.ClassRule;
import org.junit.Rule;
import org.junit.Test;
import java.util.concurrent.atomic.AtomicInteger;
import static org.junit.Assert.assertEquals; | package com.github.mike10004.xvfbtesting;
public class EagerNoInvocationTest {
private final AtomicInteger creationCalls = new AtomicInteger();
@ClassRule
public static PlatformRule platformRule = PlatformRule.requireNotWindows();
@Rule
public final XvfbRule rule = XvfbRule.builder() | // Path: xvfb-testing/src/test/java/com/github/mike10004/xvfbtesting/LazyRuleTest.java
// static class ControllerCreationCountingManager extends XvfbManager {
// public final AtomicInteger controllerCreationCounter;
//
// public ControllerCreationCountingManager(AtomicInteger controllerCreationCounter) {
// this.controllerCreationCounter = controllerCreationCounter;
// }
//
// @Override
// protected DefaultXvfbController createController(ProcessMonitor<File, File> future, String display, File framebufferDir) {
// controllerCreationCounter.incrementAndGet();
// return super.createController(future, display, framebufferDir);
// }
// }
// Path: xvfb-testing/src/test/java/com/github/mike10004/xvfbtesting/EagerNoInvocationTest.java
import com.github.mike10004.xvfbtesting.LazyRuleTest.ControllerCreationCountingManager;
import org.junit.After;
import org.junit.ClassRule;
import org.junit.Rule;
import org.junit.Test;
import java.util.concurrent.atomic.AtomicInteger;
import static org.junit.Assert.assertEquals;
package com.github.mike10004.xvfbtesting;
public class EagerNoInvocationTest {
private final AtomicInteger creationCalls = new AtomicInteger();
@ClassRule
public static PlatformRule platformRule = PlatformRule.requireNotWindows();
@Rule
public final XvfbRule rule = XvfbRule.builder() | .manager(new ControllerCreationCountingManager(creationCalls)) |
mike10004/xvfb-manager-java | xvfb-testing/src/test/java/com/github/mike10004/xvfbtesting/XvfbRule_WindowsTest.java | // Path: xvfb-manager/src/main/java/com/github/mike10004/xvfbmanager/XvfbController.java
// public interface XvfbController extends Closeable {
//
// String ENV_DISPLAY = "DISPLAY";
//
// /**
// * Waits until the display is ready, using default values for the polling
// * interval and maximum polls. Implementations may select the defaults
// * to use.
// * @throws InterruptedException if waiting is interrupted
// * @see #waitUntilReady(long, int)
// */
// void waitUntilReady() throws InterruptedException;
//
// /**
// * Waits until the X display is ready, polling at a given interval until the
// * display is ready or the given number of polls has been executed.
// * @param pollIntervalMs interval between polls in milliseconds
// * @param maxNumPolls maximum number of polls to execute
// * @throws InterruptedException if waiting is interrupted
// */
// void waitUntilReady(long pollIntervalMs, int maxNumPolls) throws InterruptedException;
//
// /**
// * Stops the virtual framebuffer process.
// */
// void stop();
//
// /**
// * Gets the display number in the format {@code :N} where {@code N} is the display number.
// * @return the display
// */
// String getDisplay();
//
// /**
// * Sets the display environment variable in the given environment.
// * @param environment map of environment variables in which display is to be set
// * @return the argument environment object
// * @see #ENV_DISPLAY
// */
// Map<String, String> configureEnvironment(Map<String, String> environment);
//
// /**
// * Creates a new, mutable environment variable map with the display variable set.
// * @return the new environment map
// * @see #configureEnvironment(Map)
// */
// @SuppressWarnings("unused")
// Map<String, String> newEnvironment();
//
// /**
// * Captures a screenshot of the virtual framebuffer.
// * @return the screenshot
// * @throws XvfbException if screenshooting goes awry
// */
// Screenshooter<?> getScreenshooter() throws XvfbException;
//
// /**
// * Class representing information about a window rendered by an X server.
// */
// class XWindow {
//
// /**
// * Window ID. This is commonly an integer in hexadecimal format, for example {@code 0x38ab0e}.
// */
// public final String id;
//
// /**
// * Window title. Null means the window has no title. The title may also
// * be empty, though that is not common.
// */
// public final @Nullable String title;
//
// /**
// * The line of output from which this window instance was parsed. This is a
// * line from {@code }
// */
// public final String line;
//
// /**
// * Constructs a new instance of the class.
// * @param id window id
// * @param title window title
// * @param line line of output from which this window information was parsed
// */
// public XWindow(String id, @Nullable String title, String line) {
// this.id = id;
// this.title = title;
// this.line = line;
// }
//
// @Override
// public String toString() {
// return "XWindow{" +
// "id=" + id +
// ", title='" + title + '\'' +
// ", length=" + (line == null ? -1 : line.length()) +
// '}';
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// XWindow xWindow = (XWindow) o;
//
// if (id != null ? !id.equals(xWindow.id) : xWindow.id != null) return false;
// if (title != null ? !title.equals(xWindow.title) : xWindow.title != null) return false;
// return line != null ? line.equals(xWindow.line) : xWindow.line == null;
// }
//
// @Override
// public int hashCode() {
// int result = id != null ? id.hashCode() : 0;
// result = 31 * result + (title != null ? title.hashCode() : 0);
// result = 31 * result + (line != null ? line.hashCode() : 0);
// return result;
// }
// }
//
// Optional<TreeNode<XWindow>> pollForWindow(Predicate<XWindow> windowFinder, long intervalMs, int maxPollAttempts) throws InterruptedException;
//
// }
| import com.github.mike10004.nativehelper.Platforms;
import com.github.mike10004.xvfbmanager.XvfbController;
import com.google.common.base.Suppliers;
import org.junit.Assume;
import org.junit.BeforeClass;
import org.junit.ClassRule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import java.util.Arrays;
import java.util.List;
import static org.junit.Assert.*; | package com.github.mike10004.xvfbtesting;
@RunWith(Parameterized.class)
public class XvfbRule_WindowsTest {
private final XvfbRule rule;
public XvfbRule_WindowsTest(XvfbRule rule) {
this.rule = rule;
}
@ClassRule
public static PlatformRule platformRule = PlatformRule.requireWindows();
@Parameterized.Parameters
public static List<XvfbRule> rules() {
return Arrays.asList(
XvfbRule.builder().build(),
XvfbRule.builder().eager().build(),
XvfbRule.builder().disabled().build(),
XvfbRule.builder().disabled(true).build(),
XvfbRule.builder().disabled(Suppliers.ofInstance(true)).build(),
XvfbRule.builder().eager().disabled().build(),
XvfbRule.builder().eager().disabled(true).build(),
XvfbRule.builder().eager().disabled(Suppliers.ofInstance(true)).build(),
XvfbRule.builder().notDisabledOnWindows().disabled(true).build(),
XvfbRule.builder().notDisabledOnWindows().disabled(Suppliers.ofInstance(true)).build()
);
}
@Test
public void testDisablingOnWindows() throws Exception {
System.out.format("rule = %s%n", rule);
new RuleUser(rule) {
@Override | // Path: xvfb-manager/src/main/java/com/github/mike10004/xvfbmanager/XvfbController.java
// public interface XvfbController extends Closeable {
//
// String ENV_DISPLAY = "DISPLAY";
//
// /**
// * Waits until the display is ready, using default values for the polling
// * interval and maximum polls. Implementations may select the defaults
// * to use.
// * @throws InterruptedException if waiting is interrupted
// * @see #waitUntilReady(long, int)
// */
// void waitUntilReady() throws InterruptedException;
//
// /**
// * Waits until the X display is ready, polling at a given interval until the
// * display is ready or the given number of polls has been executed.
// * @param pollIntervalMs interval between polls in milliseconds
// * @param maxNumPolls maximum number of polls to execute
// * @throws InterruptedException if waiting is interrupted
// */
// void waitUntilReady(long pollIntervalMs, int maxNumPolls) throws InterruptedException;
//
// /**
// * Stops the virtual framebuffer process.
// */
// void stop();
//
// /**
// * Gets the display number in the format {@code :N} where {@code N} is the display number.
// * @return the display
// */
// String getDisplay();
//
// /**
// * Sets the display environment variable in the given environment.
// * @param environment map of environment variables in which display is to be set
// * @return the argument environment object
// * @see #ENV_DISPLAY
// */
// Map<String, String> configureEnvironment(Map<String, String> environment);
//
// /**
// * Creates a new, mutable environment variable map with the display variable set.
// * @return the new environment map
// * @see #configureEnvironment(Map)
// */
// @SuppressWarnings("unused")
// Map<String, String> newEnvironment();
//
// /**
// * Captures a screenshot of the virtual framebuffer.
// * @return the screenshot
// * @throws XvfbException if screenshooting goes awry
// */
// Screenshooter<?> getScreenshooter() throws XvfbException;
//
// /**
// * Class representing information about a window rendered by an X server.
// */
// class XWindow {
//
// /**
// * Window ID. This is commonly an integer in hexadecimal format, for example {@code 0x38ab0e}.
// */
// public final String id;
//
// /**
// * Window title. Null means the window has no title. The title may also
// * be empty, though that is not common.
// */
// public final @Nullable String title;
//
// /**
// * The line of output from which this window instance was parsed. This is a
// * line from {@code }
// */
// public final String line;
//
// /**
// * Constructs a new instance of the class.
// * @param id window id
// * @param title window title
// * @param line line of output from which this window information was parsed
// */
// public XWindow(String id, @Nullable String title, String line) {
// this.id = id;
// this.title = title;
// this.line = line;
// }
//
// @Override
// public String toString() {
// return "XWindow{" +
// "id=" + id +
// ", title='" + title + '\'' +
// ", length=" + (line == null ? -1 : line.length()) +
// '}';
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// XWindow xWindow = (XWindow) o;
//
// if (id != null ? !id.equals(xWindow.id) : xWindow.id != null) return false;
// if (title != null ? !title.equals(xWindow.title) : xWindow.title != null) return false;
// return line != null ? line.equals(xWindow.line) : xWindow.line == null;
// }
//
// @Override
// public int hashCode() {
// int result = id != null ? id.hashCode() : 0;
// result = 31 * result + (title != null ? title.hashCode() : 0);
// result = 31 * result + (line != null ? line.hashCode() : 0);
// return result;
// }
// }
//
// Optional<TreeNode<XWindow>> pollForWindow(Predicate<XWindow> windowFinder, long intervalMs, int maxPollAttempts) throws InterruptedException;
//
// }
// Path: xvfb-testing/src/test/java/com/github/mike10004/xvfbtesting/XvfbRule_WindowsTest.java
import com.github.mike10004.nativehelper.Platforms;
import com.github.mike10004.xvfbmanager.XvfbController;
import com.google.common.base.Suppliers;
import org.junit.Assume;
import org.junit.BeforeClass;
import org.junit.ClassRule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import java.util.Arrays;
import java.util.List;
import static org.junit.Assert.*;
package com.github.mike10004.xvfbtesting;
@RunWith(Parameterized.class)
public class XvfbRule_WindowsTest {
private final XvfbRule rule;
public XvfbRule_WindowsTest(XvfbRule rule) {
this.rule = rule;
}
@ClassRule
public static PlatformRule platformRule = PlatformRule.requireWindows();
@Parameterized.Parameters
public static List<XvfbRule> rules() {
return Arrays.asList(
XvfbRule.builder().build(),
XvfbRule.builder().eager().build(),
XvfbRule.builder().disabled().build(),
XvfbRule.builder().disabled(true).build(),
XvfbRule.builder().disabled(Suppliers.ofInstance(true)).build(),
XvfbRule.builder().eager().disabled().build(),
XvfbRule.builder().eager().disabled(true).build(),
XvfbRule.builder().eager().disabled(Suppliers.ofInstance(true)).build(),
XvfbRule.builder().notDisabledOnWindows().disabled(true).build(),
XvfbRule.builder().notDisabledOnWindows().disabled(Suppliers.ofInstance(true)).build()
);
}
@Test
public void testDisablingOnWindows() throws Exception {
System.out.format("rule = %s%n", rule);
new RuleUser(rule) {
@Override | protected void use(XvfbController ctrl) throws Exception { |
mike10004/xvfb-manager-java | xvfb-manager/src/main/java/com/github/mike10004/xvfbmanager/XwdFileToPngConverter.java | // Path: xvfb-manager/src/main/java/com/github/mike10004/xvfbmanager/Screenshot.java
// class FileByteSource extends ByteSource {
//
// public final File file;
// private final ByteSource delegate;
//
// public FileByteSource(File file) {
// this(file, Files.asByteSource(file));
// }
//
// protected FileByteSource(File file, ByteSource delegate) {
// this.file = checkNotNull(file);
// this.delegate = checkNotNull(delegate);
// }
//
// @Override
// public CharSource asCharSource(Charset charset) {
// return delegate.asCharSource(charset);
// }
//
// @Override
// public InputStream openStream() throws IOException {
// return delegate.openStream();
// }
//
// @Override
// public InputStream openBufferedStream() throws IOException {
// return delegate.openBufferedStream();
// }
//
// @Override
// public ByteSource slice(long offset, long length) {
// return delegate.slice(offset, length);
// }
//
// @Override
// public boolean isEmpty() throws IOException {
// return delegate.isEmpty();
// }
//
// @SuppressWarnings("Guava")
// @Override
// @Beta
// public com.google.common.base.Optional<Long> sizeIfKnown() {
// return delegate.sizeIfKnown();
// }
//
// @Override
// public long size() throws IOException {
// return delegate.size();
// }
//
// @Override
// public long copyTo(OutputStream output) throws IOException {
// return delegate.copyTo(output);
// }
//
// @Override
// public long copyTo(ByteSink sink) throws IOException {
// return delegate.copyTo(sink);
// }
//
// @Override
// public byte[] read() throws IOException {
// return delegate.read();
// }
//
// @Override
// @Beta
// public <T> T read(ByteProcessor<T> processor) throws IOException {
// return delegate.read(processor);
// }
//
// @Override
// public HashCode hash(HashFunction hashFunction) throws IOException {
// return delegate.hash(hashFunction);
// }
//
// @Override
// public boolean contentEquals(ByteSource other) throws IOException {
// return delegate.contentEquals(other);
// }
// }
| import io.github.mike10004.subprocess.ProcessMonitor;
import io.github.mike10004.subprocess.ProcessResult;
import io.github.mike10004.subprocess.ProcessTracker;
import io.github.mike10004.subprocess.Subprocess;
import com.github.mike10004.xvfbmanager.Screenshot.FileByteSource;
import com.google.common.collect.ImmutableSet;
import com.google.common.io.ByteSource;
import com.google.common.io.Files;
import org.apache.commons.io.output.ByteArrayOutputStream;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.nio.file.Path;
import java.util.concurrent.TimeUnit;
import static com.google.common.base.Preconditions.checkNotNull;
import static java.util.Objects.requireNonNull; | this.processTracker = requireNonNull(processTracker);
}
@Override
public ImageioReadableScreenshot convert(Screenshot source) throws IOException, XvfbException {
File pnmFile = File.createTempFile("xwdtopnm-stdout", ".ppm", tempDir.toFile());
try {
return convert(source, pnmFile);
} finally {
if (!pnmFile.delete()) {
log.info("failed to delete {}", pnmFile);
}
}
}
protected ImageioReadableScreenshot convert(Screenshot source, File pnmFile) throws IOException, XvfbException {
File stderrFile = File.createTempFile("xwdtopnm-stderr", ".txt", tempDir.toFile());
try {
return convert(source, pnmFile, stderrFile);
} finally {
if (!stderrFile.delete()) {
log.info("failed to delete {}", stderrFile);
}
}
}
public ImageioReadableScreenshot convert(Screenshot source, File pnmFile, File stderrFile) throws IOException, XvfbException {
final File inputFile;
final boolean deleteInputFile;
ByteSource inputSource = source.asByteSource(); | // Path: xvfb-manager/src/main/java/com/github/mike10004/xvfbmanager/Screenshot.java
// class FileByteSource extends ByteSource {
//
// public final File file;
// private final ByteSource delegate;
//
// public FileByteSource(File file) {
// this(file, Files.asByteSource(file));
// }
//
// protected FileByteSource(File file, ByteSource delegate) {
// this.file = checkNotNull(file);
// this.delegate = checkNotNull(delegate);
// }
//
// @Override
// public CharSource asCharSource(Charset charset) {
// return delegate.asCharSource(charset);
// }
//
// @Override
// public InputStream openStream() throws IOException {
// return delegate.openStream();
// }
//
// @Override
// public InputStream openBufferedStream() throws IOException {
// return delegate.openBufferedStream();
// }
//
// @Override
// public ByteSource slice(long offset, long length) {
// return delegate.slice(offset, length);
// }
//
// @Override
// public boolean isEmpty() throws IOException {
// return delegate.isEmpty();
// }
//
// @SuppressWarnings("Guava")
// @Override
// @Beta
// public com.google.common.base.Optional<Long> sizeIfKnown() {
// return delegate.sizeIfKnown();
// }
//
// @Override
// public long size() throws IOException {
// return delegate.size();
// }
//
// @Override
// public long copyTo(OutputStream output) throws IOException {
// return delegate.copyTo(output);
// }
//
// @Override
// public long copyTo(ByteSink sink) throws IOException {
// return delegate.copyTo(sink);
// }
//
// @Override
// public byte[] read() throws IOException {
// return delegate.read();
// }
//
// @Override
// @Beta
// public <T> T read(ByteProcessor<T> processor) throws IOException {
// return delegate.read(processor);
// }
//
// @Override
// public HashCode hash(HashFunction hashFunction) throws IOException {
// return delegate.hash(hashFunction);
// }
//
// @Override
// public boolean contentEquals(ByteSource other) throws IOException {
// return delegate.contentEquals(other);
// }
// }
// Path: xvfb-manager/src/main/java/com/github/mike10004/xvfbmanager/XwdFileToPngConverter.java
import io.github.mike10004.subprocess.ProcessMonitor;
import io.github.mike10004.subprocess.ProcessResult;
import io.github.mike10004.subprocess.ProcessTracker;
import io.github.mike10004.subprocess.Subprocess;
import com.github.mike10004.xvfbmanager.Screenshot.FileByteSource;
import com.google.common.collect.ImmutableSet;
import com.google.common.io.ByteSource;
import com.google.common.io.Files;
import org.apache.commons.io.output.ByteArrayOutputStream;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.nio.file.Path;
import java.util.concurrent.TimeUnit;
import static com.google.common.base.Preconditions.checkNotNull;
import static java.util.Objects.requireNonNull;
this.processTracker = requireNonNull(processTracker);
}
@Override
public ImageioReadableScreenshot convert(Screenshot source) throws IOException, XvfbException {
File pnmFile = File.createTempFile("xwdtopnm-stdout", ".ppm", tempDir.toFile());
try {
return convert(source, pnmFile);
} finally {
if (!pnmFile.delete()) {
log.info("failed to delete {}", pnmFile);
}
}
}
protected ImageioReadableScreenshot convert(Screenshot source, File pnmFile) throws IOException, XvfbException {
File stderrFile = File.createTempFile("xwdtopnm-stderr", ".txt", tempDir.toFile());
try {
return convert(source, pnmFile, stderrFile);
} finally {
if (!stderrFile.delete()) {
log.info("failed to delete {}", stderrFile);
}
}
}
public ImageioReadableScreenshot convert(Screenshot source, File pnmFile, File stderrFile) throws IOException, XvfbException {
final File inputFile;
final boolean deleteInputFile;
ByteSource inputSource = source.asByteSource(); | if (inputSource instanceof FileByteSource) { |
mike10004/xvfb-manager-java | xvfb-testing/src/test/java/com/github/mike10004/xvfbtesting/LazyNoInvocationTest.java | // Path: xvfb-testing/src/test/java/com/github/mike10004/xvfbtesting/LazyRuleTest.java
// static class ControllerCreationCountingManager extends XvfbManager {
// public final AtomicInteger controllerCreationCounter;
//
// public ControllerCreationCountingManager(AtomicInteger controllerCreationCounter) {
// this.controllerCreationCounter = controllerCreationCounter;
// }
//
// @Override
// protected DefaultXvfbController createController(ProcessMonitor<File, File> future, String display, File framebufferDir) {
// controllerCreationCounter.incrementAndGet();
// return super.createController(future, display, framebufferDir);
// }
// }
| import com.github.mike10004.xvfbtesting.LazyRuleTest.ControllerCreationCountingManager;
import org.junit.After;
import org.junit.Rule;
import org.junit.Test;
import java.util.concurrent.atomic.AtomicInteger;
import static org.junit.Assert.assertEquals; | package com.github.mike10004.xvfbtesting;
/**
* Unit test that runs on all platforms. A lazy rule is created but {@link XvfbRule#getController()} is never
* invoked, so no attempt to execute an Xvfb process should be made.
*/
public class LazyNoInvocationTest {
private final AtomicInteger creationCalls = new AtomicInteger();
@Rule
public final XvfbRule rule = XvfbRule.builder() | // Path: xvfb-testing/src/test/java/com/github/mike10004/xvfbtesting/LazyRuleTest.java
// static class ControllerCreationCountingManager extends XvfbManager {
// public final AtomicInteger controllerCreationCounter;
//
// public ControllerCreationCountingManager(AtomicInteger controllerCreationCounter) {
// this.controllerCreationCounter = controllerCreationCounter;
// }
//
// @Override
// protected DefaultXvfbController createController(ProcessMonitor<File, File> future, String display, File framebufferDir) {
// controllerCreationCounter.incrementAndGet();
// return super.createController(future, display, framebufferDir);
// }
// }
// Path: xvfb-testing/src/test/java/com/github/mike10004/xvfbtesting/LazyNoInvocationTest.java
import com.github.mike10004.xvfbtesting.LazyRuleTest.ControllerCreationCountingManager;
import org.junit.After;
import org.junit.Rule;
import org.junit.Test;
import java.util.concurrent.atomic.AtomicInteger;
import static org.junit.Assert.assertEquals;
package com.github.mike10004.xvfbtesting;
/**
* Unit test that runs on all platforms. A lazy rule is created but {@link XvfbRule#getController()} is never
* invoked, so no attempt to execute an Xvfb process should be made.
*/
public class LazyNoInvocationTest {
private final AtomicInteger creationCalls = new AtomicInteger();
@Rule
public final XvfbRule rule = XvfbRule.builder() | .manager(new ControllerCreationCountingManager(creationCalls)) |
mike10004/xvfb-manager-java | xvfb-manager/src/main/java/com/github/mike10004/xvfbmanager/Poller.java | // Path: xvfb-manager/src/main/java/com/github/mike10004/xvfbmanager/Sleeper.java
// class DefaultSleeper implements Sleeper {
//
// private DefaultSleeper() {
// }
//
// private static final DefaultSleeper instance = new DefaultSleeper();
//
// /**
// * Gets the singleton instance of this class.
// * @return the singleton
// */
// public static DefaultSleeper getInstance() {
// return instance;
// }
//
// @Override
// public void sleep(long millis) throws InterruptedException {
// Thread.sleep(millis);
// }
// }
| import com.github.mike10004.xvfbmanager.Sleeper.DefaultSleeper;
import javax.annotation.Nullable;
import java.time.Duration;
import java.time.temporal.ChronoUnit;
import java.util.Iterator;
import java.util.function.Supplier;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull; | package com.github.mike10004.xvfbmanager;
/**
* Class that facilitates polling for an arbitrary condition. Polling is
* the act of repeatedly querying the state at defined intervals. Polling
* stops when this poller's {@link #check(int) evaluation function}
* answers with a reason to stop, or the iterator of intervals to wait
* between polls is exhausted. Reasons to stop include
* {@link PollAction#RESOLVE resolution}, meaning the poller is satisfied
* with the result, or {@link PollAction#ABORT abortion} meaning polling
* must stop early without a resolution.
*
* @param <T> type of content returned upon resolution
*/
public abstract class Poller<T> {
private final Sleeper sleeper;
/**
* Creates a new poller. The poller waits between polls using the
* default {@link Sleeper}. Subclasses can use an alternate sleeper,
* is helpful if you want to test your poller without actually waiting.
*/
public Poller() { | // Path: xvfb-manager/src/main/java/com/github/mike10004/xvfbmanager/Sleeper.java
// class DefaultSleeper implements Sleeper {
//
// private DefaultSleeper() {
// }
//
// private static final DefaultSleeper instance = new DefaultSleeper();
//
// /**
// * Gets the singleton instance of this class.
// * @return the singleton
// */
// public static DefaultSleeper getInstance() {
// return instance;
// }
//
// @Override
// public void sleep(long millis) throws InterruptedException {
// Thread.sleep(millis);
// }
// }
// Path: xvfb-manager/src/main/java/com/github/mike10004/xvfbmanager/Poller.java
import com.github.mike10004.xvfbmanager.Sleeper.DefaultSleeper;
import javax.annotation.Nullable;
import java.time.Duration;
import java.time.temporal.ChronoUnit;
import java.util.Iterator;
import java.util.function.Supplier;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
package com.github.mike10004.xvfbmanager;
/**
* Class that facilitates polling for an arbitrary condition. Polling is
* the act of repeatedly querying the state at defined intervals. Polling
* stops when this poller's {@link #check(int) evaluation function}
* answers with a reason to stop, or the iterator of intervals to wait
* between polls is exhausted. Reasons to stop include
* {@link PollAction#RESOLVE resolution}, meaning the poller is satisfied
* with the result, or {@link PollAction#ABORT abortion} meaning polling
* must stop early without a resolution.
*
* @param <T> type of content returned upon resolution
*/
public abstract class Poller<T> {
private final Sleeper sleeper;
/**
* Creates a new poller. The poller waits between polls using the
* default {@link Sleeper}. Subclasses can use an alternate sleeper,
* is helpful if you want to test your poller without actually waiting.
*/
public Poller() { | this(DefaultSleeper.getInstance()); |
mike10004/xvfb-manager-java | xvfb-manager/src/main/java/com/github/mike10004/xvfbmanager/PollingXLockFileChecker.java | // Path: xvfb-manager/src/main/java/com/github/mike10004/xvfbmanager/Poller.java
// public static class PollOutcome<E> {
//
// /**
// * Reason polling stopped.
// */
// public final StopReason reason;
//
// /**
// * An object that represents the resolved state of the poll.
// */
// public final @Nullable E content;
//
// /**
// * Gets the polling duration. This may not be exact.
// */
// public final Duration duration;
//
// private final int numAttempts;
//
// private PollOutcome(StopReason reason, @Nullable E content, Duration duration, int numAttempts) {
// this.reason = checkNotNull(reason);
// this.content = content;
// this.duration = checkNotNull(duration);
// this.numAttempts = numAttempts;
// }
//
// @Override
// public String toString() {
// return "PollOutcome{" +
// "reason=" + reason +
// ", content=" + content +
// ", duration=" + duration +
// ", attempts=" + numAttempts +
// '}';
// }
//
// /**
// * Gets the number of times the poll was attempted. This is the numbef of
// * times the {@link #check(int) check()} function is invoked.
// * @return count of attempts
// */
// public int getNumAttempts() {
// return numAttempts;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// PollOutcome<?> that = (PollOutcome<?>) o;
//
// if (numAttempts != that.numAttempts) return false;
// if (reason != that.reason) return false;
// if (content != null ? !content.equals(that.content) : that.content != null) return false;
// return duration.equals(that.duration);
// }
//
// @Override
// public int hashCode() {
// int result = reason.hashCode();
// result = 31 * result + (content != null ? content.hashCode() : 0);
// result = 31 * result + duration.hashCode();
// result = 31 * result + numAttempts;
// return result;
// }
// }
//
// Path: xvfb-manager/src/main/java/com/github/mike10004/xvfbmanager/Poller.java
// public enum StopReason {
//
// /**
// * State was resolved to the poller's satisfaction.
// */
// RESOLVED,
//
// /**
// * State was not resolved to the poller's satisfaction,
// * but polling must cease anyway.
// */
// ABORTED,
//
// /**
// * The poller's iterator of intervals was exhausted
// * prior to resolution or abortion of polling.
// */
// TIMEOUT
// }
| import com.github.mike10004.xvfbmanager.Poller.PollOutcome;
import com.github.mike10004.xvfbmanager.Poller.StopReason;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.primitives.Ints;
import java.io.File;
import java.io.IOException;
import static com.google.common.base.Preconditions.checkNotNull; | /*
* (c) 2016 Novetta
*
* Created by mike
*/
package com.github.mike10004.xvfbmanager;
public class PollingXLockFileChecker implements DefaultXvfbController.XLockFileChecker {
private final long pollIntervalMs;
private final Sleeper sleeper;
private final XLockFileUtility lockFileUtility;
public PollingXLockFileChecker(long pollIntervalMs, Sleeper sleeper) {
this(pollIntervalMs, sleeper, XLockFileUtility.getInstance());
}
@VisibleForTesting
PollingXLockFileChecker(long pollIntervalMs, Sleeper sleeper, XLockFileUtility lockFileUtility) {
this.pollIntervalMs = pollIntervalMs;
this.sleeper = sleeper;
this.lockFileUtility = checkNotNull(lockFileUtility);
}
@Override
public void waitForCleanup(String display, long timeoutMs) throws LockFileCheckingException {
File lockFile;
try {
lockFile = lockFileUtility.constructLockFilePathname(display);
} catch (IOException e) {
throw new LockFileCheckingException(e);
}
int maxNumPolls = Ints.checkedCast(Math.round(Math.ceil((float) timeoutMs / (float) pollIntervalMs)));
long startTime = System.currentTimeMillis(); | // Path: xvfb-manager/src/main/java/com/github/mike10004/xvfbmanager/Poller.java
// public static class PollOutcome<E> {
//
// /**
// * Reason polling stopped.
// */
// public final StopReason reason;
//
// /**
// * An object that represents the resolved state of the poll.
// */
// public final @Nullable E content;
//
// /**
// * Gets the polling duration. This may not be exact.
// */
// public final Duration duration;
//
// private final int numAttempts;
//
// private PollOutcome(StopReason reason, @Nullable E content, Duration duration, int numAttempts) {
// this.reason = checkNotNull(reason);
// this.content = content;
// this.duration = checkNotNull(duration);
// this.numAttempts = numAttempts;
// }
//
// @Override
// public String toString() {
// return "PollOutcome{" +
// "reason=" + reason +
// ", content=" + content +
// ", duration=" + duration +
// ", attempts=" + numAttempts +
// '}';
// }
//
// /**
// * Gets the number of times the poll was attempted. This is the numbef of
// * times the {@link #check(int) check()} function is invoked.
// * @return count of attempts
// */
// public int getNumAttempts() {
// return numAttempts;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// PollOutcome<?> that = (PollOutcome<?>) o;
//
// if (numAttempts != that.numAttempts) return false;
// if (reason != that.reason) return false;
// if (content != null ? !content.equals(that.content) : that.content != null) return false;
// return duration.equals(that.duration);
// }
//
// @Override
// public int hashCode() {
// int result = reason.hashCode();
// result = 31 * result + (content != null ? content.hashCode() : 0);
// result = 31 * result + duration.hashCode();
// result = 31 * result + numAttempts;
// return result;
// }
// }
//
// Path: xvfb-manager/src/main/java/com/github/mike10004/xvfbmanager/Poller.java
// public enum StopReason {
//
// /**
// * State was resolved to the poller's satisfaction.
// */
// RESOLVED,
//
// /**
// * State was not resolved to the poller's satisfaction,
// * but polling must cease anyway.
// */
// ABORTED,
//
// /**
// * The poller's iterator of intervals was exhausted
// * prior to resolution or abortion of polling.
// */
// TIMEOUT
// }
// Path: xvfb-manager/src/main/java/com/github/mike10004/xvfbmanager/PollingXLockFileChecker.java
import com.github.mike10004.xvfbmanager.Poller.PollOutcome;
import com.github.mike10004.xvfbmanager.Poller.StopReason;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.primitives.Ints;
import java.io.File;
import java.io.IOException;
import static com.google.common.base.Preconditions.checkNotNull;
/*
* (c) 2016 Novetta
*
* Created by mike
*/
package com.github.mike10004.xvfbmanager;
public class PollingXLockFileChecker implements DefaultXvfbController.XLockFileChecker {
private final long pollIntervalMs;
private final Sleeper sleeper;
private final XLockFileUtility lockFileUtility;
public PollingXLockFileChecker(long pollIntervalMs, Sleeper sleeper) {
this(pollIntervalMs, sleeper, XLockFileUtility.getInstance());
}
@VisibleForTesting
PollingXLockFileChecker(long pollIntervalMs, Sleeper sleeper, XLockFileUtility lockFileUtility) {
this.pollIntervalMs = pollIntervalMs;
this.sleeper = sleeper;
this.lockFileUtility = checkNotNull(lockFileUtility);
}
@Override
public void waitForCleanup(String display, long timeoutMs) throws LockFileCheckingException {
File lockFile;
try {
lockFile = lockFileUtility.constructLockFilePathname(display);
} catch (IOException e) {
throw new LockFileCheckingException(e);
}
int maxNumPolls = Ints.checkedCast(Math.round(Math.ceil((float) timeoutMs / (float) pollIntervalMs)));
long startTime = System.currentTimeMillis(); | PollOutcome<?> pollOutcome; |
mike10004/xvfb-manager-java | xvfb-manager/src/main/java/com/github/mike10004/xvfbmanager/PollingXLockFileChecker.java | // Path: xvfb-manager/src/main/java/com/github/mike10004/xvfbmanager/Poller.java
// public static class PollOutcome<E> {
//
// /**
// * Reason polling stopped.
// */
// public final StopReason reason;
//
// /**
// * An object that represents the resolved state of the poll.
// */
// public final @Nullable E content;
//
// /**
// * Gets the polling duration. This may not be exact.
// */
// public final Duration duration;
//
// private final int numAttempts;
//
// private PollOutcome(StopReason reason, @Nullable E content, Duration duration, int numAttempts) {
// this.reason = checkNotNull(reason);
// this.content = content;
// this.duration = checkNotNull(duration);
// this.numAttempts = numAttempts;
// }
//
// @Override
// public String toString() {
// return "PollOutcome{" +
// "reason=" + reason +
// ", content=" + content +
// ", duration=" + duration +
// ", attempts=" + numAttempts +
// '}';
// }
//
// /**
// * Gets the number of times the poll was attempted. This is the numbef of
// * times the {@link #check(int) check()} function is invoked.
// * @return count of attempts
// */
// public int getNumAttempts() {
// return numAttempts;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// PollOutcome<?> that = (PollOutcome<?>) o;
//
// if (numAttempts != that.numAttempts) return false;
// if (reason != that.reason) return false;
// if (content != null ? !content.equals(that.content) : that.content != null) return false;
// return duration.equals(that.duration);
// }
//
// @Override
// public int hashCode() {
// int result = reason.hashCode();
// result = 31 * result + (content != null ? content.hashCode() : 0);
// result = 31 * result + duration.hashCode();
// result = 31 * result + numAttempts;
// return result;
// }
// }
//
// Path: xvfb-manager/src/main/java/com/github/mike10004/xvfbmanager/Poller.java
// public enum StopReason {
//
// /**
// * State was resolved to the poller's satisfaction.
// */
// RESOLVED,
//
// /**
// * State was not resolved to the poller's satisfaction,
// * but polling must cease anyway.
// */
// ABORTED,
//
// /**
// * The poller's iterator of intervals was exhausted
// * prior to resolution or abortion of polling.
// */
// TIMEOUT
// }
| import com.github.mike10004.xvfbmanager.Poller.PollOutcome;
import com.github.mike10004.xvfbmanager.Poller.StopReason;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.primitives.Ints;
import java.io.File;
import java.io.IOException;
import static com.google.common.base.Preconditions.checkNotNull; | this.pollIntervalMs = pollIntervalMs;
this.sleeper = sleeper;
this.lockFileUtility = checkNotNull(lockFileUtility);
}
@Override
public void waitForCleanup(String display, long timeoutMs) throws LockFileCheckingException {
File lockFile;
try {
lockFile = lockFileUtility.constructLockFilePathname(display);
} catch (IOException e) {
throw new LockFileCheckingException(e);
}
int maxNumPolls = Ints.checkedCast(Math.round(Math.ceil((float) timeoutMs / (float) pollIntervalMs)));
long startTime = System.currentTimeMillis();
PollOutcome<?> pollOutcome;
try {
pollOutcome = new Poller<Void>(sleeper) {
@Override
protected PollAnswer<Void> check(int pollAttemptsSoFar) {
long now = System.currentTimeMillis();
if (now - startTime > timeoutMs) {
return abortPolling();
}
return lockFile.exists() ? continuePolling() : resolve(null);
}
}.poll(pollIntervalMs, maxNumPolls);
} catch (InterruptedException e) {
throw new LockFileCheckingException(e);
} | // Path: xvfb-manager/src/main/java/com/github/mike10004/xvfbmanager/Poller.java
// public static class PollOutcome<E> {
//
// /**
// * Reason polling stopped.
// */
// public final StopReason reason;
//
// /**
// * An object that represents the resolved state of the poll.
// */
// public final @Nullable E content;
//
// /**
// * Gets the polling duration. This may not be exact.
// */
// public final Duration duration;
//
// private final int numAttempts;
//
// private PollOutcome(StopReason reason, @Nullable E content, Duration duration, int numAttempts) {
// this.reason = checkNotNull(reason);
// this.content = content;
// this.duration = checkNotNull(duration);
// this.numAttempts = numAttempts;
// }
//
// @Override
// public String toString() {
// return "PollOutcome{" +
// "reason=" + reason +
// ", content=" + content +
// ", duration=" + duration +
// ", attempts=" + numAttempts +
// '}';
// }
//
// /**
// * Gets the number of times the poll was attempted. This is the numbef of
// * times the {@link #check(int) check()} function is invoked.
// * @return count of attempts
// */
// public int getNumAttempts() {
// return numAttempts;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// PollOutcome<?> that = (PollOutcome<?>) o;
//
// if (numAttempts != that.numAttempts) return false;
// if (reason != that.reason) return false;
// if (content != null ? !content.equals(that.content) : that.content != null) return false;
// return duration.equals(that.duration);
// }
//
// @Override
// public int hashCode() {
// int result = reason.hashCode();
// result = 31 * result + (content != null ? content.hashCode() : 0);
// result = 31 * result + duration.hashCode();
// result = 31 * result + numAttempts;
// return result;
// }
// }
//
// Path: xvfb-manager/src/main/java/com/github/mike10004/xvfbmanager/Poller.java
// public enum StopReason {
//
// /**
// * State was resolved to the poller's satisfaction.
// */
// RESOLVED,
//
// /**
// * State was not resolved to the poller's satisfaction,
// * but polling must cease anyway.
// */
// ABORTED,
//
// /**
// * The poller's iterator of intervals was exhausted
// * prior to resolution or abortion of polling.
// */
// TIMEOUT
// }
// Path: xvfb-manager/src/main/java/com/github/mike10004/xvfbmanager/PollingXLockFileChecker.java
import com.github.mike10004.xvfbmanager.Poller.PollOutcome;
import com.github.mike10004.xvfbmanager.Poller.StopReason;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.primitives.Ints;
import java.io.File;
import java.io.IOException;
import static com.google.common.base.Preconditions.checkNotNull;
this.pollIntervalMs = pollIntervalMs;
this.sleeper = sleeper;
this.lockFileUtility = checkNotNull(lockFileUtility);
}
@Override
public void waitForCleanup(String display, long timeoutMs) throws LockFileCheckingException {
File lockFile;
try {
lockFile = lockFileUtility.constructLockFilePathname(display);
} catch (IOException e) {
throw new LockFileCheckingException(e);
}
int maxNumPolls = Ints.checkedCast(Math.round(Math.ceil((float) timeoutMs / (float) pollIntervalMs)));
long startTime = System.currentTimeMillis();
PollOutcome<?> pollOutcome;
try {
pollOutcome = new Poller<Void>(sleeper) {
@Override
protected PollAnswer<Void> check(int pollAttemptsSoFar) {
long now = System.currentTimeMillis();
if (now - startTime > timeoutMs) {
return abortPolling();
}
return lockFile.exists() ? continuePolling() : resolve(null);
}
}.poll(pollIntervalMs, maxNumPolls);
} catch (InterruptedException e) {
throw new LockFileCheckingException(e);
} | if (pollOutcome.reason == StopReason.ABORTED || pollOutcome.reason == StopReason.TIMEOUT) { |
mike10004/xvfb-manager-java | xvfb-unittest-help/src/test/java/com/github/mike10004/xvfbunittesthelp/FatalAssumerTest.java | // Path: xvfb-unittest-help/src/main/java/com/github/mike10004/xvfbunittesthelp/FatalAssumer.java
// static class AssumptionViolatedError extends Error {
//
// public AssumptionViolatedError() {
// }
//
// public AssumptionViolatedError(String message) {
// super(message);
// }
//
// public AssumptionViolatedError(String message, Throwable cause) {
// super(message, cause);
// }
//
// public AssumptionViolatedError(Throwable cause) {
// super(cause);
// }
// }
| import com.github.mike10004.xvfbunittesthelp.FatalAssumer.AssumptionViolatedError;
import org.junit.Test;
import static org.junit.Assert.*; | package com.github.mike10004.xvfbunittesthelp;
public class FatalAssumerTest {
@Test
public void format() throws Exception {
String actual = FatalAssumer.format("hello %s", "world");
assertEquals("formatted", "hello world", actual);
}
@Test
public void assumeTrue_message() throws Exception {
String message = "hello world";
try {
new FatalAssumer().assumeTrue(message, false); | // Path: xvfb-unittest-help/src/main/java/com/github/mike10004/xvfbunittesthelp/FatalAssumer.java
// static class AssumptionViolatedError extends Error {
//
// public AssumptionViolatedError() {
// }
//
// public AssumptionViolatedError(String message) {
// super(message);
// }
//
// public AssumptionViolatedError(String message, Throwable cause) {
// super(message, cause);
// }
//
// public AssumptionViolatedError(Throwable cause) {
// super(cause);
// }
// }
// Path: xvfb-unittest-help/src/test/java/com/github/mike10004/xvfbunittesthelp/FatalAssumerTest.java
import com.github.mike10004.xvfbunittesthelp.FatalAssumer.AssumptionViolatedError;
import org.junit.Test;
import static org.junit.Assert.*;
package com.github.mike10004.xvfbunittesthelp;
public class FatalAssumerTest {
@Test
public void format() throws Exception {
String actual = FatalAssumer.format("hello %s", "world");
assertEquals("formatted", "hello world", actual);
}
@Test
public void assumeTrue_message() throws Exception {
String message = "hello world";
try {
new FatalAssumer().assumeTrue(message, false); | } catch (AssumptionViolatedError e) { |
mike10004/xvfb-manager-java | xvfb-manager/src/main/java/com/github/mike10004/xvfbmanager/XvfbManager.java | // Path: xvfb-manager/src/main/java/com/github/mike10004/xvfbmanager/Poller.java
// public static class PollOutcome<E> {
//
// /**
// * Reason polling stopped.
// */
// public final StopReason reason;
//
// /**
// * An object that represents the resolved state of the poll.
// */
// public final @Nullable E content;
//
// /**
// * Gets the polling duration. This may not be exact.
// */
// public final Duration duration;
//
// private final int numAttempts;
//
// private PollOutcome(StopReason reason, @Nullable E content, Duration duration, int numAttempts) {
// this.reason = checkNotNull(reason);
// this.content = content;
// this.duration = checkNotNull(duration);
// this.numAttempts = numAttempts;
// }
//
// @Override
// public String toString() {
// return "PollOutcome{" +
// "reason=" + reason +
// ", content=" + content +
// ", duration=" + duration +
// ", attempts=" + numAttempts +
// '}';
// }
//
// /**
// * Gets the number of times the poll was attempted. This is the numbef of
// * times the {@link #check(int) check()} function is invoked.
// * @return count of attempts
// */
// public int getNumAttempts() {
// return numAttempts;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// PollOutcome<?> that = (PollOutcome<?>) o;
//
// if (numAttempts != that.numAttempts) return false;
// if (reason != that.reason) return false;
// if (content != null ? !content.equals(that.content) : that.content != null) return false;
// return duration.equals(that.duration);
// }
//
// @Override
// public int hashCode() {
// int result = reason.hashCode();
// result = 31 * result + (content != null ? content.hashCode() : 0);
// result = 31 * result + duration.hashCode();
// result = 31 * result + numAttempts;
// return result;
// }
// }
//
// Path: xvfb-manager/src/main/java/com/github/mike10004/xvfbmanager/Poller.java
// public enum StopReason {
//
// /**
// * State was resolved to the poller's satisfaction.
// */
// RESOLVED,
//
// /**
// * State was not resolved to the poller's satisfaction,
// * but polling must cease anyway.
// */
// ABORTED,
//
// /**
// * The poller's iterator of intervals was exhausted
// * prior to resolution or abortion of polling.
// */
// TIMEOUT
// }
| import com.github.mike10004.nativehelper.Whicher;
import com.google.common.util.concurrent.JdkFutureAdapters;
import io.github.mike10004.subprocess.ProcessMonitor;
import io.github.mike10004.subprocess.ProcessResult;
import io.github.mike10004.subprocess.ProcessTracker;
import io.github.mike10004.subprocess.Subprocess;
import com.github.mike10004.xvfbmanager.Poller.PollOutcome;
import com.github.mike10004.xvfbmanager.Poller.StopReason;
import com.google.common.base.Suppliers;
import com.google.common.collect.Iterables;
import com.google.common.io.CharSource;
import com.google.common.io.Files;
import com.google.common.util.concurrent.FutureCallback;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.MoreExecutors;
import io.github.mike10004.subprocess.SubprocessLaunchSupport;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.annotation.Nullable;
import java.io.File;
import java.io.FileDescriptor;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Path;
import java.util.concurrent.Executor;
import java.util.function.Supplier;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkState;
import static java.util.Objects.requireNonNull; | return true;
}
};
}
private static final long AUTO_DISPLAY_POLL_INTERVAL_MS = 100;
private static final int AUTO_DISPLAY_POLLS_MAX = 20;
protected int pollForDisplayNumber(final CharSource cs) {
Poller<Integer> poller = new Poller<Integer>() {
@Override
protected PollAnswer<Integer> check(int pollAttemptsSoFar) {
@Nullable String lastLine = null;
try {
lastLine = Iterables.getFirst(cs.readLines().reverse(), null);
} catch (IOException e) {
log.info("failed to read from {}", cs);
}
if (lastLine != null) {
lastLine = lastLine.trim();
if (lastLine.matches("\\d+")) {
int displayNumber = Integer.parseInt(lastLine);
return resolve(displayNumber);
} else {
log.debug("last line of xvfb output is not an integer: {}", StringUtils.abbreviate(lastLine, 128));
}
}
return continuePolling();
}
}; | // Path: xvfb-manager/src/main/java/com/github/mike10004/xvfbmanager/Poller.java
// public static class PollOutcome<E> {
//
// /**
// * Reason polling stopped.
// */
// public final StopReason reason;
//
// /**
// * An object that represents the resolved state of the poll.
// */
// public final @Nullable E content;
//
// /**
// * Gets the polling duration. This may not be exact.
// */
// public final Duration duration;
//
// private final int numAttempts;
//
// private PollOutcome(StopReason reason, @Nullable E content, Duration duration, int numAttempts) {
// this.reason = checkNotNull(reason);
// this.content = content;
// this.duration = checkNotNull(duration);
// this.numAttempts = numAttempts;
// }
//
// @Override
// public String toString() {
// return "PollOutcome{" +
// "reason=" + reason +
// ", content=" + content +
// ", duration=" + duration +
// ", attempts=" + numAttempts +
// '}';
// }
//
// /**
// * Gets the number of times the poll was attempted. This is the numbef of
// * times the {@link #check(int) check()} function is invoked.
// * @return count of attempts
// */
// public int getNumAttempts() {
// return numAttempts;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// PollOutcome<?> that = (PollOutcome<?>) o;
//
// if (numAttempts != that.numAttempts) return false;
// if (reason != that.reason) return false;
// if (content != null ? !content.equals(that.content) : that.content != null) return false;
// return duration.equals(that.duration);
// }
//
// @Override
// public int hashCode() {
// int result = reason.hashCode();
// result = 31 * result + (content != null ? content.hashCode() : 0);
// result = 31 * result + duration.hashCode();
// result = 31 * result + numAttempts;
// return result;
// }
// }
//
// Path: xvfb-manager/src/main/java/com/github/mike10004/xvfbmanager/Poller.java
// public enum StopReason {
//
// /**
// * State was resolved to the poller's satisfaction.
// */
// RESOLVED,
//
// /**
// * State was not resolved to the poller's satisfaction,
// * but polling must cease anyway.
// */
// ABORTED,
//
// /**
// * The poller's iterator of intervals was exhausted
// * prior to resolution or abortion of polling.
// */
// TIMEOUT
// }
// Path: xvfb-manager/src/main/java/com/github/mike10004/xvfbmanager/XvfbManager.java
import com.github.mike10004.nativehelper.Whicher;
import com.google.common.util.concurrent.JdkFutureAdapters;
import io.github.mike10004.subprocess.ProcessMonitor;
import io.github.mike10004.subprocess.ProcessResult;
import io.github.mike10004.subprocess.ProcessTracker;
import io.github.mike10004.subprocess.Subprocess;
import com.github.mike10004.xvfbmanager.Poller.PollOutcome;
import com.github.mike10004.xvfbmanager.Poller.StopReason;
import com.google.common.base.Suppliers;
import com.google.common.collect.Iterables;
import com.google.common.io.CharSource;
import com.google.common.io.Files;
import com.google.common.util.concurrent.FutureCallback;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.MoreExecutors;
import io.github.mike10004.subprocess.SubprocessLaunchSupport;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.annotation.Nullable;
import java.io.File;
import java.io.FileDescriptor;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Path;
import java.util.concurrent.Executor;
import java.util.function.Supplier;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkState;
import static java.util.Objects.requireNonNull;
return true;
}
};
}
private static final long AUTO_DISPLAY_POLL_INTERVAL_MS = 100;
private static final int AUTO_DISPLAY_POLLS_MAX = 20;
protected int pollForDisplayNumber(final CharSource cs) {
Poller<Integer> poller = new Poller<Integer>() {
@Override
protected PollAnswer<Integer> check(int pollAttemptsSoFar) {
@Nullable String lastLine = null;
try {
lastLine = Iterables.getFirst(cs.readLines().reverse(), null);
} catch (IOException e) {
log.info("failed to read from {}", cs);
}
if (lastLine != null) {
lastLine = lastLine.trim();
if (lastLine.matches("\\d+")) {
int displayNumber = Integer.parseInt(lastLine);
return resolve(displayNumber);
} else {
log.debug("last line of xvfb output is not an integer: {}", StringUtils.abbreviate(lastLine, 128));
}
}
return continuePolling();
}
}; | PollOutcome<Integer> pollOutcome; |
mike10004/xvfb-manager-java | xvfb-manager/src/main/java/com/github/mike10004/xvfbmanager/XvfbManager.java | // Path: xvfb-manager/src/main/java/com/github/mike10004/xvfbmanager/Poller.java
// public static class PollOutcome<E> {
//
// /**
// * Reason polling stopped.
// */
// public final StopReason reason;
//
// /**
// * An object that represents the resolved state of the poll.
// */
// public final @Nullable E content;
//
// /**
// * Gets the polling duration. This may not be exact.
// */
// public final Duration duration;
//
// private final int numAttempts;
//
// private PollOutcome(StopReason reason, @Nullable E content, Duration duration, int numAttempts) {
// this.reason = checkNotNull(reason);
// this.content = content;
// this.duration = checkNotNull(duration);
// this.numAttempts = numAttempts;
// }
//
// @Override
// public String toString() {
// return "PollOutcome{" +
// "reason=" + reason +
// ", content=" + content +
// ", duration=" + duration +
// ", attempts=" + numAttempts +
// '}';
// }
//
// /**
// * Gets the number of times the poll was attempted. This is the numbef of
// * times the {@link #check(int) check()} function is invoked.
// * @return count of attempts
// */
// public int getNumAttempts() {
// return numAttempts;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// PollOutcome<?> that = (PollOutcome<?>) o;
//
// if (numAttempts != that.numAttempts) return false;
// if (reason != that.reason) return false;
// if (content != null ? !content.equals(that.content) : that.content != null) return false;
// return duration.equals(that.duration);
// }
//
// @Override
// public int hashCode() {
// int result = reason.hashCode();
// result = 31 * result + (content != null ? content.hashCode() : 0);
// result = 31 * result + duration.hashCode();
// result = 31 * result + numAttempts;
// return result;
// }
// }
//
// Path: xvfb-manager/src/main/java/com/github/mike10004/xvfbmanager/Poller.java
// public enum StopReason {
//
// /**
// * State was resolved to the poller's satisfaction.
// */
// RESOLVED,
//
// /**
// * State was not resolved to the poller's satisfaction,
// * but polling must cease anyway.
// */
// ABORTED,
//
// /**
// * The poller's iterator of intervals was exhausted
// * prior to resolution or abortion of polling.
// */
// TIMEOUT
// }
| import com.github.mike10004.nativehelper.Whicher;
import com.google.common.util.concurrent.JdkFutureAdapters;
import io.github.mike10004.subprocess.ProcessMonitor;
import io.github.mike10004.subprocess.ProcessResult;
import io.github.mike10004.subprocess.ProcessTracker;
import io.github.mike10004.subprocess.Subprocess;
import com.github.mike10004.xvfbmanager.Poller.PollOutcome;
import com.github.mike10004.xvfbmanager.Poller.StopReason;
import com.google.common.base.Suppliers;
import com.google.common.collect.Iterables;
import com.google.common.io.CharSource;
import com.google.common.io.Files;
import com.google.common.util.concurrent.FutureCallback;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.MoreExecutors;
import io.github.mike10004.subprocess.SubprocessLaunchSupport;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.annotation.Nullable;
import java.io.File;
import java.io.FileDescriptor;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Path;
import java.util.concurrent.Executor;
import java.util.function.Supplier;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkState;
import static java.util.Objects.requireNonNull; | private static final int AUTO_DISPLAY_POLLS_MAX = 20;
protected int pollForDisplayNumber(final CharSource cs) {
Poller<Integer> poller = new Poller<Integer>() {
@Override
protected PollAnswer<Integer> check(int pollAttemptsSoFar) {
@Nullable String lastLine = null;
try {
lastLine = Iterables.getFirst(cs.readLines().reverse(), null);
} catch (IOException e) {
log.info("failed to read from {}", cs);
}
if (lastLine != null) {
lastLine = lastLine.trim();
if (lastLine.matches("\\d+")) {
int displayNumber = Integer.parseInt(lastLine);
return resolve(displayNumber);
} else {
log.debug("last line of xvfb output is not an integer: {}", StringUtils.abbreviate(lastLine, 128));
}
}
return continuePolling();
}
};
PollOutcome<Integer> pollOutcome;
try {
pollOutcome = poller.poll(AUTO_DISPLAY_POLL_INTERVAL_MS, AUTO_DISPLAY_POLLS_MAX);
} catch (InterruptedException e) {
throw new XvfbException("interrupted while polling for display number", e);
} | // Path: xvfb-manager/src/main/java/com/github/mike10004/xvfbmanager/Poller.java
// public static class PollOutcome<E> {
//
// /**
// * Reason polling stopped.
// */
// public final StopReason reason;
//
// /**
// * An object that represents the resolved state of the poll.
// */
// public final @Nullable E content;
//
// /**
// * Gets the polling duration. This may not be exact.
// */
// public final Duration duration;
//
// private final int numAttempts;
//
// private PollOutcome(StopReason reason, @Nullable E content, Duration duration, int numAttempts) {
// this.reason = checkNotNull(reason);
// this.content = content;
// this.duration = checkNotNull(duration);
// this.numAttempts = numAttempts;
// }
//
// @Override
// public String toString() {
// return "PollOutcome{" +
// "reason=" + reason +
// ", content=" + content +
// ", duration=" + duration +
// ", attempts=" + numAttempts +
// '}';
// }
//
// /**
// * Gets the number of times the poll was attempted. This is the numbef of
// * times the {@link #check(int) check()} function is invoked.
// * @return count of attempts
// */
// public int getNumAttempts() {
// return numAttempts;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// PollOutcome<?> that = (PollOutcome<?>) o;
//
// if (numAttempts != that.numAttempts) return false;
// if (reason != that.reason) return false;
// if (content != null ? !content.equals(that.content) : that.content != null) return false;
// return duration.equals(that.duration);
// }
//
// @Override
// public int hashCode() {
// int result = reason.hashCode();
// result = 31 * result + (content != null ? content.hashCode() : 0);
// result = 31 * result + duration.hashCode();
// result = 31 * result + numAttempts;
// return result;
// }
// }
//
// Path: xvfb-manager/src/main/java/com/github/mike10004/xvfbmanager/Poller.java
// public enum StopReason {
//
// /**
// * State was resolved to the poller's satisfaction.
// */
// RESOLVED,
//
// /**
// * State was not resolved to the poller's satisfaction,
// * but polling must cease anyway.
// */
// ABORTED,
//
// /**
// * The poller's iterator of intervals was exhausted
// * prior to resolution or abortion of polling.
// */
// TIMEOUT
// }
// Path: xvfb-manager/src/main/java/com/github/mike10004/xvfbmanager/XvfbManager.java
import com.github.mike10004.nativehelper.Whicher;
import com.google.common.util.concurrent.JdkFutureAdapters;
import io.github.mike10004.subprocess.ProcessMonitor;
import io.github.mike10004.subprocess.ProcessResult;
import io.github.mike10004.subprocess.ProcessTracker;
import io.github.mike10004.subprocess.Subprocess;
import com.github.mike10004.xvfbmanager.Poller.PollOutcome;
import com.github.mike10004.xvfbmanager.Poller.StopReason;
import com.google.common.base.Suppliers;
import com.google.common.collect.Iterables;
import com.google.common.io.CharSource;
import com.google.common.io.Files;
import com.google.common.util.concurrent.FutureCallback;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.MoreExecutors;
import io.github.mike10004.subprocess.SubprocessLaunchSupport;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.annotation.Nullable;
import java.io.File;
import java.io.FileDescriptor;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Path;
import java.util.concurrent.Executor;
import java.util.function.Supplier;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkState;
import static java.util.Objects.requireNonNull;
private static final int AUTO_DISPLAY_POLLS_MAX = 20;
protected int pollForDisplayNumber(final CharSource cs) {
Poller<Integer> poller = new Poller<Integer>() {
@Override
protected PollAnswer<Integer> check(int pollAttemptsSoFar) {
@Nullable String lastLine = null;
try {
lastLine = Iterables.getFirst(cs.readLines().reverse(), null);
} catch (IOException e) {
log.info("failed to read from {}", cs);
}
if (lastLine != null) {
lastLine = lastLine.trim();
if (lastLine.matches("\\d+")) {
int displayNumber = Integer.parseInt(lastLine);
return resolve(displayNumber);
} else {
log.debug("last line of xvfb output is not an integer: {}", StringUtils.abbreviate(lastLine, 128));
}
}
return continuePolling();
}
};
PollOutcome<Integer> pollOutcome;
try {
pollOutcome = poller.poll(AUTO_DISPLAY_POLL_INTERVAL_MS, AUTO_DISPLAY_POLLS_MAX);
} catch (InterruptedException e) {
throw new XvfbException("interrupted while polling for display number", e);
} | if (pollOutcome.reason == StopReason.RESOLVED) { |
mike10004/xvfb-manager-java | xvfb-manager/src/test/java/com/github/mike10004/xvfbmanager/PollerTest.java | // Path: xvfb-manager/src/main/java/com/github/mike10004/xvfbmanager/Poller.java
// public static class PollOutcome<E> {
//
// /**
// * Reason polling stopped.
// */
// public final StopReason reason;
//
// /**
// * An object that represents the resolved state of the poll.
// */
// public final @Nullable E content;
//
// /**
// * Gets the polling duration. This may not be exact.
// */
// public final Duration duration;
//
// private final int numAttempts;
//
// private PollOutcome(StopReason reason, @Nullable E content, Duration duration, int numAttempts) {
// this.reason = checkNotNull(reason);
// this.content = content;
// this.duration = checkNotNull(duration);
// this.numAttempts = numAttempts;
// }
//
// @Override
// public String toString() {
// return "PollOutcome{" +
// "reason=" + reason +
// ", content=" + content +
// ", duration=" + duration +
// ", attempts=" + numAttempts +
// '}';
// }
//
// /**
// * Gets the number of times the poll was attempted. This is the numbef of
// * times the {@link #check(int) check()} function is invoked.
// * @return count of attempts
// */
// public int getNumAttempts() {
// return numAttempts;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// PollOutcome<?> that = (PollOutcome<?>) o;
//
// if (numAttempts != that.numAttempts) return false;
// if (reason != that.reason) return false;
// if (content != null ? !content.equals(that.content) : that.content != null) return false;
// return duration.equals(that.duration);
// }
//
// @Override
// public int hashCode() {
// int result = reason.hashCode();
// result = 31 * result + (content != null ? content.hashCode() : 0);
// result = 31 * result + duration.hashCode();
// result = 31 * result + numAttempts;
// return result;
// }
// }
//
// Path: xvfb-manager/src/main/java/com/github/mike10004/xvfbmanager/Poller.java
// protected static class SimplePoller extends Poller<Void> {
//
// private final Supplier<Boolean> condition;
//
// public SimplePoller(Sleeper sleeper, Supplier<Boolean> condition) {
// super(sleeper);
// this.condition = checkNotNull(condition);
// }
//
// public SimplePoller(Supplier<Boolean> condition) {
// super();
// this.condition = checkNotNull(condition);
// }
//
// @Override
// protected PollAnswer<Void> check(int pollAttemptsSoFar) {
// boolean state = condition.get();
// if (state) {
// return resolve(null);
// } else {
// return continuePolling();
// }
// }
// }
//
// Path: xvfb-manager/src/main/java/com/github/mike10004/xvfbmanager/Poller.java
// public enum StopReason {
//
// /**
// * State was resolved to the poller's satisfaction.
// */
// RESOLVED,
//
// /**
// * State was not resolved to the poller's satisfaction,
// * but polling must cease anyway.
// */
// ABORTED,
//
// /**
// * The poller's iterator of intervals was exhausted
// * prior to resolution or abortion of polling.
// */
// TIMEOUT
// }
| import com.github.mike10004.xvfbmanager.Poller.PollOutcome;
import com.github.mike10004.xvfbmanager.Poller.SimplePoller;
import com.github.mike10004.xvfbmanager.Poller.StopReason;
import com.google.common.base.Suppliers;
import org.junit.Test;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import static org.junit.Assert.assertEquals; | package com.github.mike10004.xvfbmanager;
public class PollerTest {
@Test
public void poll_immediatelyTrue() throws Exception { | // Path: xvfb-manager/src/main/java/com/github/mike10004/xvfbmanager/Poller.java
// public static class PollOutcome<E> {
//
// /**
// * Reason polling stopped.
// */
// public final StopReason reason;
//
// /**
// * An object that represents the resolved state of the poll.
// */
// public final @Nullable E content;
//
// /**
// * Gets the polling duration. This may not be exact.
// */
// public final Duration duration;
//
// private final int numAttempts;
//
// private PollOutcome(StopReason reason, @Nullable E content, Duration duration, int numAttempts) {
// this.reason = checkNotNull(reason);
// this.content = content;
// this.duration = checkNotNull(duration);
// this.numAttempts = numAttempts;
// }
//
// @Override
// public String toString() {
// return "PollOutcome{" +
// "reason=" + reason +
// ", content=" + content +
// ", duration=" + duration +
// ", attempts=" + numAttempts +
// '}';
// }
//
// /**
// * Gets the number of times the poll was attempted. This is the numbef of
// * times the {@link #check(int) check()} function is invoked.
// * @return count of attempts
// */
// public int getNumAttempts() {
// return numAttempts;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// PollOutcome<?> that = (PollOutcome<?>) o;
//
// if (numAttempts != that.numAttempts) return false;
// if (reason != that.reason) return false;
// if (content != null ? !content.equals(that.content) : that.content != null) return false;
// return duration.equals(that.duration);
// }
//
// @Override
// public int hashCode() {
// int result = reason.hashCode();
// result = 31 * result + (content != null ? content.hashCode() : 0);
// result = 31 * result + duration.hashCode();
// result = 31 * result + numAttempts;
// return result;
// }
// }
//
// Path: xvfb-manager/src/main/java/com/github/mike10004/xvfbmanager/Poller.java
// protected static class SimplePoller extends Poller<Void> {
//
// private final Supplier<Boolean> condition;
//
// public SimplePoller(Sleeper sleeper, Supplier<Boolean> condition) {
// super(sleeper);
// this.condition = checkNotNull(condition);
// }
//
// public SimplePoller(Supplier<Boolean> condition) {
// super();
// this.condition = checkNotNull(condition);
// }
//
// @Override
// protected PollAnswer<Void> check(int pollAttemptsSoFar) {
// boolean state = condition.get();
// if (state) {
// return resolve(null);
// } else {
// return continuePolling();
// }
// }
// }
//
// Path: xvfb-manager/src/main/java/com/github/mike10004/xvfbmanager/Poller.java
// public enum StopReason {
//
// /**
// * State was resolved to the poller's satisfaction.
// */
// RESOLVED,
//
// /**
// * State was not resolved to the poller's satisfaction,
// * but polling must cease anyway.
// */
// ABORTED,
//
// /**
// * The poller's iterator of intervals was exhausted
// * prior to resolution or abortion of polling.
// */
// TIMEOUT
// }
// Path: xvfb-manager/src/test/java/com/github/mike10004/xvfbmanager/PollerTest.java
import com.github.mike10004.xvfbmanager.Poller.PollOutcome;
import com.github.mike10004.xvfbmanager.Poller.SimplePoller;
import com.github.mike10004.xvfbmanager.Poller.StopReason;
import com.google.common.base.Suppliers;
import org.junit.Test;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import static org.junit.Assert.assertEquals;
package com.github.mike10004.xvfbmanager;
public class PollerTest {
@Test
public void poll_immediatelyTrue() throws Exception { | testPoller(0, 0, 1000, StopReason.TIMEOUT, 0); |
mike10004/xvfb-manager-java | xvfb-manager/src/test/java/com/github/mike10004/xvfbmanager/PollerTest.java | // Path: xvfb-manager/src/main/java/com/github/mike10004/xvfbmanager/Poller.java
// public static class PollOutcome<E> {
//
// /**
// * Reason polling stopped.
// */
// public final StopReason reason;
//
// /**
// * An object that represents the resolved state of the poll.
// */
// public final @Nullable E content;
//
// /**
// * Gets the polling duration. This may not be exact.
// */
// public final Duration duration;
//
// private final int numAttempts;
//
// private PollOutcome(StopReason reason, @Nullable E content, Duration duration, int numAttempts) {
// this.reason = checkNotNull(reason);
// this.content = content;
// this.duration = checkNotNull(duration);
// this.numAttempts = numAttempts;
// }
//
// @Override
// public String toString() {
// return "PollOutcome{" +
// "reason=" + reason +
// ", content=" + content +
// ", duration=" + duration +
// ", attempts=" + numAttempts +
// '}';
// }
//
// /**
// * Gets the number of times the poll was attempted. This is the numbef of
// * times the {@link #check(int) check()} function is invoked.
// * @return count of attempts
// */
// public int getNumAttempts() {
// return numAttempts;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// PollOutcome<?> that = (PollOutcome<?>) o;
//
// if (numAttempts != that.numAttempts) return false;
// if (reason != that.reason) return false;
// if (content != null ? !content.equals(that.content) : that.content != null) return false;
// return duration.equals(that.duration);
// }
//
// @Override
// public int hashCode() {
// int result = reason.hashCode();
// result = 31 * result + (content != null ? content.hashCode() : 0);
// result = 31 * result + duration.hashCode();
// result = 31 * result + numAttempts;
// return result;
// }
// }
//
// Path: xvfb-manager/src/main/java/com/github/mike10004/xvfbmanager/Poller.java
// protected static class SimplePoller extends Poller<Void> {
//
// private final Supplier<Boolean> condition;
//
// public SimplePoller(Sleeper sleeper, Supplier<Boolean> condition) {
// super(sleeper);
// this.condition = checkNotNull(condition);
// }
//
// public SimplePoller(Supplier<Boolean> condition) {
// super();
// this.condition = checkNotNull(condition);
// }
//
// @Override
// protected PollAnswer<Void> check(int pollAttemptsSoFar) {
// boolean state = condition.get();
// if (state) {
// return resolve(null);
// } else {
// return continuePolling();
// }
// }
// }
//
// Path: xvfb-manager/src/main/java/com/github/mike10004/xvfbmanager/Poller.java
// public enum StopReason {
//
// /**
// * State was resolved to the poller's satisfaction.
// */
// RESOLVED,
//
// /**
// * State was not resolved to the poller's satisfaction,
// * but polling must cease anyway.
// */
// ABORTED,
//
// /**
// * The poller's iterator of intervals was exhausted
// * prior to resolution or abortion of polling.
// */
// TIMEOUT
// }
| import com.github.mike10004.xvfbmanager.Poller.PollOutcome;
import com.github.mike10004.xvfbmanager.Poller.SimplePoller;
import com.github.mike10004.xvfbmanager.Poller.StopReason;
import com.google.common.base.Suppliers;
import org.junit.Test;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import static org.junit.Assert.assertEquals; | testPoller(0, 100, 1000, StopReason.RESOLVED, 0);
}
@Test
public void poll_trueAfterOne() throws Exception {
testPoller(1, 100, 1000, StopReason.RESOLVED, 1000);
}
@Test
public void poll_notTrueBeforeLimit() throws Exception {
testPoller(5, 4, 1000, StopReason.TIMEOUT, 4000);
}
@Test
public void poll_abortFromCheck_0() throws Exception {
poll_abortFromCheck(0);
}
@Test
public void poll_abortFromCheck_1() throws Exception {
poll_abortFromCheck(1);
}
@Test
public void poll_abortFromCheck_2() throws Exception {
poll_abortFromCheck(2);
}
public void poll_abortFromCheck(final int attempts) throws Exception {
TestSleeper sleeper = new TestSleeper(); | // Path: xvfb-manager/src/main/java/com/github/mike10004/xvfbmanager/Poller.java
// public static class PollOutcome<E> {
//
// /**
// * Reason polling stopped.
// */
// public final StopReason reason;
//
// /**
// * An object that represents the resolved state of the poll.
// */
// public final @Nullable E content;
//
// /**
// * Gets the polling duration. This may not be exact.
// */
// public final Duration duration;
//
// private final int numAttempts;
//
// private PollOutcome(StopReason reason, @Nullable E content, Duration duration, int numAttempts) {
// this.reason = checkNotNull(reason);
// this.content = content;
// this.duration = checkNotNull(duration);
// this.numAttempts = numAttempts;
// }
//
// @Override
// public String toString() {
// return "PollOutcome{" +
// "reason=" + reason +
// ", content=" + content +
// ", duration=" + duration +
// ", attempts=" + numAttempts +
// '}';
// }
//
// /**
// * Gets the number of times the poll was attempted. This is the numbef of
// * times the {@link #check(int) check()} function is invoked.
// * @return count of attempts
// */
// public int getNumAttempts() {
// return numAttempts;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// PollOutcome<?> that = (PollOutcome<?>) o;
//
// if (numAttempts != that.numAttempts) return false;
// if (reason != that.reason) return false;
// if (content != null ? !content.equals(that.content) : that.content != null) return false;
// return duration.equals(that.duration);
// }
//
// @Override
// public int hashCode() {
// int result = reason.hashCode();
// result = 31 * result + (content != null ? content.hashCode() : 0);
// result = 31 * result + duration.hashCode();
// result = 31 * result + numAttempts;
// return result;
// }
// }
//
// Path: xvfb-manager/src/main/java/com/github/mike10004/xvfbmanager/Poller.java
// protected static class SimplePoller extends Poller<Void> {
//
// private final Supplier<Boolean> condition;
//
// public SimplePoller(Sleeper sleeper, Supplier<Boolean> condition) {
// super(sleeper);
// this.condition = checkNotNull(condition);
// }
//
// public SimplePoller(Supplier<Boolean> condition) {
// super();
// this.condition = checkNotNull(condition);
// }
//
// @Override
// protected PollAnswer<Void> check(int pollAttemptsSoFar) {
// boolean state = condition.get();
// if (state) {
// return resolve(null);
// } else {
// return continuePolling();
// }
// }
// }
//
// Path: xvfb-manager/src/main/java/com/github/mike10004/xvfbmanager/Poller.java
// public enum StopReason {
//
// /**
// * State was resolved to the poller's satisfaction.
// */
// RESOLVED,
//
// /**
// * State was not resolved to the poller's satisfaction,
// * but polling must cease anyway.
// */
// ABORTED,
//
// /**
// * The poller's iterator of intervals was exhausted
// * prior to resolution or abortion of polling.
// */
// TIMEOUT
// }
// Path: xvfb-manager/src/test/java/com/github/mike10004/xvfbmanager/PollerTest.java
import com.github.mike10004.xvfbmanager.Poller.PollOutcome;
import com.github.mike10004.xvfbmanager.Poller.SimplePoller;
import com.github.mike10004.xvfbmanager.Poller.StopReason;
import com.google.common.base.Suppliers;
import org.junit.Test;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import static org.junit.Assert.assertEquals;
testPoller(0, 100, 1000, StopReason.RESOLVED, 0);
}
@Test
public void poll_trueAfterOne() throws Exception {
testPoller(1, 100, 1000, StopReason.RESOLVED, 1000);
}
@Test
public void poll_notTrueBeforeLimit() throws Exception {
testPoller(5, 4, 1000, StopReason.TIMEOUT, 4000);
}
@Test
public void poll_abortFromCheck_0() throws Exception {
poll_abortFromCheck(0);
}
@Test
public void poll_abortFromCheck_1() throws Exception {
poll_abortFromCheck(1);
}
@Test
public void poll_abortFromCheck_2() throws Exception {
poll_abortFromCheck(2);
}
public void poll_abortFromCheck(final int attempts) throws Exception {
TestSleeper sleeper = new TestSleeper(); | PollOutcome<?> outcome = new Poller<Void>(sleeper) { |
mike10004/xvfb-manager-java | xvfb-manager/src/test/java/com/github/mike10004/xvfbmanager/PollerTest.java | // Path: xvfb-manager/src/main/java/com/github/mike10004/xvfbmanager/Poller.java
// public static class PollOutcome<E> {
//
// /**
// * Reason polling stopped.
// */
// public final StopReason reason;
//
// /**
// * An object that represents the resolved state of the poll.
// */
// public final @Nullable E content;
//
// /**
// * Gets the polling duration. This may not be exact.
// */
// public final Duration duration;
//
// private final int numAttempts;
//
// private PollOutcome(StopReason reason, @Nullable E content, Duration duration, int numAttempts) {
// this.reason = checkNotNull(reason);
// this.content = content;
// this.duration = checkNotNull(duration);
// this.numAttempts = numAttempts;
// }
//
// @Override
// public String toString() {
// return "PollOutcome{" +
// "reason=" + reason +
// ", content=" + content +
// ", duration=" + duration +
// ", attempts=" + numAttempts +
// '}';
// }
//
// /**
// * Gets the number of times the poll was attempted. This is the numbef of
// * times the {@link #check(int) check()} function is invoked.
// * @return count of attempts
// */
// public int getNumAttempts() {
// return numAttempts;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// PollOutcome<?> that = (PollOutcome<?>) o;
//
// if (numAttempts != that.numAttempts) return false;
// if (reason != that.reason) return false;
// if (content != null ? !content.equals(that.content) : that.content != null) return false;
// return duration.equals(that.duration);
// }
//
// @Override
// public int hashCode() {
// int result = reason.hashCode();
// result = 31 * result + (content != null ? content.hashCode() : 0);
// result = 31 * result + duration.hashCode();
// result = 31 * result + numAttempts;
// return result;
// }
// }
//
// Path: xvfb-manager/src/main/java/com/github/mike10004/xvfbmanager/Poller.java
// protected static class SimplePoller extends Poller<Void> {
//
// private final Supplier<Boolean> condition;
//
// public SimplePoller(Sleeper sleeper, Supplier<Boolean> condition) {
// super(sleeper);
// this.condition = checkNotNull(condition);
// }
//
// public SimplePoller(Supplier<Boolean> condition) {
// super();
// this.condition = checkNotNull(condition);
// }
//
// @Override
// protected PollAnswer<Void> check(int pollAttemptsSoFar) {
// boolean state = condition.get();
// if (state) {
// return resolve(null);
// } else {
// return continuePolling();
// }
// }
// }
//
// Path: xvfb-manager/src/main/java/com/github/mike10004/xvfbmanager/Poller.java
// public enum StopReason {
//
// /**
// * State was resolved to the poller's satisfaction.
// */
// RESOLVED,
//
// /**
// * State was not resolved to the poller's satisfaction,
// * but polling must cease anyway.
// */
// ABORTED,
//
// /**
// * The poller's iterator of intervals was exhausted
// * prior to resolution or abortion of polling.
// */
// TIMEOUT
// }
| import com.github.mike10004.xvfbmanager.Poller.PollOutcome;
import com.github.mike10004.xvfbmanager.Poller.SimplePoller;
import com.github.mike10004.xvfbmanager.Poller.StopReason;
import com.google.common.base.Suppliers;
import org.junit.Test;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import static org.junit.Assert.assertEquals; | public void poll_timeoutOverridesAbort(final int attempts) throws Exception {
TestSleeper sleeper = new TestSleeper();
PollOutcome<?> outcome = new Poller<Void>(sleeper) {
@Override
protected PollAnswer<Void> check(int pollAttemptsSoFar) {
return pollAttemptsSoFar >= attempts ? abortPolling() : continuePolling();
}
}.poll(1000, attempts); // poll forever
assertEquals("reason", StopReason.TIMEOUT, outcome.reason);
assertEquals("duration", attempts * 1000, sleeper.getDuration());
assertEquals("sleep count", attempts, sleeper.getCount());
}
@Test(expected = IllegalArgumentException.class)
public void poll_badArgs() throws Exception {
testPoller(5, 4, -1000, null, 0);
}
@Test
public void testDoNotSleepIfAboutToTimeOut_1() throws Exception {
testDoNotSleepIfAboutToTimeOut(1000, 1, StopReason.TIMEOUT, 1000, 1);
}
@Test
public void testDoNotSleepIfAboutToTimeOut_2() throws Exception {
testDoNotSleepIfAboutToTimeOut(1000, 2, StopReason.TIMEOUT, 2000, 2);
}
public void testDoNotSleepIfAboutToTimeOut(long intervalMs, int maxPolls, StopReason stopReason, long expectedDuration, int expectedSleeps) throws Exception {
TestSleeper sleeper = new TestSleeper(); | // Path: xvfb-manager/src/main/java/com/github/mike10004/xvfbmanager/Poller.java
// public static class PollOutcome<E> {
//
// /**
// * Reason polling stopped.
// */
// public final StopReason reason;
//
// /**
// * An object that represents the resolved state of the poll.
// */
// public final @Nullable E content;
//
// /**
// * Gets the polling duration. This may not be exact.
// */
// public final Duration duration;
//
// private final int numAttempts;
//
// private PollOutcome(StopReason reason, @Nullable E content, Duration duration, int numAttempts) {
// this.reason = checkNotNull(reason);
// this.content = content;
// this.duration = checkNotNull(duration);
// this.numAttempts = numAttempts;
// }
//
// @Override
// public String toString() {
// return "PollOutcome{" +
// "reason=" + reason +
// ", content=" + content +
// ", duration=" + duration +
// ", attempts=" + numAttempts +
// '}';
// }
//
// /**
// * Gets the number of times the poll was attempted. This is the numbef of
// * times the {@link #check(int) check()} function is invoked.
// * @return count of attempts
// */
// public int getNumAttempts() {
// return numAttempts;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// PollOutcome<?> that = (PollOutcome<?>) o;
//
// if (numAttempts != that.numAttempts) return false;
// if (reason != that.reason) return false;
// if (content != null ? !content.equals(that.content) : that.content != null) return false;
// return duration.equals(that.duration);
// }
//
// @Override
// public int hashCode() {
// int result = reason.hashCode();
// result = 31 * result + (content != null ? content.hashCode() : 0);
// result = 31 * result + duration.hashCode();
// result = 31 * result + numAttempts;
// return result;
// }
// }
//
// Path: xvfb-manager/src/main/java/com/github/mike10004/xvfbmanager/Poller.java
// protected static class SimplePoller extends Poller<Void> {
//
// private final Supplier<Boolean> condition;
//
// public SimplePoller(Sleeper sleeper, Supplier<Boolean> condition) {
// super(sleeper);
// this.condition = checkNotNull(condition);
// }
//
// public SimplePoller(Supplier<Boolean> condition) {
// super();
// this.condition = checkNotNull(condition);
// }
//
// @Override
// protected PollAnswer<Void> check(int pollAttemptsSoFar) {
// boolean state = condition.get();
// if (state) {
// return resolve(null);
// } else {
// return continuePolling();
// }
// }
// }
//
// Path: xvfb-manager/src/main/java/com/github/mike10004/xvfbmanager/Poller.java
// public enum StopReason {
//
// /**
// * State was resolved to the poller's satisfaction.
// */
// RESOLVED,
//
// /**
// * State was not resolved to the poller's satisfaction,
// * but polling must cease anyway.
// */
// ABORTED,
//
// /**
// * The poller's iterator of intervals was exhausted
// * prior to resolution or abortion of polling.
// */
// TIMEOUT
// }
// Path: xvfb-manager/src/test/java/com/github/mike10004/xvfbmanager/PollerTest.java
import com.github.mike10004.xvfbmanager.Poller.PollOutcome;
import com.github.mike10004.xvfbmanager.Poller.SimplePoller;
import com.github.mike10004.xvfbmanager.Poller.StopReason;
import com.google.common.base.Suppliers;
import org.junit.Test;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import static org.junit.Assert.assertEquals;
public void poll_timeoutOverridesAbort(final int attempts) throws Exception {
TestSleeper sleeper = new TestSleeper();
PollOutcome<?> outcome = new Poller<Void>(sleeper) {
@Override
protected PollAnswer<Void> check(int pollAttemptsSoFar) {
return pollAttemptsSoFar >= attempts ? abortPolling() : continuePolling();
}
}.poll(1000, attempts); // poll forever
assertEquals("reason", StopReason.TIMEOUT, outcome.reason);
assertEquals("duration", attempts * 1000, sleeper.getDuration());
assertEquals("sleep count", attempts, sleeper.getCount());
}
@Test(expected = IllegalArgumentException.class)
public void poll_badArgs() throws Exception {
testPoller(5, 4, -1000, null, 0);
}
@Test
public void testDoNotSleepIfAboutToTimeOut_1() throws Exception {
testDoNotSleepIfAboutToTimeOut(1000, 1, StopReason.TIMEOUT, 1000, 1);
}
@Test
public void testDoNotSleepIfAboutToTimeOut_2() throws Exception {
testDoNotSleepIfAboutToTimeOut(1000, 2, StopReason.TIMEOUT, 2000, 2);
}
public void testDoNotSleepIfAboutToTimeOut(long intervalMs, int maxPolls, StopReason stopReason, long expectedDuration, int expectedSleeps) throws Exception {
TestSleeper sleeper = new TestSleeper(); | PollOutcome<Void> outcome = new SimplePoller(sleeper, Suppliers.ofInstance(false)).poll(intervalMs, maxPolls); |
openwebnet/rx-openwebnet | example/src/main/java/com/github/niqdev/openwebnet/OpenWebNetExample.java | // Path: lib/src/main/java/com/github/niqdev/openwebnet/OpenWebNet.java
// public static OpenGateway defaultGateway(String host) {
// return gateway(host, OpenGateway.DEFAULT_PORT);
// }
//
// Path: lib/src/main/java/com/github/niqdev/openwebnet/OpenWebNet.java
// public static OpenGateway gateway(final String host, final int port, final String password) {
// return new OpenGateway() {
//
// @Override
// public String getHost() {
// return host;
// }
//
// @Override
// public int getPort() {
// return port;
// }
//
// @Override
// public String getPassword() {
// return password;
// }
// };
// }
| import com.github.niqdev.openwebnet.message.*;
import rx.schedulers.Schedulers;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import static com.github.niqdev.openwebnet.OpenWebNet.defaultGateway;
import static com.github.niqdev.openwebnet.OpenWebNet.gateway;
import static java.util.Arrays.asList; | package com.github.niqdev.openwebnet;
/**
* ./gradlew runOpenWebNetExample
*/
public class OpenWebNetExample {
private static final String LOCALHOST = "localhost";
private static final String LOCALHOST_ANDROID = "10.0.2.2";
private static final String HOST = "192.168.1.41";
private static final String HOST_DOMAIN = "vpn.home.it";
private static final String HOST_PWD = "192.168.1.35";
private static final String HOST_HTTP = "http://192.168.1.41";
private static final String PASSWORD = "12345";
private static final int PORT = 20000;
private static final ExecutorService executor = Executors.newSingleThreadExecutor();
public static void main(String[] args) {
//example1();
//example2();
//exampleLightStatus();
//exampleLightTurnOn();
//exampleHeating();
//exampleSoundSystem();
//exampleSoundSystemStatus();
//exampleScenario();
//exampleScenarioStatus();
//exampleEnergy();
//exampleSoundSystemVolume();
//exampleSoundSystemStation();
}
private static void example1() {
OpenWebNet | // Path: lib/src/main/java/com/github/niqdev/openwebnet/OpenWebNet.java
// public static OpenGateway defaultGateway(String host) {
// return gateway(host, OpenGateway.DEFAULT_PORT);
// }
//
// Path: lib/src/main/java/com/github/niqdev/openwebnet/OpenWebNet.java
// public static OpenGateway gateway(final String host, final int port, final String password) {
// return new OpenGateway() {
//
// @Override
// public String getHost() {
// return host;
// }
//
// @Override
// public int getPort() {
// return port;
// }
//
// @Override
// public String getPassword() {
// return password;
// }
// };
// }
// Path: example/src/main/java/com/github/niqdev/openwebnet/OpenWebNetExample.java
import com.github.niqdev.openwebnet.message.*;
import rx.schedulers.Schedulers;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import static com.github.niqdev.openwebnet.OpenWebNet.defaultGateway;
import static com.github.niqdev.openwebnet.OpenWebNet.gateway;
import static java.util.Arrays.asList;
package com.github.niqdev.openwebnet;
/**
* ./gradlew runOpenWebNetExample
*/
public class OpenWebNetExample {
private static final String LOCALHOST = "localhost";
private static final String LOCALHOST_ANDROID = "10.0.2.2";
private static final String HOST = "192.168.1.41";
private static final String HOST_DOMAIN = "vpn.home.it";
private static final String HOST_PWD = "192.168.1.35";
private static final String HOST_HTTP = "http://192.168.1.41";
private static final String PASSWORD = "12345";
private static final int PORT = 20000;
private static final ExecutorService executor = Executors.newSingleThreadExecutor();
public static void main(String[] args) {
//example1();
//example2();
//exampleLightStatus();
//exampleLightTurnOn();
//exampleHeating();
//exampleSoundSystem();
//exampleSoundSystemStatus();
//exampleScenario();
//exampleScenarioStatus();
//exampleEnergy();
//exampleSoundSystemVolume();
//exampleSoundSystemStation();
}
private static void example1() {
OpenWebNet | .newClient(defaultGateway(LOCALHOST)) |
openwebnet/rx-openwebnet | example/src/main/java/com/github/niqdev/openwebnet/OpenWebNetExample.java | // Path: lib/src/main/java/com/github/niqdev/openwebnet/OpenWebNet.java
// public static OpenGateway defaultGateway(String host) {
// return gateway(host, OpenGateway.DEFAULT_PORT);
// }
//
// Path: lib/src/main/java/com/github/niqdev/openwebnet/OpenWebNet.java
// public static OpenGateway gateway(final String host, final int port, final String password) {
// return new OpenGateway() {
//
// @Override
// public String getHost() {
// return host;
// }
//
// @Override
// public int getPort() {
// return port;
// }
//
// @Override
// public String getPassword() {
// return password;
// }
// };
// }
| import com.github.niqdev.openwebnet.message.*;
import rx.schedulers.Schedulers;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import static com.github.niqdev.openwebnet.OpenWebNet.defaultGateway;
import static com.github.niqdev.openwebnet.OpenWebNet.gateway;
import static java.util.Arrays.asList; | package com.github.niqdev.openwebnet;
/**
* ./gradlew runOpenWebNetExample
*/
public class OpenWebNetExample {
private static final String LOCALHOST = "localhost";
private static final String LOCALHOST_ANDROID = "10.0.2.2";
private static final String HOST = "192.168.1.41";
private static final String HOST_DOMAIN = "vpn.home.it";
private static final String HOST_PWD = "192.168.1.35";
private static final String HOST_HTTP = "http://192.168.1.41";
private static final String PASSWORD = "12345";
private static final int PORT = 20000;
private static final ExecutorService executor = Executors.newSingleThreadExecutor();
public static void main(String[] args) {
//example1();
//example2();
//exampleLightStatus();
//exampleLightTurnOn();
//exampleHeating();
//exampleSoundSystem();
//exampleSoundSystemStatus();
//exampleScenario();
//exampleScenarioStatus();
//exampleEnergy();
//exampleSoundSystemVolume();
//exampleSoundSystemStation();
}
private static void example1() {
OpenWebNet
.newClient(defaultGateway(LOCALHOST))
.send(() -> "*#1*21##")
.subscribe(System.out::println);
}
private static void example2() {
System.out.println("before " + Thread.currentThread().getName());
OpenWebNet | // Path: lib/src/main/java/com/github/niqdev/openwebnet/OpenWebNet.java
// public static OpenGateway defaultGateway(String host) {
// return gateway(host, OpenGateway.DEFAULT_PORT);
// }
//
// Path: lib/src/main/java/com/github/niqdev/openwebnet/OpenWebNet.java
// public static OpenGateway gateway(final String host, final int port, final String password) {
// return new OpenGateway() {
//
// @Override
// public String getHost() {
// return host;
// }
//
// @Override
// public int getPort() {
// return port;
// }
//
// @Override
// public String getPassword() {
// return password;
// }
// };
// }
// Path: example/src/main/java/com/github/niqdev/openwebnet/OpenWebNetExample.java
import com.github.niqdev.openwebnet.message.*;
import rx.schedulers.Schedulers;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import static com.github.niqdev.openwebnet.OpenWebNet.defaultGateway;
import static com.github.niqdev.openwebnet.OpenWebNet.gateway;
import static java.util.Arrays.asList;
package com.github.niqdev.openwebnet;
/**
* ./gradlew runOpenWebNetExample
*/
public class OpenWebNetExample {
private static final String LOCALHOST = "localhost";
private static final String LOCALHOST_ANDROID = "10.0.2.2";
private static final String HOST = "192.168.1.41";
private static final String HOST_DOMAIN = "vpn.home.it";
private static final String HOST_PWD = "192.168.1.35";
private static final String HOST_HTTP = "http://192.168.1.41";
private static final String PASSWORD = "12345";
private static final int PORT = 20000;
private static final ExecutorService executor = Executors.newSingleThreadExecutor();
public static void main(String[] args) {
//example1();
//example2();
//exampleLightStatus();
//exampleLightTurnOn();
//exampleHeating();
//exampleSoundSystem();
//exampleSoundSystemStatus();
//exampleScenario();
//exampleScenarioStatus();
//exampleEnergy();
//exampleSoundSystemVolume();
//exampleSoundSystemStation();
}
private static void example1() {
OpenWebNet
.newClient(defaultGateway(LOCALHOST))
.send(() -> "*#1*21##")
.subscribe(System.out::println);
}
private static void example2() {
System.out.println("before " + Thread.currentThread().getName());
OpenWebNet | .newClient(gateway(LOCALHOST, PORT)) |
openwebnet/rx-openwebnet | lib/src/main/java/com/github/niqdev/openwebnet/message/EnergyManagement.java | // Path: lib/src/main/java/com/github/niqdev/openwebnet/OpenSession.java
// public class OpenSession {
//
// private final OpenMessage request;
// private final List<OpenMessage> response = new ArrayList<>();
//
// private OpenSession(OpenMessage request) {
// checkNotNull(request, "request can't be null");
// this.request = request;
// }
//
// /**
// * Helper method to create a new session.
// *
// * @param request message
// * @return session
// */
// public static OpenSession newSession(OpenMessage request) {
// return new OpenSession(request);
// }
//
// /**
// * Update the response messages.
// *
// * @param response messages
// * @return session
// */
// public OpenSession addAllResponse(List<OpenMessage> response) {
// checkNotNull(response, "response can't be null");
// this.response.addAll(response);
// return this;
// }
//
// /**
// * Update the response messages.
// *
// * @param response messages
// * @return session
// */
// public OpenSession addResponse(OpenMessage response) {
// checkNotNull(response, "response can't be null");
// this.response.add(response);
// return this;
// }
//
// /**
// * Returns the initial request message.
// *
// * @return request
// */
// public OpenMessage getRequest() {
// return request;
// }
//
// /**
// * Returns the response messages.
// *
// * @return response
// */
// public List<OpenMessage> getResponse() {
// return response;
// }
//
// @Override
// public String toString() {
// return MoreObjects.toStringHelper(this)
// .add("request", request.getValue())
// .add("response", response)
// .toString();
// }
// }
| import com.github.niqdev.openwebnet.OpenSession;
import com.google.common.collect.Lists;
import rx.functions.Action0;
import rx.functions.Action1;
import rx.functions.Func1;
import java.util.List;
import static com.github.niqdev.openwebnet.message.Who.ENERGY_MANAGEMENT;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static java.lang.String.format; | * @param version Energy management {@link Version}
* @return message
*/
public static EnergyManagement requestMonthlyPower(String where, Version version) {
return buildRequestPower(where, version, MONTHLY_POWER);
}
private static EnergyManagement buildRequestPower(String where, Version version, int period) {
checkRange(WHERE_MIN_VALUE_ENERGY, WHERE_MAX_VALUE_ENERGY, checkIsInteger(where));
checkNotNull(version, "invalid null version");
switch (version) {
case MODEL_F520: case MODEL_F523: case MODEL_3522:
return new EnergyManagement(format(FORMAT_DIMENSION_ENERGY, WHO, where, period));
case MODEL_F522_A: case MODEL_F523_A:
return new EnergyManagement(format(FORMAT_DIMENSION_ENERGY_A, WHO, where, period));
}
throw new IllegalArgumentException("invalid version");
}
/**
* Handle response from {@link EnergyManagement#requestInstantaneousPower(String, Version)},
* {@link EnergyManagement#requestDailyPower(String, Version)} and
* {@link EnergyManagement#requestMonthlyPower(String, Version)}.
*
* This is a best effort: often the responses are incomplete or impossible to parse.
*
* @param onSuccess invoked if the powers have been read correctly
* @param onError invoked otherwise
* @return {@code Observable<List<OpenSession>>}
*/ | // Path: lib/src/main/java/com/github/niqdev/openwebnet/OpenSession.java
// public class OpenSession {
//
// private final OpenMessage request;
// private final List<OpenMessage> response = new ArrayList<>();
//
// private OpenSession(OpenMessage request) {
// checkNotNull(request, "request can't be null");
// this.request = request;
// }
//
// /**
// * Helper method to create a new session.
// *
// * @param request message
// * @return session
// */
// public static OpenSession newSession(OpenMessage request) {
// return new OpenSession(request);
// }
//
// /**
// * Update the response messages.
// *
// * @param response messages
// * @return session
// */
// public OpenSession addAllResponse(List<OpenMessage> response) {
// checkNotNull(response, "response can't be null");
// this.response.addAll(response);
// return this;
// }
//
// /**
// * Update the response messages.
// *
// * @param response messages
// * @return session
// */
// public OpenSession addResponse(OpenMessage response) {
// checkNotNull(response, "response can't be null");
// this.response.add(response);
// return this;
// }
//
// /**
// * Returns the initial request message.
// *
// * @return request
// */
// public OpenMessage getRequest() {
// return request;
// }
//
// /**
// * Returns the response messages.
// *
// * @return response
// */
// public List<OpenMessage> getResponse() {
// return response;
// }
//
// @Override
// public String toString() {
// return MoreObjects.toStringHelper(this)
// .add("request", request.getValue())
// .add("response", response)
// .toString();
// }
// }
// Path: lib/src/main/java/com/github/niqdev/openwebnet/message/EnergyManagement.java
import com.github.niqdev.openwebnet.OpenSession;
import com.google.common.collect.Lists;
import rx.functions.Action0;
import rx.functions.Action1;
import rx.functions.Func1;
import java.util.List;
import static com.github.niqdev.openwebnet.message.Who.ENERGY_MANAGEMENT;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static java.lang.String.format;
* @param version Energy management {@link Version}
* @return message
*/
public static EnergyManagement requestMonthlyPower(String where, Version version) {
return buildRequestPower(where, version, MONTHLY_POWER);
}
private static EnergyManagement buildRequestPower(String where, Version version, int period) {
checkRange(WHERE_MIN_VALUE_ENERGY, WHERE_MAX_VALUE_ENERGY, checkIsInteger(where));
checkNotNull(version, "invalid null version");
switch (version) {
case MODEL_F520: case MODEL_F523: case MODEL_3522:
return new EnergyManagement(format(FORMAT_DIMENSION_ENERGY, WHO, where, period));
case MODEL_F522_A: case MODEL_F523_A:
return new EnergyManagement(format(FORMAT_DIMENSION_ENERGY_A, WHO, where, period));
}
throw new IllegalArgumentException("invalid version");
}
/**
* Handle response from {@link EnergyManagement#requestInstantaneousPower(String, Version)},
* {@link EnergyManagement#requestDailyPower(String, Version)} and
* {@link EnergyManagement#requestMonthlyPower(String, Version)}.
*
* This is a best effort: often the responses are incomplete or impossible to parse.
*
* @param onSuccess invoked if the powers have been read correctly
* @param onError invoked otherwise
* @return {@code Observable<List<OpenSession>>}
*/ | public static Func1<List<OpenSession>, List<OpenSession>> handlePowers(Action1<List<String>> onSuccess, Action0 onError) { |
openwebnet/rx-openwebnet | lib/src/main/java/com/github/niqdev/openwebnet/message/SoundSystem.java | // Path: lib/src/main/java/com/github/niqdev/openwebnet/OpenSession.java
// public class OpenSession {
//
// private final OpenMessage request;
// private final List<OpenMessage> response = new ArrayList<>();
//
// private OpenSession(OpenMessage request) {
// checkNotNull(request, "request can't be null");
// this.request = request;
// }
//
// /**
// * Helper method to create a new session.
// *
// * @param request message
// * @return session
// */
// public static OpenSession newSession(OpenMessage request) {
// return new OpenSession(request);
// }
//
// /**
// * Update the response messages.
// *
// * @param response messages
// * @return session
// */
// public OpenSession addAllResponse(List<OpenMessage> response) {
// checkNotNull(response, "response can't be null");
// this.response.addAll(response);
// return this;
// }
//
// /**
// * Update the response messages.
// *
// * @param response messages
// * @return session
// */
// public OpenSession addResponse(OpenMessage response) {
// checkNotNull(response, "response can't be null");
// this.response.add(response);
// return this;
// }
//
// /**
// * Returns the initial request message.
// *
// * @return request
// */
// public OpenMessage getRequest() {
// return request;
// }
//
// /**
// * Returns the response messages.
// *
// * @return response
// */
// public List<OpenMessage> getResponse() {
// return response;
// }
//
// @Override
// public String toString() {
// return MoreObjects.toStringHelper(this)
// .add("request", request.getValue())
// .add("response", response)
// .toString();
// }
// }
| import com.github.niqdev.openwebnet.OpenSession;
import com.google.common.collect.FluentIterable;
import rx.functions.Action0;
import rx.functions.Func1;
import java.util.List;
import static com.github.niqdev.openwebnet.message.Who.SOUND_SYSTEM_1;
import static com.github.niqdev.openwebnet.message.Who.SOUND_SYSTEM_2;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static java.lang.String.format; | * @return message
*/
public static SoundSystem requestTurnOff(String where, Type type, Source source) {
return buildRequest(where, type, source, OFF_SOURCE_BASE_BAND, OFF_SOURCE_STEREO_CHANNEL);
}
private static SoundSystem buildRequest(String where, Type type, Source source, int baseBandValue, int stereoValue) {
checkArgument(Type.isValid(type, where), "invalid where|type");
switch (source) {
case BASE_BAND:
return new SoundSystem(format(FORMAT_REQUEST, WHO_16, baseBandValue, buildWhereValue(where, type)));
case STEREO_CHANNEL:
return new SoundSystem(format(FORMAT_REQUEST, WHO_16, stereoValue, buildWhereValue(where, type)));
}
throw new IllegalArgumentException("invalid source");
}
/**
* Handle response from:
* - {@link SoundSystem#requestTurnOn(String, Type, Source)}
* - {@link SoundSystem#requestTurnOff(String, Type, Source)}
* - {@link SoundSystem#requestVolumeUp(String, Type)}
* - {@link SoundSystem#requestVolumeDown(String, Type)}
* - {@link SoundSystem#requestStationUp(String, Type)}
* - {@link SoundSystem#requestStationDown(String, Type)}
*
* @param onSuccess invoked if the request has been successfully received
* @param onFail invoked otherwise
* @return {@code Observable<OpenSession>}
*/ | // Path: lib/src/main/java/com/github/niqdev/openwebnet/OpenSession.java
// public class OpenSession {
//
// private final OpenMessage request;
// private final List<OpenMessage> response = new ArrayList<>();
//
// private OpenSession(OpenMessage request) {
// checkNotNull(request, "request can't be null");
// this.request = request;
// }
//
// /**
// * Helper method to create a new session.
// *
// * @param request message
// * @return session
// */
// public static OpenSession newSession(OpenMessage request) {
// return new OpenSession(request);
// }
//
// /**
// * Update the response messages.
// *
// * @param response messages
// * @return session
// */
// public OpenSession addAllResponse(List<OpenMessage> response) {
// checkNotNull(response, "response can't be null");
// this.response.addAll(response);
// return this;
// }
//
// /**
// * Update the response messages.
// *
// * @param response messages
// * @return session
// */
// public OpenSession addResponse(OpenMessage response) {
// checkNotNull(response, "response can't be null");
// this.response.add(response);
// return this;
// }
//
// /**
// * Returns the initial request message.
// *
// * @return request
// */
// public OpenMessage getRequest() {
// return request;
// }
//
// /**
// * Returns the response messages.
// *
// * @return response
// */
// public List<OpenMessage> getResponse() {
// return response;
// }
//
// @Override
// public String toString() {
// return MoreObjects.toStringHelper(this)
// .add("request", request.getValue())
// .add("response", response)
// .toString();
// }
// }
// Path: lib/src/main/java/com/github/niqdev/openwebnet/message/SoundSystem.java
import com.github.niqdev.openwebnet.OpenSession;
import com.google.common.collect.FluentIterable;
import rx.functions.Action0;
import rx.functions.Func1;
import java.util.List;
import static com.github.niqdev.openwebnet.message.Who.SOUND_SYSTEM_1;
import static com.github.niqdev.openwebnet.message.Who.SOUND_SYSTEM_2;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static java.lang.String.format;
* @return message
*/
public static SoundSystem requestTurnOff(String where, Type type, Source source) {
return buildRequest(where, type, source, OFF_SOURCE_BASE_BAND, OFF_SOURCE_STEREO_CHANNEL);
}
private static SoundSystem buildRequest(String where, Type type, Source source, int baseBandValue, int stereoValue) {
checkArgument(Type.isValid(type, where), "invalid where|type");
switch (source) {
case BASE_BAND:
return new SoundSystem(format(FORMAT_REQUEST, WHO_16, baseBandValue, buildWhereValue(where, type)));
case STEREO_CHANNEL:
return new SoundSystem(format(FORMAT_REQUEST, WHO_16, stereoValue, buildWhereValue(where, type)));
}
throw new IllegalArgumentException("invalid source");
}
/**
* Handle response from:
* - {@link SoundSystem#requestTurnOn(String, Type, Source)}
* - {@link SoundSystem#requestTurnOff(String, Type, Source)}
* - {@link SoundSystem#requestVolumeUp(String, Type)}
* - {@link SoundSystem#requestVolumeDown(String, Type)}
* - {@link SoundSystem#requestStationUp(String, Type)}
* - {@link SoundSystem#requestStationDown(String, Type)}
*
* @param onSuccess invoked if the request has been successfully received
* @param onFail invoked otherwise
* @return {@code Observable<OpenSession>}
*/ | public static Func1<OpenSession, OpenSession> handleResponse(Action0 onSuccess, Action0 onFail) { |
openwebnet/rx-openwebnet | lib/src/main/java/com/github/niqdev/openwebnet/message/Lighting.java | // Path: lib/src/main/java/com/github/niqdev/openwebnet/OpenSession.java
// public class OpenSession {
//
// private final OpenMessage request;
// private final List<OpenMessage> response = new ArrayList<>();
//
// private OpenSession(OpenMessage request) {
// checkNotNull(request, "request can't be null");
// this.request = request;
// }
//
// /**
// * Helper method to create a new session.
// *
// * @param request message
// * @return session
// */
// public static OpenSession newSession(OpenMessage request) {
// return new OpenSession(request);
// }
//
// /**
// * Update the response messages.
// *
// * @param response messages
// * @return session
// */
// public OpenSession addAllResponse(List<OpenMessage> response) {
// checkNotNull(response, "response can't be null");
// this.response.addAll(response);
// return this;
// }
//
// /**
// * Update the response messages.
// *
// * @param response messages
// * @return session
// */
// public OpenSession addResponse(OpenMessage response) {
// checkNotNull(response, "response can't be null");
// this.response.add(response);
// return this;
// }
//
// /**
// * Returns the initial request message.
// *
// * @return request
// */
// public OpenMessage getRequest() {
// return request;
// }
//
// /**
// * Returns the response messages.
// *
// * @return response
// */
// public List<OpenMessage> getResponse() {
// return response;
// }
//
// @Override
// public String toString() {
// return MoreObjects.toStringHelper(this)
// .add("request", request.getValue())
// .add("response", response)
// .toString();
// }
// }
| import com.github.niqdev.openwebnet.OpenSession;
import rx.functions.Action0;
import rx.functions.Func1;
import java.util.List;
import static com.github.niqdev.openwebnet.message.Who.LIGHTING;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static java.lang.String.format; | *
* @param where Value between 0 and 9999
* @return message
* @deprecated use {@link Lighting#requestTurnOff(String, Type, String)}
*/
public static Lighting requestTurnOff(String where) {
checkRange(WHERE_MIN_VALUE, WHERE_MAX_VALUE, checkIsInteger(where));
return new Lighting(format(FORMAT_REQUEST, WHO, OFF, where));
}
/**
* OpenWebNet message request to turn light <i>OFF</i> with value <b>*1*0*WHERE##</b>.
*
* @param where Value
* @param type Type {@link Type}
* @param bus Value
* @return message
*/
public static Lighting requestTurnOff(String where, Type type, String bus) {
checkRangeType(where, type, bus);
return new Lighting(format(FORMAT_REQUEST, WHO, OFF, buildWhereValue(where, type, bus)));
}
/**
* Handle response from {@link Lighting#requestTurnOn(String)} and {@link Lighting#requestTurnOff(String)}.
*
* @param onSuccess invoked if the request has been successfully received
* @param onFail invoked otherwise
* @return {@code Observable<OpenSession>}
*/ | // Path: lib/src/main/java/com/github/niqdev/openwebnet/OpenSession.java
// public class OpenSession {
//
// private final OpenMessage request;
// private final List<OpenMessage> response = new ArrayList<>();
//
// private OpenSession(OpenMessage request) {
// checkNotNull(request, "request can't be null");
// this.request = request;
// }
//
// /**
// * Helper method to create a new session.
// *
// * @param request message
// * @return session
// */
// public static OpenSession newSession(OpenMessage request) {
// return new OpenSession(request);
// }
//
// /**
// * Update the response messages.
// *
// * @param response messages
// * @return session
// */
// public OpenSession addAllResponse(List<OpenMessage> response) {
// checkNotNull(response, "response can't be null");
// this.response.addAll(response);
// return this;
// }
//
// /**
// * Update the response messages.
// *
// * @param response messages
// * @return session
// */
// public OpenSession addResponse(OpenMessage response) {
// checkNotNull(response, "response can't be null");
// this.response.add(response);
// return this;
// }
//
// /**
// * Returns the initial request message.
// *
// * @return request
// */
// public OpenMessage getRequest() {
// return request;
// }
//
// /**
// * Returns the response messages.
// *
// * @return response
// */
// public List<OpenMessage> getResponse() {
// return response;
// }
//
// @Override
// public String toString() {
// return MoreObjects.toStringHelper(this)
// .add("request", request.getValue())
// .add("response", response)
// .toString();
// }
// }
// Path: lib/src/main/java/com/github/niqdev/openwebnet/message/Lighting.java
import com.github.niqdev.openwebnet.OpenSession;
import rx.functions.Action0;
import rx.functions.Func1;
import java.util.List;
import static com.github.niqdev.openwebnet.message.Who.LIGHTING;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static java.lang.String.format;
*
* @param where Value between 0 and 9999
* @return message
* @deprecated use {@link Lighting#requestTurnOff(String, Type, String)}
*/
public static Lighting requestTurnOff(String where) {
checkRange(WHERE_MIN_VALUE, WHERE_MAX_VALUE, checkIsInteger(where));
return new Lighting(format(FORMAT_REQUEST, WHO, OFF, where));
}
/**
* OpenWebNet message request to turn light <i>OFF</i> with value <b>*1*0*WHERE##</b>.
*
* @param where Value
* @param type Type {@link Type}
* @param bus Value
* @return message
*/
public static Lighting requestTurnOff(String where, Type type, String bus) {
checkRangeType(where, type, bus);
return new Lighting(format(FORMAT_REQUEST, WHO, OFF, buildWhereValue(where, type, bus)));
}
/**
* Handle response from {@link Lighting#requestTurnOn(String)} and {@link Lighting#requestTurnOff(String)}.
*
* @param onSuccess invoked if the request has been successfully received
* @param onFail invoked otherwise
* @return {@code Observable<OpenSession>}
*/ | public static Func1<OpenSession, OpenSession> handleResponse(Action0 onSuccess, Action0 onFail) { |
openwebnet/rx-openwebnet | lib/src/main/java/com/github/niqdev/openwebnet/message/Automation.java | // Path: lib/src/main/java/com/github/niqdev/openwebnet/OpenSession.java
// public class OpenSession {
//
// private final OpenMessage request;
// private final List<OpenMessage> response = new ArrayList<>();
//
// private OpenSession(OpenMessage request) {
// checkNotNull(request, "request can't be null");
// this.request = request;
// }
//
// /**
// * Helper method to create a new session.
// *
// * @param request message
// * @return session
// */
// public static OpenSession newSession(OpenMessage request) {
// return new OpenSession(request);
// }
//
// /**
// * Update the response messages.
// *
// * @param response messages
// * @return session
// */
// public OpenSession addAllResponse(List<OpenMessage> response) {
// checkNotNull(response, "response can't be null");
// this.response.addAll(response);
// return this;
// }
//
// /**
// * Update the response messages.
// *
// * @param response messages
// * @return session
// */
// public OpenSession addResponse(OpenMessage response) {
// checkNotNull(response, "response can't be null");
// this.response.add(response);
// return this;
// }
//
// /**
// * Returns the initial request message.
// *
// * @return request
// */
// public OpenMessage getRequest() {
// return request;
// }
//
// /**
// * Returns the response messages.
// *
// * @return response
// */
// public List<OpenMessage> getResponse() {
// return response;
// }
//
// @Override
// public String toString() {
// return MoreObjects.toStringHelper(this)
// .add("request", request.getValue())
// .add("response", response)
// .toString();
// }
// }
| import com.github.niqdev.openwebnet.OpenSession;
import rx.functions.Action0;
import rx.functions.Func1;
import java.util.List;
import static com.github.niqdev.openwebnet.message.Who.AUTOMATION;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static java.lang.String.format; | * @param where Value between 0 and 9999
* @return message
*
* @deprecated use {@link Automation#requestMoveDown(String, Type, String)}
*/
public static Automation requestMoveDown(String where) {
checkRange(WHERE_MIN_VALUE, WHERE_MAX_VALUE, checkIsInteger(where));
return new Automation(format(FORMAT_REQUEST, WHO, DOWN, where));
}
/**
* OpenWebNet message request to send the <i>DOWN</i> automation command with value <b>*2*2*WHERE##</b>.
*
* @param where Value between 0 and 9999
* @param type Type {@link Type}
* @param bus Value
* @return message
*/
public static Automation requestMoveDown(String where, Type type, String bus) {
checkRangeType(where, type, bus);
return new Automation(format(FORMAT_REQUEST, WHO, DOWN, buildWhereValue(where, type, bus)));
}
/**
* Handle response from {@link Automation#requestMoveUp(String)}, {@link Automation#requestMoveDown(String)} and {@link Automation#requestStop(String)}.
*
* @param onSuccess invoked if request has been successfully received
* @param onFail invoked otherwise
* @return {@code Observable<OpenSession>}
*/ | // Path: lib/src/main/java/com/github/niqdev/openwebnet/OpenSession.java
// public class OpenSession {
//
// private final OpenMessage request;
// private final List<OpenMessage> response = new ArrayList<>();
//
// private OpenSession(OpenMessage request) {
// checkNotNull(request, "request can't be null");
// this.request = request;
// }
//
// /**
// * Helper method to create a new session.
// *
// * @param request message
// * @return session
// */
// public static OpenSession newSession(OpenMessage request) {
// return new OpenSession(request);
// }
//
// /**
// * Update the response messages.
// *
// * @param response messages
// * @return session
// */
// public OpenSession addAllResponse(List<OpenMessage> response) {
// checkNotNull(response, "response can't be null");
// this.response.addAll(response);
// return this;
// }
//
// /**
// * Update the response messages.
// *
// * @param response messages
// * @return session
// */
// public OpenSession addResponse(OpenMessage response) {
// checkNotNull(response, "response can't be null");
// this.response.add(response);
// return this;
// }
//
// /**
// * Returns the initial request message.
// *
// * @return request
// */
// public OpenMessage getRequest() {
// return request;
// }
//
// /**
// * Returns the response messages.
// *
// * @return response
// */
// public List<OpenMessage> getResponse() {
// return response;
// }
//
// @Override
// public String toString() {
// return MoreObjects.toStringHelper(this)
// .add("request", request.getValue())
// .add("response", response)
// .toString();
// }
// }
// Path: lib/src/main/java/com/github/niqdev/openwebnet/message/Automation.java
import com.github.niqdev.openwebnet.OpenSession;
import rx.functions.Action0;
import rx.functions.Func1;
import java.util.List;
import static com.github.niqdev.openwebnet.message.Who.AUTOMATION;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static java.lang.String.format;
* @param where Value between 0 and 9999
* @return message
*
* @deprecated use {@link Automation#requestMoveDown(String, Type, String)}
*/
public static Automation requestMoveDown(String where) {
checkRange(WHERE_MIN_VALUE, WHERE_MAX_VALUE, checkIsInteger(where));
return new Automation(format(FORMAT_REQUEST, WHO, DOWN, where));
}
/**
* OpenWebNet message request to send the <i>DOWN</i> automation command with value <b>*2*2*WHERE##</b>.
*
* @param where Value between 0 and 9999
* @param type Type {@link Type}
* @param bus Value
* @return message
*/
public static Automation requestMoveDown(String where, Type type, String bus) {
checkRangeType(where, type, bus);
return new Automation(format(FORMAT_REQUEST, WHO, DOWN, buildWhereValue(where, type, bus)));
}
/**
* Handle response from {@link Automation#requestMoveUp(String)}, {@link Automation#requestMoveDown(String)} and {@link Automation#requestStop(String)}.
*
* @param onSuccess invoked if request has been successfully received
* @param onFail invoked otherwise
* @return {@code Observable<OpenSession>}
*/ | public static Func1<OpenSession, OpenSession> handleResponse(Action0 onSuccess, Action0 onFail) { |
openwebnet/rx-openwebnet | lib/src/main/java/com/github/niqdev/openwebnet/OpenWebNetApp.java | // Path: lib/src/main/java/com/github/niqdev/openwebnet/OpenWebNet.java
// public static OpenGateway gateway(final String host, final int port, final String password) {
// return new OpenGateway() {
//
// @Override
// public String getHost() {
// return host;
// }
//
// @Override
// public int getPort() {
// return port;
// }
//
// @Override
// public String getPassword() {
// return password;
// }
// };
// }
| import com.beust.jcommander.JCommander;
import com.beust.jcommander.Parameter;
import com.beust.jcommander.ParameterException;
import rx.schedulers.Schedulers;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import static com.github.niqdev.openwebnet.OpenWebNet.gateway; | package com.github.niqdev.openwebnet;
public class OpenWebNetApp {
@Parameter(names={"--host", "-h"}, required = true, description = "IP address or hostname of the Gateway")
String host;
@Parameter(names={"--port", "-p"}, description = "Port of the Gateway")
int port = 20000;
@Parameter(names={"--password"}, description = "Optional password of the Gateway")
String password;
@Parameter(names={"--frame", "-f"}, required = true, description = "Request frame")
String frame;
public static void main(String[] args) {
OpenWebNetApp main = new OpenWebNetApp();
try {
JCommander.newBuilder()
.addObject(main)
.build()
.parse(args);
main.run();
} catch (ParameterException e) {
e.usage();
}
}
private void run() {
ExecutorService executor = Executors.newSingleThreadExecutor();
OpenWebNet | // Path: lib/src/main/java/com/github/niqdev/openwebnet/OpenWebNet.java
// public static OpenGateway gateway(final String host, final int port, final String password) {
// return new OpenGateway() {
//
// @Override
// public String getHost() {
// return host;
// }
//
// @Override
// public int getPort() {
// return port;
// }
//
// @Override
// public String getPassword() {
// return password;
// }
// };
// }
// Path: lib/src/main/java/com/github/niqdev/openwebnet/OpenWebNetApp.java
import com.beust.jcommander.JCommander;
import com.beust.jcommander.Parameter;
import com.beust.jcommander.ParameterException;
import rx.schedulers.Schedulers;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import static com.github.niqdev.openwebnet.OpenWebNet.gateway;
package com.github.niqdev.openwebnet;
public class OpenWebNetApp {
@Parameter(names={"--host", "-h"}, required = true, description = "IP address or hostname of the Gateway")
String host;
@Parameter(names={"--port", "-p"}, description = "Port of the Gateway")
int port = 20000;
@Parameter(names={"--password"}, description = "Optional password of the Gateway")
String password;
@Parameter(names={"--frame", "-f"}, required = true, description = "Request frame")
String frame;
public static void main(String[] args) {
OpenWebNetApp main = new OpenWebNetApp();
try {
JCommander.newBuilder()
.addObject(main)
.build()
.parse(args);
main.run();
} catch (ParameterException e) {
e.usage();
}
}
private void run() {
ExecutorService executor = Executors.newSingleThreadExecutor();
OpenWebNet | .newClient(gateway(host, port, password)) |
openwebnet/rx-openwebnet | lib/src/test/java/com/github/niqdev/openwebnet/message/BaseOpenMessageTest.java | // Path: lib/src/test/java/com/github/niqdev/openwebnet/ThrowableCaptor.java
// public static Throwable captureThrowable(Actor actor) {
// Throwable result = null;
// try {
// actor.act();
// } catch (Throwable throwable) {
// result = throwable;
// }
// return result;
// }
//
// Path: lib/src/main/java/com/github/niqdev/openwebnet/message/BaseOpenMessage.java
// protected static String checkBus(String bus) {
// checkIsInteger(bus);
// checkArgument(bus.length() == 2, "invalid length [2]");
// // name from docs
// int i3 = Integer.parseInt(bus.substring(0, 1));
// int i4 = Integer.parseInt(bus.substring(1));
//
// checkArgument(i3 == 0 || i3 == 1, "invalid i3 [0-1]");
//
// if (i3 == 0) {
// checkArgument(i4 >= 1 && i4 <= 9, "invalid i4 [1-9]");
// }
// if (i3 == 1) {
// checkArgument(i4 >= 1 && i4 <= 5, "invalid i4 [1-5]");
// }
//
// return bus;
// }
//
// Path: lib/src/main/java/com/github/niqdev/openwebnet/message/BaseOpenMessage.java
// protected static Boolean isValidBus(String bus) {
// try {
// checkBus(bus);
// return true;
// } catch (Throwable e) {
// return false;
// }
// }
| import org.junit.Test;
import static com.github.niqdev.openwebnet.ThrowableCaptor.captureThrowable;
import static com.github.niqdev.openwebnet.message.BaseOpenMessage.checkBus;
import static com.github.niqdev.openwebnet.message.BaseOpenMessage.isValidBus;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.*; | package com.github.niqdev.openwebnet.message;
public class BaseOpenMessageTest {
@Test
public void testCheckBus() { | // Path: lib/src/test/java/com/github/niqdev/openwebnet/ThrowableCaptor.java
// public static Throwable captureThrowable(Actor actor) {
// Throwable result = null;
// try {
// actor.act();
// } catch (Throwable throwable) {
// result = throwable;
// }
// return result;
// }
//
// Path: lib/src/main/java/com/github/niqdev/openwebnet/message/BaseOpenMessage.java
// protected static String checkBus(String bus) {
// checkIsInteger(bus);
// checkArgument(bus.length() == 2, "invalid length [2]");
// // name from docs
// int i3 = Integer.parseInt(bus.substring(0, 1));
// int i4 = Integer.parseInt(bus.substring(1));
//
// checkArgument(i3 == 0 || i3 == 1, "invalid i3 [0-1]");
//
// if (i3 == 0) {
// checkArgument(i4 >= 1 && i4 <= 9, "invalid i4 [1-9]");
// }
// if (i3 == 1) {
// checkArgument(i4 >= 1 && i4 <= 5, "invalid i4 [1-5]");
// }
//
// return bus;
// }
//
// Path: lib/src/main/java/com/github/niqdev/openwebnet/message/BaseOpenMessage.java
// protected static Boolean isValidBus(String bus) {
// try {
// checkBus(bus);
// return true;
// } catch (Throwable e) {
// return false;
// }
// }
// Path: lib/src/test/java/com/github/niqdev/openwebnet/message/BaseOpenMessageTest.java
import org.junit.Test;
import static com.github.niqdev.openwebnet.ThrowableCaptor.captureThrowable;
import static com.github.niqdev.openwebnet.message.BaseOpenMessage.checkBus;
import static com.github.niqdev.openwebnet.message.BaseOpenMessage.isValidBus;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.*;
package com.github.niqdev.openwebnet.message;
public class BaseOpenMessageTest {
@Test
public void testCheckBus() { | assertEquals("should be a valid value", "01", checkBus("01")); |
openwebnet/rx-openwebnet | lib/src/test/java/com/github/niqdev/openwebnet/message/BaseOpenMessageTest.java | // Path: lib/src/test/java/com/github/niqdev/openwebnet/ThrowableCaptor.java
// public static Throwable captureThrowable(Actor actor) {
// Throwable result = null;
// try {
// actor.act();
// } catch (Throwable throwable) {
// result = throwable;
// }
// return result;
// }
//
// Path: lib/src/main/java/com/github/niqdev/openwebnet/message/BaseOpenMessage.java
// protected static String checkBus(String bus) {
// checkIsInteger(bus);
// checkArgument(bus.length() == 2, "invalid length [2]");
// // name from docs
// int i3 = Integer.parseInt(bus.substring(0, 1));
// int i4 = Integer.parseInt(bus.substring(1));
//
// checkArgument(i3 == 0 || i3 == 1, "invalid i3 [0-1]");
//
// if (i3 == 0) {
// checkArgument(i4 >= 1 && i4 <= 9, "invalid i4 [1-9]");
// }
// if (i3 == 1) {
// checkArgument(i4 >= 1 && i4 <= 5, "invalid i4 [1-5]");
// }
//
// return bus;
// }
//
// Path: lib/src/main/java/com/github/niqdev/openwebnet/message/BaseOpenMessage.java
// protected static Boolean isValidBus(String bus) {
// try {
// checkBus(bus);
// return true;
// } catch (Throwable e) {
// return false;
// }
// }
| import org.junit.Test;
import static com.github.niqdev.openwebnet.ThrowableCaptor.captureThrowable;
import static com.github.niqdev.openwebnet.message.BaseOpenMessage.checkBus;
import static com.github.niqdev.openwebnet.message.BaseOpenMessage.isValidBus;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.*; | package com.github.niqdev.openwebnet.message;
public class BaseOpenMessageTest {
@Test
public void testCheckBus() {
assertEquals("should be a valid value", "01", checkBus("01"));
assertEquals("should be a valid value", "09", checkBus("09"));
assertEquals("should be a valid value", "11", checkBus("11"));
assertEquals("should be a valid value", "15", checkBus("15"));
}
@Test
public void testCheckBusInvalid() { | // Path: lib/src/test/java/com/github/niqdev/openwebnet/ThrowableCaptor.java
// public static Throwable captureThrowable(Actor actor) {
// Throwable result = null;
// try {
// actor.act();
// } catch (Throwable throwable) {
// result = throwable;
// }
// return result;
// }
//
// Path: lib/src/main/java/com/github/niqdev/openwebnet/message/BaseOpenMessage.java
// protected static String checkBus(String bus) {
// checkIsInteger(bus);
// checkArgument(bus.length() == 2, "invalid length [2]");
// // name from docs
// int i3 = Integer.parseInt(bus.substring(0, 1));
// int i4 = Integer.parseInt(bus.substring(1));
//
// checkArgument(i3 == 0 || i3 == 1, "invalid i3 [0-1]");
//
// if (i3 == 0) {
// checkArgument(i4 >= 1 && i4 <= 9, "invalid i4 [1-9]");
// }
// if (i3 == 1) {
// checkArgument(i4 >= 1 && i4 <= 5, "invalid i4 [1-5]");
// }
//
// return bus;
// }
//
// Path: lib/src/main/java/com/github/niqdev/openwebnet/message/BaseOpenMessage.java
// protected static Boolean isValidBus(String bus) {
// try {
// checkBus(bus);
// return true;
// } catch (Throwable e) {
// return false;
// }
// }
// Path: lib/src/test/java/com/github/niqdev/openwebnet/message/BaseOpenMessageTest.java
import org.junit.Test;
import static com.github.niqdev.openwebnet.ThrowableCaptor.captureThrowable;
import static com.github.niqdev.openwebnet.message.BaseOpenMessage.checkBus;
import static com.github.niqdev.openwebnet.message.BaseOpenMessage.isValidBus;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.*;
package com.github.niqdev.openwebnet.message;
public class BaseOpenMessageTest {
@Test
public void testCheckBus() {
assertEquals("should be a valid value", "01", checkBus("01"));
assertEquals("should be a valid value", "09", checkBus("09"));
assertEquals("should be a valid value", "11", checkBus("11"));
assertEquals("should be a valid value", "15", checkBus("15"));
}
@Test
public void testCheckBusInvalid() { | assertThat(captureThrowable(() -> checkBus(null))) |
openwebnet/rx-openwebnet | lib/src/test/java/com/github/niqdev/openwebnet/message/BaseOpenMessageTest.java | // Path: lib/src/test/java/com/github/niqdev/openwebnet/ThrowableCaptor.java
// public static Throwable captureThrowable(Actor actor) {
// Throwable result = null;
// try {
// actor.act();
// } catch (Throwable throwable) {
// result = throwable;
// }
// return result;
// }
//
// Path: lib/src/main/java/com/github/niqdev/openwebnet/message/BaseOpenMessage.java
// protected static String checkBus(String bus) {
// checkIsInteger(bus);
// checkArgument(bus.length() == 2, "invalid length [2]");
// // name from docs
// int i3 = Integer.parseInt(bus.substring(0, 1));
// int i4 = Integer.parseInt(bus.substring(1));
//
// checkArgument(i3 == 0 || i3 == 1, "invalid i3 [0-1]");
//
// if (i3 == 0) {
// checkArgument(i4 >= 1 && i4 <= 9, "invalid i4 [1-9]");
// }
// if (i3 == 1) {
// checkArgument(i4 >= 1 && i4 <= 5, "invalid i4 [1-5]");
// }
//
// return bus;
// }
//
// Path: lib/src/main/java/com/github/niqdev/openwebnet/message/BaseOpenMessage.java
// protected static Boolean isValidBus(String bus) {
// try {
// checkBus(bus);
// return true;
// } catch (Throwable e) {
// return false;
// }
// }
| import org.junit.Test;
import static com.github.niqdev.openwebnet.ThrowableCaptor.captureThrowable;
import static com.github.niqdev.openwebnet.message.BaseOpenMessage.checkBus;
import static com.github.niqdev.openwebnet.message.BaseOpenMessage.isValidBus;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.*; | .isInstanceOf(IllegalArgumentException.class)
.hasMessage("invalid integer format");
assertThat(captureThrowable(() -> checkBus("0")))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("invalid length [2]");
assertThat(captureThrowable(() -> checkBus("010")))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("invalid length [2]");
assertThat(captureThrowable(() -> checkBus("20")))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("invalid i3 [0-1]");
assertThat(captureThrowable(() -> checkBus("00")))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("invalid i4 [1-9]");
assertThat(captureThrowable(() -> checkBus("10")))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("invalid i4 [1-5]");
assertThat(captureThrowable(() -> checkBus("16")))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("invalid i4 [1-5]");
}
@Test
public void testIsValidBus() { | // Path: lib/src/test/java/com/github/niqdev/openwebnet/ThrowableCaptor.java
// public static Throwable captureThrowable(Actor actor) {
// Throwable result = null;
// try {
// actor.act();
// } catch (Throwable throwable) {
// result = throwable;
// }
// return result;
// }
//
// Path: lib/src/main/java/com/github/niqdev/openwebnet/message/BaseOpenMessage.java
// protected static String checkBus(String bus) {
// checkIsInteger(bus);
// checkArgument(bus.length() == 2, "invalid length [2]");
// // name from docs
// int i3 = Integer.parseInt(bus.substring(0, 1));
// int i4 = Integer.parseInt(bus.substring(1));
//
// checkArgument(i3 == 0 || i3 == 1, "invalid i3 [0-1]");
//
// if (i3 == 0) {
// checkArgument(i4 >= 1 && i4 <= 9, "invalid i4 [1-9]");
// }
// if (i3 == 1) {
// checkArgument(i4 >= 1 && i4 <= 5, "invalid i4 [1-5]");
// }
//
// return bus;
// }
//
// Path: lib/src/main/java/com/github/niqdev/openwebnet/message/BaseOpenMessage.java
// protected static Boolean isValidBus(String bus) {
// try {
// checkBus(bus);
// return true;
// } catch (Throwable e) {
// return false;
// }
// }
// Path: lib/src/test/java/com/github/niqdev/openwebnet/message/BaseOpenMessageTest.java
import org.junit.Test;
import static com.github.niqdev.openwebnet.ThrowableCaptor.captureThrowable;
import static com.github.niqdev.openwebnet.message.BaseOpenMessage.checkBus;
import static com.github.niqdev.openwebnet.message.BaseOpenMessage.isValidBus;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.*;
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("invalid integer format");
assertThat(captureThrowable(() -> checkBus("0")))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("invalid length [2]");
assertThat(captureThrowable(() -> checkBus("010")))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("invalid length [2]");
assertThat(captureThrowable(() -> checkBus("20")))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("invalid i3 [0-1]");
assertThat(captureThrowable(() -> checkBus("00")))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("invalid i4 [1-9]");
assertThat(captureThrowable(() -> checkBus("10")))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("invalid i4 [1-5]");
assertThat(captureThrowable(() -> checkBus("16")))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("invalid i4 [1-5]");
}
@Test
public void testIsValidBus() { | assertTrue("should be a valid value", isValidBus("01")); |
openwebnet/rx-openwebnet | lib/src/main/java/com/github/niqdev/openwebnet/message/Heating.java | // Path: lib/src/main/java/com/github/niqdev/openwebnet/OpenSession.java
// public class OpenSession {
//
// private final OpenMessage request;
// private final List<OpenMessage> response = new ArrayList<>();
//
// private OpenSession(OpenMessage request) {
// checkNotNull(request, "request can't be null");
// this.request = request;
// }
//
// /**
// * Helper method to create a new session.
// *
// * @param request message
// * @return session
// */
// public static OpenSession newSession(OpenMessage request) {
// return new OpenSession(request);
// }
//
// /**
// * Update the response messages.
// *
// * @param response messages
// * @return session
// */
// public OpenSession addAllResponse(List<OpenMessage> response) {
// checkNotNull(response, "response can't be null");
// this.response.addAll(response);
// return this;
// }
//
// /**
// * Update the response messages.
// *
// * @param response messages
// * @return session
// */
// public OpenSession addResponse(OpenMessage response) {
// checkNotNull(response, "response can't be null");
// this.response.add(response);
// return this;
// }
//
// /**
// * Returns the initial request message.
// *
// * @return request
// */
// public OpenMessage getRequest() {
// return request;
// }
//
// /**
// * Returns the response messages.
// *
// * @return response
// */
// public List<OpenMessage> getResponse() {
// return response;
// }
//
// @Override
// public String toString() {
// return MoreObjects.toStringHelper(this)
// .add("request", request.getValue())
// .add("response", response)
// .toString();
// }
// }
| import com.github.niqdev.openwebnet.OpenSession;
import rx.functions.Action0;
import rx.functions.Action1;
import rx.functions.Func1;
import java.text.DecimalFormat;
import java.util.List;
import static com.github.niqdev.openwebnet.message.Who.TEMPERATURE_CONTROL;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static java.lang.String.format; | package com.github.niqdev.openwebnet.message;
/**
* OpenWebNet Heating.
*
* <pre>
* {@code
*
* import static com.github.niqdev.openwebnet.OpenWebNet.defaultGateway;
*
* // reads temperature
* OpenWebNet
* .newClient(defaultGateway("IP_ADDRESS"))
* .send(Heating.requestTemperature("WHERE"))
* .map(Heating.handleTemperature(value -> System.out.println(value), () -> System.out.println("error")))
* .subscribe(System.out::println);
* }
* </pre>
*/
public class Heating extends BaseOpenMessage {
/**
* Common temperature scale.
*/
public enum TemperatureScale {
CELSIUS, FAHRENHEIT, KELVIN
}
private static final int READ_TEMPERATURE = 0;
private static final int WHERE_MAX_VALUE_TEMPERATURE = 899;
private static final int WHO = TEMPERATURE_CONTROL.value();
private final TemperatureScale temperatureScale;
private Heating(String value, TemperatureScale scale) {
super(value);
this.temperatureScale = scale;
}
/**
* OpenWebNet message request to read temperature with a specific {@link TemperatureScale} and value <b>*4*WHERE*0##</b>.
*
* @param where Value between 0 and 899
* @param scale Temperature scale
* @return message
*/
public static Heating requestTemperature(String where, TemperatureScale scale) {
checkRange(WHERE_MIN_VALUE, WHERE_MAX_VALUE_TEMPERATURE, checkIsInteger(where));
checkNotNull(scale, "invalid null scale");
return new Heating(format(FORMAT_DIMENSION, WHO, where, READ_TEMPERATURE), scale);
}
/**
* OpenWebNet message request to read temperature in {@link TemperatureScale#CELSIUS} and value <b>*4*WHERE*0##</b>.
*
* @param where Value between 0 and 899
* @return message
*/
public static Heating requestTemperature(String where) {
return requestTemperature(where, TemperatureScale.CELSIUS);
}
/**
* Handle response from {@link Heating#requestTemperature(String, TemperatureScale)}.
*
* @param onSuccess invoked if the temperature has been read correctly
* @param onError invoked otherwise
* @return {@code Observable<OpenSession>}
*/ | // Path: lib/src/main/java/com/github/niqdev/openwebnet/OpenSession.java
// public class OpenSession {
//
// private final OpenMessage request;
// private final List<OpenMessage> response = new ArrayList<>();
//
// private OpenSession(OpenMessage request) {
// checkNotNull(request, "request can't be null");
// this.request = request;
// }
//
// /**
// * Helper method to create a new session.
// *
// * @param request message
// * @return session
// */
// public static OpenSession newSession(OpenMessage request) {
// return new OpenSession(request);
// }
//
// /**
// * Update the response messages.
// *
// * @param response messages
// * @return session
// */
// public OpenSession addAllResponse(List<OpenMessage> response) {
// checkNotNull(response, "response can't be null");
// this.response.addAll(response);
// return this;
// }
//
// /**
// * Update the response messages.
// *
// * @param response messages
// * @return session
// */
// public OpenSession addResponse(OpenMessage response) {
// checkNotNull(response, "response can't be null");
// this.response.add(response);
// return this;
// }
//
// /**
// * Returns the initial request message.
// *
// * @return request
// */
// public OpenMessage getRequest() {
// return request;
// }
//
// /**
// * Returns the response messages.
// *
// * @return response
// */
// public List<OpenMessage> getResponse() {
// return response;
// }
//
// @Override
// public String toString() {
// return MoreObjects.toStringHelper(this)
// .add("request", request.getValue())
// .add("response", response)
// .toString();
// }
// }
// Path: lib/src/main/java/com/github/niqdev/openwebnet/message/Heating.java
import com.github.niqdev.openwebnet.OpenSession;
import rx.functions.Action0;
import rx.functions.Action1;
import rx.functions.Func1;
import java.text.DecimalFormat;
import java.util.List;
import static com.github.niqdev.openwebnet.message.Who.TEMPERATURE_CONTROL;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static java.lang.String.format;
package com.github.niqdev.openwebnet.message;
/**
* OpenWebNet Heating.
*
* <pre>
* {@code
*
* import static com.github.niqdev.openwebnet.OpenWebNet.defaultGateway;
*
* // reads temperature
* OpenWebNet
* .newClient(defaultGateway("IP_ADDRESS"))
* .send(Heating.requestTemperature("WHERE"))
* .map(Heating.handleTemperature(value -> System.out.println(value), () -> System.out.println("error")))
* .subscribe(System.out::println);
* }
* </pre>
*/
public class Heating extends BaseOpenMessage {
/**
* Common temperature scale.
*/
public enum TemperatureScale {
CELSIUS, FAHRENHEIT, KELVIN
}
private static final int READ_TEMPERATURE = 0;
private static final int WHERE_MAX_VALUE_TEMPERATURE = 899;
private static final int WHO = TEMPERATURE_CONTROL.value();
private final TemperatureScale temperatureScale;
private Heating(String value, TemperatureScale scale) {
super(value);
this.temperatureScale = scale;
}
/**
* OpenWebNet message request to read temperature with a specific {@link TemperatureScale} and value <b>*4*WHERE*0##</b>.
*
* @param where Value between 0 and 899
* @param scale Temperature scale
* @return message
*/
public static Heating requestTemperature(String where, TemperatureScale scale) {
checkRange(WHERE_MIN_VALUE, WHERE_MAX_VALUE_TEMPERATURE, checkIsInteger(where));
checkNotNull(scale, "invalid null scale");
return new Heating(format(FORMAT_DIMENSION, WHO, where, READ_TEMPERATURE), scale);
}
/**
* OpenWebNet message request to read temperature in {@link TemperatureScale#CELSIUS} and value <b>*4*WHERE*0##</b>.
*
* @param where Value between 0 and 899
* @return message
*/
public static Heating requestTemperature(String where) {
return requestTemperature(where, TemperatureScale.CELSIUS);
}
/**
* Handle response from {@link Heating#requestTemperature(String, TemperatureScale)}.
*
* @param onSuccess invoked if the temperature has been read correctly
* @param onError invoked otherwise
* @return {@code Observable<OpenSession>}
*/ | public static Func1<OpenSession, OpenSession> handleTemperature(Action1<Double> onSuccess, Action0 onError) { |
openwebnet/rx-openwebnet | lib/src/main/java/com/github/niqdev/openwebnet/message/BaseOpenMessage.java | // Path: lib/src/main/java/com/github/niqdev/openwebnet/OpenSession.java
// public class OpenSession {
//
// private final OpenMessage request;
// private final List<OpenMessage> response = new ArrayList<>();
//
// private OpenSession(OpenMessage request) {
// checkNotNull(request, "request can't be null");
// this.request = request;
// }
//
// /**
// * Helper method to create a new session.
// *
// * @param request message
// * @return session
// */
// public static OpenSession newSession(OpenMessage request) {
// return new OpenSession(request);
// }
//
// /**
// * Update the response messages.
// *
// * @param response messages
// * @return session
// */
// public OpenSession addAllResponse(List<OpenMessage> response) {
// checkNotNull(response, "response can't be null");
// this.response.addAll(response);
// return this;
// }
//
// /**
// * Update the response messages.
// *
// * @param response messages
// * @return session
// */
// public OpenSession addResponse(OpenMessage response) {
// checkNotNull(response, "response can't be null");
// this.response.add(response);
// return this;
// }
//
// /**
// * Returns the initial request message.
// *
// * @return request
// */
// public OpenMessage getRequest() {
// return request;
// }
//
// /**
// * Returns the response messages.
// *
// * @return response
// */
// public List<OpenMessage> getResponse() {
// return response;
// }
//
// @Override
// public String toString() {
// return MoreObjects.toStringHelper(this)
// .add("request", request.getValue())
// .add("response", response)
// .toString();
// }
// }
| import com.github.niqdev.openwebnet.OpenSession;
import rx.functions.Action0;
import rx.functions.Func1;
import java.util.List;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static java.lang.String.format; | }
protected static void checkRange(Integer from, Integer to, Integer value) {
checkNotNull(value, "invalid null value");
checkArgument(isInRange(from, to, value), format("value must be between %d and %d", from, to));
}
protected static boolean isInRange(Integer from, Integer to, Integer value) {
checkNotNull(value, "invalid null value");
return value >= from && value <= to;
}
/*
* See also org.apache.commons.lang.StringUtils.isNumeric
*/
protected static int checkIsInteger(String value) {
try {
return Integer.parseInt(value);
} catch (NumberFormatException e) {
throw new IllegalArgumentException("invalid integer format");
}
}
protected static void isValidPrefixType(OpenMessage request, String format, int who) {
checkNotNull(request, "request is null");
checkNotNull(request.getValue(), "request value is null");
boolean isValidWho = request.getValue().startsWith(format(format, who));
checkArgument(isValidWho, "invalid request of type " + who);
}
| // Path: lib/src/main/java/com/github/niqdev/openwebnet/OpenSession.java
// public class OpenSession {
//
// private final OpenMessage request;
// private final List<OpenMessage> response = new ArrayList<>();
//
// private OpenSession(OpenMessage request) {
// checkNotNull(request, "request can't be null");
// this.request = request;
// }
//
// /**
// * Helper method to create a new session.
// *
// * @param request message
// * @return session
// */
// public static OpenSession newSession(OpenMessage request) {
// return new OpenSession(request);
// }
//
// /**
// * Update the response messages.
// *
// * @param response messages
// * @return session
// */
// public OpenSession addAllResponse(List<OpenMessage> response) {
// checkNotNull(response, "response can't be null");
// this.response.addAll(response);
// return this;
// }
//
// /**
// * Update the response messages.
// *
// * @param response messages
// * @return session
// */
// public OpenSession addResponse(OpenMessage response) {
// checkNotNull(response, "response can't be null");
// this.response.add(response);
// return this;
// }
//
// /**
// * Returns the initial request message.
// *
// * @return request
// */
// public OpenMessage getRequest() {
// return request;
// }
//
// /**
// * Returns the response messages.
// *
// * @return response
// */
// public List<OpenMessage> getResponse() {
// return response;
// }
//
// @Override
// public String toString() {
// return MoreObjects.toStringHelper(this)
// .add("request", request.getValue())
// .add("response", response)
// .toString();
// }
// }
// Path: lib/src/main/java/com/github/niqdev/openwebnet/message/BaseOpenMessage.java
import com.github.niqdev.openwebnet.OpenSession;
import rx.functions.Action0;
import rx.functions.Func1;
import java.util.List;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static java.lang.String.format;
}
protected static void checkRange(Integer from, Integer to, Integer value) {
checkNotNull(value, "invalid null value");
checkArgument(isInRange(from, to, value), format("value must be between %d and %d", from, to));
}
protected static boolean isInRange(Integer from, Integer to, Integer value) {
checkNotNull(value, "invalid null value");
return value >= from && value <= to;
}
/*
* See also org.apache.commons.lang.StringUtils.isNumeric
*/
protected static int checkIsInteger(String value) {
try {
return Integer.parseInt(value);
} catch (NumberFormatException e) {
throw new IllegalArgumentException("invalid integer format");
}
}
protected static void isValidPrefixType(OpenMessage request, String format, int who) {
checkNotNull(request, "request is null");
checkNotNull(request.getValue(), "request value is null");
boolean isValidWho = request.getValue().startsWith(format(format, who));
checkArgument(isValidWho, "invalid request of type " + who);
}
| protected static Func1<OpenSession, OpenSession> handleResponse(Action0 onSuccess, Action0 onFail, int who) { |
openwebnet/rx-openwebnet | lib/src/main/java/com/github/niqdev/openwebnet/message/Scenario.java | // Path: lib/src/main/java/com/github/niqdev/openwebnet/OpenSession.java
// public class OpenSession {
//
// private final OpenMessage request;
// private final List<OpenMessage> response = new ArrayList<>();
//
// private OpenSession(OpenMessage request) {
// checkNotNull(request, "request can't be null");
// this.request = request;
// }
//
// /**
// * Helper method to create a new session.
// *
// * @param request message
// * @return session
// */
// public static OpenSession newSession(OpenMessage request) {
// return new OpenSession(request);
// }
//
// /**
// * Update the response messages.
// *
// * @param response messages
// * @return session
// */
// public OpenSession addAllResponse(List<OpenMessage> response) {
// checkNotNull(response, "response can't be null");
// this.response.addAll(response);
// return this;
// }
//
// /**
// * Update the response messages.
// *
// * @param response messages
// * @return session
// */
// public OpenSession addResponse(OpenMessage response) {
// checkNotNull(response, "response can't be null");
// this.response.add(response);
// return this;
// }
//
// /**
// * Returns the initial request message.
// *
// * @return request
// */
// public OpenMessage getRequest() {
// return request;
// }
//
// /**
// * Returns the response messages.
// *
// * @return response
// */
// public List<OpenMessage> getResponse() {
// return response;
// }
//
// @Override
// public String toString() {
// return MoreObjects.toStringHelper(this)
// .add("request", request.getValue())
// .add("response", response)
// .toString();
// }
// }
| import com.github.niqdev.openwebnet.OpenSession;
import com.google.common.collect.FluentIterable;
import rx.functions.Action0;
import rx.functions.Func1;
import java.util.List;
import static com.github.niqdev.openwebnet.message.Who.SCENARIO_PROGRAMMING;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static java.lang.String.format; | package com.github.niqdev.openwebnet.message;
/**
* OpenWebNet Scenario.
*
* <pre>
* {@code
*
* import static com.github.niqdev.openwebnet.OpenWebNet.defaultGateway;
*
* OpenWebNet client = OpenWebNet.newClient(defaultGateway("IP_ADDRESS"));
*
* // start scenario 31
* client
* .send(Scenario.requestStart("31", Scenario.Version.MH200N))
* .map(Scenario.handleResponse(() -> System.out.println("START"), () -> System.out.println("STOP")))
* .subscribe(System.out::println);
*
* // requests status scenario 31
* client
* .send(Scenario.requestStatus("31"))
* .map(Scenario.handleStatus(
* () -> System.out.println("STARTED"),
* () -> System.out.println("STOPPED"),
* () -> System.out.println("ENABLED"),
* () -> System.out.println("DISABLED")))
* .subscribe(System.out::println);
* }
* </pre>
*/
public class Scenario extends BaseOpenMessage {
private static final int START = 1;
private static final int STOP = 2;
private static final int ENABLE = 3;
private static final int DISABLE = 4;
private static final int WHO = SCENARIO_PROGRAMMING.value();
public enum Version {
// 0-300
MH200N,
// numeric 0-9999
MH202
}
private Scenario(String value) {
super(value);
}
/**
* OpenWebNet message request to send the <i>START</i> scenario command with value <b>*17*1*WHERE##</b>.
*
* @param where Value between 0 and 9999
* @return message
*/
public static Scenario requestStart(String where) {
checkRange(WHERE_MIN_VALUE, WHERE_MAX_VALUE, checkIsInteger(where));
return new Scenario(format(FORMAT_REQUEST, WHO, START, where));
}
/**
* OpenWebNet message request to send the <i>START</i> scenario command with value <b>*17*1*WHERE##</b>.
*
* @param where Value between 0 and 300 if MH200N or 0 and 9999 if MH202
* @param version MH200N or MH202
* @return message
*/
public static Scenario requestStart(String where, Version version) {
checkRangeVersion(where, version);
return new Scenario(format(FORMAT_REQUEST, WHO, START, where));
}
/**
* OpenWebNet message request to send the <i>STOP</i> scenario command with value <b>*17*2*WHERE##</b>.
*
* @param where Value between 0 and 9999
* @return message
*/
public static Scenario requestStop(String where) {
checkRange(WHERE_MIN_VALUE, WHERE_MAX_VALUE, checkIsInteger(where));
return new Scenario(format(FORMAT_REQUEST, WHO, STOP, where));
}
/**
* OpenWebNet message request to send the <i>STOP</i> scenario command with value <b>*17*2*WHERE##</b>.
*
* @param where Value between 0 and 300 if MH200N or 0 and 9999 if MH202
* @param version MH200N or MH202
* @return message
*/
public static Scenario requestStop(String where, Version version) {
checkRangeVersion(where, version);
return new Scenario(format(FORMAT_REQUEST, WHO, STOP, where));
}
/**
* Handle response from {@link Scenario#requestStart(String)} and {@link Scenario#requestStop(String)}.
*
* @param onSuccess invoked if the request has been successfully received
* @param onFail invoked otherwise
* @return {@code Observable<OpenSession>}
*/ | // Path: lib/src/main/java/com/github/niqdev/openwebnet/OpenSession.java
// public class OpenSession {
//
// private final OpenMessage request;
// private final List<OpenMessage> response = new ArrayList<>();
//
// private OpenSession(OpenMessage request) {
// checkNotNull(request, "request can't be null");
// this.request = request;
// }
//
// /**
// * Helper method to create a new session.
// *
// * @param request message
// * @return session
// */
// public static OpenSession newSession(OpenMessage request) {
// return new OpenSession(request);
// }
//
// /**
// * Update the response messages.
// *
// * @param response messages
// * @return session
// */
// public OpenSession addAllResponse(List<OpenMessage> response) {
// checkNotNull(response, "response can't be null");
// this.response.addAll(response);
// return this;
// }
//
// /**
// * Update the response messages.
// *
// * @param response messages
// * @return session
// */
// public OpenSession addResponse(OpenMessage response) {
// checkNotNull(response, "response can't be null");
// this.response.add(response);
// return this;
// }
//
// /**
// * Returns the initial request message.
// *
// * @return request
// */
// public OpenMessage getRequest() {
// return request;
// }
//
// /**
// * Returns the response messages.
// *
// * @return response
// */
// public List<OpenMessage> getResponse() {
// return response;
// }
//
// @Override
// public String toString() {
// return MoreObjects.toStringHelper(this)
// .add("request", request.getValue())
// .add("response", response)
// .toString();
// }
// }
// Path: lib/src/main/java/com/github/niqdev/openwebnet/message/Scenario.java
import com.github.niqdev.openwebnet.OpenSession;
import com.google.common.collect.FluentIterable;
import rx.functions.Action0;
import rx.functions.Func1;
import java.util.List;
import static com.github.niqdev.openwebnet.message.Who.SCENARIO_PROGRAMMING;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static java.lang.String.format;
package com.github.niqdev.openwebnet.message;
/**
* OpenWebNet Scenario.
*
* <pre>
* {@code
*
* import static com.github.niqdev.openwebnet.OpenWebNet.defaultGateway;
*
* OpenWebNet client = OpenWebNet.newClient(defaultGateway("IP_ADDRESS"));
*
* // start scenario 31
* client
* .send(Scenario.requestStart("31", Scenario.Version.MH200N))
* .map(Scenario.handleResponse(() -> System.out.println("START"), () -> System.out.println("STOP")))
* .subscribe(System.out::println);
*
* // requests status scenario 31
* client
* .send(Scenario.requestStatus("31"))
* .map(Scenario.handleStatus(
* () -> System.out.println("STARTED"),
* () -> System.out.println("STOPPED"),
* () -> System.out.println("ENABLED"),
* () -> System.out.println("DISABLED")))
* .subscribe(System.out::println);
* }
* </pre>
*/
public class Scenario extends BaseOpenMessage {
private static final int START = 1;
private static final int STOP = 2;
private static final int ENABLE = 3;
private static final int DISABLE = 4;
private static final int WHO = SCENARIO_PROGRAMMING.value();
public enum Version {
// 0-300
MH200N,
// numeric 0-9999
MH202
}
private Scenario(String value) {
super(value);
}
/**
* OpenWebNet message request to send the <i>START</i> scenario command with value <b>*17*1*WHERE##</b>.
*
* @param where Value between 0 and 9999
* @return message
*/
public static Scenario requestStart(String where) {
checkRange(WHERE_MIN_VALUE, WHERE_MAX_VALUE, checkIsInteger(where));
return new Scenario(format(FORMAT_REQUEST, WHO, START, where));
}
/**
* OpenWebNet message request to send the <i>START</i> scenario command with value <b>*17*1*WHERE##</b>.
*
* @param where Value between 0 and 300 if MH200N or 0 and 9999 if MH202
* @param version MH200N or MH202
* @return message
*/
public static Scenario requestStart(String where, Version version) {
checkRangeVersion(where, version);
return new Scenario(format(FORMAT_REQUEST, WHO, START, where));
}
/**
* OpenWebNet message request to send the <i>STOP</i> scenario command with value <b>*17*2*WHERE##</b>.
*
* @param where Value between 0 and 9999
* @return message
*/
public static Scenario requestStop(String where) {
checkRange(WHERE_MIN_VALUE, WHERE_MAX_VALUE, checkIsInteger(where));
return new Scenario(format(FORMAT_REQUEST, WHO, STOP, where));
}
/**
* OpenWebNet message request to send the <i>STOP</i> scenario command with value <b>*17*2*WHERE##</b>.
*
* @param where Value between 0 and 300 if MH200N or 0 and 9999 if MH202
* @param version MH200N or MH202
* @return message
*/
public static Scenario requestStop(String where, Version version) {
checkRangeVersion(where, version);
return new Scenario(format(FORMAT_REQUEST, WHO, STOP, where));
}
/**
* Handle response from {@link Scenario#requestStart(String)} and {@link Scenario#requestStop(String)}.
*
* @param onSuccess invoked if the request has been successfully received
* @param onFail invoked otherwise
* @return {@code Observable<OpenSession>}
*/ | public static Func1<OpenSession, OpenSession> handleResponse(Action0 onSuccess, Action0 onFail) { |
openwebnet/rx-openwebnet | lib/src/test/java/com/github/niqdev/openwebnet/message/WhoTest.java | // Path: lib/src/test/java/com/github/niqdev/openwebnet/ThrowableCaptor.java
// public static Throwable captureThrowable(Actor actor) {
// Throwable result = null;
// try {
// actor.act();
// } catch (Throwable throwable) {
// result = throwable;
// }
// return result;
// }
//
// Path: lib/src/main/java/com/github/niqdev/openwebnet/message/Who.java
// public enum Who {
//
// SCENARIO(0),
// LIGHTING(1),
// AUTOMATION(2),
// LOAD_CONTROL(3),
// // heating
// TEMPERATURE_CONTROL(4),
// // intrusion
// BURGLAR_ALARM(5),
// DOOR_ENTRY_SYSTEM(6),
// // multimedia
// VIDEO_DOOR_ENTRY_SYSTEM(7),
// AUXILIARY(9),
// GATEWAY_MANAGEMENT(13),
// LIGHT_SHUTTER_ACTUATORS_LOCK(14),
// CEN_SCENARIO_SCHEDULER_SWITCH(15),
// // audio
// SOUND_SYSTEM_1(16),
// // MH200N
// SCENARIO_PROGRAMMING(17),
// ENERGY_MANAGEMENT(18),
// // audio
// SOUND_SYSTEM_2(22),
// LIGHTING_MANAGEMENT(24),
// CEN_SCENARIO_SCHEDULER_BUTTON(25),
// DIAGNOSTIC(1000),
// AUTOMATIC_DIAGNOSTIC(1001),
// THERMOREGULATION_DIAGNOSTIC(1004),
// DEVICE_DIAGNOSTIC(1013);
//
// private final Integer value;
//
// Who(Integer value) {
// this.value = value;
// }
//
// public Integer value() {
// return value;
// }
//
// public static boolean isValidName(String name) {
// return name != null && findWho(isEqualName(name)).isPresent();
// }
//
// public static boolean isValidValue(Integer value) {
// return value != null && findWho(isEqualValue(value)).isPresent();
// }
//
// public static Who fromName(String name) {
// checkArgument(isValidName(name), "invalid name");
// return findWho(isEqualName(name)).get();
// }
//
// public static Who fromValue(Integer value) {
// checkArgument(isValidValue(value), "invalid value");
// return findWho(isEqualValue(value)).get();
// }
//
// private static Predicate<Who> isEqualName(String name) {
// return who -> who.name().equals(name);
// }
//
// private static Predicate<Who> isEqualValue(Integer value) {
// return who -> who.value().intValue() == value.intValue();
// }
//
// private static Optional<Who> findWho(Predicate<Who> isEqual) {
// return EnumSet.allOf(Who.class).stream().filter(isEqual).findFirst();
// }
//
// }
| import org.junit.Ignore;
import org.junit.Test;
import static com.github.niqdev.openwebnet.ThrowableCaptor.captureThrowable;
import static com.github.niqdev.openwebnet.message.Who.*;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.*; | package com.github.niqdev.openwebnet.message;
public class WhoTest {
@Test
@Ignore
public void testIsValidName() {
assertTrue("should be a valid name", isValidName("LIGHTING"));
assertFalse("should not be a valid name", isValidName("lighting"));
assertFalse("should not be a valid name", isValidName(null));
}
@Test
@Ignore
public void testIsValidValue() {
assertTrue("should be a valid value", isValidValue(1));
assertFalse("should not be a valid value", isValidValue(-1));
assertFalse("should not be a valid value", isValidValue(100));
assertFalse("should not be a valid value", isValidValue(null));
}
@Test
@Ignore
public void testFromName() {
assertEquals("should retrieve element by name", LIGHTING, fromName("LIGHTING"));
| // Path: lib/src/test/java/com/github/niqdev/openwebnet/ThrowableCaptor.java
// public static Throwable captureThrowable(Actor actor) {
// Throwable result = null;
// try {
// actor.act();
// } catch (Throwable throwable) {
// result = throwable;
// }
// return result;
// }
//
// Path: lib/src/main/java/com/github/niqdev/openwebnet/message/Who.java
// public enum Who {
//
// SCENARIO(0),
// LIGHTING(1),
// AUTOMATION(2),
// LOAD_CONTROL(3),
// // heating
// TEMPERATURE_CONTROL(4),
// // intrusion
// BURGLAR_ALARM(5),
// DOOR_ENTRY_SYSTEM(6),
// // multimedia
// VIDEO_DOOR_ENTRY_SYSTEM(7),
// AUXILIARY(9),
// GATEWAY_MANAGEMENT(13),
// LIGHT_SHUTTER_ACTUATORS_LOCK(14),
// CEN_SCENARIO_SCHEDULER_SWITCH(15),
// // audio
// SOUND_SYSTEM_1(16),
// // MH200N
// SCENARIO_PROGRAMMING(17),
// ENERGY_MANAGEMENT(18),
// // audio
// SOUND_SYSTEM_2(22),
// LIGHTING_MANAGEMENT(24),
// CEN_SCENARIO_SCHEDULER_BUTTON(25),
// DIAGNOSTIC(1000),
// AUTOMATIC_DIAGNOSTIC(1001),
// THERMOREGULATION_DIAGNOSTIC(1004),
// DEVICE_DIAGNOSTIC(1013);
//
// private final Integer value;
//
// Who(Integer value) {
// this.value = value;
// }
//
// public Integer value() {
// return value;
// }
//
// public static boolean isValidName(String name) {
// return name != null && findWho(isEqualName(name)).isPresent();
// }
//
// public static boolean isValidValue(Integer value) {
// return value != null && findWho(isEqualValue(value)).isPresent();
// }
//
// public static Who fromName(String name) {
// checkArgument(isValidName(name), "invalid name");
// return findWho(isEqualName(name)).get();
// }
//
// public static Who fromValue(Integer value) {
// checkArgument(isValidValue(value), "invalid value");
// return findWho(isEqualValue(value)).get();
// }
//
// private static Predicate<Who> isEqualName(String name) {
// return who -> who.name().equals(name);
// }
//
// private static Predicate<Who> isEqualValue(Integer value) {
// return who -> who.value().intValue() == value.intValue();
// }
//
// private static Optional<Who> findWho(Predicate<Who> isEqual) {
// return EnumSet.allOf(Who.class).stream().filter(isEqual).findFirst();
// }
//
// }
// Path: lib/src/test/java/com/github/niqdev/openwebnet/message/WhoTest.java
import org.junit.Ignore;
import org.junit.Test;
import static com.github.niqdev.openwebnet.ThrowableCaptor.captureThrowable;
import static com.github.niqdev.openwebnet.message.Who.*;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.*;
package com.github.niqdev.openwebnet.message;
public class WhoTest {
@Test
@Ignore
public void testIsValidName() {
assertTrue("should be a valid name", isValidName("LIGHTING"));
assertFalse("should not be a valid name", isValidName("lighting"));
assertFalse("should not be a valid name", isValidName(null));
}
@Test
@Ignore
public void testIsValidValue() {
assertTrue("should be a valid value", isValidValue(1));
assertFalse("should not be a valid value", isValidValue(-1));
assertFalse("should not be a valid value", isValidValue(100));
assertFalse("should not be a valid value", isValidValue(null));
}
@Test
@Ignore
public void testFromName() {
assertEquals("should retrieve element by name", LIGHTING, fromName("LIGHTING"));
| assertThat(captureThrowable(() -> fromName("lighting"))) |
openwebnet/rx-openwebnet | lib/src/main/java/com/github/niqdev/openwebnet/OpenWebNetObservable.java | // Path: lib/src/main/java/com/github/niqdev/openwebnet/message/OpenMessage.java
// public interface OpenMessage {
//
// String ACK = "*#*1##";
// String NACK = "*#*0##";
// String FRAME_START = "*";
// String FRAME_END = "##";
//
// /**
// * Raw message value.
// *
// * @return value
// */
// String getValue();
//
// }
//
// Path: lib/src/main/java/com/github/niqdev/openwebnet/message/ResponseOpenMessage.java
// public class ResponseOpenMessage implements OpenMessage {
//
// private final String value;
//
// public ResponseOpenMessage(String value) {
// this.value = value;
// }
//
// @Override
// public String getValue() {
// return value;
// }
//
// @Override
// public String toString() {
// return String.format("{response=%s}", value);
// }
// }
//
// Path: lib/src/main/java/com/github/niqdev/openwebnet/OpenSession.java
// public static OpenSession newSession(OpenMessage request) {
// return new OpenSession(request);
// }
//
// Path: lib/src/main/java/com/github/niqdev/openwebnet/OpenWebNet.java
// enum Channel {
//
// COMMAND("*99*0##"),
// EVENT("*99*1##");
//
// private final String value;
//
// Channel(String value) {
// this.value = value;
// }
//
// public String value() {
// return value;
// }
//
// }
//
// Path: lib/src/main/java/com/github/niqdev/openwebnet/OpenWebNet.java
// public interface OpenGateway {
//
// /**
// * Default gateway port is 20000.
// */
// int DEFAULT_PORT = 20000;
//
// /**
// * Returns the gateway ip address or domain.
// *
// * @return host
// */
// String getHost();
//
// /**
// * Returns the gateway port.
// *
// * @return port
// */
// int getPort();
//
// /**
// * Returns the gateway password.
// *
// * @return password
// */
// String getPassword();
// }
| import com.github.niqdev.openwebnet.message.OpenMessage;
import com.github.niqdev.openwebnet.message.ResponseOpenMessage;
import com.google.common.base.Splitter;
import com.google.common.collect.FluentIterable;
import com.google.common.collect.ImmutableList;
import rx.Observable;
import rx.Statement;
import rx.functions.Func1;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import static com.github.niqdev.openwebnet.OpenSession.newSession;
import static com.github.niqdev.openwebnet.OpenWebNet.Channel;
import static com.github.niqdev.openwebnet.OpenWebNet.OpenGateway;
import static com.github.niqdev.openwebnet.message.OpenMessage.ACK;
import static com.github.niqdev.openwebnet.message.OpenMessage.FRAME_END; | package com.github.niqdev.openwebnet;
/**
* OpenWebNet observable helper class.
*
* @author niqdev
*/
class OpenWebNetObservable {
private static void log(String message) {
System.out.println(String.format("[%s] - %s", Thread.currentThread().getName(), message));
}
// no instance
private OpenWebNetObservable() {}
| // Path: lib/src/main/java/com/github/niqdev/openwebnet/message/OpenMessage.java
// public interface OpenMessage {
//
// String ACK = "*#*1##";
// String NACK = "*#*0##";
// String FRAME_START = "*";
// String FRAME_END = "##";
//
// /**
// * Raw message value.
// *
// * @return value
// */
// String getValue();
//
// }
//
// Path: lib/src/main/java/com/github/niqdev/openwebnet/message/ResponseOpenMessage.java
// public class ResponseOpenMessage implements OpenMessage {
//
// private final String value;
//
// public ResponseOpenMessage(String value) {
// this.value = value;
// }
//
// @Override
// public String getValue() {
// return value;
// }
//
// @Override
// public String toString() {
// return String.format("{response=%s}", value);
// }
// }
//
// Path: lib/src/main/java/com/github/niqdev/openwebnet/OpenSession.java
// public static OpenSession newSession(OpenMessage request) {
// return new OpenSession(request);
// }
//
// Path: lib/src/main/java/com/github/niqdev/openwebnet/OpenWebNet.java
// enum Channel {
//
// COMMAND("*99*0##"),
// EVENT("*99*1##");
//
// private final String value;
//
// Channel(String value) {
// this.value = value;
// }
//
// public String value() {
// return value;
// }
//
// }
//
// Path: lib/src/main/java/com/github/niqdev/openwebnet/OpenWebNet.java
// public interface OpenGateway {
//
// /**
// * Default gateway port is 20000.
// */
// int DEFAULT_PORT = 20000;
//
// /**
// * Returns the gateway ip address or domain.
// *
// * @return host
// */
// String getHost();
//
// /**
// * Returns the gateway port.
// *
// * @return port
// */
// int getPort();
//
// /**
// * Returns the gateway password.
// *
// * @return password
// */
// String getPassword();
// }
// Path: lib/src/main/java/com/github/niqdev/openwebnet/OpenWebNetObservable.java
import com.github.niqdev.openwebnet.message.OpenMessage;
import com.github.niqdev.openwebnet.message.ResponseOpenMessage;
import com.google.common.base.Splitter;
import com.google.common.collect.FluentIterable;
import com.google.common.collect.ImmutableList;
import rx.Observable;
import rx.Statement;
import rx.functions.Func1;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import static com.github.niqdev.openwebnet.OpenSession.newSession;
import static com.github.niqdev.openwebnet.OpenWebNet.Channel;
import static com.github.niqdev.openwebnet.OpenWebNet.OpenGateway;
import static com.github.niqdev.openwebnet.message.OpenMessage.ACK;
import static com.github.niqdev.openwebnet.message.OpenMessage.FRAME_END;
package com.github.niqdev.openwebnet;
/**
* OpenWebNet observable helper class.
*
* @author niqdev
*/
class OpenWebNetObservable {
private static void log(String message) {
System.out.println(String.format("[%s] - %s", Thread.currentThread().getName(), message));
}
// no instance
private OpenWebNetObservable() {}
| static Observable<OpenContext> connect(OpenGateway gateway) { |
openwebnet/rx-openwebnet | lib/src/main/java/com/github/niqdev/openwebnet/OpenWebNetObservable.java | // Path: lib/src/main/java/com/github/niqdev/openwebnet/message/OpenMessage.java
// public interface OpenMessage {
//
// String ACK = "*#*1##";
// String NACK = "*#*0##";
// String FRAME_START = "*";
// String FRAME_END = "##";
//
// /**
// * Raw message value.
// *
// * @return value
// */
// String getValue();
//
// }
//
// Path: lib/src/main/java/com/github/niqdev/openwebnet/message/ResponseOpenMessage.java
// public class ResponseOpenMessage implements OpenMessage {
//
// private final String value;
//
// public ResponseOpenMessage(String value) {
// this.value = value;
// }
//
// @Override
// public String getValue() {
// return value;
// }
//
// @Override
// public String toString() {
// return String.format("{response=%s}", value);
// }
// }
//
// Path: lib/src/main/java/com/github/niqdev/openwebnet/OpenSession.java
// public static OpenSession newSession(OpenMessage request) {
// return new OpenSession(request);
// }
//
// Path: lib/src/main/java/com/github/niqdev/openwebnet/OpenWebNet.java
// enum Channel {
//
// COMMAND("*99*0##"),
// EVENT("*99*1##");
//
// private final String value;
//
// Channel(String value) {
// this.value = value;
// }
//
// public String value() {
// return value;
// }
//
// }
//
// Path: lib/src/main/java/com/github/niqdev/openwebnet/OpenWebNet.java
// public interface OpenGateway {
//
// /**
// * Default gateway port is 20000.
// */
// int DEFAULT_PORT = 20000;
//
// /**
// * Returns the gateway ip address or domain.
// *
// * @return host
// */
// String getHost();
//
// /**
// * Returns the gateway port.
// *
// * @return port
// */
// int getPort();
//
// /**
// * Returns the gateway password.
// *
// * @return password
// */
// String getPassword();
// }
| import com.github.niqdev.openwebnet.message.OpenMessage;
import com.github.niqdev.openwebnet.message.ResponseOpenMessage;
import com.google.common.base.Splitter;
import com.google.common.collect.FluentIterable;
import com.google.common.collect.ImmutableList;
import rx.Observable;
import rx.Statement;
import rx.functions.Func1;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import static com.github.niqdev.openwebnet.OpenSession.newSession;
import static com.github.niqdev.openwebnet.OpenWebNet.Channel;
import static com.github.niqdev.openwebnet.OpenWebNet.OpenGateway;
import static com.github.niqdev.openwebnet.message.OpenMessage.ACK;
import static com.github.niqdev.openwebnet.message.OpenMessage.FRAME_END; | package com.github.niqdev.openwebnet;
/**
* OpenWebNet observable helper class.
*
* @author niqdev
*/
class OpenWebNetObservable {
private static void log(String message) {
System.out.println(String.format("[%s] - %s", Thread.currentThread().getName(), message));
}
// no instance
private OpenWebNetObservable() {}
static Observable<OpenContext> connect(OpenGateway gateway) {
return Observable.defer(() -> {
try {
OpenContext context = OpenContext.setup(gateway);
context.connect();
log("connected!");
return Observable.just(context);
} catch (IOException e) {
return Observable.error(e);
}
})
.doAfterTerminate(() -> {
// TODO how retrieve context to handle unsubscribe/close socket?
//context.disconnect();
})
.timeout(5, TimeUnit.SECONDS)
.doOnError(throwable -> {
System.out.println("ERROR connect: " + throwable);
});
}
| // Path: lib/src/main/java/com/github/niqdev/openwebnet/message/OpenMessage.java
// public interface OpenMessage {
//
// String ACK = "*#*1##";
// String NACK = "*#*0##";
// String FRAME_START = "*";
// String FRAME_END = "##";
//
// /**
// * Raw message value.
// *
// * @return value
// */
// String getValue();
//
// }
//
// Path: lib/src/main/java/com/github/niqdev/openwebnet/message/ResponseOpenMessage.java
// public class ResponseOpenMessage implements OpenMessage {
//
// private final String value;
//
// public ResponseOpenMessage(String value) {
// this.value = value;
// }
//
// @Override
// public String getValue() {
// return value;
// }
//
// @Override
// public String toString() {
// return String.format("{response=%s}", value);
// }
// }
//
// Path: lib/src/main/java/com/github/niqdev/openwebnet/OpenSession.java
// public static OpenSession newSession(OpenMessage request) {
// return new OpenSession(request);
// }
//
// Path: lib/src/main/java/com/github/niqdev/openwebnet/OpenWebNet.java
// enum Channel {
//
// COMMAND("*99*0##"),
// EVENT("*99*1##");
//
// private final String value;
//
// Channel(String value) {
// this.value = value;
// }
//
// public String value() {
// return value;
// }
//
// }
//
// Path: lib/src/main/java/com/github/niqdev/openwebnet/OpenWebNet.java
// public interface OpenGateway {
//
// /**
// * Default gateway port is 20000.
// */
// int DEFAULT_PORT = 20000;
//
// /**
// * Returns the gateway ip address or domain.
// *
// * @return host
// */
// String getHost();
//
// /**
// * Returns the gateway port.
// *
// * @return port
// */
// int getPort();
//
// /**
// * Returns the gateway password.
// *
// * @return password
// */
// String getPassword();
// }
// Path: lib/src/main/java/com/github/niqdev/openwebnet/OpenWebNetObservable.java
import com.github.niqdev.openwebnet.message.OpenMessage;
import com.github.niqdev.openwebnet.message.ResponseOpenMessage;
import com.google.common.base.Splitter;
import com.google.common.collect.FluentIterable;
import com.google.common.collect.ImmutableList;
import rx.Observable;
import rx.Statement;
import rx.functions.Func1;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import static com.github.niqdev.openwebnet.OpenSession.newSession;
import static com.github.niqdev.openwebnet.OpenWebNet.Channel;
import static com.github.niqdev.openwebnet.OpenWebNet.OpenGateway;
import static com.github.niqdev.openwebnet.message.OpenMessage.ACK;
import static com.github.niqdev.openwebnet.message.OpenMessage.FRAME_END;
package com.github.niqdev.openwebnet;
/**
* OpenWebNet observable helper class.
*
* @author niqdev
*/
class OpenWebNetObservable {
private static void log(String message) {
System.out.println(String.format("[%s] - %s", Thread.currentThread().getName(), message));
}
// no instance
private OpenWebNetObservable() {}
static Observable<OpenContext> connect(OpenGateway gateway) {
return Observable.defer(() -> {
try {
OpenContext context = OpenContext.setup(gateway);
context.connect();
log("connected!");
return Observable.just(context);
} catch (IOException e) {
return Observable.error(e);
}
})
.doAfterTerminate(() -> {
// TODO how retrieve context to handle unsubscribe/close socket?
//context.disconnect();
})
.timeout(5, TimeUnit.SECONDS)
.doOnError(throwable -> {
System.out.println("ERROR connect: " + throwable);
});
}
| static Func1<OpenContext, Observable<OpenContext>> doHandshake(Channel channel) { |
openwebnet/rx-openwebnet | lib/src/main/java/com/github/niqdev/openwebnet/OpenWebNetObservable.java | // Path: lib/src/main/java/com/github/niqdev/openwebnet/message/OpenMessage.java
// public interface OpenMessage {
//
// String ACK = "*#*1##";
// String NACK = "*#*0##";
// String FRAME_START = "*";
// String FRAME_END = "##";
//
// /**
// * Raw message value.
// *
// * @return value
// */
// String getValue();
//
// }
//
// Path: lib/src/main/java/com/github/niqdev/openwebnet/message/ResponseOpenMessage.java
// public class ResponseOpenMessage implements OpenMessage {
//
// private final String value;
//
// public ResponseOpenMessage(String value) {
// this.value = value;
// }
//
// @Override
// public String getValue() {
// return value;
// }
//
// @Override
// public String toString() {
// return String.format("{response=%s}", value);
// }
// }
//
// Path: lib/src/main/java/com/github/niqdev/openwebnet/OpenSession.java
// public static OpenSession newSession(OpenMessage request) {
// return new OpenSession(request);
// }
//
// Path: lib/src/main/java/com/github/niqdev/openwebnet/OpenWebNet.java
// enum Channel {
//
// COMMAND("*99*0##"),
// EVENT("*99*1##");
//
// private final String value;
//
// Channel(String value) {
// this.value = value;
// }
//
// public String value() {
// return value;
// }
//
// }
//
// Path: lib/src/main/java/com/github/niqdev/openwebnet/OpenWebNet.java
// public interface OpenGateway {
//
// /**
// * Default gateway port is 20000.
// */
// int DEFAULT_PORT = 20000;
//
// /**
// * Returns the gateway ip address or domain.
// *
// * @return host
// */
// String getHost();
//
// /**
// * Returns the gateway port.
// *
// * @return port
// */
// int getPort();
//
// /**
// * Returns the gateway password.
// *
// * @return password
// */
// String getPassword();
// }
| import com.github.niqdev.openwebnet.message.OpenMessage;
import com.github.niqdev.openwebnet.message.ResponseOpenMessage;
import com.google.common.base.Splitter;
import com.google.common.collect.FluentIterable;
import com.google.common.collect.ImmutableList;
import rx.Observable;
import rx.Statement;
import rx.functions.Func1;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import static com.github.niqdev.openwebnet.OpenSession.newSession;
import static com.github.niqdev.openwebnet.OpenWebNet.Channel;
import static com.github.niqdev.openwebnet.OpenWebNet.OpenGateway;
import static com.github.niqdev.openwebnet.message.OpenMessage.ACK;
import static com.github.niqdev.openwebnet.message.OpenMessage.FRAME_END; | return Observable.defer(() -> {
try {
OpenContext context = OpenContext.setup(gateway);
context.connect();
log("connected!");
return Observable.just(context);
} catch (IOException e) {
return Observable.error(e);
}
})
.doAfterTerminate(() -> {
// TODO how retrieve context to handle unsubscribe/close socket?
//context.disconnect();
})
.timeout(5, TimeUnit.SECONDS)
.doOnError(throwable -> {
System.out.println("ERROR connect: " + throwable);
});
}
static Func1<OpenContext, Observable<OpenContext>> doHandshake(Channel channel) {
return context -> Observable.just(context)
.flatMap(read())
.flatMap(expectedAck(context))
.flatMap(write(channel.value()))
.flatMap(read())
.flatMap(verifyCredential(context))
.flatMap(expectedAck(context));
}
| // Path: lib/src/main/java/com/github/niqdev/openwebnet/message/OpenMessage.java
// public interface OpenMessage {
//
// String ACK = "*#*1##";
// String NACK = "*#*0##";
// String FRAME_START = "*";
// String FRAME_END = "##";
//
// /**
// * Raw message value.
// *
// * @return value
// */
// String getValue();
//
// }
//
// Path: lib/src/main/java/com/github/niqdev/openwebnet/message/ResponseOpenMessage.java
// public class ResponseOpenMessage implements OpenMessage {
//
// private final String value;
//
// public ResponseOpenMessage(String value) {
// this.value = value;
// }
//
// @Override
// public String getValue() {
// return value;
// }
//
// @Override
// public String toString() {
// return String.format("{response=%s}", value);
// }
// }
//
// Path: lib/src/main/java/com/github/niqdev/openwebnet/OpenSession.java
// public static OpenSession newSession(OpenMessage request) {
// return new OpenSession(request);
// }
//
// Path: lib/src/main/java/com/github/niqdev/openwebnet/OpenWebNet.java
// enum Channel {
//
// COMMAND("*99*0##"),
// EVENT("*99*1##");
//
// private final String value;
//
// Channel(String value) {
// this.value = value;
// }
//
// public String value() {
// return value;
// }
//
// }
//
// Path: lib/src/main/java/com/github/niqdev/openwebnet/OpenWebNet.java
// public interface OpenGateway {
//
// /**
// * Default gateway port is 20000.
// */
// int DEFAULT_PORT = 20000;
//
// /**
// * Returns the gateway ip address or domain.
// *
// * @return host
// */
// String getHost();
//
// /**
// * Returns the gateway port.
// *
// * @return port
// */
// int getPort();
//
// /**
// * Returns the gateway password.
// *
// * @return password
// */
// String getPassword();
// }
// Path: lib/src/main/java/com/github/niqdev/openwebnet/OpenWebNetObservable.java
import com.github.niqdev.openwebnet.message.OpenMessage;
import com.github.niqdev.openwebnet.message.ResponseOpenMessage;
import com.google.common.base.Splitter;
import com.google.common.collect.FluentIterable;
import com.google.common.collect.ImmutableList;
import rx.Observable;
import rx.Statement;
import rx.functions.Func1;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import static com.github.niqdev.openwebnet.OpenSession.newSession;
import static com.github.niqdev.openwebnet.OpenWebNet.Channel;
import static com.github.niqdev.openwebnet.OpenWebNet.OpenGateway;
import static com.github.niqdev.openwebnet.message.OpenMessage.ACK;
import static com.github.niqdev.openwebnet.message.OpenMessage.FRAME_END;
return Observable.defer(() -> {
try {
OpenContext context = OpenContext.setup(gateway);
context.connect();
log("connected!");
return Observable.just(context);
} catch (IOException e) {
return Observable.error(e);
}
})
.doAfterTerminate(() -> {
// TODO how retrieve context to handle unsubscribe/close socket?
//context.disconnect();
})
.timeout(5, TimeUnit.SECONDS)
.doOnError(throwable -> {
System.out.println("ERROR connect: " + throwable);
});
}
static Func1<OpenContext, Observable<OpenContext>> doHandshake(Channel channel) {
return context -> Observable.just(context)
.flatMap(read())
.flatMap(expectedAck(context))
.flatMap(write(channel.value()))
.flatMap(read())
.flatMap(verifyCredential(context))
.flatMap(expectedAck(context));
}
| static Func1<OpenContext, Observable<List<OpenSession>>> doRequests(List<OpenMessage> requests) { |
openwebnet/rx-openwebnet | lib/src/main/java/com/github/niqdev/openwebnet/OpenWebNetObservable.java | // Path: lib/src/main/java/com/github/niqdev/openwebnet/message/OpenMessage.java
// public interface OpenMessage {
//
// String ACK = "*#*1##";
// String NACK = "*#*0##";
// String FRAME_START = "*";
// String FRAME_END = "##";
//
// /**
// * Raw message value.
// *
// * @return value
// */
// String getValue();
//
// }
//
// Path: lib/src/main/java/com/github/niqdev/openwebnet/message/ResponseOpenMessage.java
// public class ResponseOpenMessage implements OpenMessage {
//
// private final String value;
//
// public ResponseOpenMessage(String value) {
// this.value = value;
// }
//
// @Override
// public String getValue() {
// return value;
// }
//
// @Override
// public String toString() {
// return String.format("{response=%s}", value);
// }
// }
//
// Path: lib/src/main/java/com/github/niqdev/openwebnet/OpenSession.java
// public static OpenSession newSession(OpenMessage request) {
// return new OpenSession(request);
// }
//
// Path: lib/src/main/java/com/github/niqdev/openwebnet/OpenWebNet.java
// enum Channel {
//
// COMMAND("*99*0##"),
// EVENT("*99*1##");
//
// private final String value;
//
// Channel(String value) {
// this.value = value;
// }
//
// public String value() {
// return value;
// }
//
// }
//
// Path: lib/src/main/java/com/github/niqdev/openwebnet/OpenWebNet.java
// public interface OpenGateway {
//
// /**
// * Default gateway port is 20000.
// */
// int DEFAULT_PORT = 20000;
//
// /**
// * Returns the gateway ip address or domain.
// *
// * @return host
// */
// String getHost();
//
// /**
// * Returns the gateway port.
// *
// * @return port
// */
// int getPort();
//
// /**
// * Returns the gateway password.
// *
// * @return password
// */
// String getPassword();
// }
| import com.github.niqdev.openwebnet.message.OpenMessage;
import com.github.niqdev.openwebnet.message.ResponseOpenMessage;
import com.google.common.base.Splitter;
import com.google.common.collect.FluentIterable;
import com.google.common.collect.ImmutableList;
import rx.Observable;
import rx.Statement;
import rx.functions.Func1;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import static com.github.niqdev.openwebnet.OpenSession.newSession;
import static com.github.niqdev.openwebnet.OpenWebNet.Channel;
import static com.github.niqdev.openwebnet.OpenWebNet.OpenGateway;
import static com.github.niqdev.openwebnet.message.OpenMessage.ACK;
import static com.github.niqdev.openwebnet.message.OpenMessage.FRAME_END; | .doOnError(throwable -> {
System.out.println("ERROR connect: " + throwable);
});
}
static Func1<OpenContext, Observable<OpenContext>> doHandshake(Channel channel) {
return context -> Observable.just(context)
.flatMap(read())
.flatMap(expectedAck(context))
.flatMap(write(channel.value()))
.flatMap(read())
.flatMap(verifyCredential(context))
.flatMap(expectedAck(context));
}
static Func1<OpenContext, Observable<List<OpenSession>>> doRequests(List<OpenMessage> requests) {
return context -> Observable.just(requests)
.flatMapIterable(messages -> messages)
.flatMap(request -> Observable.just(context).flatMap(doRequest(request)))
.reduce(new ArrayList<>(), (openSessions, session) -> {
openSessions.add(session);
return openSessions;
});
}
static Func1<OpenContext, Observable<OpenSession>> doRequest(OpenMessage request) {
return context -> Observable.just(context)
.flatMap(write(request.getValue()))
.flatMap(read())
.flatMap(parseMessages()) | // Path: lib/src/main/java/com/github/niqdev/openwebnet/message/OpenMessage.java
// public interface OpenMessage {
//
// String ACK = "*#*1##";
// String NACK = "*#*0##";
// String FRAME_START = "*";
// String FRAME_END = "##";
//
// /**
// * Raw message value.
// *
// * @return value
// */
// String getValue();
//
// }
//
// Path: lib/src/main/java/com/github/niqdev/openwebnet/message/ResponseOpenMessage.java
// public class ResponseOpenMessage implements OpenMessage {
//
// private final String value;
//
// public ResponseOpenMessage(String value) {
// this.value = value;
// }
//
// @Override
// public String getValue() {
// return value;
// }
//
// @Override
// public String toString() {
// return String.format("{response=%s}", value);
// }
// }
//
// Path: lib/src/main/java/com/github/niqdev/openwebnet/OpenSession.java
// public static OpenSession newSession(OpenMessage request) {
// return new OpenSession(request);
// }
//
// Path: lib/src/main/java/com/github/niqdev/openwebnet/OpenWebNet.java
// enum Channel {
//
// COMMAND("*99*0##"),
// EVENT("*99*1##");
//
// private final String value;
//
// Channel(String value) {
// this.value = value;
// }
//
// public String value() {
// return value;
// }
//
// }
//
// Path: lib/src/main/java/com/github/niqdev/openwebnet/OpenWebNet.java
// public interface OpenGateway {
//
// /**
// * Default gateway port is 20000.
// */
// int DEFAULT_PORT = 20000;
//
// /**
// * Returns the gateway ip address or domain.
// *
// * @return host
// */
// String getHost();
//
// /**
// * Returns the gateway port.
// *
// * @return port
// */
// int getPort();
//
// /**
// * Returns the gateway password.
// *
// * @return password
// */
// String getPassword();
// }
// Path: lib/src/main/java/com/github/niqdev/openwebnet/OpenWebNetObservable.java
import com.github.niqdev.openwebnet.message.OpenMessage;
import com.github.niqdev.openwebnet.message.ResponseOpenMessage;
import com.google.common.base.Splitter;
import com.google.common.collect.FluentIterable;
import com.google.common.collect.ImmutableList;
import rx.Observable;
import rx.Statement;
import rx.functions.Func1;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import static com.github.niqdev.openwebnet.OpenSession.newSession;
import static com.github.niqdev.openwebnet.OpenWebNet.Channel;
import static com.github.niqdev.openwebnet.OpenWebNet.OpenGateway;
import static com.github.niqdev.openwebnet.message.OpenMessage.ACK;
import static com.github.niqdev.openwebnet.message.OpenMessage.FRAME_END;
.doOnError(throwable -> {
System.out.println("ERROR connect: " + throwable);
});
}
static Func1<OpenContext, Observable<OpenContext>> doHandshake(Channel channel) {
return context -> Observable.just(context)
.flatMap(read())
.flatMap(expectedAck(context))
.flatMap(write(channel.value()))
.flatMap(read())
.flatMap(verifyCredential(context))
.flatMap(expectedAck(context));
}
static Func1<OpenContext, Observable<List<OpenSession>>> doRequests(List<OpenMessage> requests) {
return context -> Observable.just(requests)
.flatMapIterable(messages -> messages)
.flatMap(request -> Observable.just(context).flatMap(doRequest(request)))
.reduce(new ArrayList<>(), (openSessions, session) -> {
openSessions.add(session);
return openSessions;
});
}
static Func1<OpenContext, Observable<OpenSession>> doRequest(OpenMessage request) {
return context -> Observable.just(context)
.flatMap(write(request.getValue()))
.flatMap(read())
.flatMap(parseMessages()) | .map(response -> newSession(request).addAllResponse(response)); |
openwebnet/rx-openwebnet | lib/src/main/java/com/github/niqdev/openwebnet/OpenWebNetObservable.java | // Path: lib/src/main/java/com/github/niqdev/openwebnet/message/OpenMessage.java
// public interface OpenMessage {
//
// String ACK = "*#*1##";
// String NACK = "*#*0##";
// String FRAME_START = "*";
// String FRAME_END = "##";
//
// /**
// * Raw message value.
// *
// * @return value
// */
// String getValue();
//
// }
//
// Path: lib/src/main/java/com/github/niqdev/openwebnet/message/ResponseOpenMessage.java
// public class ResponseOpenMessage implements OpenMessage {
//
// private final String value;
//
// public ResponseOpenMessage(String value) {
// this.value = value;
// }
//
// @Override
// public String getValue() {
// return value;
// }
//
// @Override
// public String toString() {
// return String.format("{response=%s}", value);
// }
// }
//
// Path: lib/src/main/java/com/github/niqdev/openwebnet/OpenSession.java
// public static OpenSession newSession(OpenMessage request) {
// return new OpenSession(request);
// }
//
// Path: lib/src/main/java/com/github/niqdev/openwebnet/OpenWebNet.java
// enum Channel {
//
// COMMAND("*99*0##"),
// EVENT("*99*1##");
//
// private final String value;
//
// Channel(String value) {
// this.value = value;
// }
//
// public String value() {
// return value;
// }
//
// }
//
// Path: lib/src/main/java/com/github/niqdev/openwebnet/OpenWebNet.java
// public interface OpenGateway {
//
// /**
// * Default gateway port is 20000.
// */
// int DEFAULT_PORT = 20000;
//
// /**
// * Returns the gateway ip address or domain.
// *
// * @return host
// */
// String getHost();
//
// /**
// * Returns the gateway port.
// *
// * @return port
// */
// int getPort();
//
// /**
// * Returns the gateway password.
// *
// * @return password
// */
// String getPassword();
// }
| import com.github.niqdev.openwebnet.message.OpenMessage;
import com.github.niqdev.openwebnet.message.ResponseOpenMessage;
import com.google.common.base.Splitter;
import com.google.common.collect.FluentIterable;
import com.google.common.collect.ImmutableList;
import rx.Observable;
import rx.Statement;
import rx.functions.Func1;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import static com.github.niqdev.openwebnet.OpenSession.newSession;
import static com.github.niqdev.openwebnet.OpenWebNet.Channel;
import static com.github.niqdev.openwebnet.OpenWebNet.OpenGateway;
import static com.github.niqdev.openwebnet.message.OpenMessage.ACK;
import static com.github.niqdev.openwebnet.message.OpenMessage.FRAME_END; | log(String.format("with credential: %s", context.getCredential()));
return Observable.just(context)
.flatMap(write(buildPasswordMessage(context.getCredential(), s)))
.flatMap(read());
};
}
static Func1<OpenContext, Observable<OpenContext>> write(String value) {
return context -> {
try {
byte[] message = new String(value).getBytes();
ByteBuffer buffer = ByteBuffer.wrap(message);
Integer count = context.getClient().write(buffer);
log(String.format("write: %d|%s", count, value));
return Observable.just(context);
} catch (IOException e) {
return Observable.error(e);
}
};
}
static Func1<String, Observable<List<OpenMessage>>> parseMessages() {
return messages -> {
ImmutableList<OpenMessage> response =
FluentIterable
.from(Splitter.on(FRAME_END)
.trimResults()
.omitEmptyStrings()
.split(messages))
.transform(value -> value.concat(FRAME_END)) | // Path: lib/src/main/java/com/github/niqdev/openwebnet/message/OpenMessage.java
// public interface OpenMessage {
//
// String ACK = "*#*1##";
// String NACK = "*#*0##";
// String FRAME_START = "*";
// String FRAME_END = "##";
//
// /**
// * Raw message value.
// *
// * @return value
// */
// String getValue();
//
// }
//
// Path: lib/src/main/java/com/github/niqdev/openwebnet/message/ResponseOpenMessage.java
// public class ResponseOpenMessage implements OpenMessage {
//
// private final String value;
//
// public ResponseOpenMessage(String value) {
// this.value = value;
// }
//
// @Override
// public String getValue() {
// return value;
// }
//
// @Override
// public String toString() {
// return String.format("{response=%s}", value);
// }
// }
//
// Path: lib/src/main/java/com/github/niqdev/openwebnet/OpenSession.java
// public static OpenSession newSession(OpenMessage request) {
// return new OpenSession(request);
// }
//
// Path: lib/src/main/java/com/github/niqdev/openwebnet/OpenWebNet.java
// enum Channel {
//
// COMMAND("*99*0##"),
// EVENT("*99*1##");
//
// private final String value;
//
// Channel(String value) {
// this.value = value;
// }
//
// public String value() {
// return value;
// }
//
// }
//
// Path: lib/src/main/java/com/github/niqdev/openwebnet/OpenWebNet.java
// public interface OpenGateway {
//
// /**
// * Default gateway port is 20000.
// */
// int DEFAULT_PORT = 20000;
//
// /**
// * Returns the gateway ip address or domain.
// *
// * @return host
// */
// String getHost();
//
// /**
// * Returns the gateway port.
// *
// * @return port
// */
// int getPort();
//
// /**
// * Returns the gateway password.
// *
// * @return password
// */
// String getPassword();
// }
// Path: lib/src/main/java/com/github/niqdev/openwebnet/OpenWebNetObservable.java
import com.github.niqdev.openwebnet.message.OpenMessage;
import com.github.niqdev.openwebnet.message.ResponseOpenMessage;
import com.google.common.base.Splitter;
import com.google.common.collect.FluentIterable;
import com.google.common.collect.ImmutableList;
import rx.Observable;
import rx.Statement;
import rx.functions.Func1;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import static com.github.niqdev.openwebnet.OpenSession.newSession;
import static com.github.niqdev.openwebnet.OpenWebNet.Channel;
import static com.github.niqdev.openwebnet.OpenWebNet.OpenGateway;
import static com.github.niqdev.openwebnet.message.OpenMessage.ACK;
import static com.github.niqdev.openwebnet.message.OpenMessage.FRAME_END;
log(String.format("with credential: %s", context.getCredential()));
return Observable.just(context)
.flatMap(write(buildPasswordMessage(context.getCredential(), s)))
.flatMap(read());
};
}
static Func1<OpenContext, Observable<OpenContext>> write(String value) {
return context -> {
try {
byte[] message = new String(value).getBytes();
ByteBuffer buffer = ByteBuffer.wrap(message);
Integer count = context.getClient().write(buffer);
log(String.format("write: %d|%s", count, value));
return Observable.just(context);
} catch (IOException e) {
return Observable.error(e);
}
};
}
static Func1<String, Observable<List<OpenMessage>>> parseMessages() {
return messages -> {
ImmutableList<OpenMessage> response =
FluentIterable
.from(Splitter.on(FRAME_END)
.trimResults()
.omitEmptyStrings()
.split(messages))
.transform(value -> value.concat(FRAME_END)) | .transform(message -> (OpenMessage) new ResponseOpenMessage(message)) |
aaronjwood/PortAuthority | app/src/main/java/com/aaronjwood/portauthority/runnable/ScanPortsRunnable.java | // Path: app/src/main/java/com/aaronjwood/portauthority/response/HostAsyncResponse.java
// public interface HostAsyncResponse extends LanHostAsyncResponse, WanHostAsyncResponse, ErrorAsyncResponse {
// }
| import android.util.SparseArray;
import com.aaronjwood.portauthority.response.HostAsyncResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.lang.ref.WeakReference;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.nio.channels.IllegalBlockingModeException; | package com.aaronjwood.portauthority.runnable;
public class ScanPortsRunnable implements Runnable {
private final String ip;
private final int startPort;
private final int stopPort;
private final int timeout; | // Path: app/src/main/java/com/aaronjwood/portauthority/response/HostAsyncResponse.java
// public interface HostAsyncResponse extends LanHostAsyncResponse, WanHostAsyncResponse, ErrorAsyncResponse {
// }
// Path: app/src/main/java/com/aaronjwood/portauthority/runnable/ScanPortsRunnable.java
import android.util.SparseArray;
import com.aaronjwood.portauthority.response.HostAsyncResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.lang.ref.WeakReference;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.nio.channels.IllegalBlockingModeException;
package com.aaronjwood.portauthority.runnable;
public class ScanPortsRunnable implements Runnable {
private final String ip;
private final int startPort;
private final int stopPort;
private final int timeout; | private final WeakReference<HostAsyncResponse> delegate; |
aaronjwood/PortAuthority | app/src/main/java/com/aaronjwood/portauthority/network/Wireless.java | // Path: app/src/main/java/com/aaronjwood/portauthority/async/WanIpAsyncTask.java
// public class WanIpAsyncTask extends AsyncTask<Void, Void, String> {
//
// // IP service is 100% open source https://github.com/aaronjwood/public-ip-api
// private static final String EXTERNAL_IP_SERVICE = "https://yourip.aaronjwood.com/";
// private final WeakReference<MainAsyncResponse> delegate;
//
// /**
// * Constructor to set the delegate
// *
// * @param delegate Called when the external IP has been fetched
// */
// public WanIpAsyncTask(MainAsyncResponse delegate) {
// this.delegate = new WeakReference<>(delegate);
// }
//
// /**
// * Fetch the external IP address
// *
// * @param params
// * @return External IP address
// */
// @Override
// @SuppressLint("NewApi")
// protected String doInBackground(Void... params) {
// MainAsyncResponse activity = delegate.get();
// Context ctx = (Context) activity;
// OkHttpClient httpClient = new OkHttpClient();
// Request request = new Request.Builder().url(EXTERNAL_IP_SERVICE).build();
//
// try (Response response = httpClient.newCall(request).execute()) {
// ResponseBody body = response.body();
// if (!response.isSuccessful() || body == null) {
// return ctx.getResources().getString(R.string.errExternIp);
// }
//
// return body.string().trim();
// } catch (IOException e) {
// return ctx.getResources().getString(R.string.errExternIp);
// }
// }
//
// /**
// * Calls the delegate when the external IP has been fetched
// *
// * @param result External IP address
// */
// @Override
// protected void onPostExecute(String result) {
// MainAsyncResponse activity = delegate.get();
// if (activity != null) {
// activity.processFinish(result);
// }
// }
// }
//
// Path: app/src/main/java/com/aaronjwood/portauthority/response/MainAsyncResponse.java
// public interface MainAsyncResponse extends ErrorAsyncResponse {
//
// /**
// * Delegate to handle Host + AtomicInteger outputs
// *
// * @param h
// * @param i
// */
// void processFinish(Host h, AtomicInteger i);
//
// /**
// * Delegate to handle integer outputs
// *
// * @param output
// */
// void processFinish(int output);
//
// /**
// * Delegate to handle string outputs
// *
// * @param output
// */
// void processFinish(String output);
//
// /**
// * Delegate to handle boolean outputs
// *
// * @param output
// */
// void processFinish(boolean output);
//
// }
| import android.content.Context;
import android.net.ConnectivityManager;
import android.net.DhcpInfo;
import android.net.NetworkInfo;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.AsyncTask;
import com.aaronjwood.portauthority.async.WanIpAsyncTask;
import com.aaronjwood.portauthority.response.MainAsyncResponse;
import java.math.BigInteger;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.InterfaceAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.nio.ByteOrder;
import java.util.Enumeration; |
/**
* Gets the device's internal LAN IP address associated with the cellular network
*
* @return Local cellular network LAN IP address
*/
public static String getInternalMobileIpAddress() {
try {
for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en != null && en.hasMoreElements(); ) {
NetworkInterface intf = en.nextElement();
for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements(); ) {
InetAddress inetAddress = enumIpAddr.nextElement();
if (!inetAddress.isLoopbackAddress() && inetAddress instanceof Inet4Address) {
return inetAddress.getHostAddress();
}
}
}
} catch (SocketException ex) {
return "Unknown";
}
return "Unknown";
}
/**
* Gets the device's external (WAN) IP address
*
* @param delegate Called when the external IP address has been fetched
*/ | // Path: app/src/main/java/com/aaronjwood/portauthority/async/WanIpAsyncTask.java
// public class WanIpAsyncTask extends AsyncTask<Void, Void, String> {
//
// // IP service is 100% open source https://github.com/aaronjwood/public-ip-api
// private static final String EXTERNAL_IP_SERVICE = "https://yourip.aaronjwood.com/";
// private final WeakReference<MainAsyncResponse> delegate;
//
// /**
// * Constructor to set the delegate
// *
// * @param delegate Called when the external IP has been fetched
// */
// public WanIpAsyncTask(MainAsyncResponse delegate) {
// this.delegate = new WeakReference<>(delegate);
// }
//
// /**
// * Fetch the external IP address
// *
// * @param params
// * @return External IP address
// */
// @Override
// @SuppressLint("NewApi")
// protected String doInBackground(Void... params) {
// MainAsyncResponse activity = delegate.get();
// Context ctx = (Context) activity;
// OkHttpClient httpClient = new OkHttpClient();
// Request request = new Request.Builder().url(EXTERNAL_IP_SERVICE).build();
//
// try (Response response = httpClient.newCall(request).execute()) {
// ResponseBody body = response.body();
// if (!response.isSuccessful() || body == null) {
// return ctx.getResources().getString(R.string.errExternIp);
// }
//
// return body.string().trim();
// } catch (IOException e) {
// return ctx.getResources().getString(R.string.errExternIp);
// }
// }
//
// /**
// * Calls the delegate when the external IP has been fetched
// *
// * @param result External IP address
// */
// @Override
// protected void onPostExecute(String result) {
// MainAsyncResponse activity = delegate.get();
// if (activity != null) {
// activity.processFinish(result);
// }
// }
// }
//
// Path: app/src/main/java/com/aaronjwood/portauthority/response/MainAsyncResponse.java
// public interface MainAsyncResponse extends ErrorAsyncResponse {
//
// /**
// * Delegate to handle Host + AtomicInteger outputs
// *
// * @param h
// * @param i
// */
// void processFinish(Host h, AtomicInteger i);
//
// /**
// * Delegate to handle integer outputs
// *
// * @param output
// */
// void processFinish(int output);
//
// /**
// * Delegate to handle string outputs
// *
// * @param output
// */
// void processFinish(String output);
//
// /**
// * Delegate to handle boolean outputs
// *
// * @param output
// */
// void processFinish(boolean output);
//
// }
// Path: app/src/main/java/com/aaronjwood/portauthority/network/Wireless.java
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.DhcpInfo;
import android.net.NetworkInfo;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.AsyncTask;
import com.aaronjwood.portauthority.async.WanIpAsyncTask;
import com.aaronjwood.portauthority.response.MainAsyncResponse;
import java.math.BigInteger;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.InterfaceAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.nio.ByteOrder;
import java.util.Enumeration;
/**
* Gets the device's internal LAN IP address associated with the cellular network
*
* @return Local cellular network LAN IP address
*/
public static String getInternalMobileIpAddress() {
try {
for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en != null && en.hasMoreElements(); ) {
NetworkInterface intf = en.nextElement();
for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements(); ) {
InetAddress inetAddress = enumIpAddr.nextElement();
if (!inetAddress.isLoopbackAddress() && inetAddress instanceof Inet4Address) {
return inetAddress.getHostAddress();
}
}
}
} catch (SocketException ex) {
return "Unknown";
}
return "Unknown";
}
/**
* Gets the device's external (WAN) IP address
*
* @param delegate Called when the external IP address has been fetched
*/ | public void getExternalIpAddress(MainAsyncResponse delegate) { |
aaronjwood/PortAuthority | app/src/main/java/com/aaronjwood/portauthority/network/Wireless.java | // Path: app/src/main/java/com/aaronjwood/portauthority/async/WanIpAsyncTask.java
// public class WanIpAsyncTask extends AsyncTask<Void, Void, String> {
//
// // IP service is 100% open source https://github.com/aaronjwood/public-ip-api
// private static final String EXTERNAL_IP_SERVICE = "https://yourip.aaronjwood.com/";
// private final WeakReference<MainAsyncResponse> delegate;
//
// /**
// * Constructor to set the delegate
// *
// * @param delegate Called when the external IP has been fetched
// */
// public WanIpAsyncTask(MainAsyncResponse delegate) {
// this.delegate = new WeakReference<>(delegate);
// }
//
// /**
// * Fetch the external IP address
// *
// * @param params
// * @return External IP address
// */
// @Override
// @SuppressLint("NewApi")
// protected String doInBackground(Void... params) {
// MainAsyncResponse activity = delegate.get();
// Context ctx = (Context) activity;
// OkHttpClient httpClient = new OkHttpClient();
// Request request = new Request.Builder().url(EXTERNAL_IP_SERVICE).build();
//
// try (Response response = httpClient.newCall(request).execute()) {
// ResponseBody body = response.body();
// if (!response.isSuccessful() || body == null) {
// return ctx.getResources().getString(R.string.errExternIp);
// }
//
// return body.string().trim();
// } catch (IOException e) {
// return ctx.getResources().getString(R.string.errExternIp);
// }
// }
//
// /**
// * Calls the delegate when the external IP has been fetched
// *
// * @param result External IP address
// */
// @Override
// protected void onPostExecute(String result) {
// MainAsyncResponse activity = delegate.get();
// if (activity != null) {
// activity.processFinish(result);
// }
// }
// }
//
// Path: app/src/main/java/com/aaronjwood/portauthority/response/MainAsyncResponse.java
// public interface MainAsyncResponse extends ErrorAsyncResponse {
//
// /**
// * Delegate to handle Host + AtomicInteger outputs
// *
// * @param h
// * @param i
// */
// void processFinish(Host h, AtomicInteger i);
//
// /**
// * Delegate to handle integer outputs
// *
// * @param output
// */
// void processFinish(int output);
//
// /**
// * Delegate to handle string outputs
// *
// * @param output
// */
// void processFinish(String output);
//
// /**
// * Delegate to handle boolean outputs
// *
// * @param output
// */
// void processFinish(boolean output);
//
// }
| import android.content.Context;
import android.net.ConnectivityManager;
import android.net.DhcpInfo;
import android.net.NetworkInfo;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.AsyncTask;
import com.aaronjwood.portauthority.async.WanIpAsyncTask;
import com.aaronjwood.portauthority.response.MainAsyncResponse;
import java.math.BigInteger;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.InterfaceAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.nio.ByteOrder;
import java.util.Enumeration; |
/**
* Gets the device's internal LAN IP address associated with the cellular network
*
* @return Local cellular network LAN IP address
*/
public static String getInternalMobileIpAddress() {
try {
for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en != null && en.hasMoreElements(); ) {
NetworkInterface intf = en.nextElement();
for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements(); ) {
InetAddress inetAddress = enumIpAddr.nextElement();
if (!inetAddress.isLoopbackAddress() && inetAddress instanceof Inet4Address) {
return inetAddress.getHostAddress();
}
}
}
} catch (SocketException ex) {
return "Unknown";
}
return "Unknown";
}
/**
* Gets the device's external (WAN) IP address
*
* @param delegate Called when the external IP address has been fetched
*/
public void getExternalIpAddress(MainAsyncResponse delegate) { | // Path: app/src/main/java/com/aaronjwood/portauthority/async/WanIpAsyncTask.java
// public class WanIpAsyncTask extends AsyncTask<Void, Void, String> {
//
// // IP service is 100% open source https://github.com/aaronjwood/public-ip-api
// private static final String EXTERNAL_IP_SERVICE = "https://yourip.aaronjwood.com/";
// private final WeakReference<MainAsyncResponse> delegate;
//
// /**
// * Constructor to set the delegate
// *
// * @param delegate Called when the external IP has been fetched
// */
// public WanIpAsyncTask(MainAsyncResponse delegate) {
// this.delegate = new WeakReference<>(delegate);
// }
//
// /**
// * Fetch the external IP address
// *
// * @param params
// * @return External IP address
// */
// @Override
// @SuppressLint("NewApi")
// protected String doInBackground(Void... params) {
// MainAsyncResponse activity = delegate.get();
// Context ctx = (Context) activity;
// OkHttpClient httpClient = new OkHttpClient();
// Request request = new Request.Builder().url(EXTERNAL_IP_SERVICE).build();
//
// try (Response response = httpClient.newCall(request).execute()) {
// ResponseBody body = response.body();
// if (!response.isSuccessful() || body == null) {
// return ctx.getResources().getString(R.string.errExternIp);
// }
//
// return body.string().trim();
// } catch (IOException e) {
// return ctx.getResources().getString(R.string.errExternIp);
// }
// }
//
// /**
// * Calls the delegate when the external IP has been fetched
// *
// * @param result External IP address
// */
// @Override
// protected void onPostExecute(String result) {
// MainAsyncResponse activity = delegate.get();
// if (activity != null) {
// activity.processFinish(result);
// }
// }
// }
//
// Path: app/src/main/java/com/aaronjwood/portauthority/response/MainAsyncResponse.java
// public interface MainAsyncResponse extends ErrorAsyncResponse {
//
// /**
// * Delegate to handle Host + AtomicInteger outputs
// *
// * @param h
// * @param i
// */
// void processFinish(Host h, AtomicInteger i);
//
// /**
// * Delegate to handle integer outputs
// *
// * @param output
// */
// void processFinish(int output);
//
// /**
// * Delegate to handle string outputs
// *
// * @param output
// */
// void processFinish(String output);
//
// /**
// * Delegate to handle boolean outputs
// *
// * @param output
// */
// void processFinish(boolean output);
//
// }
// Path: app/src/main/java/com/aaronjwood/portauthority/network/Wireless.java
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.DhcpInfo;
import android.net.NetworkInfo;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.AsyncTask;
import com.aaronjwood.portauthority.async.WanIpAsyncTask;
import com.aaronjwood.portauthority.response.MainAsyncResponse;
import java.math.BigInteger;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.InterfaceAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.nio.ByteOrder;
import java.util.Enumeration;
/**
* Gets the device's internal LAN IP address associated with the cellular network
*
* @return Local cellular network LAN IP address
*/
public static String getInternalMobileIpAddress() {
try {
for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en != null && en.hasMoreElements(); ) {
NetworkInterface intf = en.nextElement();
for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements(); ) {
InetAddress inetAddress = enumIpAddr.nextElement();
if (!inetAddress.isLoopbackAddress() && inetAddress instanceof Inet4Address) {
return inetAddress.getHostAddress();
}
}
}
} catch (SocketException ex) {
return "Unknown";
}
return "Unknown";
}
/**
* Gets the device's external (WAN) IP address
*
* @param delegate Called when the external IP address has been fetched
*/
public void getExternalIpAddress(MainAsyncResponse delegate) { | new WanIpAsyncTask(delegate).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); |
aaronjwood/PortAuthority | app/src/main/java/com/aaronjwood/portauthority/runnable/ScanHostsRunnable.java | // Path: app/src/main/java/com/aaronjwood/portauthority/response/MainAsyncResponse.java
// public interface MainAsyncResponse extends ErrorAsyncResponse {
//
// /**
// * Delegate to handle Host + AtomicInteger outputs
// *
// * @param h
// * @param i
// */
// void processFinish(Host h, AtomicInteger i);
//
// /**
// * Delegate to handle integer outputs
// *
// * @param output
// */
// void processFinish(int output);
//
// /**
// * Delegate to handle string outputs
// *
// * @param output
// */
// void processFinish(String output);
//
// /**
// * Delegate to handle boolean outputs
// *
// * @param output
// */
// void processFinish(boolean output);
//
// }
| import com.aaronjwood.portauthority.response.MainAsyncResponse;
import java.io.IOException;
import java.lang.ref.WeakReference;
import java.math.BigInteger;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket; | package com.aaronjwood.portauthority.runnable;
public class ScanHostsRunnable implements Runnable {
private final int start;
private final int stop;
private final int timeout; | // Path: app/src/main/java/com/aaronjwood/portauthority/response/MainAsyncResponse.java
// public interface MainAsyncResponse extends ErrorAsyncResponse {
//
// /**
// * Delegate to handle Host + AtomicInteger outputs
// *
// * @param h
// * @param i
// */
// void processFinish(Host h, AtomicInteger i);
//
// /**
// * Delegate to handle integer outputs
// *
// * @param output
// */
// void processFinish(int output);
//
// /**
// * Delegate to handle string outputs
// *
// * @param output
// */
// void processFinish(String output);
//
// /**
// * Delegate to handle boolean outputs
// *
// * @param output
// */
// void processFinish(boolean output);
//
// }
// Path: app/src/main/java/com/aaronjwood/portauthority/runnable/ScanHostsRunnable.java
import com.aaronjwood.portauthority.response.MainAsyncResponse;
import java.io.IOException;
import java.lang.ref.WeakReference;
import java.math.BigInteger;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
package com.aaronjwood.portauthority.runnable;
public class ScanHostsRunnable implements Runnable {
private final int start;
private final int stop;
private final int timeout; | private final WeakReference<MainAsyncResponse> delegate; |
aaronjwood/PortAuthority | app/src/main/java/com/aaronjwood/portauthority/async/WanIpAsyncTask.java | // Path: app/src/main/java/com/aaronjwood/portauthority/response/HostAsyncResponse.java
// public interface HostAsyncResponse extends LanHostAsyncResponse, WanHostAsyncResponse, ErrorAsyncResponse {
// }
//
// Path: app/src/main/java/com/aaronjwood/portauthority/response/MainAsyncResponse.java
// public interface MainAsyncResponse extends ErrorAsyncResponse {
//
// /**
// * Delegate to handle Host + AtomicInteger outputs
// *
// * @param h
// * @param i
// */
// void processFinish(Host h, AtomicInteger i);
//
// /**
// * Delegate to handle integer outputs
// *
// * @param output
// */
// void processFinish(int output);
//
// /**
// * Delegate to handle string outputs
// *
// * @param output
// */
// void processFinish(String output);
//
// /**
// * Delegate to handle boolean outputs
// *
// * @param output
// */
// void processFinish(boolean output);
//
// }
| import android.annotation.SuppressLint;
import android.content.Context;
import android.os.AsyncTask;
import com.aaronjwood.portauthority.R;
import com.aaronjwood.portauthority.response.HostAsyncResponse;
import com.aaronjwood.portauthority.response.MainAsyncResponse;
import java.io.IOException;
import java.lang.ref.WeakReference;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody; | package com.aaronjwood.portauthority.async;
public class WanIpAsyncTask extends AsyncTask<Void, Void, String> {
// IP service is 100% open source https://github.com/aaronjwood/public-ip-api
private static final String EXTERNAL_IP_SERVICE = "https://yourip.aaronjwood.com/"; | // Path: app/src/main/java/com/aaronjwood/portauthority/response/HostAsyncResponse.java
// public interface HostAsyncResponse extends LanHostAsyncResponse, WanHostAsyncResponse, ErrorAsyncResponse {
// }
//
// Path: app/src/main/java/com/aaronjwood/portauthority/response/MainAsyncResponse.java
// public interface MainAsyncResponse extends ErrorAsyncResponse {
//
// /**
// * Delegate to handle Host + AtomicInteger outputs
// *
// * @param h
// * @param i
// */
// void processFinish(Host h, AtomicInteger i);
//
// /**
// * Delegate to handle integer outputs
// *
// * @param output
// */
// void processFinish(int output);
//
// /**
// * Delegate to handle string outputs
// *
// * @param output
// */
// void processFinish(String output);
//
// /**
// * Delegate to handle boolean outputs
// *
// * @param output
// */
// void processFinish(boolean output);
//
// }
// Path: app/src/main/java/com/aaronjwood/portauthority/async/WanIpAsyncTask.java
import android.annotation.SuppressLint;
import android.content.Context;
import android.os.AsyncTask;
import com.aaronjwood.portauthority.R;
import com.aaronjwood.portauthority.response.HostAsyncResponse;
import com.aaronjwood.portauthority.response.MainAsyncResponse;
import java.io.IOException;
import java.lang.ref.WeakReference;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;
package com.aaronjwood.portauthority.async;
public class WanIpAsyncTask extends AsyncTask<Void, Void, String> {
// IP service is 100% open source https://github.com/aaronjwood/public-ip-api
private static final String EXTERNAL_IP_SERVICE = "https://yourip.aaronjwood.com/"; | private final WeakReference<MainAsyncResponse> delegate; |
macacajs/wd.java | src/main/java/macaca/client/common/Utils.java | // Path: src/main/java/macaca/client/model/JsonWireStatus.java
// public enum JsonWireStatus {
//
// Success(0, "The command executed successfully."),
// NoSuchElement(7, "An element could not be located on the page using the given search parameters."),
// NoSuchFrame(8, "A request to switch to a frame could not be satisfied because the frame could not be found."),
// UnknownCommand(9, "The requested resource could not be found, or a request was received using an HTTP method that is not supported by the mapped resource."),
// StaleElementReference(10, "An element command failed because the referenced element is no longer attached to the DOM."),
// ElementNotVisible(11, "An element command could not be completed because the element is not visible on the page."),
// InvalidElementState(12, "An element command could not be completed because the element is in an invalid state (e.g. attempting to click a disabled element)."),
// UnknownError(13, "An unknown server-side error occurred while processing the command."),
// ElementIsNotSelectable(15, "An attempt was made to select an element that cannot be selected."),
// JavaScriptError(17, "An error occurred while executing user supplied JavaScript."),
// XPathLookupError(19, "An error occurred while searching for an element by XPath."),
// Timeout(21, "An operation did not complete before its timeout expired."),
// NoSuchWindow(23, "A request to switch to a different window could not be satisfied because the window could not be found."),
// InvalidCookieDomain(24, "An illegal attempt was made to set a cookie under a different domain than the current page."),
// UnableToSetCookie(25, "A request to set a cookie\'s value could not be satisfied."),
// UnexpectedAlertOpen(26, "A modal dialog was open, blocking this operation."),
// NoAlertOpenError(27, "An attempt was made to operate on a modal dialog when one was not open."),
// ScriptTimeout(28, "A script did not complete before its timeout expired."),
// InvalidElementCoordinates(29, "The coordinates provided to an interactions operation are invalid."),
// IMENotAvailable(30, "IME was not available."),
// IMEEngineActivationFailed(31, "An IME engine could not be started."),
// InvalidSelector(32, "Argument was an invalid selector (e.g. XPath/CSS)."),
// Default(-1, "");
//
// private int code;
// private String message;
//
// JsonWireStatus(int code, String message) {
// this.code = code;
// this.message = message;
// }
//
// public static JsonWireStatus findByStatus(int code) {
// for (JsonWireStatus exception : JsonWireStatus.values()) {
// if (exception.code == code) {
// return exception;
// }
// }
// return Default;
// }
//
// public String message() {
// return message;
// }
//
// }
| import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import macaca.client.model.JsonWireStatus;
import org.apache.http.HttpEntity;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.util.EntityUtils;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicHeader;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import org.apache.http.client.config.CookieSpecs;
import org.apache.http.client.config.RequestConfig; | HttpDelete httpdelete = new HttpDelete(url);
executeRequest(httpdelete);
return jsonResponse;
}
public Object request(String method, String url, JSONObject jsonObj) throws Exception {
try {
if ("GET".equals(method.toUpperCase())) {
return getRequest(url, jsonObj);
} else if ("POST".equals(method.toUpperCase())) {
return postRequest(url, jsonObj);
} else if ("DELETE".equals(method.toUpperCase())) {
return deleteRequest(url, jsonObj);
}
} catch (Exception e) {
// if exceptionCallback return Boolean.TRUE, throw exception again
if (exceptionCallback != null) {
Boolean needThrow = exceptionCallback.call(e);
if (needThrow != null && needThrow.booleanValue()) {
throw e;
}
} else {
throw e;
}
}
return null;
}
void handleStatus(int statusCode) throws Exception { | // Path: src/main/java/macaca/client/model/JsonWireStatus.java
// public enum JsonWireStatus {
//
// Success(0, "The command executed successfully."),
// NoSuchElement(7, "An element could not be located on the page using the given search parameters."),
// NoSuchFrame(8, "A request to switch to a frame could not be satisfied because the frame could not be found."),
// UnknownCommand(9, "The requested resource could not be found, or a request was received using an HTTP method that is not supported by the mapped resource."),
// StaleElementReference(10, "An element command failed because the referenced element is no longer attached to the DOM."),
// ElementNotVisible(11, "An element command could not be completed because the element is not visible on the page."),
// InvalidElementState(12, "An element command could not be completed because the element is in an invalid state (e.g. attempting to click a disabled element)."),
// UnknownError(13, "An unknown server-side error occurred while processing the command."),
// ElementIsNotSelectable(15, "An attempt was made to select an element that cannot be selected."),
// JavaScriptError(17, "An error occurred while executing user supplied JavaScript."),
// XPathLookupError(19, "An error occurred while searching for an element by XPath."),
// Timeout(21, "An operation did not complete before its timeout expired."),
// NoSuchWindow(23, "A request to switch to a different window could not be satisfied because the window could not be found."),
// InvalidCookieDomain(24, "An illegal attempt was made to set a cookie under a different domain than the current page."),
// UnableToSetCookie(25, "A request to set a cookie\'s value could not be satisfied."),
// UnexpectedAlertOpen(26, "A modal dialog was open, blocking this operation."),
// NoAlertOpenError(27, "An attempt was made to operate on a modal dialog when one was not open."),
// ScriptTimeout(28, "A script did not complete before its timeout expired."),
// InvalidElementCoordinates(29, "The coordinates provided to an interactions operation are invalid."),
// IMENotAvailable(30, "IME was not available."),
// IMEEngineActivationFailed(31, "An IME engine could not be started."),
// InvalidSelector(32, "Argument was an invalid selector (e.g. XPath/CSS)."),
// Default(-1, "");
//
// private int code;
// private String message;
//
// JsonWireStatus(int code, String message) {
// this.code = code;
// this.message = message;
// }
//
// public static JsonWireStatus findByStatus(int code) {
// for (JsonWireStatus exception : JsonWireStatus.values()) {
// if (exception.code == code) {
// return exception;
// }
// }
// return Default;
// }
//
// public String message() {
// return message;
// }
//
// }
// Path: src/main/java/macaca/client/common/Utils.java
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import macaca.client.model.JsonWireStatus;
import org.apache.http.HttpEntity;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.util.EntityUtils;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicHeader;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import org.apache.http.client.config.CookieSpecs;
import org.apache.http.client.config.RequestConfig;
HttpDelete httpdelete = new HttpDelete(url);
executeRequest(httpdelete);
return jsonResponse;
}
public Object request(String method, String url, JSONObject jsonObj) throws Exception {
try {
if ("GET".equals(method.toUpperCase())) {
return getRequest(url, jsonObj);
} else if ("POST".equals(method.toUpperCase())) {
return postRequest(url, jsonObj);
} else if ("DELETE".equals(method.toUpperCase())) {
return deleteRequest(url, jsonObj);
}
} catch (Exception e) {
// if exceptionCallback return Boolean.TRUE, throw exception again
if (exceptionCallback != null) {
Boolean needThrow = exceptionCallback.call(e);
if (needThrow != null && needThrow.booleanValue()) {
throw e;
}
} else {
throw e;
}
}
return null;
}
void handleStatus(int statusCode) throws Exception { | JsonWireStatus status = JsonWireStatus.findByStatus(statusCode); |
wangchongjie/multi-engine | src/test/java/com/baidu/unbiz/multiengine/service/ExplicitDefTask.java | // Path: src/test/java/com/baidu/unbiz/multiengine/vo/DeviceRequest.java
// public class DeviceRequest {
//
// private List<Integer> deviceIds;
//
// public List<Integer> getDeviceIds() {
// return deviceIds;
// }
//
// public void setDeviceIds(List<Integer> deviceIds) {
// this.deviceIds = deviceIds;
// }
//
// public static DeviceRequest build(QueryParam target) {
// DeviceRequest req = new DeviceRequest();
// // req.copyProperties(target);
// return req;
// }
// }
//
// Path: src/test/java/com/baidu/unbiz/multiengine/vo/DeviceViewItem.java
// public class DeviceViewItem {
//
// private static final long serialVersionUID = 6132709579470894604L;
//
// private int planId;
//
// private String planName;
//
// private Integer deviceId;
//
// private String deviceName ;
//
// // getter and setter
// public int getPlanId() {
// return planId;
// }
//
// public void setPlanId(int planId) {
// this.planId = planId;
// }
//
// public Integer getDeviceId() {
// return deviceId;
// }
//
// public void setDeviceId(Integer deviceId) {
// this.deviceId = deviceId;
// }
//
// public String getPlanName() {
// return planName;
// }
//
// public void setPlanName(String planName) {
// this.planName = planName;
// }
//
// public String getDeviceName() {
// return deviceName;
// }
//
// public void setDeviceName(String deviceName) {
// this.deviceName = deviceName;
// }
//
// public String toString() {
// return ToStringBuilder.reflectionToString(this, ToStringStyle.SHORT_PREFIX_STYLE);
// }
// }
| import java.util.ArrayList;
import java.util.List;
import org.springframework.stereotype.Service;
import com.baidu.unbiz.multitask.task.Taskable;
import com.baidu.unbiz.multiengine.vo.DeviceRequest;
import com.baidu.unbiz.multiengine.vo.DeviceViewItem; | package com.baidu.unbiz.multiengine.service;
/**
* Created by wangchongjie on 15/12/21.
*/
@Service
public class ExplicitDefTask implements Taskable<List<DeviceViewItem>> {
public <E> List<DeviceViewItem> work(E request) { | // Path: src/test/java/com/baidu/unbiz/multiengine/vo/DeviceRequest.java
// public class DeviceRequest {
//
// private List<Integer> deviceIds;
//
// public List<Integer> getDeviceIds() {
// return deviceIds;
// }
//
// public void setDeviceIds(List<Integer> deviceIds) {
// this.deviceIds = deviceIds;
// }
//
// public static DeviceRequest build(QueryParam target) {
// DeviceRequest req = new DeviceRequest();
// // req.copyProperties(target);
// return req;
// }
// }
//
// Path: src/test/java/com/baidu/unbiz/multiengine/vo/DeviceViewItem.java
// public class DeviceViewItem {
//
// private static final long serialVersionUID = 6132709579470894604L;
//
// private int planId;
//
// private String planName;
//
// private Integer deviceId;
//
// private String deviceName ;
//
// // getter and setter
// public int getPlanId() {
// return planId;
// }
//
// public void setPlanId(int planId) {
// this.planId = planId;
// }
//
// public Integer getDeviceId() {
// return deviceId;
// }
//
// public void setDeviceId(Integer deviceId) {
// this.deviceId = deviceId;
// }
//
// public String getPlanName() {
// return planName;
// }
//
// public void setPlanName(String planName) {
// this.planName = planName;
// }
//
// public String getDeviceName() {
// return deviceName;
// }
//
// public void setDeviceName(String deviceName) {
// this.deviceName = deviceName;
// }
//
// public String toString() {
// return ToStringBuilder.reflectionToString(this, ToStringStyle.SHORT_PREFIX_STYLE);
// }
// }
// Path: src/test/java/com/baidu/unbiz/multiengine/service/ExplicitDefTask.java
import java.util.ArrayList;
import java.util.List;
import org.springframework.stereotype.Service;
import com.baidu.unbiz.multitask.task.Taskable;
import com.baidu.unbiz.multiengine.vo.DeviceRequest;
import com.baidu.unbiz.multiengine.vo.DeviceViewItem;
package com.baidu.unbiz.multiengine.service;
/**
* Created by wangchongjie on 15/12/21.
*/
@Service
public class ExplicitDefTask implements Taskable<List<DeviceViewItem>> {
public <E> List<DeviceViewItem> work(E request) { | if (request instanceof DeviceRequest) { |
wangchongjie/multi-engine | src/main/java/com/baidu/unbiz/multiengine/transport/client/TaskClientContext.java | // Path: src/main/java/com/baidu/unbiz/multiengine/transport/dto/Signal.java
// public class Signal<T> {
//
// protected long seqId;
// protected T message;
// protected SignalType type = SignalType.TASK_COMMOND;
//
// public Signal() {
// }
//
// public Signal(T message) {
// this.message = message;
// }
//
// public T getMessage() {
// return message;
// }
//
// public void setMessage(T message) {
// this.message = message;
// }
//
// public long getSeqId() {
// return seqId;
// }
//
// public void setSeqId(long seqId) {
// this.seqId = seqId;
// }
//
// public String toString() {
// return ToStringBuilder.reflectionToString(this, ToStringStyle.SHORT_PREFIX_STYLE);
// }
//
// public SignalType getType() {
// return type;
// }
//
// public void setType(SignalType type) {
// this.type = type;
// }
// }
| import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import org.apache.commons.collections.MapUtils;
import org.slf4j.Logger;
import org.springframework.util.Assert;
import com.baidu.unbiz.multiengine.transport.dto.Signal;
import com.baidu.unbiz.multitask.log.AopLogFactory;
import io.netty.channel.Channel;
import io.netty.util.AttributeKey; | package com.baidu.unbiz.multiengine.transport.client;
/**
* Created by wangchongjie on 16/4/11.
*/
public class TaskClientContext {
private static final Logger LOG = AopLogFactory.getLogger(TaskClientContext.class);
public static ConcurrentHashMap<String, Channel> sessionChannelMap = new ConcurrentHashMap<String, Channel>();
public static ConcurrentHashMap<String, TaskClient> sessionClientMap = new ConcurrentHashMap<String, TaskClient>();
public static final AttributeKey<String> SESSION_ATTRIBUTE = AttributeKey.newInstance("SESSION_ATTRIBUTE");
private static ConcurrentHashMap<String, ConcurrentHashMap<Long, SendFuture>> sessionResultMap =
new ConcurrentHashMap<String, ConcurrentHashMap<Long, SendFuture>>();
private static Long DEFAULT_RESULT_CAPACITY = 1000L;
public static void placeSessionResult(String sessionKey, Long seqId, SendFuture futrue) {
ConcurrentHashMap<Long, SendFuture> resultMap = sessionResultMap.get(sessionKey);
if (resultMap == null) {
resultMap = new ConcurrentHashMap<Long, SendFuture>();
sessionResultMap.putIfAbsent(sessionKey, resultMap);
resultMap = sessionResultMap.get(sessionKey);
}
resultMap.put(seqId, futrue);
}
| // Path: src/main/java/com/baidu/unbiz/multiengine/transport/dto/Signal.java
// public class Signal<T> {
//
// protected long seqId;
// protected T message;
// protected SignalType type = SignalType.TASK_COMMOND;
//
// public Signal() {
// }
//
// public Signal(T message) {
// this.message = message;
// }
//
// public T getMessage() {
// return message;
// }
//
// public void setMessage(T message) {
// this.message = message;
// }
//
// public long getSeqId() {
// return seqId;
// }
//
// public void setSeqId(long seqId) {
// this.seqId = seqId;
// }
//
// public String toString() {
// return ToStringBuilder.reflectionToString(this, ToStringStyle.SHORT_PREFIX_STYLE);
// }
//
// public SignalType getType() {
// return type;
// }
//
// public void setType(SignalType type) {
// this.type = type;
// }
// }
// Path: src/main/java/com/baidu/unbiz/multiengine/transport/client/TaskClientContext.java
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import org.apache.commons.collections.MapUtils;
import org.slf4j.Logger;
import org.springframework.util.Assert;
import com.baidu.unbiz.multiengine.transport.dto.Signal;
import com.baidu.unbiz.multitask.log.AopLogFactory;
import io.netty.channel.Channel;
import io.netty.util.AttributeKey;
package com.baidu.unbiz.multiengine.transport.client;
/**
* Created by wangchongjie on 16/4/11.
*/
public class TaskClientContext {
private static final Logger LOG = AopLogFactory.getLogger(TaskClientContext.class);
public static ConcurrentHashMap<String, Channel> sessionChannelMap = new ConcurrentHashMap<String, Channel>();
public static ConcurrentHashMap<String, TaskClient> sessionClientMap = new ConcurrentHashMap<String, TaskClient>();
public static final AttributeKey<String> SESSION_ATTRIBUTE = AttributeKey.newInstance("SESSION_ATTRIBUTE");
private static ConcurrentHashMap<String, ConcurrentHashMap<Long, SendFuture>> sessionResultMap =
new ConcurrentHashMap<String, ConcurrentHashMap<Long, SendFuture>>();
private static Long DEFAULT_RESULT_CAPACITY = 1000L;
public static void placeSessionResult(String sessionKey, Long seqId, SendFuture futrue) {
ConcurrentHashMap<Long, SendFuture> resultMap = sessionResultMap.get(sessionKey);
if (resultMap == null) {
resultMap = new ConcurrentHashMap<Long, SendFuture>();
sessionResultMap.putIfAbsent(sessionKey, resultMap);
resultMap = sessionResultMap.get(sessionKey);
}
resultMap.put(seqId, futrue);
}
| public static void fillSessionResult(String sessionKey, Signal signal) { |
wangchongjie/multi-engine | src/main/java/com/baidu/unbiz/multiengine/endpoint/EndpointPool.java | // Path: src/main/java/com/baidu/unbiz/multiengine/exception/MultiEngineException.java
// public class MultiEngineException extends RuntimeException {
//
// /**
// * serialVersionUID
// */
// private static final long serialVersionUID = 2396421433506179782L;
//
// /**
// * Creates a new instance of CodecException.
// */
// public MultiEngineException() {
// super();
// }
//
// /**
// * Creates a new instance of CodecException.
// *
// * @param arg0
// * @param arg1
// */
// public MultiEngineException(String arg0, Throwable arg1) {
// super(arg0, arg1);
// }
//
// /**
// * Creates a new instance of CodecException.
// *
// * @param arg0
// */
// public MultiEngineException(String arg0) {
// super(arg0);
// }
//
// /**
// * Creates a new instance of CodecException.
// *
// * @param arg0
// */
// public MultiEngineException(Throwable arg0) {
// super(arg0);
// }
//
// }
//
// Path: src/main/java/com/baidu/unbiz/multiengine/transport/client/TaskClient.java
// public final class TaskClient extends AbstractTaskClient {
//
// private static final Logger LOG = AopLogFactory.getLogger(TaskClient.class);
//
// private CountDownLatch initDone = new CountDownLatch(1);
// private AtomicBoolean initSuccess = new AtomicBoolean(true);
// private TaskClientStatus status = new TaskClientStatus();
//
// public <T> T call(TaskCommand command) {
// return (T) syncSend(command);
// }
//
// public SendFuture asyncCall(TaskCommand request) {
// return asyncSend(request);
// }
//
// public boolean heartBeat(HeartbeatInfo hbi) {
// Signal<HeartbeatInfo> signal = new Signal<HeartbeatInfo>();
// signal.setType(SignalType.HEART_BEAT);
// try {
// syncSend(signal, hbi.getTimeout(), TimeUnit.MILLISECONDS);
// } catch (TimeoutException e) {
// return false;
// } catch (InterruptedException e) {
// return false;
// }
// return true;
// }
//
// public void syncGossip() {
// Signal<GossipSync> signal = new Signal<GossipSync>();
// signal.setType(SignalType.GOSSIP_SYNC);
// try {
// onewaySend(signal);
// } catch (Exception e) {
// LOG.warn("sync gossip:", e);
// }
// }
//
// public boolean restart() {
// this.stop();
// initDone = new CountDownLatch(1);
// initSuccess.set(false);
// return start();
// }
//
// public boolean start() {
// final AbstractTaskClient client = this;
// new Thread() {
// @Override
// public void run() {
// try {
// client.doStart();
// } catch (Exception e) {
// LOG.error("client start fail:", e);
// }
// }
// }.start();
//
// try {
// initDone.await();
// } catch (InterruptedException e) {
// LOG.error("client await fail:" + client.getHostConf());
// initSuccess.set(false);
// }
// return initSuccess.get();
// }
//
// public void stop() {
// Channel channel = TaskClientContext.sessionChannelMap.get(sessionKey);
// if (channel == null) {
// return;
// }
// channel.close();
// }
//
// public void callbackOnException(Exception e) {
// LOG.error("client start fail:", e);
// initSuccess.set(false);
// initDone.countDown();
// }
//
// public TaskClient() {
// }
//
// public TaskClient(HostConf hostConf) {
// this.hostConf = hostConf;
// }
//
// public void callbackPostInit() {
// initDone.countDown();
// }
//
// public AtomicBoolean getInvalid() {
// return status.getInvalid();
// }
//
// public boolean isInvalid() {
// return status.getInvalid().get();
// }
//
// public void setInvalid(AtomicBoolean invalid) {
// this.status.setInvalid(invalid);
// }
//
// public void setInvalid(boolean invalid) {
// this.status.getInvalid().set(invalid);
// }
//
// public boolean initSuccess() {
// return initSuccess.get();
// }
// }
//
// Path: src/main/java/com/baidu/unbiz/multiengine/transport/client/TaskClientFactory.java
// public class TaskClientFactory {
//
// private static SessionIdProvider idProvider = new DefaultSessionIdProvider("TaskClient");
//
// public static TaskClient createTaskClient(HostConf hostConf) {
// TaskClient taskClient = new TaskClient(hostConf);
// taskClient.setIdGen(new SequenceIdGen());
// String sessionKey = idProvider.getSessionId(true);
// taskClient.setSessionKey(sessionKey);
// TaskClientContext.sessionClientMap.putIfAbsent(sessionKey, taskClient);
// return taskClient;
// }
// }
| import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.springframework.util.Assert;
import com.baidu.unbiz.multiengine.exception.MultiEngineException;
import com.baidu.unbiz.multiengine.transport.client.TaskClient;
import com.baidu.unbiz.multiengine.transport.client.TaskClientFactory;
import com.baidu.unbiz.multitask.log.AopLogFactory; | package com.baidu.unbiz.multiengine.endpoint;
/**
* Created by wangchongjie on 16/4/14.
*/
public class EndpointPool {
private static final Logger LOG = AopLogFactory.getLogger(EndpointPool.class);
| // Path: src/main/java/com/baidu/unbiz/multiengine/exception/MultiEngineException.java
// public class MultiEngineException extends RuntimeException {
//
// /**
// * serialVersionUID
// */
// private static final long serialVersionUID = 2396421433506179782L;
//
// /**
// * Creates a new instance of CodecException.
// */
// public MultiEngineException() {
// super();
// }
//
// /**
// * Creates a new instance of CodecException.
// *
// * @param arg0
// * @param arg1
// */
// public MultiEngineException(String arg0, Throwable arg1) {
// super(arg0, arg1);
// }
//
// /**
// * Creates a new instance of CodecException.
// *
// * @param arg0
// */
// public MultiEngineException(String arg0) {
// super(arg0);
// }
//
// /**
// * Creates a new instance of CodecException.
// *
// * @param arg0
// */
// public MultiEngineException(Throwable arg0) {
// super(arg0);
// }
//
// }
//
// Path: src/main/java/com/baidu/unbiz/multiengine/transport/client/TaskClient.java
// public final class TaskClient extends AbstractTaskClient {
//
// private static final Logger LOG = AopLogFactory.getLogger(TaskClient.class);
//
// private CountDownLatch initDone = new CountDownLatch(1);
// private AtomicBoolean initSuccess = new AtomicBoolean(true);
// private TaskClientStatus status = new TaskClientStatus();
//
// public <T> T call(TaskCommand command) {
// return (T) syncSend(command);
// }
//
// public SendFuture asyncCall(TaskCommand request) {
// return asyncSend(request);
// }
//
// public boolean heartBeat(HeartbeatInfo hbi) {
// Signal<HeartbeatInfo> signal = new Signal<HeartbeatInfo>();
// signal.setType(SignalType.HEART_BEAT);
// try {
// syncSend(signal, hbi.getTimeout(), TimeUnit.MILLISECONDS);
// } catch (TimeoutException e) {
// return false;
// } catch (InterruptedException e) {
// return false;
// }
// return true;
// }
//
// public void syncGossip() {
// Signal<GossipSync> signal = new Signal<GossipSync>();
// signal.setType(SignalType.GOSSIP_SYNC);
// try {
// onewaySend(signal);
// } catch (Exception e) {
// LOG.warn("sync gossip:", e);
// }
// }
//
// public boolean restart() {
// this.stop();
// initDone = new CountDownLatch(1);
// initSuccess.set(false);
// return start();
// }
//
// public boolean start() {
// final AbstractTaskClient client = this;
// new Thread() {
// @Override
// public void run() {
// try {
// client.doStart();
// } catch (Exception e) {
// LOG.error("client start fail:", e);
// }
// }
// }.start();
//
// try {
// initDone.await();
// } catch (InterruptedException e) {
// LOG.error("client await fail:" + client.getHostConf());
// initSuccess.set(false);
// }
// return initSuccess.get();
// }
//
// public void stop() {
// Channel channel = TaskClientContext.sessionChannelMap.get(sessionKey);
// if (channel == null) {
// return;
// }
// channel.close();
// }
//
// public void callbackOnException(Exception e) {
// LOG.error("client start fail:", e);
// initSuccess.set(false);
// initDone.countDown();
// }
//
// public TaskClient() {
// }
//
// public TaskClient(HostConf hostConf) {
// this.hostConf = hostConf;
// }
//
// public void callbackPostInit() {
// initDone.countDown();
// }
//
// public AtomicBoolean getInvalid() {
// return status.getInvalid();
// }
//
// public boolean isInvalid() {
// return status.getInvalid().get();
// }
//
// public void setInvalid(AtomicBoolean invalid) {
// this.status.setInvalid(invalid);
// }
//
// public void setInvalid(boolean invalid) {
// this.status.getInvalid().set(invalid);
// }
//
// public boolean initSuccess() {
// return initSuccess.get();
// }
// }
//
// Path: src/main/java/com/baidu/unbiz/multiengine/transport/client/TaskClientFactory.java
// public class TaskClientFactory {
//
// private static SessionIdProvider idProvider = new DefaultSessionIdProvider("TaskClient");
//
// public static TaskClient createTaskClient(HostConf hostConf) {
// TaskClient taskClient = new TaskClient(hostConf);
// taskClient.setIdGen(new SequenceIdGen());
// String sessionKey = idProvider.getSessionId(true);
// taskClient.setSessionKey(sessionKey);
// TaskClientContext.sessionClientMap.putIfAbsent(sessionKey, taskClient);
// return taskClient;
// }
// }
// Path: src/main/java/com/baidu/unbiz/multiengine/endpoint/EndpointPool.java
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.springframework.util.Assert;
import com.baidu.unbiz.multiengine.exception.MultiEngineException;
import com.baidu.unbiz.multiengine.transport.client.TaskClient;
import com.baidu.unbiz.multiengine.transport.client.TaskClientFactory;
import com.baidu.unbiz.multitask.log.AopLogFactory;
package com.baidu.unbiz.multiengine.endpoint;
/**
* Created by wangchongjie on 16/4/14.
*/
public class EndpointPool {
private static final Logger LOG = AopLogFactory.getLogger(EndpointPool.class);
| private static List<TaskClient> pool = new CopyOnWriteArrayList<TaskClient>(); |
wangchongjie/multi-engine | src/main/java/com/baidu/unbiz/multiengine/endpoint/EndpointPool.java | // Path: src/main/java/com/baidu/unbiz/multiengine/exception/MultiEngineException.java
// public class MultiEngineException extends RuntimeException {
//
// /**
// * serialVersionUID
// */
// private static final long serialVersionUID = 2396421433506179782L;
//
// /**
// * Creates a new instance of CodecException.
// */
// public MultiEngineException() {
// super();
// }
//
// /**
// * Creates a new instance of CodecException.
// *
// * @param arg0
// * @param arg1
// */
// public MultiEngineException(String arg0, Throwable arg1) {
// super(arg0, arg1);
// }
//
// /**
// * Creates a new instance of CodecException.
// *
// * @param arg0
// */
// public MultiEngineException(String arg0) {
// super(arg0);
// }
//
// /**
// * Creates a new instance of CodecException.
// *
// * @param arg0
// */
// public MultiEngineException(Throwable arg0) {
// super(arg0);
// }
//
// }
//
// Path: src/main/java/com/baidu/unbiz/multiengine/transport/client/TaskClient.java
// public final class TaskClient extends AbstractTaskClient {
//
// private static final Logger LOG = AopLogFactory.getLogger(TaskClient.class);
//
// private CountDownLatch initDone = new CountDownLatch(1);
// private AtomicBoolean initSuccess = new AtomicBoolean(true);
// private TaskClientStatus status = new TaskClientStatus();
//
// public <T> T call(TaskCommand command) {
// return (T) syncSend(command);
// }
//
// public SendFuture asyncCall(TaskCommand request) {
// return asyncSend(request);
// }
//
// public boolean heartBeat(HeartbeatInfo hbi) {
// Signal<HeartbeatInfo> signal = new Signal<HeartbeatInfo>();
// signal.setType(SignalType.HEART_BEAT);
// try {
// syncSend(signal, hbi.getTimeout(), TimeUnit.MILLISECONDS);
// } catch (TimeoutException e) {
// return false;
// } catch (InterruptedException e) {
// return false;
// }
// return true;
// }
//
// public void syncGossip() {
// Signal<GossipSync> signal = new Signal<GossipSync>();
// signal.setType(SignalType.GOSSIP_SYNC);
// try {
// onewaySend(signal);
// } catch (Exception e) {
// LOG.warn("sync gossip:", e);
// }
// }
//
// public boolean restart() {
// this.stop();
// initDone = new CountDownLatch(1);
// initSuccess.set(false);
// return start();
// }
//
// public boolean start() {
// final AbstractTaskClient client = this;
// new Thread() {
// @Override
// public void run() {
// try {
// client.doStart();
// } catch (Exception e) {
// LOG.error("client start fail:", e);
// }
// }
// }.start();
//
// try {
// initDone.await();
// } catch (InterruptedException e) {
// LOG.error("client await fail:" + client.getHostConf());
// initSuccess.set(false);
// }
// return initSuccess.get();
// }
//
// public void stop() {
// Channel channel = TaskClientContext.sessionChannelMap.get(sessionKey);
// if (channel == null) {
// return;
// }
// channel.close();
// }
//
// public void callbackOnException(Exception e) {
// LOG.error("client start fail:", e);
// initSuccess.set(false);
// initDone.countDown();
// }
//
// public TaskClient() {
// }
//
// public TaskClient(HostConf hostConf) {
// this.hostConf = hostConf;
// }
//
// public void callbackPostInit() {
// initDone.countDown();
// }
//
// public AtomicBoolean getInvalid() {
// return status.getInvalid();
// }
//
// public boolean isInvalid() {
// return status.getInvalid().get();
// }
//
// public void setInvalid(AtomicBoolean invalid) {
// this.status.setInvalid(invalid);
// }
//
// public void setInvalid(boolean invalid) {
// this.status.getInvalid().set(invalid);
// }
//
// public boolean initSuccess() {
// return initSuccess.get();
// }
// }
//
// Path: src/main/java/com/baidu/unbiz/multiengine/transport/client/TaskClientFactory.java
// public class TaskClientFactory {
//
// private static SessionIdProvider idProvider = new DefaultSessionIdProvider("TaskClient");
//
// public static TaskClient createTaskClient(HostConf hostConf) {
// TaskClient taskClient = new TaskClient(hostConf);
// taskClient.setIdGen(new SequenceIdGen());
// String sessionKey = idProvider.getSessionId(true);
// taskClient.setSessionKey(sessionKey);
// TaskClientContext.sessionClientMap.putIfAbsent(sessionKey, taskClient);
// return taskClient;
// }
// }
| import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.springframework.util.Assert;
import com.baidu.unbiz.multiengine.exception.MultiEngineException;
import com.baidu.unbiz.multiengine.transport.client.TaskClient;
import com.baidu.unbiz.multiengine.transport.client.TaskClientFactory;
import com.baidu.unbiz.multitask.log.AopLogFactory; | package com.baidu.unbiz.multiengine.endpoint;
/**
* Created by wangchongjie on 16/4/14.
*/
public class EndpointPool {
private static final Logger LOG = AopLogFactory.getLogger(EndpointPool.class);
private static List<TaskClient> pool = new CopyOnWriteArrayList<TaskClient>(); | // Path: src/main/java/com/baidu/unbiz/multiengine/exception/MultiEngineException.java
// public class MultiEngineException extends RuntimeException {
//
// /**
// * serialVersionUID
// */
// private static final long serialVersionUID = 2396421433506179782L;
//
// /**
// * Creates a new instance of CodecException.
// */
// public MultiEngineException() {
// super();
// }
//
// /**
// * Creates a new instance of CodecException.
// *
// * @param arg0
// * @param arg1
// */
// public MultiEngineException(String arg0, Throwable arg1) {
// super(arg0, arg1);
// }
//
// /**
// * Creates a new instance of CodecException.
// *
// * @param arg0
// */
// public MultiEngineException(String arg0) {
// super(arg0);
// }
//
// /**
// * Creates a new instance of CodecException.
// *
// * @param arg0
// */
// public MultiEngineException(Throwable arg0) {
// super(arg0);
// }
//
// }
//
// Path: src/main/java/com/baidu/unbiz/multiengine/transport/client/TaskClient.java
// public final class TaskClient extends AbstractTaskClient {
//
// private static final Logger LOG = AopLogFactory.getLogger(TaskClient.class);
//
// private CountDownLatch initDone = new CountDownLatch(1);
// private AtomicBoolean initSuccess = new AtomicBoolean(true);
// private TaskClientStatus status = new TaskClientStatus();
//
// public <T> T call(TaskCommand command) {
// return (T) syncSend(command);
// }
//
// public SendFuture asyncCall(TaskCommand request) {
// return asyncSend(request);
// }
//
// public boolean heartBeat(HeartbeatInfo hbi) {
// Signal<HeartbeatInfo> signal = new Signal<HeartbeatInfo>();
// signal.setType(SignalType.HEART_BEAT);
// try {
// syncSend(signal, hbi.getTimeout(), TimeUnit.MILLISECONDS);
// } catch (TimeoutException e) {
// return false;
// } catch (InterruptedException e) {
// return false;
// }
// return true;
// }
//
// public void syncGossip() {
// Signal<GossipSync> signal = new Signal<GossipSync>();
// signal.setType(SignalType.GOSSIP_SYNC);
// try {
// onewaySend(signal);
// } catch (Exception e) {
// LOG.warn("sync gossip:", e);
// }
// }
//
// public boolean restart() {
// this.stop();
// initDone = new CountDownLatch(1);
// initSuccess.set(false);
// return start();
// }
//
// public boolean start() {
// final AbstractTaskClient client = this;
// new Thread() {
// @Override
// public void run() {
// try {
// client.doStart();
// } catch (Exception e) {
// LOG.error("client start fail:", e);
// }
// }
// }.start();
//
// try {
// initDone.await();
// } catch (InterruptedException e) {
// LOG.error("client await fail:" + client.getHostConf());
// initSuccess.set(false);
// }
// return initSuccess.get();
// }
//
// public void stop() {
// Channel channel = TaskClientContext.sessionChannelMap.get(sessionKey);
// if (channel == null) {
// return;
// }
// channel.close();
// }
//
// public void callbackOnException(Exception e) {
// LOG.error("client start fail:", e);
// initSuccess.set(false);
// initDone.countDown();
// }
//
// public TaskClient() {
// }
//
// public TaskClient(HostConf hostConf) {
// this.hostConf = hostConf;
// }
//
// public void callbackPostInit() {
// initDone.countDown();
// }
//
// public AtomicBoolean getInvalid() {
// return status.getInvalid();
// }
//
// public boolean isInvalid() {
// return status.getInvalid().get();
// }
//
// public void setInvalid(AtomicBoolean invalid) {
// this.status.setInvalid(invalid);
// }
//
// public void setInvalid(boolean invalid) {
// this.status.getInvalid().set(invalid);
// }
//
// public boolean initSuccess() {
// return initSuccess.get();
// }
// }
//
// Path: src/main/java/com/baidu/unbiz/multiengine/transport/client/TaskClientFactory.java
// public class TaskClientFactory {
//
// private static SessionIdProvider idProvider = new DefaultSessionIdProvider("TaskClient");
//
// public static TaskClient createTaskClient(HostConf hostConf) {
// TaskClient taskClient = new TaskClient(hostConf);
// taskClient.setIdGen(new SequenceIdGen());
// String sessionKey = idProvider.getSessionId(true);
// taskClient.setSessionKey(sessionKey);
// TaskClientContext.sessionClientMap.putIfAbsent(sessionKey, taskClient);
// return taskClient;
// }
// }
// Path: src/main/java/com/baidu/unbiz/multiengine/endpoint/EndpointPool.java
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.springframework.util.Assert;
import com.baidu.unbiz.multiengine.exception.MultiEngineException;
import com.baidu.unbiz.multiengine.transport.client.TaskClient;
import com.baidu.unbiz.multiengine.transport.client.TaskClientFactory;
import com.baidu.unbiz.multitask.log.AopLogFactory;
package com.baidu.unbiz.multiengine.endpoint;
/**
* Created by wangchongjie on 16/4/14.
*/
public class EndpointPool {
private static final Logger LOG = AopLogFactory.getLogger(EndpointPool.class);
private static List<TaskClient> pool = new CopyOnWriteArrayList<TaskClient>(); | private static TaskClientFactory clientFactory = new TaskClientFactory(); |
wangchongjie/multi-engine | src/main/java/com/baidu/unbiz/multiengine/endpoint/gossip/GossipInfo.java | // Path: src/main/java/com/baidu/unbiz/multiengine/endpoint/HostConf.java
// public class HostConf {
//
// private String host = System.getProperty("host", "127.0.0.1");
// private int port = Integer.parseInt(System.getProperty("port", "8007"));
// private boolean ssl = System.getProperty("ssl") != null;
//
// public HostConf() {
// try {
// InetAddress addr = InetAddress.getLocalHost();
// host = addr.getHostAddress();
// } catch (UnknownHostException e) {
// // do nothing
// }
// }
//
// public HostConf(String host, int port) {
// this();
// this.host = host;
// this.port = port;
// }
//
// @Override
// public boolean equals(Object obj) {
// if (!(obj instanceof HostConf)) {
// return false;
// }
// HostConf other = (HostConf) obj;
// return this.host.equals(other.getHost()) && this.port == other.getPort() && this.ssl == other.isSsl();
// }
//
// @Override
// public int hashCode() {
// return this.host.hashCode() + this.host.hashCode();
// }
//
// public static List<HostConf> resolveHost(String hosts) {
// List<HostConf> hostConfs = new ArrayList<HostConf>();
// if (StringUtils.isEmpty(hosts)) {
// return hostConfs;
// }
// String[] hostStrs = hosts.split(";");
// for (String host : hostStrs) {
// String ip = host.replaceAll(":.*", "");
// String port = host.replaceAll(".*:", "");
// hostConfs.add(new HostConf(ip, Integer.parseInt(port)));
// }
// return hostConfs;
// }
//
// public static List<HostConf> resolvePort(String ports) {
//
// List<HostConf> hostConfs = new ArrayList<HostConf>();
// if (StringUtils.isEmpty(ports)) {
// return hostConfs;
// }
// String[] ps = ports.split(";");
// for (String port : ps) {
// HostConf hostConf = new HostConf();
// hostConf.setPort(Integer.parseInt(port));
// hostConfs.add(hostConf);
// }
// return hostConfs;
// }
//
// public String info() {
// StringBuilder sb = new StringBuilder();
// sb.append(this.getHost()).append(":").append(this.getPort());
// return sb.toString();
// }
//
// public int getPort() {
// return port;
// }
//
// public void setPort(int port) {
// this.port = port;
// }
//
// public String getHost() {
// return host;
// }
//
// public void setHost(String host) {
// this.host = host;
// }
//
// public boolean isSsl() {
// return ssl;
// }
//
// public void setSsl(boolean ssl) {
// this.ssl = ssl;
// }
//
// public String toString() {
// return ToStringBuilder.reflectionToString(this, ToStringStyle.SHORT_PREFIX_STYLE);
// }
//
// }
| import java.util.List;
import org.apache.commons.lang.builder.ToStringBuilder;
import org.apache.commons.lang.builder.ToStringStyle;
import com.baidu.unbiz.multiengine.endpoint.HostConf; | package com.baidu.unbiz.multiengine.endpoint.gossip;
/**
* Created by wangchongjie on 16/4/19.
*/
public class GossipInfo {
// TODO version and sys/net infos sync
private long version; | // Path: src/main/java/com/baidu/unbiz/multiengine/endpoint/HostConf.java
// public class HostConf {
//
// private String host = System.getProperty("host", "127.0.0.1");
// private int port = Integer.parseInt(System.getProperty("port", "8007"));
// private boolean ssl = System.getProperty("ssl") != null;
//
// public HostConf() {
// try {
// InetAddress addr = InetAddress.getLocalHost();
// host = addr.getHostAddress();
// } catch (UnknownHostException e) {
// // do nothing
// }
// }
//
// public HostConf(String host, int port) {
// this();
// this.host = host;
// this.port = port;
// }
//
// @Override
// public boolean equals(Object obj) {
// if (!(obj instanceof HostConf)) {
// return false;
// }
// HostConf other = (HostConf) obj;
// return this.host.equals(other.getHost()) && this.port == other.getPort() && this.ssl == other.isSsl();
// }
//
// @Override
// public int hashCode() {
// return this.host.hashCode() + this.host.hashCode();
// }
//
// public static List<HostConf> resolveHost(String hosts) {
// List<HostConf> hostConfs = new ArrayList<HostConf>();
// if (StringUtils.isEmpty(hosts)) {
// return hostConfs;
// }
// String[] hostStrs = hosts.split(";");
// for (String host : hostStrs) {
// String ip = host.replaceAll(":.*", "");
// String port = host.replaceAll(".*:", "");
// hostConfs.add(new HostConf(ip, Integer.parseInt(port)));
// }
// return hostConfs;
// }
//
// public static List<HostConf> resolvePort(String ports) {
//
// List<HostConf> hostConfs = new ArrayList<HostConf>();
// if (StringUtils.isEmpty(ports)) {
// return hostConfs;
// }
// String[] ps = ports.split(";");
// for (String port : ps) {
// HostConf hostConf = new HostConf();
// hostConf.setPort(Integer.parseInt(port));
// hostConfs.add(hostConf);
// }
// return hostConfs;
// }
//
// public String info() {
// StringBuilder sb = new StringBuilder();
// sb.append(this.getHost()).append(":").append(this.getPort());
// return sb.toString();
// }
//
// public int getPort() {
// return port;
// }
//
// public void setPort(int port) {
// this.port = port;
// }
//
// public String getHost() {
// return host;
// }
//
// public void setHost(String host) {
// this.host = host;
// }
//
// public boolean isSsl() {
// return ssl;
// }
//
// public void setSsl(boolean ssl) {
// this.ssl = ssl;
// }
//
// public String toString() {
// return ToStringBuilder.reflectionToString(this, ToStringStyle.SHORT_PREFIX_STYLE);
// }
//
// }
// Path: src/main/java/com/baidu/unbiz/multiengine/endpoint/gossip/GossipInfo.java
import java.util.List;
import org.apache.commons.lang.builder.ToStringBuilder;
import org.apache.commons.lang.builder.ToStringStyle;
import com.baidu.unbiz.multiengine.endpoint.HostConf;
package com.baidu.unbiz.multiengine.endpoint.gossip;
/**
* Created by wangchongjie on 16/4/19.
*/
public class GossipInfo {
// TODO version and sys/net infos sync
private long version; | private List<HostConf> hostConfs; |
wangchongjie/multi-engine | src/test/java/com/baidu/unbiz/multiengine/demo/test/TestMultiProcessServer3.java | // Path: src/main/java/com/baidu/unbiz/multiengine/endpoint/supervisor/DefaultEndpointSupervisor.java
// public class DefaultEndpointSupervisor implements EndpointSupervisor {
// private static final Logger LOG = AopLogFactory.getLogger(DefaultEndpointSupervisor.class);
//
// private static List<TaskServer> taskServers;
// private GossipSupport gossipSupport;
// private HeartbeatSupport heartbeatSupport;
//
// private String exportPort;
// private String serverHost;
//
// public DefaultEndpointSupervisor() {
// taskServers = new CopyOnWriteArrayList<TaskServer>();
// gossipSupport = new GossipSupport();
// heartbeatSupport = new HeartbeatSupport() {
// @Override
// public void tryRestartEndpoint(TaskClient taskClient) {
// doTryRestartEndpoint(taskClient);
// }
// };
// }
//
// public static List<HostConf> getTaskHostConf() {
// List<HostConf> hostConfs = new ArrayList<HostConf>();
// // fixme
// // for(TaskServer taskServer : taskServers){
// // hostConfs.internalAdd(taskServer.getHostConf());
// // }
// hostConfs.addAll(EndpointPool.getTaskHostConf());
// return hostConfs;
// }
//
// public static List<HostConf> mergeTaskServer(List<HostConf> otherHost) {
// List<HostConf> hostConfs = getTaskHostConf();
// otherHost.removeAll(hostConfs);
// EndpointPool.add(otherHost);
// return hostConfs;
// }
//
// /**
// * default: heartbeat and gossip
// */
// @Override
// public void init() {
// List<HostConf> exportHosts = HostConf.resolvePort(exportPort);
// for (HostConf hostConf : exportHosts) {
// TaskServer taskServer = TaskServerFactory.createTaskServer(hostConf);
// taskServer.start();
// taskServers.add(taskServer);
// }
// List<HostConf> clientHost = HostConf.resolveHost(this.serverHost);
// EndpointPool.init(clientHost);
//
// heartbeatSupport.scheduleHeartbeat();
// gossipSupport.scheduleGossip();
// }
//
// @Override
// public void stop() {
// EndpointPool.stop();
// if (CollectionUtils.isEmpty(taskServers)) {
// return;
// }
// for (TaskServer taskServer : taskServers) {
// taskServer.stop();
// }
//
// heartbeatSupport.shutdownScheduler();
// gossipSupport.shutdownScheduler();
// }
//
// protected void doTryRestartEndpoint(TaskClient taskClient) {
// try {
// taskClient.restart();
// } catch (Exception e) {
// // do nothing
// }
// }
//
// public String getServerHost() {
// return serverHost;
// }
//
// public void setServerHost(String serverHost) {
// this.serverHost = serverHost;
// }
//
// public String getExportPort() {
// return exportPort;
// }
//
// public void setExportPort(String exportPort) {
// this.exportPort = exportPort;
// }
// }
//
// Path: src/test/java/com/baidu/unbiz/multiengine/utils/TestUtils.java
// public class TestUtils {
// public static final long VERY_LONG_TIME = 2000 * 1000;
//
// public static void dumySleep(long time) {
// try {
// Thread.sleep(time);
// } catch (InterruptedException e) {
// // do nothing
// }
// }
// }
| import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import com.baidu.unbiz.multiengine.endpoint.supervisor.DefaultEndpointSupervisor;
import com.baidu.unbiz.multiengine.utils.TestUtils; | package com.baidu.unbiz.multiengine.demo.test;
/**
* Created by wangchongjie on 16/4/18.
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "/applicationContext-test2.xml")
public class TestMultiProcessServer3 {
| // Path: src/main/java/com/baidu/unbiz/multiengine/endpoint/supervisor/DefaultEndpointSupervisor.java
// public class DefaultEndpointSupervisor implements EndpointSupervisor {
// private static final Logger LOG = AopLogFactory.getLogger(DefaultEndpointSupervisor.class);
//
// private static List<TaskServer> taskServers;
// private GossipSupport gossipSupport;
// private HeartbeatSupport heartbeatSupport;
//
// private String exportPort;
// private String serverHost;
//
// public DefaultEndpointSupervisor() {
// taskServers = new CopyOnWriteArrayList<TaskServer>();
// gossipSupport = new GossipSupport();
// heartbeatSupport = new HeartbeatSupport() {
// @Override
// public void tryRestartEndpoint(TaskClient taskClient) {
// doTryRestartEndpoint(taskClient);
// }
// };
// }
//
// public static List<HostConf> getTaskHostConf() {
// List<HostConf> hostConfs = new ArrayList<HostConf>();
// // fixme
// // for(TaskServer taskServer : taskServers){
// // hostConfs.internalAdd(taskServer.getHostConf());
// // }
// hostConfs.addAll(EndpointPool.getTaskHostConf());
// return hostConfs;
// }
//
// public static List<HostConf> mergeTaskServer(List<HostConf> otherHost) {
// List<HostConf> hostConfs = getTaskHostConf();
// otherHost.removeAll(hostConfs);
// EndpointPool.add(otherHost);
// return hostConfs;
// }
//
// /**
// * default: heartbeat and gossip
// */
// @Override
// public void init() {
// List<HostConf> exportHosts = HostConf.resolvePort(exportPort);
// for (HostConf hostConf : exportHosts) {
// TaskServer taskServer = TaskServerFactory.createTaskServer(hostConf);
// taskServer.start();
// taskServers.add(taskServer);
// }
// List<HostConf> clientHost = HostConf.resolveHost(this.serverHost);
// EndpointPool.init(clientHost);
//
// heartbeatSupport.scheduleHeartbeat();
// gossipSupport.scheduleGossip();
// }
//
// @Override
// public void stop() {
// EndpointPool.stop();
// if (CollectionUtils.isEmpty(taskServers)) {
// return;
// }
// for (TaskServer taskServer : taskServers) {
// taskServer.stop();
// }
//
// heartbeatSupport.shutdownScheduler();
// gossipSupport.shutdownScheduler();
// }
//
// protected void doTryRestartEndpoint(TaskClient taskClient) {
// try {
// taskClient.restart();
// } catch (Exception e) {
// // do nothing
// }
// }
//
// public String getServerHost() {
// return serverHost;
// }
//
// public void setServerHost(String serverHost) {
// this.serverHost = serverHost;
// }
//
// public String getExportPort() {
// return exportPort;
// }
//
// public void setExportPort(String exportPort) {
// this.exportPort = exportPort;
// }
// }
//
// Path: src/test/java/com/baidu/unbiz/multiengine/utils/TestUtils.java
// public class TestUtils {
// public static final long VERY_LONG_TIME = 2000 * 1000;
//
// public static void dumySleep(long time) {
// try {
// Thread.sleep(time);
// } catch (InterruptedException e) {
// // do nothing
// }
// }
// }
// Path: src/test/java/com/baidu/unbiz/multiengine/demo/test/TestMultiProcessServer3.java
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import com.baidu.unbiz.multiengine.endpoint.supervisor.DefaultEndpointSupervisor;
import com.baidu.unbiz.multiengine.utils.TestUtils;
package com.baidu.unbiz.multiengine.demo.test;
/**
* Created by wangchongjie on 16/4/18.
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "/applicationContext-test2.xml")
public class TestMultiProcessServer3 {
| private DefaultEndpointSupervisor supervisor = new DefaultEndpointSupervisor(); |
wangchongjie/multi-engine | src/test/java/com/baidu/unbiz/multiengine/demo/test/TestMultiProcessServer3.java | // Path: src/main/java/com/baidu/unbiz/multiengine/endpoint/supervisor/DefaultEndpointSupervisor.java
// public class DefaultEndpointSupervisor implements EndpointSupervisor {
// private static final Logger LOG = AopLogFactory.getLogger(DefaultEndpointSupervisor.class);
//
// private static List<TaskServer> taskServers;
// private GossipSupport gossipSupport;
// private HeartbeatSupport heartbeatSupport;
//
// private String exportPort;
// private String serverHost;
//
// public DefaultEndpointSupervisor() {
// taskServers = new CopyOnWriteArrayList<TaskServer>();
// gossipSupport = new GossipSupport();
// heartbeatSupport = new HeartbeatSupport() {
// @Override
// public void tryRestartEndpoint(TaskClient taskClient) {
// doTryRestartEndpoint(taskClient);
// }
// };
// }
//
// public static List<HostConf> getTaskHostConf() {
// List<HostConf> hostConfs = new ArrayList<HostConf>();
// // fixme
// // for(TaskServer taskServer : taskServers){
// // hostConfs.internalAdd(taskServer.getHostConf());
// // }
// hostConfs.addAll(EndpointPool.getTaskHostConf());
// return hostConfs;
// }
//
// public static List<HostConf> mergeTaskServer(List<HostConf> otherHost) {
// List<HostConf> hostConfs = getTaskHostConf();
// otherHost.removeAll(hostConfs);
// EndpointPool.add(otherHost);
// return hostConfs;
// }
//
// /**
// * default: heartbeat and gossip
// */
// @Override
// public void init() {
// List<HostConf> exportHosts = HostConf.resolvePort(exportPort);
// for (HostConf hostConf : exportHosts) {
// TaskServer taskServer = TaskServerFactory.createTaskServer(hostConf);
// taskServer.start();
// taskServers.add(taskServer);
// }
// List<HostConf> clientHost = HostConf.resolveHost(this.serverHost);
// EndpointPool.init(clientHost);
//
// heartbeatSupport.scheduleHeartbeat();
// gossipSupport.scheduleGossip();
// }
//
// @Override
// public void stop() {
// EndpointPool.stop();
// if (CollectionUtils.isEmpty(taskServers)) {
// return;
// }
// for (TaskServer taskServer : taskServers) {
// taskServer.stop();
// }
//
// heartbeatSupport.shutdownScheduler();
// gossipSupport.shutdownScheduler();
// }
//
// protected void doTryRestartEndpoint(TaskClient taskClient) {
// try {
// taskClient.restart();
// } catch (Exception e) {
// // do nothing
// }
// }
//
// public String getServerHost() {
// return serverHost;
// }
//
// public void setServerHost(String serverHost) {
// this.serverHost = serverHost;
// }
//
// public String getExportPort() {
// return exportPort;
// }
//
// public void setExportPort(String exportPort) {
// this.exportPort = exportPort;
// }
// }
//
// Path: src/test/java/com/baidu/unbiz/multiengine/utils/TestUtils.java
// public class TestUtils {
// public static final long VERY_LONG_TIME = 2000 * 1000;
//
// public static void dumySleep(long time) {
// try {
// Thread.sleep(time);
// } catch (InterruptedException e) {
// // do nothing
// }
// }
// }
| import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import com.baidu.unbiz.multiengine.endpoint.supervisor.DefaultEndpointSupervisor;
import com.baidu.unbiz.multiengine.utils.TestUtils; | package com.baidu.unbiz.multiengine.demo.test;
/**
* Created by wangchongjie on 16/4/18.
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "/applicationContext-test2.xml")
public class TestMultiProcessServer3 {
private DefaultEndpointSupervisor supervisor = new DefaultEndpointSupervisor();
@Before
public void init() {
supervisor.setExportPort("8803");
supervisor.setServerHost("127.0.0.1:8801;127.0.0.1:8803");
supervisor.init();
}
@After
public void clean() {
supervisor.stop();
}
/**
* 测试分布式并行执行task
*/
@Test
public void runServer() { | // Path: src/main/java/com/baidu/unbiz/multiengine/endpoint/supervisor/DefaultEndpointSupervisor.java
// public class DefaultEndpointSupervisor implements EndpointSupervisor {
// private static final Logger LOG = AopLogFactory.getLogger(DefaultEndpointSupervisor.class);
//
// private static List<TaskServer> taskServers;
// private GossipSupport gossipSupport;
// private HeartbeatSupport heartbeatSupport;
//
// private String exportPort;
// private String serverHost;
//
// public DefaultEndpointSupervisor() {
// taskServers = new CopyOnWriteArrayList<TaskServer>();
// gossipSupport = new GossipSupport();
// heartbeatSupport = new HeartbeatSupport() {
// @Override
// public void tryRestartEndpoint(TaskClient taskClient) {
// doTryRestartEndpoint(taskClient);
// }
// };
// }
//
// public static List<HostConf> getTaskHostConf() {
// List<HostConf> hostConfs = new ArrayList<HostConf>();
// // fixme
// // for(TaskServer taskServer : taskServers){
// // hostConfs.internalAdd(taskServer.getHostConf());
// // }
// hostConfs.addAll(EndpointPool.getTaskHostConf());
// return hostConfs;
// }
//
// public static List<HostConf> mergeTaskServer(List<HostConf> otherHost) {
// List<HostConf> hostConfs = getTaskHostConf();
// otherHost.removeAll(hostConfs);
// EndpointPool.add(otherHost);
// return hostConfs;
// }
//
// /**
// * default: heartbeat and gossip
// */
// @Override
// public void init() {
// List<HostConf> exportHosts = HostConf.resolvePort(exportPort);
// for (HostConf hostConf : exportHosts) {
// TaskServer taskServer = TaskServerFactory.createTaskServer(hostConf);
// taskServer.start();
// taskServers.add(taskServer);
// }
// List<HostConf> clientHost = HostConf.resolveHost(this.serverHost);
// EndpointPool.init(clientHost);
//
// heartbeatSupport.scheduleHeartbeat();
// gossipSupport.scheduleGossip();
// }
//
// @Override
// public void stop() {
// EndpointPool.stop();
// if (CollectionUtils.isEmpty(taskServers)) {
// return;
// }
// for (TaskServer taskServer : taskServers) {
// taskServer.stop();
// }
//
// heartbeatSupport.shutdownScheduler();
// gossipSupport.shutdownScheduler();
// }
//
// protected void doTryRestartEndpoint(TaskClient taskClient) {
// try {
// taskClient.restart();
// } catch (Exception e) {
// // do nothing
// }
// }
//
// public String getServerHost() {
// return serverHost;
// }
//
// public void setServerHost(String serverHost) {
// this.serverHost = serverHost;
// }
//
// public String getExportPort() {
// return exportPort;
// }
//
// public void setExportPort(String exportPort) {
// this.exportPort = exportPort;
// }
// }
//
// Path: src/test/java/com/baidu/unbiz/multiengine/utils/TestUtils.java
// public class TestUtils {
// public static final long VERY_LONG_TIME = 2000 * 1000;
//
// public static void dumySleep(long time) {
// try {
// Thread.sleep(time);
// } catch (InterruptedException e) {
// // do nothing
// }
// }
// }
// Path: src/test/java/com/baidu/unbiz/multiengine/demo/test/TestMultiProcessServer3.java
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import com.baidu.unbiz.multiengine.endpoint.supervisor.DefaultEndpointSupervisor;
import com.baidu.unbiz.multiengine.utils.TestUtils;
package com.baidu.unbiz.multiengine.demo.test;
/**
* Created by wangchongjie on 16/4/18.
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "/applicationContext-test2.xml")
public class TestMultiProcessServer3 {
private DefaultEndpointSupervisor supervisor = new DefaultEndpointSupervisor();
@Before
public void init() {
supervisor.setExportPort("8803");
supervisor.setServerHost("127.0.0.1:8801;127.0.0.1:8803");
supervisor.init();
}
@After
public void clean() {
supervisor.stop();
}
/**
* 测试分布式并行执行task
*/
@Test
public void runServer() { | TestUtils.dumySleep(TestUtils.VERY_LONG_TIME); |
wangchongjie/multi-engine | src/test/java/com/baidu/unbiz/multiengine/demo/test/TestMultiProcessServer1.java | // Path: src/test/java/com/baidu/unbiz/multiengine/utils/TestUtils.java
// public class TestUtils {
// public static final long VERY_LONG_TIME = 2000 * 1000;
//
// public static void dumySleep(long time) {
// try {
// Thread.sleep(time);
// } catch (InterruptedException e) {
// // do nothing
// }
// }
// }
//
// Path: src/main/java/com/baidu/unbiz/multiengine/endpoint/supervisor/DefaultEndpointSupervisor.java
// public class DefaultEndpointSupervisor implements EndpointSupervisor {
// private static final Logger LOG = AopLogFactory.getLogger(DefaultEndpointSupervisor.class);
//
// private static List<TaskServer> taskServers;
// private GossipSupport gossipSupport;
// private HeartbeatSupport heartbeatSupport;
//
// private String exportPort;
// private String serverHost;
//
// public DefaultEndpointSupervisor() {
// taskServers = new CopyOnWriteArrayList<TaskServer>();
// gossipSupport = new GossipSupport();
// heartbeatSupport = new HeartbeatSupport() {
// @Override
// public void tryRestartEndpoint(TaskClient taskClient) {
// doTryRestartEndpoint(taskClient);
// }
// };
// }
//
// public static List<HostConf> getTaskHostConf() {
// List<HostConf> hostConfs = new ArrayList<HostConf>();
// // fixme
// // for(TaskServer taskServer : taskServers){
// // hostConfs.internalAdd(taskServer.getHostConf());
// // }
// hostConfs.addAll(EndpointPool.getTaskHostConf());
// return hostConfs;
// }
//
// public static List<HostConf> mergeTaskServer(List<HostConf> otherHost) {
// List<HostConf> hostConfs = getTaskHostConf();
// otherHost.removeAll(hostConfs);
// EndpointPool.add(otherHost);
// return hostConfs;
// }
//
// /**
// * default: heartbeat and gossip
// */
// @Override
// public void init() {
// List<HostConf> exportHosts = HostConf.resolvePort(exportPort);
// for (HostConf hostConf : exportHosts) {
// TaskServer taskServer = TaskServerFactory.createTaskServer(hostConf);
// taskServer.start();
// taskServers.add(taskServer);
// }
// List<HostConf> clientHost = HostConf.resolveHost(this.serverHost);
// EndpointPool.init(clientHost);
//
// heartbeatSupport.scheduleHeartbeat();
// gossipSupport.scheduleGossip();
// }
//
// @Override
// public void stop() {
// EndpointPool.stop();
// if (CollectionUtils.isEmpty(taskServers)) {
// return;
// }
// for (TaskServer taskServer : taskServers) {
// taskServer.stop();
// }
//
// heartbeatSupport.shutdownScheduler();
// gossipSupport.shutdownScheduler();
// }
//
// protected void doTryRestartEndpoint(TaskClient taskClient) {
// try {
// taskClient.restart();
// } catch (Exception e) {
// // do nothing
// }
// }
//
// public String getServerHost() {
// return serverHost;
// }
//
// public void setServerHost(String serverHost) {
// this.serverHost = serverHost;
// }
//
// public String getExportPort() {
// return exportPort;
// }
//
// public void setExportPort(String exportPort) {
// this.exportPort = exportPort;
// }
// }
| import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import com.baidu.unbiz.multiengine.utils.TestUtils;
import com.baidu.unbiz.multiengine.endpoint.supervisor.DefaultEndpointSupervisor; | package com.baidu.unbiz.multiengine.demo.test;
/**
* Created by wangchongjie on 16/4/18.
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "/applicationContext-test2.xml")
public class TestMultiProcessServer1 {
| // Path: src/test/java/com/baidu/unbiz/multiengine/utils/TestUtils.java
// public class TestUtils {
// public static final long VERY_LONG_TIME = 2000 * 1000;
//
// public static void dumySleep(long time) {
// try {
// Thread.sleep(time);
// } catch (InterruptedException e) {
// // do nothing
// }
// }
// }
//
// Path: src/main/java/com/baidu/unbiz/multiengine/endpoint/supervisor/DefaultEndpointSupervisor.java
// public class DefaultEndpointSupervisor implements EndpointSupervisor {
// private static final Logger LOG = AopLogFactory.getLogger(DefaultEndpointSupervisor.class);
//
// private static List<TaskServer> taskServers;
// private GossipSupport gossipSupport;
// private HeartbeatSupport heartbeatSupport;
//
// private String exportPort;
// private String serverHost;
//
// public DefaultEndpointSupervisor() {
// taskServers = new CopyOnWriteArrayList<TaskServer>();
// gossipSupport = new GossipSupport();
// heartbeatSupport = new HeartbeatSupport() {
// @Override
// public void tryRestartEndpoint(TaskClient taskClient) {
// doTryRestartEndpoint(taskClient);
// }
// };
// }
//
// public static List<HostConf> getTaskHostConf() {
// List<HostConf> hostConfs = new ArrayList<HostConf>();
// // fixme
// // for(TaskServer taskServer : taskServers){
// // hostConfs.internalAdd(taskServer.getHostConf());
// // }
// hostConfs.addAll(EndpointPool.getTaskHostConf());
// return hostConfs;
// }
//
// public static List<HostConf> mergeTaskServer(List<HostConf> otherHost) {
// List<HostConf> hostConfs = getTaskHostConf();
// otherHost.removeAll(hostConfs);
// EndpointPool.add(otherHost);
// return hostConfs;
// }
//
// /**
// * default: heartbeat and gossip
// */
// @Override
// public void init() {
// List<HostConf> exportHosts = HostConf.resolvePort(exportPort);
// for (HostConf hostConf : exportHosts) {
// TaskServer taskServer = TaskServerFactory.createTaskServer(hostConf);
// taskServer.start();
// taskServers.add(taskServer);
// }
// List<HostConf> clientHost = HostConf.resolveHost(this.serverHost);
// EndpointPool.init(clientHost);
//
// heartbeatSupport.scheduleHeartbeat();
// gossipSupport.scheduleGossip();
// }
//
// @Override
// public void stop() {
// EndpointPool.stop();
// if (CollectionUtils.isEmpty(taskServers)) {
// return;
// }
// for (TaskServer taskServer : taskServers) {
// taskServer.stop();
// }
//
// heartbeatSupport.shutdownScheduler();
// gossipSupport.shutdownScheduler();
// }
//
// protected void doTryRestartEndpoint(TaskClient taskClient) {
// try {
// taskClient.restart();
// } catch (Exception e) {
// // do nothing
// }
// }
//
// public String getServerHost() {
// return serverHost;
// }
//
// public void setServerHost(String serverHost) {
// this.serverHost = serverHost;
// }
//
// public String getExportPort() {
// return exportPort;
// }
//
// public void setExportPort(String exportPort) {
// this.exportPort = exportPort;
// }
// }
// Path: src/test/java/com/baidu/unbiz/multiengine/demo/test/TestMultiProcessServer1.java
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import com.baidu.unbiz.multiengine.utils.TestUtils;
import com.baidu.unbiz.multiengine.endpoint.supervisor.DefaultEndpointSupervisor;
package com.baidu.unbiz.multiengine.demo.test;
/**
* Created by wangchongjie on 16/4/18.
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "/applicationContext-test2.xml")
public class TestMultiProcessServer1 {
| private DefaultEndpointSupervisor supervisor = new DefaultEndpointSupervisor(); |
wangchongjie/multi-engine | src/test/java/com/baidu/unbiz/multiengine/demo/test/TestMultiProcessServer1.java | // Path: src/test/java/com/baidu/unbiz/multiengine/utils/TestUtils.java
// public class TestUtils {
// public static final long VERY_LONG_TIME = 2000 * 1000;
//
// public static void dumySleep(long time) {
// try {
// Thread.sleep(time);
// } catch (InterruptedException e) {
// // do nothing
// }
// }
// }
//
// Path: src/main/java/com/baidu/unbiz/multiengine/endpoint/supervisor/DefaultEndpointSupervisor.java
// public class DefaultEndpointSupervisor implements EndpointSupervisor {
// private static final Logger LOG = AopLogFactory.getLogger(DefaultEndpointSupervisor.class);
//
// private static List<TaskServer> taskServers;
// private GossipSupport gossipSupport;
// private HeartbeatSupport heartbeatSupport;
//
// private String exportPort;
// private String serverHost;
//
// public DefaultEndpointSupervisor() {
// taskServers = new CopyOnWriteArrayList<TaskServer>();
// gossipSupport = new GossipSupport();
// heartbeatSupport = new HeartbeatSupport() {
// @Override
// public void tryRestartEndpoint(TaskClient taskClient) {
// doTryRestartEndpoint(taskClient);
// }
// };
// }
//
// public static List<HostConf> getTaskHostConf() {
// List<HostConf> hostConfs = new ArrayList<HostConf>();
// // fixme
// // for(TaskServer taskServer : taskServers){
// // hostConfs.internalAdd(taskServer.getHostConf());
// // }
// hostConfs.addAll(EndpointPool.getTaskHostConf());
// return hostConfs;
// }
//
// public static List<HostConf> mergeTaskServer(List<HostConf> otherHost) {
// List<HostConf> hostConfs = getTaskHostConf();
// otherHost.removeAll(hostConfs);
// EndpointPool.add(otherHost);
// return hostConfs;
// }
//
// /**
// * default: heartbeat and gossip
// */
// @Override
// public void init() {
// List<HostConf> exportHosts = HostConf.resolvePort(exportPort);
// for (HostConf hostConf : exportHosts) {
// TaskServer taskServer = TaskServerFactory.createTaskServer(hostConf);
// taskServer.start();
// taskServers.add(taskServer);
// }
// List<HostConf> clientHost = HostConf.resolveHost(this.serverHost);
// EndpointPool.init(clientHost);
//
// heartbeatSupport.scheduleHeartbeat();
// gossipSupport.scheduleGossip();
// }
//
// @Override
// public void stop() {
// EndpointPool.stop();
// if (CollectionUtils.isEmpty(taskServers)) {
// return;
// }
// for (TaskServer taskServer : taskServers) {
// taskServer.stop();
// }
//
// heartbeatSupport.shutdownScheduler();
// gossipSupport.shutdownScheduler();
// }
//
// protected void doTryRestartEndpoint(TaskClient taskClient) {
// try {
// taskClient.restart();
// } catch (Exception e) {
// // do nothing
// }
// }
//
// public String getServerHost() {
// return serverHost;
// }
//
// public void setServerHost(String serverHost) {
// this.serverHost = serverHost;
// }
//
// public String getExportPort() {
// return exportPort;
// }
//
// public void setExportPort(String exportPort) {
// this.exportPort = exportPort;
// }
// }
| import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import com.baidu.unbiz.multiengine.utils.TestUtils;
import com.baidu.unbiz.multiengine.endpoint.supervisor.DefaultEndpointSupervisor; | package com.baidu.unbiz.multiengine.demo.test;
/**
* Created by wangchongjie on 16/4/18.
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "/applicationContext-test2.xml")
public class TestMultiProcessServer1 {
private DefaultEndpointSupervisor supervisor = new DefaultEndpointSupervisor();
@Before
public void init() {
supervisor.setExportPort("8801");
supervisor.setServerHost("127.0.0.1:8801;127.0.0.1:8803");
supervisor.init();
}
@After
public void clean() {
supervisor.stop();
}
/**
* 测试分布式并行执行task
*/
@Test
public void runServer() { | // Path: src/test/java/com/baidu/unbiz/multiengine/utils/TestUtils.java
// public class TestUtils {
// public static final long VERY_LONG_TIME = 2000 * 1000;
//
// public static void dumySleep(long time) {
// try {
// Thread.sleep(time);
// } catch (InterruptedException e) {
// // do nothing
// }
// }
// }
//
// Path: src/main/java/com/baidu/unbiz/multiengine/endpoint/supervisor/DefaultEndpointSupervisor.java
// public class DefaultEndpointSupervisor implements EndpointSupervisor {
// private static final Logger LOG = AopLogFactory.getLogger(DefaultEndpointSupervisor.class);
//
// private static List<TaskServer> taskServers;
// private GossipSupport gossipSupport;
// private HeartbeatSupport heartbeatSupport;
//
// private String exportPort;
// private String serverHost;
//
// public DefaultEndpointSupervisor() {
// taskServers = new CopyOnWriteArrayList<TaskServer>();
// gossipSupport = new GossipSupport();
// heartbeatSupport = new HeartbeatSupport() {
// @Override
// public void tryRestartEndpoint(TaskClient taskClient) {
// doTryRestartEndpoint(taskClient);
// }
// };
// }
//
// public static List<HostConf> getTaskHostConf() {
// List<HostConf> hostConfs = new ArrayList<HostConf>();
// // fixme
// // for(TaskServer taskServer : taskServers){
// // hostConfs.internalAdd(taskServer.getHostConf());
// // }
// hostConfs.addAll(EndpointPool.getTaskHostConf());
// return hostConfs;
// }
//
// public static List<HostConf> mergeTaskServer(List<HostConf> otherHost) {
// List<HostConf> hostConfs = getTaskHostConf();
// otherHost.removeAll(hostConfs);
// EndpointPool.add(otherHost);
// return hostConfs;
// }
//
// /**
// * default: heartbeat and gossip
// */
// @Override
// public void init() {
// List<HostConf> exportHosts = HostConf.resolvePort(exportPort);
// for (HostConf hostConf : exportHosts) {
// TaskServer taskServer = TaskServerFactory.createTaskServer(hostConf);
// taskServer.start();
// taskServers.add(taskServer);
// }
// List<HostConf> clientHost = HostConf.resolveHost(this.serverHost);
// EndpointPool.init(clientHost);
//
// heartbeatSupport.scheduleHeartbeat();
// gossipSupport.scheduleGossip();
// }
//
// @Override
// public void stop() {
// EndpointPool.stop();
// if (CollectionUtils.isEmpty(taskServers)) {
// return;
// }
// for (TaskServer taskServer : taskServers) {
// taskServer.stop();
// }
//
// heartbeatSupport.shutdownScheduler();
// gossipSupport.shutdownScheduler();
// }
//
// protected void doTryRestartEndpoint(TaskClient taskClient) {
// try {
// taskClient.restart();
// } catch (Exception e) {
// // do nothing
// }
// }
//
// public String getServerHost() {
// return serverHost;
// }
//
// public void setServerHost(String serverHost) {
// this.serverHost = serverHost;
// }
//
// public String getExportPort() {
// return exportPort;
// }
//
// public void setExportPort(String exportPort) {
// this.exportPort = exportPort;
// }
// }
// Path: src/test/java/com/baidu/unbiz/multiengine/demo/test/TestMultiProcessServer1.java
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import com.baidu.unbiz.multiengine.utils.TestUtils;
import com.baidu.unbiz.multiengine.endpoint.supervisor.DefaultEndpointSupervisor;
package com.baidu.unbiz.multiengine.demo.test;
/**
* Created by wangchongjie on 16/4/18.
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "/applicationContext-test2.xml")
public class TestMultiProcessServer1 {
private DefaultEndpointSupervisor supervisor = new DefaultEndpointSupervisor();
@Before
public void init() {
supervisor.setExportPort("8801");
supervisor.setServerHost("127.0.0.1:8801;127.0.0.1:8803");
supervisor.init();
}
@After
public void clean() {
supervisor.stop();
}
/**
* 测试分布式并行执行task
*/
@Test
public void runServer() { | TestUtils.dumySleep(TestUtils.VERY_LONG_TIME); |
wangchongjie/multi-engine | src/main/java/com/baidu/unbiz/multiengine/codec/bytebuf/DefaultByteCodecFactory.java | // Path: src/main/java/com/baidu/unbiz/multiengine/codec/HeadCodec.java
// public interface HeadCodec extends MsgCodec {
// /**
// * 反序列化
// *
// * @param clazz 反序列化后的类定义
// * @param bytes 字节码
// *
// * @return 反序列化后的对象
// *
// * @throws CodecException
// */
// <T> T decode(Class<T> clazz, byte[] bytes) throws CodecException;
//
// /**
// * 序列化
// *
// * @param object 待序列化的对象
// *
// * @return 字节码
// *
// * @throws CodecException
// */
// <T> byte[] encode(T object) throws CodecException;
//
// /**
// * head的类型
// *
// * @return
// */
// Class getHeadClass();
// }
//
// Path: src/main/java/com/baidu/unbiz/multiengine/codec/MsgCodec.java
// public interface MsgCodec {
// /**
// * 反序列化
// *
// * @param clazz 反序列化后的类定义
// * @param bytes 字节码
// * @return 反序列化后的对象
// * @throws CodecException
// */
// <T> T decode(Class<T> clazz, byte[] bytes) throws CodecException;
//
// /**
// * 序列化
// *
// * @param object 待序列化的对象
// * @return 字节码
// * @throws CodecException
// */
// <T> byte[] encode(T object) throws CodecException;
// }
| import com.baidu.unbiz.multiengine.codec.HeadCodec;
import com.baidu.unbiz.multiengine.codec.MsgCodec;
import io.netty.handler.codec.ByteToMessageDecoder;
import io.netty.handler.codec.MessageToByteEncoder; | package com.baidu.unbiz.multiengine.codec.bytebuf;
/**
* 默认的二进制编解码器工厂
*/
public class DefaultByteCodecFactory implements ByteCodecFactory {
private MsgCodec msgCodec; | // Path: src/main/java/com/baidu/unbiz/multiengine/codec/HeadCodec.java
// public interface HeadCodec extends MsgCodec {
// /**
// * 反序列化
// *
// * @param clazz 反序列化后的类定义
// * @param bytes 字节码
// *
// * @return 反序列化后的对象
// *
// * @throws CodecException
// */
// <T> T decode(Class<T> clazz, byte[] bytes) throws CodecException;
//
// /**
// * 序列化
// *
// * @param object 待序列化的对象
// *
// * @return 字节码
// *
// * @throws CodecException
// */
// <T> byte[] encode(T object) throws CodecException;
//
// /**
// * head的类型
// *
// * @return
// */
// Class getHeadClass();
// }
//
// Path: src/main/java/com/baidu/unbiz/multiengine/codec/MsgCodec.java
// public interface MsgCodec {
// /**
// * 反序列化
// *
// * @param clazz 反序列化后的类定义
// * @param bytes 字节码
// * @return 反序列化后的对象
// * @throws CodecException
// */
// <T> T decode(Class<T> clazz, byte[] bytes) throws CodecException;
//
// /**
// * 序列化
// *
// * @param object 待序列化的对象
// * @return 字节码
// * @throws CodecException
// */
// <T> byte[] encode(T object) throws CodecException;
// }
// Path: src/main/java/com/baidu/unbiz/multiengine/codec/bytebuf/DefaultByteCodecFactory.java
import com.baidu.unbiz.multiengine.codec.HeadCodec;
import com.baidu.unbiz.multiengine.codec.MsgCodec;
import io.netty.handler.codec.ByteToMessageDecoder;
import io.netty.handler.codec.MessageToByteEncoder;
package com.baidu.unbiz.multiengine.codec.bytebuf;
/**
* 默认的二进制编解码器工厂
*/
public class DefaultByteCodecFactory implements ByteCodecFactory {
private MsgCodec msgCodec; | private HeadCodec headCodec; |
wangchongjie/multi-engine | src/main/java/com/baidu/unbiz/multiengine/transport/client/SimpleSendFutrue.java | // Path: src/main/java/com/baidu/unbiz/multiengine/exception/MultiEngineException.java
// public class MultiEngineException extends RuntimeException {
//
// /**
// * serialVersionUID
// */
// private static final long serialVersionUID = 2396421433506179782L;
//
// /**
// * Creates a new instance of CodecException.
// */
// public MultiEngineException() {
// super();
// }
//
// /**
// * Creates a new instance of CodecException.
// *
// * @param arg0
// * @param arg1
// */
// public MultiEngineException(String arg0, Throwable arg1) {
// super(arg0, arg1);
// }
//
// /**
// * Creates a new instance of CodecException.
// *
// * @param arg0
// */
// public MultiEngineException(String arg0) {
// super(arg0);
// }
//
// /**
// * Creates a new instance of CodecException.
// *
// * @param arg0
// */
// public MultiEngineException(Throwable arg0) {
// super(arg0);
// }
//
// }
| import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import com.baidu.unbiz.multiengine.exception.MultiEngineException; | package com.baidu.unbiz.multiengine.transport.client;
/**
* 调用方异步发送消息时所持有的发送结果占位符实现,它实现如下接口:
* <ul>
* <li>SendFuture 被调用方使用</li>
* </ul>
*
* @author wagnchongjie
*/
class SimpleSendFutrue implements SendFuture {
private final CountDownLatch internalWaiter = new CountDownLatch(1);
/**
* 结果信息
*/
private volatile Object result;
private volatile boolean hasInit = false;
@Override
public <T> T get() {
try {
internalWaiter.await();
} catch (InterruptedException e) { | // Path: src/main/java/com/baidu/unbiz/multiengine/exception/MultiEngineException.java
// public class MultiEngineException extends RuntimeException {
//
// /**
// * serialVersionUID
// */
// private static final long serialVersionUID = 2396421433506179782L;
//
// /**
// * Creates a new instance of CodecException.
// */
// public MultiEngineException() {
// super();
// }
//
// /**
// * Creates a new instance of CodecException.
// *
// * @param arg0
// * @param arg1
// */
// public MultiEngineException(String arg0, Throwable arg1) {
// super(arg0, arg1);
// }
//
// /**
// * Creates a new instance of CodecException.
// *
// * @param arg0
// */
// public MultiEngineException(String arg0) {
// super(arg0);
// }
//
// /**
// * Creates a new instance of CodecException.
// *
// * @param arg0
// */
// public MultiEngineException(Throwable arg0) {
// super(arg0);
// }
//
// }
// Path: src/main/java/com/baidu/unbiz/multiengine/transport/client/SimpleSendFutrue.java
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import com.baidu.unbiz.multiengine.exception.MultiEngineException;
package com.baidu.unbiz.multiengine.transport.client;
/**
* 调用方异步发送消息时所持有的发送结果占位符实现,它实现如下接口:
* <ul>
* <li>SendFuture 被调用方使用</li>
* </ul>
*
* @author wagnchongjie
*/
class SimpleSendFutrue implements SendFuture {
private final CountDownLatch internalWaiter = new CountDownLatch(1);
/**
* 结果信息
*/
private volatile Object result;
private volatile boolean hasInit = false;
@Override
public <T> T get() {
try {
internalWaiter.await();
} catch (InterruptedException e) { | throw new MultiEngineException(e); |
wangchongjie/multi-engine | src/main/java/com/baidu/unbiz/multiengine/codec/bytebuf/MsgCodecAdaptor.java | // Path: src/main/java/com/baidu/unbiz/multiengine/codec/ByteBufCodec.java
// public interface ByteBufCodec {
//
// /**
// * 将对象编码成ByteBuf
// *
// * @param object 编码对象
// * @return byte数组
// * @throws CodecException
// */
// byte[] encode(Object object) throws CodecException;
//
// /**
// * 将ByteBuf解码成对象
// *
// * @param byteBuf 字节缓冲区 @see ByteBuf
// * @param length 字节长度
// * @param clazz 对象类型
// * @return 解码对象
// * @throws CodecException
// */
// <T> T decode(ByteBuf byteBuf, int length, Class<T> clazz) throws CodecException;
//
// }
//
// Path: src/main/java/com/baidu/unbiz/multiengine/codec/MsgCodec.java
// public interface MsgCodec {
// /**
// * 反序列化
// *
// * @param clazz 反序列化后的类定义
// * @param bytes 字节码
// * @return 反序列化后的对象
// * @throws CodecException
// */
// <T> T decode(Class<T> clazz, byte[] bytes) throws CodecException;
//
// /**
// * 序列化
// *
// * @param object 待序列化的对象
// * @return 字节码
// * @throws CodecException
// */
// <T> byte[] encode(T object) throws CodecException;
// }
//
// Path: src/main/java/com/baidu/unbiz/multiengine/exception/CodecException.java
// public class CodecException extends RuntimeException {
//
// /**
// * serialVersionUID
// */
// private static final long serialVersionUID = 5196421433506179782L;
//
// /**
// * Creates a new instance of CodecException.
// */
// public CodecException() {
// super();
// }
//
// /**
// * Creates a new instance of CodecException.
// *
// * @param arg0
// * @param arg1
// */
// public CodecException(String arg0, Throwable arg1) {
// super(arg0, arg1);
// }
//
// /**
// * Creates a new instance of CodecException.
// *
// * @param arg0
// */
// public CodecException(String arg0) {
// super(arg0);
// }
//
// /**
// * Creates a new instance of CodecException.
// *
// * @param arg0
// */
// public CodecException(Throwable arg0) {
// super(arg0);
// }
//
// }
//
// Path: src/main/java/com/baidu/unbiz/multiengine/utils/BufferUtils.java
// public abstract class BufferUtils {
//
// /**
// * 将ByteBuf转化成byte数组
// *
// * @param byteBuf Netty的ByteBuf @see ByteBuf
// * @return byte数组
// */
// public static byte[] bufToBytes(ByteBuf byteBuf) {
// if (byteBuf == null) {
// return null;
// }
//
// int length = byteBuf.readableBytes();
// byte[] array = new byte[length];
// byteBuf.readBytes(array);
//
// return array;
// }
//
// /**
// * 将ByteBuf转化成byte数组
// *
// * @param byteBuf Netty的ByteBuf @see ByteBuf
// * @param length 长度
// * @return byte数组
// */
// public static byte[] bufToBytes(ByteBuf byteBuf, int length) {
// if (byteBuf == null) {
// return null;
// }
//
// byte[] array = new byte[length];
// byteBuf.readBytes(array);
//
// return array;
// }
//
// }
| import org.slf4j.Logger;
import com.baidu.unbiz.multiengine.codec.ByteBufCodec;
import com.baidu.unbiz.multiengine.codec.MsgCodec;
import com.baidu.unbiz.multiengine.exception.CodecException;
import com.baidu.unbiz.multiengine.utils.BufferUtils;
import com.baidu.unbiz.multitask.log.AopLogFactory;
import io.netty.buffer.ByteBuf; | package com.baidu.unbiz.multiengine.codec.bytebuf;
/**
* 消息编解码器接口的适配器
*/
public class MsgCodecAdaptor implements ByteBufCodec {
private static final Logger LOG = AopLogFactory.getLogger(MsgCodecAdaptor.class);
/**
* 消息编解码器
*/ | // Path: src/main/java/com/baidu/unbiz/multiengine/codec/ByteBufCodec.java
// public interface ByteBufCodec {
//
// /**
// * 将对象编码成ByteBuf
// *
// * @param object 编码对象
// * @return byte数组
// * @throws CodecException
// */
// byte[] encode(Object object) throws CodecException;
//
// /**
// * 将ByteBuf解码成对象
// *
// * @param byteBuf 字节缓冲区 @see ByteBuf
// * @param length 字节长度
// * @param clazz 对象类型
// * @return 解码对象
// * @throws CodecException
// */
// <T> T decode(ByteBuf byteBuf, int length, Class<T> clazz) throws CodecException;
//
// }
//
// Path: src/main/java/com/baidu/unbiz/multiengine/codec/MsgCodec.java
// public interface MsgCodec {
// /**
// * 反序列化
// *
// * @param clazz 反序列化后的类定义
// * @param bytes 字节码
// * @return 反序列化后的对象
// * @throws CodecException
// */
// <T> T decode(Class<T> clazz, byte[] bytes) throws CodecException;
//
// /**
// * 序列化
// *
// * @param object 待序列化的对象
// * @return 字节码
// * @throws CodecException
// */
// <T> byte[] encode(T object) throws CodecException;
// }
//
// Path: src/main/java/com/baidu/unbiz/multiengine/exception/CodecException.java
// public class CodecException extends RuntimeException {
//
// /**
// * serialVersionUID
// */
// private static final long serialVersionUID = 5196421433506179782L;
//
// /**
// * Creates a new instance of CodecException.
// */
// public CodecException() {
// super();
// }
//
// /**
// * Creates a new instance of CodecException.
// *
// * @param arg0
// * @param arg1
// */
// public CodecException(String arg0, Throwable arg1) {
// super(arg0, arg1);
// }
//
// /**
// * Creates a new instance of CodecException.
// *
// * @param arg0
// */
// public CodecException(String arg0) {
// super(arg0);
// }
//
// /**
// * Creates a new instance of CodecException.
// *
// * @param arg0
// */
// public CodecException(Throwable arg0) {
// super(arg0);
// }
//
// }
//
// Path: src/main/java/com/baidu/unbiz/multiengine/utils/BufferUtils.java
// public abstract class BufferUtils {
//
// /**
// * 将ByteBuf转化成byte数组
// *
// * @param byteBuf Netty的ByteBuf @see ByteBuf
// * @return byte数组
// */
// public static byte[] bufToBytes(ByteBuf byteBuf) {
// if (byteBuf == null) {
// return null;
// }
//
// int length = byteBuf.readableBytes();
// byte[] array = new byte[length];
// byteBuf.readBytes(array);
//
// return array;
// }
//
// /**
// * 将ByteBuf转化成byte数组
// *
// * @param byteBuf Netty的ByteBuf @see ByteBuf
// * @param length 长度
// * @return byte数组
// */
// public static byte[] bufToBytes(ByteBuf byteBuf, int length) {
// if (byteBuf == null) {
// return null;
// }
//
// byte[] array = new byte[length];
// byteBuf.readBytes(array);
//
// return array;
// }
//
// }
// Path: src/main/java/com/baidu/unbiz/multiengine/codec/bytebuf/MsgCodecAdaptor.java
import org.slf4j.Logger;
import com.baidu.unbiz.multiengine.codec.ByteBufCodec;
import com.baidu.unbiz.multiengine.codec.MsgCodec;
import com.baidu.unbiz.multiengine.exception.CodecException;
import com.baidu.unbiz.multiengine.utils.BufferUtils;
import com.baidu.unbiz.multitask.log.AopLogFactory;
import io.netty.buffer.ByteBuf;
package com.baidu.unbiz.multiengine.codec.bytebuf;
/**
* 消息编解码器接口的适配器
*/
public class MsgCodecAdaptor implements ByteBufCodec {
private static final Logger LOG = AopLogFactory.getLogger(MsgCodecAdaptor.class);
/**
* 消息编解码器
*/ | private MsgCodec messageCodec; |
wangchongjie/multi-engine | src/main/java/com/baidu/unbiz/multiengine/codec/bytebuf/MsgCodecAdaptor.java | // Path: src/main/java/com/baidu/unbiz/multiengine/codec/ByteBufCodec.java
// public interface ByteBufCodec {
//
// /**
// * 将对象编码成ByteBuf
// *
// * @param object 编码对象
// * @return byte数组
// * @throws CodecException
// */
// byte[] encode(Object object) throws CodecException;
//
// /**
// * 将ByteBuf解码成对象
// *
// * @param byteBuf 字节缓冲区 @see ByteBuf
// * @param length 字节长度
// * @param clazz 对象类型
// * @return 解码对象
// * @throws CodecException
// */
// <T> T decode(ByteBuf byteBuf, int length, Class<T> clazz) throws CodecException;
//
// }
//
// Path: src/main/java/com/baidu/unbiz/multiengine/codec/MsgCodec.java
// public interface MsgCodec {
// /**
// * 反序列化
// *
// * @param clazz 反序列化后的类定义
// * @param bytes 字节码
// * @return 反序列化后的对象
// * @throws CodecException
// */
// <T> T decode(Class<T> clazz, byte[] bytes) throws CodecException;
//
// /**
// * 序列化
// *
// * @param object 待序列化的对象
// * @return 字节码
// * @throws CodecException
// */
// <T> byte[] encode(T object) throws CodecException;
// }
//
// Path: src/main/java/com/baidu/unbiz/multiengine/exception/CodecException.java
// public class CodecException extends RuntimeException {
//
// /**
// * serialVersionUID
// */
// private static final long serialVersionUID = 5196421433506179782L;
//
// /**
// * Creates a new instance of CodecException.
// */
// public CodecException() {
// super();
// }
//
// /**
// * Creates a new instance of CodecException.
// *
// * @param arg0
// * @param arg1
// */
// public CodecException(String arg0, Throwable arg1) {
// super(arg0, arg1);
// }
//
// /**
// * Creates a new instance of CodecException.
// *
// * @param arg0
// */
// public CodecException(String arg0) {
// super(arg0);
// }
//
// /**
// * Creates a new instance of CodecException.
// *
// * @param arg0
// */
// public CodecException(Throwable arg0) {
// super(arg0);
// }
//
// }
//
// Path: src/main/java/com/baidu/unbiz/multiengine/utils/BufferUtils.java
// public abstract class BufferUtils {
//
// /**
// * 将ByteBuf转化成byte数组
// *
// * @param byteBuf Netty的ByteBuf @see ByteBuf
// * @return byte数组
// */
// public static byte[] bufToBytes(ByteBuf byteBuf) {
// if (byteBuf == null) {
// return null;
// }
//
// int length = byteBuf.readableBytes();
// byte[] array = new byte[length];
// byteBuf.readBytes(array);
//
// return array;
// }
//
// /**
// * 将ByteBuf转化成byte数组
// *
// * @param byteBuf Netty的ByteBuf @see ByteBuf
// * @param length 长度
// * @return byte数组
// */
// public static byte[] bufToBytes(ByteBuf byteBuf, int length) {
// if (byteBuf == null) {
// return null;
// }
//
// byte[] array = new byte[length];
// byteBuf.readBytes(array);
//
// return array;
// }
//
// }
| import org.slf4j.Logger;
import com.baidu.unbiz.multiengine.codec.ByteBufCodec;
import com.baidu.unbiz.multiengine.codec.MsgCodec;
import com.baidu.unbiz.multiengine.exception.CodecException;
import com.baidu.unbiz.multiengine.utils.BufferUtils;
import com.baidu.unbiz.multitask.log.AopLogFactory;
import io.netty.buffer.ByteBuf; | package com.baidu.unbiz.multiengine.codec.bytebuf;
/**
* 消息编解码器接口的适配器
*/
public class MsgCodecAdaptor implements ByteBufCodec {
private static final Logger LOG = AopLogFactory.getLogger(MsgCodecAdaptor.class);
/**
* 消息编解码器
*/
private MsgCodec messageCodec;
public MsgCodecAdaptor(MsgCodec messageCodec) {
this.messageCodec = messageCodec;
}
@Override | // Path: src/main/java/com/baidu/unbiz/multiengine/codec/ByteBufCodec.java
// public interface ByteBufCodec {
//
// /**
// * 将对象编码成ByteBuf
// *
// * @param object 编码对象
// * @return byte数组
// * @throws CodecException
// */
// byte[] encode(Object object) throws CodecException;
//
// /**
// * 将ByteBuf解码成对象
// *
// * @param byteBuf 字节缓冲区 @see ByteBuf
// * @param length 字节长度
// * @param clazz 对象类型
// * @return 解码对象
// * @throws CodecException
// */
// <T> T decode(ByteBuf byteBuf, int length, Class<T> clazz) throws CodecException;
//
// }
//
// Path: src/main/java/com/baidu/unbiz/multiengine/codec/MsgCodec.java
// public interface MsgCodec {
// /**
// * 反序列化
// *
// * @param clazz 反序列化后的类定义
// * @param bytes 字节码
// * @return 反序列化后的对象
// * @throws CodecException
// */
// <T> T decode(Class<T> clazz, byte[] bytes) throws CodecException;
//
// /**
// * 序列化
// *
// * @param object 待序列化的对象
// * @return 字节码
// * @throws CodecException
// */
// <T> byte[] encode(T object) throws CodecException;
// }
//
// Path: src/main/java/com/baidu/unbiz/multiengine/exception/CodecException.java
// public class CodecException extends RuntimeException {
//
// /**
// * serialVersionUID
// */
// private static final long serialVersionUID = 5196421433506179782L;
//
// /**
// * Creates a new instance of CodecException.
// */
// public CodecException() {
// super();
// }
//
// /**
// * Creates a new instance of CodecException.
// *
// * @param arg0
// * @param arg1
// */
// public CodecException(String arg0, Throwable arg1) {
// super(arg0, arg1);
// }
//
// /**
// * Creates a new instance of CodecException.
// *
// * @param arg0
// */
// public CodecException(String arg0) {
// super(arg0);
// }
//
// /**
// * Creates a new instance of CodecException.
// *
// * @param arg0
// */
// public CodecException(Throwable arg0) {
// super(arg0);
// }
//
// }
//
// Path: src/main/java/com/baidu/unbiz/multiengine/utils/BufferUtils.java
// public abstract class BufferUtils {
//
// /**
// * 将ByteBuf转化成byte数组
// *
// * @param byteBuf Netty的ByteBuf @see ByteBuf
// * @return byte数组
// */
// public static byte[] bufToBytes(ByteBuf byteBuf) {
// if (byteBuf == null) {
// return null;
// }
//
// int length = byteBuf.readableBytes();
// byte[] array = new byte[length];
// byteBuf.readBytes(array);
//
// return array;
// }
//
// /**
// * 将ByteBuf转化成byte数组
// *
// * @param byteBuf Netty的ByteBuf @see ByteBuf
// * @param length 长度
// * @return byte数组
// */
// public static byte[] bufToBytes(ByteBuf byteBuf, int length) {
// if (byteBuf == null) {
// return null;
// }
//
// byte[] array = new byte[length];
// byteBuf.readBytes(array);
//
// return array;
// }
//
// }
// Path: src/main/java/com/baidu/unbiz/multiengine/codec/bytebuf/MsgCodecAdaptor.java
import org.slf4j.Logger;
import com.baidu.unbiz.multiengine.codec.ByteBufCodec;
import com.baidu.unbiz.multiengine.codec.MsgCodec;
import com.baidu.unbiz.multiengine.exception.CodecException;
import com.baidu.unbiz.multiengine.utils.BufferUtils;
import com.baidu.unbiz.multitask.log.AopLogFactory;
import io.netty.buffer.ByteBuf;
package com.baidu.unbiz.multiengine.codec.bytebuf;
/**
* 消息编解码器接口的适配器
*/
public class MsgCodecAdaptor implements ByteBufCodec {
private static final Logger LOG = AopLogFactory.getLogger(MsgCodecAdaptor.class);
/**
* 消息编解码器
*/
private MsgCodec messageCodec;
public MsgCodecAdaptor(MsgCodec messageCodec) {
this.messageCodec = messageCodec;
}
@Override | public byte[] encode(Object object) throws CodecException { |
wangchongjie/multi-engine | src/main/java/com/baidu/unbiz/multiengine/codec/bytebuf/MsgCodecAdaptor.java | // Path: src/main/java/com/baidu/unbiz/multiengine/codec/ByteBufCodec.java
// public interface ByteBufCodec {
//
// /**
// * 将对象编码成ByteBuf
// *
// * @param object 编码对象
// * @return byte数组
// * @throws CodecException
// */
// byte[] encode(Object object) throws CodecException;
//
// /**
// * 将ByteBuf解码成对象
// *
// * @param byteBuf 字节缓冲区 @see ByteBuf
// * @param length 字节长度
// * @param clazz 对象类型
// * @return 解码对象
// * @throws CodecException
// */
// <T> T decode(ByteBuf byteBuf, int length, Class<T> clazz) throws CodecException;
//
// }
//
// Path: src/main/java/com/baidu/unbiz/multiengine/codec/MsgCodec.java
// public interface MsgCodec {
// /**
// * 反序列化
// *
// * @param clazz 反序列化后的类定义
// * @param bytes 字节码
// * @return 反序列化后的对象
// * @throws CodecException
// */
// <T> T decode(Class<T> clazz, byte[] bytes) throws CodecException;
//
// /**
// * 序列化
// *
// * @param object 待序列化的对象
// * @return 字节码
// * @throws CodecException
// */
// <T> byte[] encode(T object) throws CodecException;
// }
//
// Path: src/main/java/com/baidu/unbiz/multiengine/exception/CodecException.java
// public class CodecException extends RuntimeException {
//
// /**
// * serialVersionUID
// */
// private static final long serialVersionUID = 5196421433506179782L;
//
// /**
// * Creates a new instance of CodecException.
// */
// public CodecException() {
// super();
// }
//
// /**
// * Creates a new instance of CodecException.
// *
// * @param arg0
// * @param arg1
// */
// public CodecException(String arg0, Throwable arg1) {
// super(arg0, arg1);
// }
//
// /**
// * Creates a new instance of CodecException.
// *
// * @param arg0
// */
// public CodecException(String arg0) {
// super(arg0);
// }
//
// /**
// * Creates a new instance of CodecException.
// *
// * @param arg0
// */
// public CodecException(Throwable arg0) {
// super(arg0);
// }
//
// }
//
// Path: src/main/java/com/baidu/unbiz/multiengine/utils/BufferUtils.java
// public abstract class BufferUtils {
//
// /**
// * 将ByteBuf转化成byte数组
// *
// * @param byteBuf Netty的ByteBuf @see ByteBuf
// * @return byte数组
// */
// public static byte[] bufToBytes(ByteBuf byteBuf) {
// if (byteBuf == null) {
// return null;
// }
//
// int length = byteBuf.readableBytes();
// byte[] array = new byte[length];
// byteBuf.readBytes(array);
//
// return array;
// }
//
// /**
// * 将ByteBuf转化成byte数组
// *
// * @param byteBuf Netty的ByteBuf @see ByteBuf
// * @param length 长度
// * @return byte数组
// */
// public static byte[] bufToBytes(ByteBuf byteBuf, int length) {
// if (byteBuf == null) {
// return null;
// }
//
// byte[] array = new byte[length];
// byteBuf.readBytes(array);
//
// return array;
// }
//
// }
| import org.slf4j.Logger;
import com.baidu.unbiz.multiengine.codec.ByteBufCodec;
import com.baidu.unbiz.multiengine.codec.MsgCodec;
import com.baidu.unbiz.multiengine.exception.CodecException;
import com.baidu.unbiz.multiengine.utils.BufferUtils;
import com.baidu.unbiz.multitask.log.AopLogFactory;
import io.netty.buffer.ByteBuf; | package com.baidu.unbiz.multiengine.codec.bytebuf;
/**
* 消息编解码器接口的适配器
*/
public class MsgCodecAdaptor implements ByteBufCodec {
private static final Logger LOG = AopLogFactory.getLogger(MsgCodecAdaptor.class);
/**
* 消息编解码器
*/
private MsgCodec messageCodec;
public MsgCodecAdaptor(MsgCodec messageCodec) {
this.messageCodec = messageCodec;
}
@Override
public byte[] encode(Object object) throws CodecException {
try {
return messageCodec.encode(object);
} catch (Exception e) {
LOG.error("encode error", e);
throw new CodecException(e);
}
}
@Override
public <T> T decode(ByteBuf byteBuf, int length, Class<T> clazz) throws CodecException {
try { | // Path: src/main/java/com/baidu/unbiz/multiengine/codec/ByteBufCodec.java
// public interface ByteBufCodec {
//
// /**
// * 将对象编码成ByteBuf
// *
// * @param object 编码对象
// * @return byte数组
// * @throws CodecException
// */
// byte[] encode(Object object) throws CodecException;
//
// /**
// * 将ByteBuf解码成对象
// *
// * @param byteBuf 字节缓冲区 @see ByteBuf
// * @param length 字节长度
// * @param clazz 对象类型
// * @return 解码对象
// * @throws CodecException
// */
// <T> T decode(ByteBuf byteBuf, int length, Class<T> clazz) throws CodecException;
//
// }
//
// Path: src/main/java/com/baidu/unbiz/multiengine/codec/MsgCodec.java
// public interface MsgCodec {
// /**
// * 反序列化
// *
// * @param clazz 反序列化后的类定义
// * @param bytes 字节码
// * @return 反序列化后的对象
// * @throws CodecException
// */
// <T> T decode(Class<T> clazz, byte[] bytes) throws CodecException;
//
// /**
// * 序列化
// *
// * @param object 待序列化的对象
// * @return 字节码
// * @throws CodecException
// */
// <T> byte[] encode(T object) throws CodecException;
// }
//
// Path: src/main/java/com/baidu/unbiz/multiengine/exception/CodecException.java
// public class CodecException extends RuntimeException {
//
// /**
// * serialVersionUID
// */
// private static final long serialVersionUID = 5196421433506179782L;
//
// /**
// * Creates a new instance of CodecException.
// */
// public CodecException() {
// super();
// }
//
// /**
// * Creates a new instance of CodecException.
// *
// * @param arg0
// * @param arg1
// */
// public CodecException(String arg0, Throwable arg1) {
// super(arg0, arg1);
// }
//
// /**
// * Creates a new instance of CodecException.
// *
// * @param arg0
// */
// public CodecException(String arg0) {
// super(arg0);
// }
//
// /**
// * Creates a new instance of CodecException.
// *
// * @param arg0
// */
// public CodecException(Throwable arg0) {
// super(arg0);
// }
//
// }
//
// Path: src/main/java/com/baidu/unbiz/multiengine/utils/BufferUtils.java
// public abstract class BufferUtils {
//
// /**
// * 将ByteBuf转化成byte数组
// *
// * @param byteBuf Netty的ByteBuf @see ByteBuf
// * @return byte数组
// */
// public static byte[] bufToBytes(ByteBuf byteBuf) {
// if (byteBuf == null) {
// return null;
// }
//
// int length = byteBuf.readableBytes();
// byte[] array = new byte[length];
// byteBuf.readBytes(array);
//
// return array;
// }
//
// /**
// * 将ByteBuf转化成byte数组
// *
// * @param byteBuf Netty的ByteBuf @see ByteBuf
// * @param length 长度
// * @return byte数组
// */
// public static byte[] bufToBytes(ByteBuf byteBuf, int length) {
// if (byteBuf == null) {
// return null;
// }
//
// byte[] array = new byte[length];
// byteBuf.readBytes(array);
//
// return array;
// }
//
// }
// Path: src/main/java/com/baidu/unbiz/multiengine/codec/bytebuf/MsgCodecAdaptor.java
import org.slf4j.Logger;
import com.baidu.unbiz.multiengine.codec.ByteBufCodec;
import com.baidu.unbiz.multiengine.codec.MsgCodec;
import com.baidu.unbiz.multiengine.exception.CodecException;
import com.baidu.unbiz.multiengine.utils.BufferUtils;
import com.baidu.unbiz.multitask.log.AopLogFactory;
import io.netty.buffer.ByteBuf;
package com.baidu.unbiz.multiengine.codec.bytebuf;
/**
* 消息编解码器接口的适配器
*/
public class MsgCodecAdaptor implements ByteBufCodec {
private static final Logger LOG = AopLogFactory.getLogger(MsgCodecAdaptor.class);
/**
* 消息编解码器
*/
private MsgCodec messageCodec;
public MsgCodecAdaptor(MsgCodec messageCodec) {
this.messageCodec = messageCodec;
}
@Override
public byte[] encode(Object object) throws CodecException {
try {
return messageCodec.encode(object);
} catch (Exception e) {
LOG.error("encode error", e);
throw new CodecException(e);
}
}
@Override
public <T> T decode(ByteBuf byteBuf, int length, Class<T> clazz) throws CodecException {
try { | return messageCodec.decode(clazz, BufferUtils.bufToBytes(byteBuf, length)); |
wangchongjie/multi-engine | src/test/java/com/baidu/unbiz/multiengine/demo/test/DistributededParallelFetchTest.java | // Path: src/main/java/com/baidu/unbiz/multiengine/common/DisTaskPair.java
// public class DisTaskPair extends TaskPair {
//
// public DisTaskPair(String taskName, Object param) {
// this.field1 = taskName;
// this.field2 = param;
// }
//
// @Override
// public TaskPair wrap(String taskName, Object param) {
// return new DisTaskPair(taskName, param);
// }
// }
//
// Path: src/test/java/com/baidu/unbiz/multiengine/vo/DeviceRequest.java
// public class DeviceRequest {
//
// private List<Integer> deviceIds;
//
// public List<Integer> getDeviceIds() {
// return deviceIds;
// }
//
// public void setDeviceIds(List<Integer> deviceIds) {
// this.deviceIds = deviceIds;
// }
//
// public static DeviceRequest build(QueryParam target) {
// DeviceRequest req = new DeviceRequest();
// // req.copyProperties(target);
// return req;
// }
// }
//
// Path: src/test/java/com/baidu/unbiz/multiengine/vo/DeviceViewItem.java
// public class DeviceViewItem {
//
// private static final long serialVersionUID = 6132709579470894604L;
//
// private int planId;
//
// private String planName;
//
// private Integer deviceId;
//
// private String deviceName ;
//
// // getter and setter
// public int getPlanId() {
// return planId;
// }
//
// public void setPlanId(int planId) {
// this.planId = planId;
// }
//
// public Integer getDeviceId() {
// return deviceId;
// }
//
// public void setDeviceId(Integer deviceId) {
// this.deviceId = deviceId;
// }
//
// public String getPlanName() {
// return planName;
// }
//
// public void setPlanName(String planName) {
// this.planName = planName;
// }
//
// public String getDeviceName() {
// return deviceName;
// }
//
// public void setDeviceName(String deviceName) {
// this.deviceName = deviceName;
// }
//
// public String toString() {
// return ToStringBuilder.reflectionToString(this, ToStringStyle.SHORT_PREFIX_STYLE);
// }
// }
//
// Path: src/test/java/com/baidu/unbiz/multiengine/vo/QueryParam.java
// public class QueryParam extends EnableCast implements TaskRequest {
//
// // 基础查询相关公共字段
// /** 起始查询日期 */
// protected Date from;
// /** 终止查询日期 */
// protected Date to;
// /** 查询的时间粒度 */
// protected int timeUnit;
// /** 第几页 */
// protected int page;
// /** 每页大小 */
// protected int pageSize = 20;
// /** 前端过滤字符 */
// protected String query;
//
// public String getQuery() {
// return query;
// }
//
// public void setQuery(String query) {
// this.query = query;
// }
//
// public Date getFrom() {
// return from;
// }
//
// public void setFrom(Date from) {
// this.from = from;
// }
//
// public Date getTo() {
// return to;
// }
//
// public void setTo(Date to) {
// this.to = to;
// }
//
// public int getTimeUnit() {
// return timeUnit;
// }
//
// public void setTimeUnit(int timeUnit) {
// this.timeUnit = timeUnit;
// }
//
// public int getPage() {
// return page;
// }
//
// public void setPage(int page) {
// this.page = page;
// }
//
// public int getPageSize() {
// return pageSize;
// }
//
// public void setPageSize(int pageSize) {
// this.pageSize = pageSize;
// }
//
//
// }
| import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import javax.annotation.Resource;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.context.annotation.DependsOn;
import org.springframework.stereotype.Component;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;
import com.baidu.unbiz.multiengine.common.DisTaskPair;
import com.baidu.unbiz.multiengine.vo.DeviceRequest;
import com.baidu.unbiz.multiengine.vo.DeviceViewItem;
import com.baidu.unbiz.multiengine.vo.QueryParam;
import com.baidu.unbiz.multitask.common.TaskPair;
import com.baidu.unbiz.multitask.forkjoin.ForkJoin;
import com.baidu.unbiz.multitask.policy.DefautExecutePolicy;
import com.baidu.unbiz.multitask.task.ParallelExePool;
import com.baidu.unbiz.multitask.task.thread.MultiResult; | package com.baidu.unbiz.multiengine.demo.test;
// 可以显示指定spring前置依赖
@DependsOn("devicePlanStatServiceImpl")
@Component
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "/applicationContext-test.xml")
public class DistributededParallelFetchTest {
@Resource(name = "distributedParallelExePool")
private ParallelExePool parallelExePool;
/**
* 测试分布式并行执行task
*/
@Test
public void testDistributedParallelRunDisTask() { | // Path: src/main/java/com/baidu/unbiz/multiengine/common/DisTaskPair.java
// public class DisTaskPair extends TaskPair {
//
// public DisTaskPair(String taskName, Object param) {
// this.field1 = taskName;
// this.field2 = param;
// }
//
// @Override
// public TaskPair wrap(String taskName, Object param) {
// return new DisTaskPair(taskName, param);
// }
// }
//
// Path: src/test/java/com/baidu/unbiz/multiengine/vo/DeviceRequest.java
// public class DeviceRequest {
//
// private List<Integer> deviceIds;
//
// public List<Integer> getDeviceIds() {
// return deviceIds;
// }
//
// public void setDeviceIds(List<Integer> deviceIds) {
// this.deviceIds = deviceIds;
// }
//
// public static DeviceRequest build(QueryParam target) {
// DeviceRequest req = new DeviceRequest();
// // req.copyProperties(target);
// return req;
// }
// }
//
// Path: src/test/java/com/baidu/unbiz/multiengine/vo/DeviceViewItem.java
// public class DeviceViewItem {
//
// private static final long serialVersionUID = 6132709579470894604L;
//
// private int planId;
//
// private String planName;
//
// private Integer deviceId;
//
// private String deviceName ;
//
// // getter and setter
// public int getPlanId() {
// return planId;
// }
//
// public void setPlanId(int planId) {
// this.planId = planId;
// }
//
// public Integer getDeviceId() {
// return deviceId;
// }
//
// public void setDeviceId(Integer deviceId) {
// this.deviceId = deviceId;
// }
//
// public String getPlanName() {
// return planName;
// }
//
// public void setPlanName(String planName) {
// this.planName = planName;
// }
//
// public String getDeviceName() {
// return deviceName;
// }
//
// public void setDeviceName(String deviceName) {
// this.deviceName = deviceName;
// }
//
// public String toString() {
// return ToStringBuilder.reflectionToString(this, ToStringStyle.SHORT_PREFIX_STYLE);
// }
// }
//
// Path: src/test/java/com/baidu/unbiz/multiengine/vo/QueryParam.java
// public class QueryParam extends EnableCast implements TaskRequest {
//
// // 基础查询相关公共字段
// /** 起始查询日期 */
// protected Date from;
// /** 终止查询日期 */
// protected Date to;
// /** 查询的时间粒度 */
// protected int timeUnit;
// /** 第几页 */
// protected int page;
// /** 每页大小 */
// protected int pageSize = 20;
// /** 前端过滤字符 */
// protected String query;
//
// public String getQuery() {
// return query;
// }
//
// public void setQuery(String query) {
// this.query = query;
// }
//
// public Date getFrom() {
// return from;
// }
//
// public void setFrom(Date from) {
// this.from = from;
// }
//
// public Date getTo() {
// return to;
// }
//
// public void setTo(Date to) {
// this.to = to;
// }
//
// public int getTimeUnit() {
// return timeUnit;
// }
//
// public void setTimeUnit(int timeUnit) {
// this.timeUnit = timeUnit;
// }
//
// public int getPage() {
// return page;
// }
//
// public void setPage(int page) {
// this.page = page;
// }
//
// public int getPageSize() {
// return pageSize;
// }
//
// public void setPageSize(int pageSize) {
// this.pageSize = pageSize;
// }
//
//
// }
// Path: src/test/java/com/baidu/unbiz/multiengine/demo/test/DistributededParallelFetchTest.java
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import javax.annotation.Resource;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.context.annotation.DependsOn;
import org.springframework.stereotype.Component;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;
import com.baidu.unbiz.multiengine.common.DisTaskPair;
import com.baidu.unbiz.multiengine.vo.DeviceRequest;
import com.baidu.unbiz.multiengine.vo.DeviceViewItem;
import com.baidu.unbiz.multiengine.vo.QueryParam;
import com.baidu.unbiz.multitask.common.TaskPair;
import com.baidu.unbiz.multitask.forkjoin.ForkJoin;
import com.baidu.unbiz.multitask.policy.DefautExecutePolicy;
import com.baidu.unbiz.multitask.task.ParallelExePool;
import com.baidu.unbiz.multitask.task.thread.MultiResult;
package com.baidu.unbiz.multiengine.demo.test;
// 可以显示指定spring前置依赖
@DependsOn("devicePlanStatServiceImpl")
@Component
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "/applicationContext-test.xml")
public class DistributededParallelFetchTest {
@Resource(name = "distributedParallelExePool")
private ParallelExePool parallelExePool;
/**
* 测试分布式并行执行task
*/
@Test
public void testDistributedParallelRunDisTask() { | QueryParam qp = new QueryParam(); |
wangchongjie/multi-engine | src/test/java/com/baidu/unbiz/multiengine/demo/test/DistributededParallelFetchTest.java | // Path: src/main/java/com/baidu/unbiz/multiengine/common/DisTaskPair.java
// public class DisTaskPair extends TaskPair {
//
// public DisTaskPair(String taskName, Object param) {
// this.field1 = taskName;
// this.field2 = param;
// }
//
// @Override
// public TaskPair wrap(String taskName, Object param) {
// return new DisTaskPair(taskName, param);
// }
// }
//
// Path: src/test/java/com/baidu/unbiz/multiengine/vo/DeviceRequest.java
// public class DeviceRequest {
//
// private List<Integer> deviceIds;
//
// public List<Integer> getDeviceIds() {
// return deviceIds;
// }
//
// public void setDeviceIds(List<Integer> deviceIds) {
// this.deviceIds = deviceIds;
// }
//
// public static DeviceRequest build(QueryParam target) {
// DeviceRequest req = new DeviceRequest();
// // req.copyProperties(target);
// return req;
// }
// }
//
// Path: src/test/java/com/baidu/unbiz/multiengine/vo/DeviceViewItem.java
// public class DeviceViewItem {
//
// private static final long serialVersionUID = 6132709579470894604L;
//
// private int planId;
//
// private String planName;
//
// private Integer deviceId;
//
// private String deviceName ;
//
// // getter and setter
// public int getPlanId() {
// return planId;
// }
//
// public void setPlanId(int planId) {
// this.planId = planId;
// }
//
// public Integer getDeviceId() {
// return deviceId;
// }
//
// public void setDeviceId(Integer deviceId) {
// this.deviceId = deviceId;
// }
//
// public String getPlanName() {
// return planName;
// }
//
// public void setPlanName(String planName) {
// this.planName = planName;
// }
//
// public String getDeviceName() {
// return deviceName;
// }
//
// public void setDeviceName(String deviceName) {
// this.deviceName = deviceName;
// }
//
// public String toString() {
// return ToStringBuilder.reflectionToString(this, ToStringStyle.SHORT_PREFIX_STYLE);
// }
// }
//
// Path: src/test/java/com/baidu/unbiz/multiengine/vo/QueryParam.java
// public class QueryParam extends EnableCast implements TaskRequest {
//
// // 基础查询相关公共字段
// /** 起始查询日期 */
// protected Date from;
// /** 终止查询日期 */
// protected Date to;
// /** 查询的时间粒度 */
// protected int timeUnit;
// /** 第几页 */
// protected int page;
// /** 每页大小 */
// protected int pageSize = 20;
// /** 前端过滤字符 */
// protected String query;
//
// public String getQuery() {
// return query;
// }
//
// public void setQuery(String query) {
// this.query = query;
// }
//
// public Date getFrom() {
// return from;
// }
//
// public void setFrom(Date from) {
// this.from = from;
// }
//
// public Date getTo() {
// return to;
// }
//
// public void setTo(Date to) {
// this.to = to;
// }
//
// public int getTimeUnit() {
// return timeUnit;
// }
//
// public void setTimeUnit(int timeUnit) {
// this.timeUnit = timeUnit;
// }
//
// public int getPage() {
// return page;
// }
//
// public void setPage(int page) {
// this.page = page;
// }
//
// public int getPageSize() {
// return pageSize;
// }
//
// public void setPageSize(int pageSize) {
// this.pageSize = pageSize;
// }
//
//
// }
| import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import javax.annotation.Resource;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.context.annotation.DependsOn;
import org.springframework.stereotype.Component;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;
import com.baidu.unbiz.multiengine.common.DisTaskPair;
import com.baidu.unbiz.multiengine.vo.DeviceRequest;
import com.baidu.unbiz.multiengine.vo.DeviceViewItem;
import com.baidu.unbiz.multiengine.vo.QueryParam;
import com.baidu.unbiz.multitask.common.TaskPair;
import com.baidu.unbiz.multitask.forkjoin.ForkJoin;
import com.baidu.unbiz.multitask.policy.DefautExecutePolicy;
import com.baidu.unbiz.multitask.task.ParallelExePool;
import com.baidu.unbiz.multitask.task.thread.MultiResult; | package com.baidu.unbiz.multiengine.demo.test;
// 可以显示指定spring前置依赖
@DependsOn("devicePlanStatServiceImpl")
@Component
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "/applicationContext-test.xml")
public class DistributededParallelFetchTest {
@Resource(name = "distributedParallelExePool")
private ParallelExePool parallelExePool;
/**
* 测试分布式并行执行task
*/
@Test
public void testDistributedParallelRunDisTask() {
QueryParam qp = new QueryParam();
MultiResult ctx =
parallelExePool.submit( | // Path: src/main/java/com/baidu/unbiz/multiengine/common/DisTaskPair.java
// public class DisTaskPair extends TaskPair {
//
// public DisTaskPair(String taskName, Object param) {
// this.field1 = taskName;
// this.field2 = param;
// }
//
// @Override
// public TaskPair wrap(String taskName, Object param) {
// return new DisTaskPair(taskName, param);
// }
// }
//
// Path: src/test/java/com/baidu/unbiz/multiengine/vo/DeviceRequest.java
// public class DeviceRequest {
//
// private List<Integer> deviceIds;
//
// public List<Integer> getDeviceIds() {
// return deviceIds;
// }
//
// public void setDeviceIds(List<Integer> deviceIds) {
// this.deviceIds = deviceIds;
// }
//
// public static DeviceRequest build(QueryParam target) {
// DeviceRequest req = new DeviceRequest();
// // req.copyProperties(target);
// return req;
// }
// }
//
// Path: src/test/java/com/baidu/unbiz/multiengine/vo/DeviceViewItem.java
// public class DeviceViewItem {
//
// private static final long serialVersionUID = 6132709579470894604L;
//
// private int planId;
//
// private String planName;
//
// private Integer deviceId;
//
// private String deviceName ;
//
// // getter and setter
// public int getPlanId() {
// return planId;
// }
//
// public void setPlanId(int planId) {
// this.planId = planId;
// }
//
// public Integer getDeviceId() {
// return deviceId;
// }
//
// public void setDeviceId(Integer deviceId) {
// this.deviceId = deviceId;
// }
//
// public String getPlanName() {
// return planName;
// }
//
// public void setPlanName(String planName) {
// this.planName = planName;
// }
//
// public String getDeviceName() {
// return deviceName;
// }
//
// public void setDeviceName(String deviceName) {
// this.deviceName = deviceName;
// }
//
// public String toString() {
// return ToStringBuilder.reflectionToString(this, ToStringStyle.SHORT_PREFIX_STYLE);
// }
// }
//
// Path: src/test/java/com/baidu/unbiz/multiengine/vo/QueryParam.java
// public class QueryParam extends EnableCast implements TaskRequest {
//
// // 基础查询相关公共字段
// /** 起始查询日期 */
// protected Date from;
// /** 终止查询日期 */
// protected Date to;
// /** 查询的时间粒度 */
// protected int timeUnit;
// /** 第几页 */
// protected int page;
// /** 每页大小 */
// protected int pageSize = 20;
// /** 前端过滤字符 */
// protected String query;
//
// public String getQuery() {
// return query;
// }
//
// public void setQuery(String query) {
// this.query = query;
// }
//
// public Date getFrom() {
// return from;
// }
//
// public void setFrom(Date from) {
// this.from = from;
// }
//
// public Date getTo() {
// return to;
// }
//
// public void setTo(Date to) {
// this.to = to;
// }
//
// public int getTimeUnit() {
// return timeUnit;
// }
//
// public void setTimeUnit(int timeUnit) {
// this.timeUnit = timeUnit;
// }
//
// public int getPage() {
// return page;
// }
//
// public void setPage(int page) {
// this.page = page;
// }
//
// public int getPageSize() {
// return pageSize;
// }
//
// public void setPageSize(int pageSize) {
// this.pageSize = pageSize;
// }
//
//
// }
// Path: src/test/java/com/baidu/unbiz/multiengine/demo/test/DistributededParallelFetchTest.java
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import javax.annotation.Resource;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.context.annotation.DependsOn;
import org.springframework.stereotype.Component;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;
import com.baidu.unbiz.multiengine.common.DisTaskPair;
import com.baidu.unbiz.multiengine.vo.DeviceRequest;
import com.baidu.unbiz.multiengine.vo.DeviceViewItem;
import com.baidu.unbiz.multiengine.vo.QueryParam;
import com.baidu.unbiz.multitask.common.TaskPair;
import com.baidu.unbiz.multitask.forkjoin.ForkJoin;
import com.baidu.unbiz.multitask.policy.DefautExecutePolicy;
import com.baidu.unbiz.multitask.task.ParallelExePool;
import com.baidu.unbiz.multitask.task.thread.MultiResult;
package com.baidu.unbiz.multiengine.demo.test;
// 可以显示指定spring前置依赖
@DependsOn("devicePlanStatServiceImpl")
@Component
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "/applicationContext-test.xml")
public class DistributededParallelFetchTest {
@Resource(name = "distributedParallelExePool")
private ParallelExePool parallelExePool;
/**
* 测试分布式并行执行task
*/
@Test
public void testDistributedParallelRunDisTask() {
QueryParam qp = new QueryParam();
MultiResult ctx =
parallelExePool.submit( | new TaskPair("deviceUvFetcher", DeviceRequest.build(qp)), |
wangchongjie/multi-engine | src/test/java/com/baidu/unbiz/multiengine/demo/test/DistributededParallelFetchTest.java | // Path: src/main/java/com/baidu/unbiz/multiengine/common/DisTaskPair.java
// public class DisTaskPair extends TaskPair {
//
// public DisTaskPair(String taskName, Object param) {
// this.field1 = taskName;
// this.field2 = param;
// }
//
// @Override
// public TaskPair wrap(String taskName, Object param) {
// return new DisTaskPair(taskName, param);
// }
// }
//
// Path: src/test/java/com/baidu/unbiz/multiengine/vo/DeviceRequest.java
// public class DeviceRequest {
//
// private List<Integer> deviceIds;
//
// public List<Integer> getDeviceIds() {
// return deviceIds;
// }
//
// public void setDeviceIds(List<Integer> deviceIds) {
// this.deviceIds = deviceIds;
// }
//
// public static DeviceRequest build(QueryParam target) {
// DeviceRequest req = new DeviceRequest();
// // req.copyProperties(target);
// return req;
// }
// }
//
// Path: src/test/java/com/baidu/unbiz/multiengine/vo/DeviceViewItem.java
// public class DeviceViewItem {
//
// private static final long serialVersionUID = 6132709579470894604L;
//
// private int planId;
//
// private String planName;
//
// private Integer deviceId;
//
// private String deviceName ;
//
// // getter and setter
// public int getPlanId() {
// return planId;
// }
//
// public void setPlanId(int planId) {
// this.planId = planId;
// }
//
// public Integer getDeviceId() {
// return deviceId;
// }
//
// public void setDeviceId(Integer deviceId) {
// this.deviceId = deviceId;
// }
//
// public String getPlanName() {
// return planName;
// }
//
// public void setPlanName(String planName) {
// this.planName = planName;
// }
//
// public String getDeviceName() {
// return deviceName;
// }
//
// public void setDeviceName(String deviceName) {
// this.deviceName = deviceName;
// }
//
// public String toString() {
// return ToStringBuilder.reflectionToString(this, ToStringStyle.SHORT_PREFIX_STYLE);
// }
// }
//
// Path: src/test/java/com/baidu/unbiz/multiengine/vo/QueryParam.java
// public class QueryParam extends EnableCast implements TaskRequest {
//
// // 基础查询相关公共字段
// /** 起始查询日期 */
// protected Date from;
// /** 终止查询日期 */
// protected Date to;
// /** 查询的时间粒度 */
// protected int timeUnit;
// /** 第几页 */
// protected int page;
// /** 每页大小 */
// protected int pageSize = 20;
// /** 前端过滤字符 */
// protected String query;
//
// public String getQuery() {
// return query;
// }
//
// public void setQuery(String query) {
// this.query = query;
// }
//
// public Date getFrom() {
// return from;
// }
//
// public void setFrom(Date from) {
// this.from = from;
// }
//
// public Date getTo() {
// return to;
// }
//
// public void setTo(Date to) {
// this.to = to;
// }
//
// public int getTimeUnit() {
// return timeUnit;
// }
//
// public void setTimeUnit(int timeUnit) {
// this.timeUnit = timeUnit;
// }
//
// public int getPage() {
// return page;
// }
//
// public void setPage(int page) {
// this.page = page;
// }
//
// public int getPageSize() {
// return pageSize;
// }
//
// public void setPageSize(int pageSize) {
// this.pageSize = pageSize;
// }
//
//
// }
| import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import javax.annotation.Resource;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.context.annotation.DependsOn;
import org.springframework.stereotype.Component;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;
import com.baidu.unbiz.multiengine.common.DisTaskPair;
import com.baidu.unbiz.multiengine.vo.DeviceRequest;
import com.baidu.unbiz.multiengine.vo.DeviceViewItem;
import com.baidu.unbiz.multiengine.vo.QueryParam;
import com.baidu.unbiz.multitask.common.TaskPair;
import com.baidu.unbiz.multitask.forkjoin.ForkJoin;
import com.baidu.unbiz.multitask.policy.DefautExecutePolicy;
import com.baidu.unbiz.multitask.task.ParallelExePool;
import com.baidu.unbiz.multitask.task.thread.MultiResult; | package com.baidu.unbiz.multiengine.demo.test;
// 可以显示指定spring前置依赖
@DependsOn("devicePlanStatServiceImpl")
@Component
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "/applicationContext-test.xml")
public class DistributededParallelFetchTest {
@Resource(name = "distributedParallelExePool")
private ParallelExePool parallelExePool;
/**
* 测试分布式并行执行task
*/
@Test
public void testDistributedParallelRunDisTask() {
QueryParam qp = new QueryParam();
MultiResult ctx =
parallelExePool.submit(
new TaskPair("deviceUvFetcher", DeviceRequest.build(qp)),
new TaskPair("voidParamFetcher", null), | // Path: src/main/java/com/baidu/unbiz/multiengine/common/DisTaskPair.java
// public class DisTaskPair extends TaskPair {
//
// public DisTaskPair(String taskName, Object param) {
// this.field1 = taskName;
// this.field2 = param;
// }
//
// @Override
// public TaskPair wrap(String taskName, Object param) {
// return new DisTaskPair(taskName, param);
// }
// }
//
// Path: src/test/java/com/baidu/unbiz/multiengine/vo/DeviceRequest.java
// public class DeviceRequest {
//
// private List<Integer> deviceIds;
//
// public List<Integer> getDeviceIds() {
// return deviceIds;
// }
//
// public void setDeviceIds(List<Integer> deviceIds) {
// this.deviceIds = deviceIds;
// }
//
// public static DeviceRequest build(QueryParam target) {
// DeviceRequest req = new DeviceRequest();
// // req.copyProperties(target);
// return req;
// }
// }
//
// Path: src/test/java/com/baidu/unbiz/multiengine/vo/DeviceViewItem.java
// public class DeviceViewItem {
//
// private static final long serialVersionUID = 6132709579470894604L;
//
// private int planId;
//
// private String planName;
//
// private Integer deviceId;
//
// private String deviceName ;
//
// // getter and setter
// public int getPlanId() {
// return planId;
// }
//
// public void setPlanId(int planId) {
// this.planId = planId;
// }
//
// public Integer getDeviceId() {
// return deviceId;
// }
//
// public void setDeviceId(Integer deviceId) {
// this.deviceId = deviceId;
// }
//
// public String getPlanName() {
// return planName;
// }
//
// public void setPlanName(String planName) {
// this.planName = planName;
// }
//
// public String getDeviceName() {
// return deviceName;
// }
//
// public void setDeviceName(String deviceName) {
// this.deviceName = deviceName;
// }
//
// public String toString() {
// return ToStringBuilder.reflectionToString(this, ToStringStyle.SHORT_PREFIX_STYLE);
// }
// }
//
// Path: src/test/java/com/baidu/unbiz/multiengine/vo/QueryParam.java
// public class QueryParam extends EnableCast implements TaskRequest {
//
// // 基础查询相关公共字段
// /** 起始查询日期 */
// protected Date from;
// /** 终止查询日期 */
// protected Date to;
// /** 查询的时间粒度 */
// protected int timeUnit;
// /** 第几页 */
// protected int page;
// /** 每页大小 */
// protected int pageSize = 20;
// /** 前端过滤字符 */
// protected String query;
//
// public String getQuery() {
// return query;
// }
//
// public void setQuery(String query) {
// this.query = query;
// }
//
// public Date getFrom() {
// return from;
// }
//
// public void setFrom(Date from) {
// this.from = from;
// }
//
// public Date getTo() {
// return to;
// }
//
// public void setTo(Date to) {
// this.to = to;
// }
//
// public int getTimeUnit() {
// return timeUnit;
// }
//
// public void setTimeUnit(int timeUnit) {
// this.timeUnit = timeUnit;
// }
//
// public int getPage() {
// return page;
// }
//
// public void setPage(int page) {
// this.page = page;
// }
//
// public int getPageSize() {
// return pageSize;
// }
//
// public void setPageSize(int pageSize) {
// this.pageSize = pageSize;
// }
//
//
// }
// Path: src/test/java/com/baidu/unbiz/multiengine/demo/test/DistributededParallelFetchTest.java
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import javax.annotation.Resource;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.context.annotation.DependsOn;
import org.springframework.stereotype.Component;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;
import com.baidu.unbiz.multiengine.common.DisTaskPair;
import com.baidu.unbiz.multiengine.vo.DeviceRequest;
import com.baidu.unbiz.multiengine.vo.DeviceViewItem;
import com.baidu.unbiz.multiengine.vo.QueryParam;
import com.baidu.unbiz.multitask.common.TaskPair;
import com.baidu.unbiz.multitask.forkjoin.ForkJoin;
import com.baidu.unbiz.multitask.policy.DefautExecutePolicy;
import com.baidu.unbiz.multitask.task.ParallelExePool;
import com.baidu.unbiz.multitask.task.thread.MultiResult;
package com.baidu.unbiz.multiengine.demo.test;
// 可以显示指定spring前置依赖
@DependsOn("devicePlanStatServiceImpl")
@Component
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "/applicationContext-test.xml")
public class DistributededParallelFetchTest {
@Resource(name = "distributedParallelExePool")
private ParallelExePool parallelExePool;
/**
* 测试分布式并行执行task
*/
@Test
public void testDistributedParallelRunDisTask() {
QueryParam qp = new QueryParam();
MultiResult ctx =
parallelExePool.submit(
new TaskPair("deviceUvFetcher", DeviceRequest.build(qp)),
new TaskPair("voidParamFetcher", null), | new DisTaskPair("deviceStatFetcher", DeviceRequest.build(qp)), |
wangchongjie/multi-engine | src/main/java/com/baidu/unbiz/multiengine/codec/common/MsgHeadCodec.java | // Path: src/main/java/com/baidu/unbiz/multiengine/codec/HeadCodec.java
// public interface HeadCodec extends MsgCodec {
// /**
// * 反序列化
// *
// * @param clazz 反序列化后的类定义
// * @param bytes 字节码
// *
// * @return 反序列化后的对象
// *
// * @throws CodecException
// */
// <T> T decode(Class<T> clazz, byte[] bytes) throws CodecException;
//
// /**
// * 序列化
// *
// * @param object 待序列化的对象
// *
// * @return 字节码
// *
// * @throws CodecException
// */
// <T> byte[] encode(T object) throws CodecException;
//
// /**
// * head的类型
// *
// * @return
// */
// Class getHeadClass();
// }
//
// Path: src/main/java/com/baidu/unbiz/multiengine/exception/CodecException.java
// public class CodecException extends RuntimeException {
//
// /**
// * serialVersionUID
// */
// private static final long serialVersionUID = 5196421433506179782L;
//
// /**
// * Creates a new instance of CodecException.
// */
// public CodecException() {
// super();
// }
//
// /**
// * Creates a new instance of CodecException.
// *
// * @param arg0
// * @param arg1
// */
// public CodecException(String arg0, Throwable arg1) {
// super(arg0, arg1);
// }
//
// /**
// * Creates a new instance of CodecException.
// *
// * @param arg0
// */
// public CodecException(String arg0) {
// super(arg0);
// }
//
// /**
// * Creates a new instance of CodecException.
// *
// * @param arg0
// */
// public CodecException(Throwable arg0) {
// super(arg0);
// }
//
// }
//
// Path: src/main/java/com/baidu/unbiz/multiengine/transport/protocol/MsgHead.java
// public final class MsgHead {
//
// /**
// * session内顺序Id
// */
// private long seqId;
//
// /**
// * int (4) 当前包的数据长度
// */
// private int bodyLen;
//
// public static final int SIZE = 12;
//
// private static String DEF_ENCODING = "GBK";
//
// private MsgHead() {
//
// }
//
// private MsgHead(long seqId, int bodyLen) {
// this.seqId = seqId;
// this.bodyLen = bodyLen;
// }
//
// public static MsgHead create() {
// return new MsgHead();
// }
//
// public static MsgHead create(long seqId) {
// MsgHead head = new MsgHead();
// head.setSeqId(seqId);
// return head;
// }
//
// /**
// * write pack_head to transport
// */
// public byte[] toBytes() {
// ByteBuffer bb = ByteBuffer.allocate(SIZE);
// bb.order(ByteOrder.LITTLE_ENDIAN);
//
// try {
// bb.putLong(seqId);
// bb.putInt(bodyLen);
// } catch (Exception e) {
// throw new RuntimeException("exception when putting bytes for nshead...", e);
// }
// return bb.array();
// }
//
// /**
// * 由byte数组解析成PackHead对象
// */
// public static MsgHead fromBytes(byte[] headBytes) {
// MsgHead head = new MsgHead();
// if (headBytes.length < MsgHead.SIZE) {
// throw new RuntimeException("NSHead's size should equal 16.");
// }
// ByteBuffer buffer = ByteBuffer.wrap(headBytes);
// buffer.order(ByteOrder.LITTLE_ENDIAN);
// head.seqId = buffer.getLong();
// head.bodyLen = buffer.getInt();
// return head;
// }
//
// public long getSeqId() {
// return seqId;
// }
//
// public void setSeqId(long seqId) {
// this.seqId = seqId;
// }
//
// public int getBodyLen() {
// return bodyLen;
// }
//
// public void setBodyLen(int bodyLen) {
// this.bodyLen = bodyLen;
// }
//
// @Override
// public String toString() {
// return ToStringBuilder.reflectionToString(this, ToStringStyle.SHORT_PREFIX_STYLE);
// }
// }
| import com.baidu.unbiz.multiengine.codec.HeadCodec;
import com.baidu.unbiz.multiengine.exception.CodecException;
import com.baidu.unbiz.multiengine.transport.protocol.MsgHead; | package com.baidu.unbiz.multiengine.codec.common;
/**
* ClassName: ProtobufCodec <br/>
* Function: protobuf序列化器,利用反射缓存<tt>method</tt>来进行调用
*/
public class MsgHeadCodec implements HeadCodec {
@Override | // Path: src/main/java/com/baidu/unbiz/multiengine/codec/HeadCodec.java
// public interface HeadCodec extends MsgCodec {
// /**
// * 反序列化
// *
// * @param clazz 反序列化后的类定义
// * @param bytes 字节码
// *
// * @return 反序列化后的对象
// *
// * @throws CodecException
// */
// <T> T decode(Class<T> clazz, byte[] bytes) throws CodecException;
//
// /**
// * 序列化
// *
// * @param object 待序列化的对象
// *
// * @return 字节码
// *
// * @throws CodecException
// */
// <T> byte[] encode(T object) throws CodecException;
//
// /**
// * head的类型
// *
// * @return
// */
// Class getHeadClass();
// }
//
// Path: src/main/java/com/baidu/unbiz/multiengine/exception/CodecException.java
// public class CodecException extends RuntimeException {
//
// /**
// * serialVersionUID
// */
// private static final long serialVersionUID = 5196421433506179782L;
//
// /**
// * Creates a new instance of CodecException.
// */
// public CodecException() {
// super();
// }
//
// /**
// * Creates a new instance of CodecException.
// *
// * @param arg0
// * @param arg1
// */
// public CodecException(String arg0, Throwable arg1) {
// super(arg0, arg1);
// }
//
// /**
// * Creates a new instance of CodecException.
// *
// * @param arg0
// */
// public CodecException(String arg0) {
// super(arg0);
// }
//
// /**
// * Creates a new instance of CodecException.
// *
// * @param arg0
// */
// public CodecException(Throwable arg0) {
// super(arg0);
// }
//
// }
//
// Path: src/main/java/com/baidu/unbiz/multiengine/transport/protocol/MsgHead.java
// public final class MsgHead {
//
// /**
// * session内顺序Id
// */
// private long seqId;
//
// /**
// * int (4) 当前包的数据长度
// */
// private int bodyLen;
//
// public static final int SIZE = 12;
//
// private static String DEF_ENCODING = "GBK";
//
// private MsgHead() {
//
// }
//
// private MsgHead(long seqId, int bodyLen) {
// this.seqId = seqId;
// this.bodyLen = bodyLen;
// }
//
// public static MsgHead create() {
// return new MsgHead();
// }
//
// public static MsgHead create(long seqId) {
// MsgHead head = new MsgHead();
// head.setSeqId(seqId);
// return head;
// }
//
// /**
// * write pack_head to transport
// */
// public byte[] toBytes() {
// ByteBuffer bb = ByteBuffer.allocate(SIZE);
// bb.order(ByteOrder.LITTLE_ENDIAN);
//
// try {
// bb.putLong(seqId);
// bb.putInt(bodyLen);
// } catch (Exception e) {
// throw new RuntimeException("exception when putting bytes for nshead...", e);
// }
// return bb.array();
// }
//
// /**
// * 由byte数组解析成PackHead对象
// */
// public static MsgHead fromBytes(byte[] headBytes) {
// MsgHead head = new MsgHead();
// if (headBytes.length < MsgHead.SIZE) {
// throw new RuntimeException("NSHead's size should equal 16.");
// }
// ByteBuffer buffer = ByteBuffer.wrap(headBytes);
// buffer.order(ByteOrder.LITTLE_ENDIAN);
// head.seqId = buffer.getLong();
// head.bodyLen = buffer.getInt();
// return head;
// }
//
// public long getSeqId() {
// return seqId;
// }
//
// public void setSeqId(long seqId) {
// this.seqId = seqId;
// }
//
// public int getBodyLen() {
// return bodyLen;
// }
//
// public void setBodyLen(int bodyLen) {
// this.bodyLen = bodyLen;
// }
//
// @Override
// public String toString() {
// return ToStringBuilder.reflectionToString(this, ToStringStyle.SHORT_PREFIX_STYLE);
// }
// }
// Path: src/main/java/com/baidu/unbiz/multiengine/codec/common/MsgHeadCodec.java
import com.baidu.unbiz.multiengine.codec.HeadCodec;
import com.baidu.unbiz.multiengine.exception.CodecException;
import com.baidu.unbiz.multiengine.transport.protocol.MsgHead;
package com.baidu.unbiz.multiengine.codec.common;
/**
* ClassName: ProtobufCodec <br/>
* Function: protobuf序列化器,利用反射缓存<tt>method</tt>来进行调用
*/
public class MsgHeadCodec implements HeadCodec {
@Override | public <T> T decode(final Class<T> clazz, byte[] data) throws CodecException { |
wangchongjie/multi-engine | src/main/java/com/baidu/unbiz/multiengine/codec/common/MsgHeadCodec.java | // Path: src/main/java/com/baidu/unbiz/multiengine/codec/HeadCodec.java
// public interface HeadCodec extends MsgCodec {
// /**
// * 反序列化
// *
// * @param clazz 反序列化后的类定义
// * @param bytes 字节码
// *
// * @return 反序列化后的对象
// *
// * @throws CodecException
// */
// <T> T decode(Class<T> clazz, byte[] bytes) throws CodecException;
//
// /**
// * 序列化
// *
// * @param object 待序列化的对象
// *
// * @return 字节码
// *
// * @throws CodecException
// */
// <T> byte[] encode(T object) throws CodecException;
//
// /**
// * head的类型
// *
// * @return
// */
// Class getHeadClass();
// }
//
// Path: src/main/java/com/baidu/unbiz/multiengine/exception/CodecException.java
// public class CodecException extends RuntimeException {
//
// /**
// * serialVersionUID
// */
// private static final long serialVersionUID = 5196421433506179782L;
//
// /**
// * Creates a new instance of CodecException.
// */
// public CodecException() {
// super();
// }
//
// /**
// * Creates a new instance of CodecException.
// *
// * @param arg0
// * @param arg1
// */
// public CodecException(String arg0, Throwable arg1) {
// super(arg0, arg1);
// }
//
// /**
// * Creates a new instance of CodecException.
// *
// * @param arg0
// */
// public CodecException(String arg0) {
// super(arg0);
// }
//
// /**
// * Creates a new instance of CodecException.
// *
// * @param arg0
// */
// public CodecException(Throwable arg0) {
// super(arg0);
// }
//
// }
//
// Path: src/main/java/com/baidu/unbiz/multiengine/transport/protocol/MsgHead.java
// public final class MsgHead {
//
// /**
// * session内顺序Id
// */
// private long seqId;
//
// /**
// * int (4) 当前包的数据长度
// */
// private int bodyLen;
//
// public static final int SIZE = 12;
//
// private static String DEF_ENCODING = "GBK";
//
// private MsgHead() {
//
// }
//
// private MsgHead(long seqId, int bodyLen) {
// this.seqId = seqId;
// this.bodyLen = bodyLen;
// }
//
// public static MsgHead create() {
// return new MsgHead();
// }
//
// public static MsgHead create(long seqId) {
// MsgHead head = new MsgHead();
// head.setSeqId(seqId);
// return head;
// }
//
// /**
// * write pack_head to transport
// */
// public byte[] toBytes() {
// ByteBuffer bb = ByteBuffer.allocate(SIZE);
// bb.order(ByteOrder.LITTLE_ENDIAN);
//
// try {
// bb.putLong(seqId);
// bb.putInt(bodyLen);
// } catch (Exception e) {
// throw new RuntimeException("exception when putting bytes for nshead...", e);
// }
// return bb.array();
// }
//
// /**
// * 由byte数组解析成PackHead对象
// */
// public static MsgHead fromBytes(byte[] headBytes) {
// MsgHead head = new MsgHead();
// if (headBytes.length < MsgHead.SIZE) {
// throw new RuntimeException("NSHead's size should equal 16.");
// }
// ByteBuffer buffer = ByteBuffer.wrap(headBytes);
// buffer.order(ByteOrder.LITTLE_ENDIAN);
// head.seqId = buffer.getLong();
// head.bodyLen = buffer.getInt();
// return head;
// }
//
// public long getSeqId() {
// return seqId;
// }
//
// public void setSeqId(long seqId) {
// this.seqId = seqId;
// }
//
// public int getBodyLen() {
// return bodyLen;
// }
//
// public void setBodyLen(int bodyLen) {
// this.bodyLen = bodyLen;
// }
//
// @Override
// public String toString() {
// return ToStringBuilder.reflectionToString(this, ToStringStyle.SHORT_PREFIX_STYLE);
// }
// }
| import com.baidu.unbiz.multiengine.codec.HeadCodec;
import com.baidu.unbiz.multiengine.exception.CodecException;
import com.baidu.unbiz.multiengine.transport.protocol.MsgHead; | package com.baidu.unbiz.multiengine.codec.common;
/**
* ClassName: ProtobufCodec <br/>
* Function: protobuf序列化器,利用反射缓存<tt>method</tt>来进行调用
*/
public class MsgHeadCodec implements HeadCodec {
@Override
public <T> T decode(final Class<T> clazz, byte[] data) throws CodecException { | // Path: src/main/java/com/baidu/unbiz/multiengine/codec/HeadCodec.java
// public interface HeadCodec extends MsgCodec {
// /**
// * 反序列化
// *
// * @param clazz 反序列化后的类定义
// * @param bytes 字节码
// *
// * @return 反序列化后的对象
// *
// * @throws CodecException
// */
// <T> T decode(Class<T> clazz, byte[] bytes) throws CodecException;
//
// /**
// * 序列化
// *
// * @param object 待序列化的对象
// *
// * @return 字节码
// *
// * @throws CodecException
// */
// <T> byte[] encode(T object) throws CodecException;
//
// /**
// * head的类型
// *
// * @return
// */
// Class getHeadClass();
// }
//
// Path: src/main/java/com/baidu/unbiz/multiengine/exception/CodecException.java
// public class CodecException extends RuntimeException {
//
// /**
// * serialVersionUID
// */
// private static final long serialVersionUID = 5196421433506179782L;
//
// /**
// * Creates a new instance of CodecException.
// */
// public CodecException() {
// super();
// }
//
// /**
// * Creates a new instance of CodecException.
// *
// * @param arg0
// * @param arg1
// */
// public CodecException(String arg0, Throwable arg1) {
// super(arg0, arg1);
// }
//
// /**
// * Creates a new instance of CodecException.
// *
// * @param arg0
// */
// public CodecException(String arg0) {
// super(arg0);
// }
//
// /**
// * Creates a new instance of CodecException.
// *
// * @param arg0
// */
// public CodecException(Throwable arg0) {
// super(arg0);
// }
//
// }
//
// Path: src/main/java/com/baidu/unbiz/multiengine/transport/protocol/MsgHead.java
// public final class MsgHead {
//
// /**
// * session内顺序Id
// */
// private long seqId;
//
// /**
// * int (4) 当前包的数据长度
// */
// private int bodyLen;
//
// public static final int SIZE = 12;
//
// private static String DEF_ENCODING = "GBK";
//
// private MsgHead() {
//
// }
//
// private MsgHead(long seqId, int bodyLen) {
// this.seqId = seqId;
// this.bodyLen = bodyLen;
// }
//
// public static MsgHead create() {
// return new MsgHead();
// }
//
// public static MsgHead create(long seqId) {
// MsgHead head = new MsgHead();
// head.setSeqId(seqId);
// return head;
// }
//
// /**
// * write pack_head to transport
// */
// public byte[] toBytes() {
// ByteBuffer bb = ByteBuffer.allocate(SIZE);
// bb.order(ByteOrder.LITTLE_ENDIAN);
//
// try {
// bb.putLong(seqId);
// bb.putInt(bodyLen);
// } catch (Exception e) {
// throw new RuntimeException("exception when putting bytes for nshead...", e);
// }
// return bb.array();
// }
//
// /**
// * 由byte数组解析成PackHead对象
// */
// public static MsgHead fromBytes(byte[] headBytes) {
// MsgHead head = new MsgHead();
// if (headBytes.length < MsgHead.SIZE) {
// throw new RuntimeException("NSHead's size should equal 16.");
// }
// ByteBuffer buffer = ByteBuffer.wrap(headBytes);
// buffer.order(ByteOrder.LITTLE_ENDIAN);
// head.seqId = buffer.getLong();
// head.bodyLen = buffer.getInt();
// return head;
// }
//
// public long getSeqId() {
// return seqId;
// }
//
// public void setSeqId(long seqId) {
// this.seqId = seqId;
// }
//
// public int getBodyLen() {
// return bodyLen;
// }
//
// public void setBodyLen(int bodyLen) {
// this.bodyLen = bodyLen;
// }
//
// @Override
// public String toString() {
// return ToStringBuilder.reflectionToString(this, ToStringStyle.SHORT_PREFIX_STYLE);
// }
// }
// Path: src/main/java/com/baidu/unbiz/multiengine/codec/common/MsgHeadCodec.java
import com.baidu.unbiz.multiengine.codec.HeadCodec;
import com.baidu.unbiz.multiengine.exception.CodecException;
import com.baidu.unbiz.multiengine.transport.protocol.MsgHead;
package com.baidu.unbiz.multiengine.codec.common;
/**
* ClassName: ProtobufCodec <br/>
* Function: protobuf序列化器,利用反射缓存<tt>method</tt>来进行调用
*/
public class MsgHeadCodec implements HeadCodec {
@Override
public <T> T decode(final Class<T> clazz, byte[] data) throws CodecException { | return (T) MsgHead.fromBytes(data); |
wangchongjie/multi-engine | src/test/java/com/baidu/unbiz/multiengine/codec/CodecTest.java | // Path: src/main/java/com/baidu/unbiz/multiengine/codec/common/JsonCodec.java
// public class JsonCodec implements MsgCodec {
// /**
// * 对象匹配映射
// */
// private final ObjectMapper mapper;
//
// public JsonCodec() {
// mapper = new ObjectMapper();
// // ignoring unknown properties makes us more robust to changes in the schema
// mapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
// // This will allow including type information all non-final types. This allows correct
// // serialization/deserialization of generic collections, for example List<MyType>.
// mapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
// }
//
// @Override
// public byte[] encode(Object object) throws CodecException {
// try {
// return mapper.writeValueAsBytes(object);
// } catch (Exception e) {
// throw new CodecException(e);
// }
// }
//
// @Override
// public <T> T decode(Class<T> clazz, byte[] bytes) throws CodecException {
// try {
// return mapper.readValue(bytes, clazz);
// } catch (Exception e) {
// throw new CodecException(e);
// }
// }
//
// }
//
// Path: src/main/java/com/baidu/unbiz/multiengine/codec/common/ProtostuffCodec.java
// public class ProtostuffCodec implements MsgCodec {
//
// /**
// * 设置编码规则
// */
// static {
// System.setProperty("protostuff.runtime.collection_schema_on_repeated_fields", "true");
// System.setProperty("protostuff.runtime.morph_collection_interfaces", "true");
// System.setProperty("protostuff.runtime.morph_map_interfaces", "true");
// }
//
// /**
// * 缓冲区
// */
// private ThreadLocal<LinkedBuffer> linkedBuffer = new ThreadLocal<LinkedBuffer>() {
// @Override
// protected LinkedBuffer initialValue() {
// return LinkedBuffer.allocate(LinkedBuffer.DEFAULT_BUFFER_SIZE);
// }
// };
//
// @Override
// public <T> T decode(final Class<T> clazz, byte[] data) throws CodecException {
// Schema<T> schema = RuntimeSchema.getSchema(clazz);
//
// T content = ReflectionUtil.newInstance(clazz);
// ProtobufIOUtil.mergeFrom(data, content, schema);
// return content;
// }
//
// @Override
// public <T> byte[] encode(T object) throws CodecException {
// try {
// @SuppressWarnings("unchecked")
// com.dyuproject.protostuff.Schema<T> schema =
// (com.dyuproject.protostuff.Schema<T>) RuntimeSchema.getSchema(object.getClass());
// byte[] protostuff = ProtobufIOUtil.toByteArray(object, schema, linkedBuffer.get());
// return protostuff;
// } finally {
// linkedBuffer.get().clear();
// }
// }
//
// }
//
// Path: src/main/java/com/baidu/unbiz/multiengine/transport/dto/Signal.java
// public class Signal<T> {
//
// protected long seqId;
// protected T message;
// protected SignalType type = SignalType.TASK_COMMOND;
//
// public Signal() {
// }
//
// public Signal(T message) {
// this.message = message;
// }
//
// public T getMessage() {
// return message;
// }
//
// public void setMessage(T message) {
// this.message = message;
// }
//
// public long getSeqId() {
// return seqId;
// }
//
// public void setSeqId(long seqId) {
// this.seqId = seqId;
// }
//
// public String toString() {
// return ToStringBuilder.reflectionToString(this, ToStringStyle.SHORT_PREFIX_STYLE);
// }
//
// public SignalType getType() {
// return type;
// }
//
// public void setType(SignalType type) {
// this.type = type;
// }
// }
//
// Path: src/test/java/com/baidu/unbiz/multiengine/vo/DeviceViewItem.java
// public class DeviceViewItem {
//
// private static final long serialVersionUID = 6132709579470894604L;
//
// private int planId;
//
// private String planName;
//
// private Integer deviceId;
//
// private String deviceName ;
//
// // getter and setter
// public int getPlanId() {
// return planId;
// }
//
// public void setPlanId(int planId) {
// this.planId = planId;
// }
//
// public Integer getDeviceId() {
// return deviceId;
// }
//
// public void setDeviceId(Integer deviceId) {
// this.deviceId = deviceId;
// }
//
// public String getPlanName() {
// return planName;
// }
//
// public void setPlanName(String planName) {
// this.planName = planName;
// }
//
// public String getDeviceName() {
// return deviceName;
// }
//
// public void setDeviceName(String deviceName) {
// this.deviceName = deviceName;
// }
//
// public String toString() {
// return ToStringBuilder.reflectionToString(this, ToStringStyle.SHORT_PREFIX_STYLE);
// }
// }
| import java.util.ArrayList;
import java.util.List;
import org.junit.Test;
import com.baidu.unbiz.multiengine.codec.common.JsonCodec;
import com.baidu.unbiz.multiengine.codec.common.ProtostuffCodec;
import com.baidu.unbiz.multiengine.transport.dto.Signal;
import com.baidu.unbiz.multiengine.vo.DeviceViewItem; | package com.baidu.unbiz.multiengine.codec;
/**
* Created by wangchongjie on 16/4/5.
*/
public class CodecTest {
@Test
public void testProtostuffCodec() { | // Path: src/main/java/com/baidu/unbiz/multiengine/codec/common/JsonCodec.java
// public class JsonCodec implements MsgCodec {
// /**
// * 对象匹配映射
// */
// private final ObjectMapper mapper;
//
// public JsonCodec() {
// mapper = new ObjectMapper();
// // ignoring unknown properties makes us more robust to changes in the schema
// mapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
// // This will allow including type information all non-final types. This allows correct
// // serialization/deserialization of generic collections, for example List<MyType>.
// mapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
// }
//
// @Override
// public byte[] encode(Object object) throws CodecException {
// try {
// return mapper.writeValueAsBytes(object);
// } catch (Exception e) {
// throw new CodecException(e);
// }
// }
//
// @Override
// public <T> T decode(Class<T> clazz, byte[] bytes) throws CodecException {
// try {
// return mapper.readValue(bytes, clazz);
// } catch (Exception e) {
// throw new CodecException(e);
// }
// }
//
// }
//
// Path: src/main/java/com/baidu/unbiz/multiengine/codec/common/ProtostuffCodec.java
// public class ProtostuffCodec implements MsgCodec {
//
// /**
// * 设置编码规则
// */
// static {
// System.setProperty("protostuff.runtime.collection_schema_on_repeated_fields", "true");
// System.setProperty("protostuff.runtime.morph_collection_interfaces", "true");
// System.setProperty("protostuff.runtime.morph_map_interfaces", "true");
// }
//
// /**
// * 缓冲区
// */
// private ThreadLocal<LinkedBuffer> linkedBuffer = new ThreadLocal<LinkedBuffer>() {
// @Override
// protected LinkedBuffer initialValue() {
// return LinkedBuffer.allocate(LinkedBuffer.DEFAULT_BUFFER_SIZE);
// }
// };
//
// @Override
// public <T> T decode(final Class<T> clazz, byte[] data) throws CodecException {
// Schema<T> schema = RuntimeSchema.getSchema(clazz);
//
// T content = ReflectionUtil.newInstance(clazz);
// ProtobufIOUtil.mergeFrom(data, content, schema);
// return content;
// }
//
// @Override
// public <T> byte[] encode(T object) throws CodecException {
// try {
// @SuppressWarnings("unchecked")
// com.dyuproject.protostuff.Schema<T> schema =
// (com.dyuproject.protostuff.Schema<T>) RuntimeSchema.getSchema(object.getClass());
// byte[] protostuff = ProtobufIOUtil.toByteArray(object, schema, linkedBuffer.get());
// return protostuff;
// } finally {
// linkedBuffer.get().clear();
// }
// }
//
// }
//
// Path: src/main/java/com/baidu/unbiz/multiengine/transport/dto/Signal.java
// public class Signal<T> {
//
// protected long seqId;
// protected T message;
// protected SignalType type = SignalType.TASK_COMMOND;
//
// public Signal() {
// }
//
// public Signal(T message) {
// this.message = message;
// }
//
// public T getMessage() {
// return message;
// }
//
// public void setMessage(T message) {
// this.message = message;
// }
//
// public long getSeqId() {
// return seqId;
// }
//
// public void setSeqId(long seqId) {
// this.seqId = seqId;
// }
//
// public String toString() {
// return ToStringBuilder.reflectionToString(this, ToStringStyle.SHORT_PREFIX_STYLE);
// }
//
// public SignalType getType() {
// return type;
// }
//
// public void setType(SignalType type) {
// this.type = type;
// }
// }
//
// Path: src/test/java/com/baidu/unbiz/multiengine/vo/DeviceViewItem.java
// public class DeviceViewItem {
//
// private static final long serialVersionUID = 6132709579470894604L;
//
// private int planId;
//
// private String planName;
//
// private Integer deviceId;
//
// private String deviceName ;
//
// // getter and setter
// public int getPlanId() {
// return planId;
// }
//
// public void setPlanId(int planId) {
// this.planId = planId;
// }
//
// public Integer getDeviceId() {
// return deviceId;
// }
//
// public void setDeviceId(Integer deviceId) {
// this.deviceId = deviceId;
// }
//
// public String getPlanName() {
// return planName;
// }
//
// public void setPlanName(String planName) {
// this.planName = planName;
// }
//
// public String getDeviceName() {
// return deviceName;
// }
//
// public void setDeviceName(String deviceName) {
// this.deviceName = deviceName;
// }
//
// public String toString() {
// return ToStringBuilder.reflectionToString(this, ToStringStyle.SHORT_PREFIX_STYLE);
// }
// }
// Path: src/test/java/com/baidu/unbiz/multiengine/codec/CodecTest.java
import java.util.ArrayList;
import java.util.List;
import org.junit.Test;
import com.baidu.unbiz.multiengine.codec.common.JsonCodec;
import com.baidu.unbiz.multiengine.codec.common.ProtostuffCodec;
import com.baidu.unbiz.multiengine.transport.dto.Signal;
import com.baidu.unbiz.multiengine.vo.DeviceViewItem;
package com.baidu.unbiz.multiengine.codec;
/**
* Created by wangchongjie on 16/4/5.
*/
public class CodecTest {
@Test
public void testProtostuffCodec() { | MsgCodec codec = new ProtostuffCodec(); |
wangchongjie/multi-engine | src/test/java/com/baidu/unbiz/multiengine/codec/CodecTest.java | // Path: src/main/java/com/baidu/unbiz/multiengine/codec/common/JsonCodec.java
// public class JsonCodec implements MsgCodec {
// /**
// * 对象匹配映射
// */
// private final ObjectMapper mapper;
//
// public JsonCodec() {
// mapper = new ObjectMapper();
// // ignoring unknown properties makes us more robust to changes in the schema
// mapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
// // This will allow including type information all non-final types. This allows correct
// // serialization/deserialization of generic collections, for example List<MyType>.
// mapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
// }
//
// @Override
// public byte[] encode(Object object) throws CodecException {
// try {
// return mapper.writeValueAsBytes(object);
// } catch (Exception e) {
// throw new CodecException(e);
// }
// }
//
// @Override
// public <T> T decode(Class<T> clazz, byte[] bytes) throws CodecException {
// try {
// return mapper.readValue(bytes, clazz);
// } catch (Exception e) {
// throw new CodecException(e);
// }
// }
//
// }
//
// Path: src/main/java/com/baidu/unbiz/multiengine/codec/common/ProtostuffCodec.java
// public class ProtostuffCodec implements MsgCodec {
//
// /**
// * 设置编码规则
// */
// static {
// System.setProperty("protostuff.runtime.collection_schema_on_repeated_fields", "true");
// System.setProperty("protostuff.runtime.morph_collection_interfaces", "true");
// System.setProperty("protostuff.runtime.morph_map_interfaces", "true");
// }
//
// /**
// * 缓冲区
// */
// private ThreadLocal<LinkedBuffer> linkedBuffer = new ThreadLocal<LinkedBuffer>() {
// @Override
// protected LinkedBuffer initialValue() {
// return LinkedBuffer.allocate(LinkedBuffer.DEFAULT_BUFFER_SIZE);
// }
// };
//
// @Override
// public <T> T decode(final Class<T> clazz, byte[] data) throws CodecException {
// Schema<T> schema = RuntimeSchema.getSchema(clazz);
//
// T content = ReflectionUtil.newInstance(clazz);
// ProtobufIOUtil.mergeFrom(data, content, schema);
// return content;
// }
//
// @Override
// public <T> byte[] encode(T object) throws CodecException {
// try {
// @SuppressWarnings("unchecked")
// com.dyuproject.protostuff.Schema<T> schema =
// (com.dyuproject.protostuff.Schema<T>) RuntimeSchema.getSchema(object.getClass());
// byte[] protostuff = ProtobufIOUtil.toByteArray(object, schema, linkedBuffer.get());
// return protostuff;
// } finally {
// linkedBuffer.get().clear();
// }
// }
//
// }
//
// Path: src/main/java/com/baidu/unbiz/multiengine/transport/dto/Signal.java
// public class Signal<T> {
//
// protected long seqId;
// protected T message;
// protected SignalType type = SignalType.TASK_COMMOND;
//
// public Signal() {
// }
//
// public Signal(T message) {
// this.message = message;
// }
//
// public T getMessage() {
// return message;
// }
//
// public void setMessage(T message) {
// this.message = message;
// }
//
// public long getSeqId() {
// return seqId;
// }
//
// public void setSeqId(long seqId) {
// this.seqId = seqId;
// }
//
// public String toString() {
// return ToStringBuilder.reflectionToString(this, ToStringStyle.SHORT_PREFIX_STYLE);
// }
//
// public SignalType getType() {
// return type;
// }
//
// public void setType(SignalType type) {
// this.type = type;
// }
// }
//
// Path: src/test/java/com/baidu/unbiz/multiengine/vo/DeviceViewItem.java
// public class DeviceViewItem {
//
// private static final long serialVersionUID = 6132709579470894604L;
//
// private int planId;
//
// private String planName;
//
// private Integer deviceId;
//
// private String deviceName ;
//
// // getter and setter
// public int getPlanId() {
// return planId;
// }
//
// public void setPlanId(int planId) {
// this.planId = planId;
// }
//
// public Integer getDeviceId() {
// return deviceId;
// }
//
// public void setDeviceId(Integer deviceId) {
// this.deviceId = deviceId;
// }
//
// public String getPlanName() {
// return planName;
// }
//
// public void setPlanName(String planName) {
// this.planName = planName;
// }
//
// public String getDeviceName() {
// return deviceName;
// }
//
// public void setDeviceName(String deviceName) {
// this.deviceName = deviceName;
// }
//
// public String toString() {
// return ToStringBuilder.reflectionToString(this, ToStringStyle.SHORT_PREFIX_STYLE);
// }
// }
| import java.util.ArrayList;
import java.util.List;
import org.junit.Test;
import com.baidu.unbiz.multiengine.codec.common.JsonCodec;
import com.baidu.unbiz.multiengine.codec.common.ProtostuffCodec;
import com.baidu.unbiz.multiengine.transport.dto.Signal;
import com.baidu.unbiz.multiengine.vo.DeviceViewItem; | package com.baidu.unbiz.multiengine.codec;
/**
* Created by wangchongjie on 16/4/5.
*/
public class CodecTest {
@Test
public void testProtostuffCodec() {
MsgCodec codec = new ProtostuffCodec(); | // Path: src/main/java/com/baidu/unbiz/multiengine/codec/common/JsonCodec.java
// public class JsonCodec implements MsgCodec {
// /**
// * 对象匹配映射
// */
// private final ObjectMapper mapper;
//
// public JsonCodec() {
// mapper = new ObjectMapper();
// // ignoring unknown properties makes us more robust to changes in the schema
// mapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
// // This will allow including type information all non-final types. This allows correct
// // serialization/deserialization of generic collections, for example List<MyType>.
// mapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
// }
//
// @Override
// public byte[] encode(Object object) throws CodecException {
// try {
// return mapper.writeValueAsBytes(object);
// } catch (Exception e) {
// throw new CodecException(e);
// }
// }
//
// @Override
// public <T> T decode(Class<T> clazz, byte[] bytes) throws CodecException {
// try {
// return mapper.readValue(bytes, clazz);
// } catch (Exception e) {
// throw new CodecException(e);
// }
// }
//
// }
//
// Path: src/main/java/com/baidu/unbiz/multiengine/codec/common/ProtostuffCodec.java
// public class ProtostuffCodec implements MsgCodec {
//
// /**
// * 设置编码规则
// */
// static {
// System.setProperty("protostuff.runtime.collection_schema_on_repeated_fields", "true");
// System.setProperty("protostuff.runtime.morph_collection_interfaces", "true");
// System.setProperty("protostuff.runtime.morph_map_interfaces", "true");
// }
//
// /**
// * 缓冲区
// */
// private ThreadLocal<LinkedBuffer> linkedBuffer = new ThreadLocal<LinkedBuffer>() {
// @Override
// protected LinkedBuffer initialValue() {
// return LinkedBuffer.allocate(LinkedBuffer.DEFAULT_BUFFER_SIZE);
// }
// };
//
// @Override
// public <T> T decode(final Class<T> clazz, byte[] data) throws CodecException {
// Schema<T> schema = RuntimeSchema.getSchema(clazz);
//
// T content = ReflectionUtil.newInstance(clazz);
// ProtobufIOUtil.mergeFrom(data, content, schema);
// return content;
// }
//
// @Override
// public <T> byte[] encode(T object) throws CodecException {
// try {
// @SuppressWarnings("unchecked")
// com.dyuproject.protostuff.Schema<T> schema =
// (com.dyuproject.protostuff.Schema<T>) RuntimeSchema.getSchema(object.getClass());
// byte[] protostuff = ProtobufIOUtil.toByteArray(object, schema, linkedBuffer.get());
// return protostuff;
// } finally {
// linkedBuffer.get().clear();
// }
// }
//
// }
//
// Path: src/main/java/com/baidu/unbiz/multiengine/transport/dto/Signal.java
// public class Signal<T> {
//
// protected long seqId;
// protected T message;
// protected SignalType type = SignalType.TASK_COMMOND;
//
// public Signal() {
// }
//
// public Signal(T message) {
// this.message = message;
// }
//
// public T getMessage() {
// return message;
// }
//
// public void setMessage(T message) {
// this.message = message;
// }
//
// public long getSeqId() {
// return seqId;
// }
//
// public void setSeqId(long seqId) {
// this.seqId = seqId;
// }
//
// public String toString() {
// return ToStringBuilder.reflectionToString(this, ToStringStyle.SHORT_PREFIX_STYLE);
// }
//
// public SignalType getType() {
// return type;
// }
//
// public void setType(SignalType type) {
// this.type = type;
// }
// }
//
// Path: src/test/java/com/baidu/unbiz/multiengine/vo/DeviceViewItem.java
// public class DeviceViewItem {
//
// private static final long serialVersionUID = 6132709579470894604L;
//
// private int planId;
//
// private String planName;
//
// private Integer deviceId;
//
// private String deviceName ;
//
// // getter and setter
// public int getPlanId() {
// return planId;
// }
//
// public void setPlanId(int planId) {
// this.planId = planId;
// }
//
// public Integer getDeviceId() {
// return deviceId;
// }
//
// public void setDeviceId(Integer deviceId) {
// this.deviceId = deviceId;
// }
//
// public String getPlanName() {
// return planName;
// }
//
// public void setPlanName(String planName) {
// this.planName = planName;
// }
//
// public String getDeviceName() {
// return deviceName;
// }
//
// public void setDeviceName(String deviceName) {
// this.deviceName = deviceName;
// }
//
// public String toString() {
// return ToStringBuilder.reflectionToString(this, ToStringStyle.SHORT_PREFIX_STYLE);
// }
// }
// Path: src/test/java/com/baidu/unbiz/multiengine/codec/CodecTest.java
import java.util.ArrayList;
import java.util.List;
import org.junit.Test;
import com.baidu.unbiz.multiengine.codec.common.JsonCodec;
import com.baidu.unbiz.multiengine.codec.common.ProtostuffCodec;
import com.baidu.unbiz.multiengine.transport.dto.Signal;
import com.baidu.unbiz.multiengine.vo.DeviceViewItem;
package com.baidu.unbiz.multiengine.codec;
/**
* Created by wangchongjie on 16/4/5.
*/
public class CodecTest {
@Test
public void testProtostuffCodec() {
MsgCodec codec = new ProtostuffCodec(); | List<DeviceViewItem> dataList = mockList(); |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.