answer
stringlengths 17
10.2M
|
|---|
// This file is part of the Kaltura Collaborative Media Suite which allows users
// to do with audio, video, and animation what Wiki platforms allow them to do with
// text.
// This program is free software: you can redistribute it and/or modify
// published by the Free Software Foundation, either version 3 of the
// This program is distributed in the hope that it will be useful,
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// @ignore
package com.kaltura.client;
import com.kaltura.client.utils.request.ConnectionConfiguration;
import com.kaltura.client.types.BaseResponseProfile;
/**
* This class was generated using generate.php
* against an XML schema provided by Kaltura.
*
* MANUAL CHANGES TO THIS CLASS WILL BE OVERWRITTEN.
*/
@SuppressWarnings("serial")
public class Client extends ClientBase {
public Client(ConnectionConfiguration config) {
super(config);
this.setClientTag("java:22-09-16");
this.setApiVersion("18.14.0");
this.clientConfiguration.put("format", 1); // JSON
}
/**
* @param clientTag
*/
public void setClientTag(String clientTag){
this.clientConfiguration.put("clientTag", clientTag);
}
/**
* @return String
*/
public String getClientTag(){
if(this.clientConfiguration.containsKey("clientTag")){
return(String) this.clientConfiguration.get("clientTag");
}
return null;
}
/**
* @param apiVersion
*/
public void setApiVersion(String apiVersion){
this.clientConfiguration.put("apiVersion", apiVersion);
}
/**
* @return String
*/
public String getApiVersion(){
if(this.clientConfiguration.containsKey("apiVersion")){
return(String) this.clientConfiguration.get("apiVersion");
}
return null;
}
/**
* @param partnerId Impersonated partner id
*/
public void setPartnerId(Integer partnerId){
this.requestConfiguration.put("partnerId", partnerId);
}
/**
* Impersonated partner id
*
* @return Integer
*/
public Integer getPartnerId(){
if(this.requestConfiguration.containsKey("partnerId")){
return(Integer) this.requestConfiguration.get("partnerId");
}
return 0;
}
/**
* @param ks Kaltura API session
*/
public void setKs(String ks){
this.requestConfiguration.put("ks", ks);
}
/**
* Kaltura API session
*
* @return String
*/
public String getKs(){
if(this.requestConfiguration.containsKey("ks")){
return(String) this.requestConfiguration.get("ks");
}
return null;
}
/**
* @param sessionId Kaltura API session
*/
public void setSessionId(String sessionId){
this.requestConfiguration.put("ks", sessionId);
}
/**
* Kaltura API session
*
* @return String
*/
public String getSessionId(){
if(this.requestConfiguration.containsKey("ks")){
return(String) this.requestConfiguration.get("ks");
}
return null;
}
/**
* @param responseProfile Response profile - this attribute will be automatically unset after every API call.
*/
public void setResponseProfile(BaseResponseProfile responseProfile){
this.requestConfiguration.put("responseProfile", responseProfile);
}
/**
* Response profile - this attribute will be automatically unset after every API call.
*
* @return BaseResponseProfile
*/
public BaseResponseProfile getResponseProfile(){
if(this.requestConfiguration.containsKey("responseProfile")){
return(BaseResponseProfile) this.requestConfiguration.get("responseProfile");
}
return null;
}
}
|
// This file is part of the Kaltura Collaborative Media Suite which allows users
// to do with audio, video, and animation what Wiki platforms allow them to do with
// text.
// This program is free software: you can redistribute it and/or modify
// published by the Free Software Foundation, either version 3 of the
// This program is distributed in the hope that it will be useful,
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// @ignore
package com.kaltura.client;
import com.kaltura.client.utils.request.ConnectionConfiguration;
import com.kaltura.client.types.BaseResponseProfile;
/**
* This class was generated using generate.php
* against an XML schema provided by Kaltura.
*
* MANUAL CHANGES TO THIS CLASS WILL BE OVERWRITTEN.
*/
@SuppressWarnings("serial")
public class Client extends ClientBase {
public Client(ConnectionConfiguration config) {
super(config);
this.setClientTag("java:21-05-18");
this.setApiVersion("17.1.0");
this.clientConfiguration.put("format", 1); // JSON
}
/**
* @param clientTag
*/
public void setClientTag(String clientTag){
this.clientConfiguration.put("clientTag", clientTag);
}
/**
* @return String
*/
public String getClientTag(){
if(this.clientConfiguration.containsKey("clientTag")){
return(String) this.clientConfiguration.get("clientTag");
}
return null;
}
/**
* @param apiVersion
*/
public void setApiVersion(String apiVersion){
this.clientConfiguration.put("apiVersion", apiVersion);
}
/**
* @return String
*/
public String getApiVersion(){
if(this.clientConfiguration.containsKey("apiVersion")){
return(String) this.clientConfiguration.get("apiVersion");
}
return null;
}
/**
* @param partnerId Impersonated partner id
*/
public void setPartnerId(Integer partnerId){
this.requestConfiguration.put("partnerId", partnerId);
}
/**
* Impersonated partner id
*
* @return Integer
*/
public Integer getPartnerId(){
if(this.requestConfiguration.containsKey("partnerId")){
return(Integer) this.requestConfiguration.get("partnerId");
}
return 0;
}
/**
* @param ks Kaltura API session
*/
public void setKs(String ks){
this.requestConfiguration.put("ks", ks);
}
/**
* Kaltura API session
*
* @return String
*/
public String getKs(){
if(this.requestConfiguration.containsKey("ks")){
return(String) this.requestConfiguration.get("ks");
}
return null;
}
/**
* @param sessionId Kaltura API session
*/
public void setSessionId(String sessionId){
this.requestConfiguration.put("ks", sessionId);
}
/**
* Kaltura API session
*
* @return String
*/
public String getSessionId(){
if(this.requestConfiguration.containsKey("ks")){
return(String) this.requestConfiguration.get("ks");
}
return null;
}
/**
* @param responseProfile Response profile - this attribute will be automatically unset after every API call.
*/
public void setResponseProfile(BaseResponseProfile responseProfile){
this.requestConfiguration.put("responseProfile", responseProfile);
}
/**
* Response profile - this attribute will be automatically unset after every API call.
*
* @return BaseResponseProfile
*/
public BaseResponseProfile getResponseProfile(){
if(this.requestConfiguration.containsKey("responseProfile")){
return(BaseResponseProfile) this.requestConfiguration.get("responseProfile");
}
return null;
}
}
|
// This file is part of the Kaltura Collaborative Media Suite which allows users
// to do with audio, video, and animation what Wiki platfroms allow them to do with
// text.
// This program is free software: you can redistribute it and/or modify
// published by the Free Software Foundation, either version 3 of the
// This program is distributed in the hope that it will be useful,
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// @ignore
package com.kaltura.client;
import com.kaltura.client.utils.request.ConnectionConfiguration;
import com.kaltura.client.types.BaseResponseProfile;
/**
* This class was generated using generate.php
* against an XML schema provided by Kaltura.
*
* MANUAL CHANGES TO THIS CLASS WILL BE OVERWRITTEN.
*/
@SuppressWarnings("serial")
public class Client extends ClientBase {
public Client(ConnectionConfiguration config) {
super(config);
this.setClientTag("java:20-01-22");
this.setApiVersion("15.15.0");
this.clientConfiguration.put("format", 1); // JSON
}
/**
* @param clientTag
*/
public void setClientTag(String clientTag){
this.clientConfiguration.put("clientTag", clientTag);
}
/**
* @return String
*/
public String getClientTag(){
if(this.clientConfiguration.containsKey("clientTag")){
return(String) this.clientConfiguration.get("clientTag");
}
return null;
}
/**
* @param apiVersion
*/
public void setApiVersion(String apiVersion){
this.clientConfiguration.put("apiVersion", apiVersion);
}
/**
* @return String
*/
public String getApiVersion(){
if(this.clientConfiguration.containsKey("apiVersion")){
return(String) this.clientConfiguration.get("apiVersion");
}
return null;
}
/**
* @param partnerId Impersonated partner id
*/
public void setPartnerId(Integer partnerId){
this.requestConfiguration.put("partnerId", partnerId);
}
/**
* Impersonated partner id
*
* @return Integer
*/
public Integer getPartnerId(){
if(this.requestConfiguration.containsKey("partnerId")){
return(Integer) this.requestConfiguration.get("partnerId");
}
return 0;
}
/**
* @param ks Kaltura API session
*/
public void setKs(String ks){
this.requestConfiguration.put("ks", ks);
}
/**
* Kaltura API session
*
* @return String
*/
public String getKs(){
if(this.requestConfiguration.containsKey("ks")){
return(String) this.requestConfiguration.get("ks");
}
return null;
}
/**
* @param sessionId Kaltura API session
*/
public void setSessionId(String sessionId){
this.requestConfiguration.put("ks", sessionId);
}
/**
* Kaltura API session
*
* @return String
*/
public String getSessionId(){
if(this.requestConfiguration.containsKey("ks")){
return(String) this.requestConfiguration.get("ks");
}
return null;
}
/**
* @param responseProfile Response profile - this attribute will be automatically unset after every API call.
*/
public void setResponseProfile(BaseResponseProfile responseProfile){
this.requestConfiguration.put("responseProfile", responseProfile);
}
/**
* Response profile - this attribute will be automatically unset after every API call.
*
* @return BaseResponseProfile
*/
public BaseResponseProfile getResponseProfile(){
if(this.requestConfiguration.containsKey("responseProfile")){
return(BaseResponseProfile) this.requestConfiguration.get("responseProfile");
}
return null;
}
}
|
package com.podio;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Locale;
import java.util.TimeZone;
import org.codehaus.jackson.jaxrs.JacksonJsonProvider;
import org.codehaus.jackson.map.DeserializationConfig.Feature;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.SerializationConfig;
import org.codehaus.jackson.map.annotate.JsonSerialize.Inclusion;
import org.codehaus.jackson.map.deser.CustomDeserializerFactory;
import org.codehaus.jackson.map.deser.StdDeserializerProvider;
import org.codehaus.jackson.map.ser.CustomSerializerFactory;
import org.eclipse.jetty.http.HttpHeaders;
import org.joda.time.DateTime;
import org.joda.time.LocalDate;
import com.podio.oauth.OAuthClientCredentials;
import com.podio.oauth.OAuthUserCredentials;
import com.podio.serialize.DateTimeDeserializer;
import com.podio.serialize.DateTimeSerializer;
import com.podio.serialize.LocalDateDeserializer;
import com.podio.serialize.LocalDateSerializer;
import com.podio.serialize.LocaleDeserializer;
import com.podio.serialize.LocaleSerializer;
import com.podio.serialize.TimeZoneDeserializer;
import com.podio.serialize.TimeZoneSerializer;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.client.config.ClientConfig;
import com.sun.jersey.api.client.config.DefaultClientConfig;
import com.sun.jersey.api.client.filter.GZIPContentEncodingFilter;
import com.sun.jersey.multipart.impl.MultiPartWriter;
/**
* This is the main low level entry point to access the Podio API. Construct
* this and pass it to the APIFactory.
*/
public final class ResourceFactory {
private final WebResource apiResource;
private final WebResource fileResource;
private final LoginFilter loginFilter;
public ResourceFactory(OAuthClientCredentials clientCredentials,
OAuthUserCredentials userCredentials) {
this("api.podio.com", "file.podio.com", 443, true, false,
clientCredentials, userCredentials);
}
public ResourceFactory(String apiHostname, String fileHostname, int port,
boolean ssl, boolean dryRun,
OAuthClientCredentials clientCredentials,
OAuthUserCredentials userCredentials) {
ClientConfig config = new DefaultClientConfig();
config.getSingletons().add(getJsonProvider());
config.getClasses().add(MultiPartWriter.class);
Client client = Client.create(config);
client.addFilter(new GZIPContentEncodingFilter(false));
client.addFilter(new ExceptionFilter());
if (dryRun) {
client.addFilter(new DryRunFilter());
}
// client.addFilter(new LoggingFilter());
this.apiResource = client.resource(getURI(apiHostname, port, ssl));
apiResource.header(HttpHeaders.USER_AGENT, "Podio Java API Client");
this.fileResource = client.resource(getURI(fileHostname, port, ssl));
fileResource.header(HttpHeaders.USER_AGENT, "Podio Java API Client");
AuthProvider authProvider = new AuthProvider(this, clientCredentials,
userCredentials);
this.loginFilter = new LoginFilter(authProvider);
}
private URI getURI(String hostname, int port, boolean ssl) {
try {
return new URI(ssl ? "https" : "http", null, hostname, port, null,
null, null);
} catch (URISyntaxException e) {
throw new RuntimeException(e);
}
}
private JacksonJsonProvider getJsonProvider() {
ObjectMapper mapper = new ObjectMapper();
mapper.disable(Feature.FAIL_ON_UNKNOWN_PROPERTIES);
mapper.disable(SerializationConfig.Feature.FAIL_ON_EMPTY_BEANS);
mapper.setSerializationInclusion(Inclusion.NON_NULL);
CustomSerializerFactory serializerFactory = new CustomSerializerFactory();
serializerFactory.addSpecificMapping(DateTime.class,
new DateTimeSerializer());
serializerFactory.addSpecificMapping(LocalDate.class,
new LocalDateSerializer());
serializerFactory.addGenericMapping(TimeZone.class,
new TimeZoneSerializer());
serializerFactory.addSpecificMapping(Locale.class,
new LocaleSerializer());
mapper.setSerializerFactory(serializerFactory);
CustomDeserializerFactory deserializerFactory = new CustomDeserializerFactory();
deserializerFactory.addSpecificMapping(DateTime.class,
new DateTimeDeserializer());
deserializerFactory.addSpecificMapping(LocalDate.class,
new LocalDateDeserializer());
deserializerFactory.addSpecificMapping(TimeZone.class,
new TimeZoneDeserializer());
deserializerFactory.addSpecificMapping(Locale.class,
new LocaleDeserializer());
mapper.setDeserializerProvider(new StdDeserializerProvider(
deserializerFactory));
return new CustomJacksonJsonProvider(mapper);
}
public WebResource getFileResource(String path) {
return getFileResource(path, true);
}
public WebResource getFileResource(String path, boolean secure) {
WebResource subResource = fileResource.path(path);
if (secure) {
subResource.addFilter(this.loginFilter);
}
return subResource;
}
public WebResource getApiResource(String path) {
return getApiResource(path, true);
}
public WebResource getApiResource(String path, boolean secure) {
WebResource subResource = apiResource.path(path);
if (secure) {
subResource.addFilter(this.loginFilter);
}
return subResource;
}
}
|
package com.profiler.context;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.TimerTask;
import com.profiler.Agent;
/**
*
* @author netspider
*
*/
public class Span {
private final TraceID traceID;
private final long createTime;
private String serviceName;
private String name;
private EndPoint endPoint;
private final List<HippoBinaryAnnotation> binaryAnnotations = new ArrayList<HippoBinaryAnnotation>(5);
private final List<HippoAnnotation> annotations = new ArrayList<HippoAnnotation>(5);
private final Set<String> annotationValues = new HashSet<String>(5);
/**
* Cancel timer logic.
* TODO: refactor this.
*/
private TimerTask timerTask;
public void setTimerTask(TimerTask task) {
this.timerTask = task;
}
public boolean cancelTimer() {
return timerTask.cancel();
}
public Span(TraceID traceId, String name, EndPoint endPoint) {
this.traceID = traceId;
this.name = name;
this.endPoint = endPoint;
this.createTime = System.currentTimeMillis();
}
public boolean addAnnotation(HippoAnnotation annotation) {
annotationValues.add(annotation.getValue());
return annotations.add(annotation);
}
public boolean addAnnotation(HippoBinaryAnnotation annotation) {
return binaryAnnotations.add(annotation);
}
public int getAnnotationSize() {
return annotations.size();
}
/**
* this method only works for Trace.mutate()
*
* @param value
* @return
*/
public boolean isExistsAnnotationType(String value) {
return annotationValues.contains(value);
}
public EndPoint getEndPoint() {
return this.endPoint;
}
public String getServiceName() {
return serviceName;
}
public void setServiceName(String serviceName) {
this.serviceName = serviceName;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public void setEndPoint(EndPoint endPoint) {
this.endPoint = endPoint;
}
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("{");
sb.append("\n\t TraceID = ").append(traceID);
sb.append(",\n\t CreateTime = ").append(createTime);
sb.append(",\n\t Name = ").append(name);
sb.append(",\n\t ServiceName = ").append(serviceName);
sb.append(",\n\t EndPoint = ").append(endPoint);
sb.append(",\n\t Annotations = {");
for (HippoAnnotation a : annotations) {
sb.append("\n\t\t").append(a);
}
sb.append("\n\t}");
sb.append(",\n\t BinaryAnnotations=");
for (HippoBinaryAnnotation a : binaryAnnotations) {
sb.append("\n\t\t").append(a);
}
sb.append("\n\t}");
sb.append("}");
return sb.toString();
}
public com.profiler.common.dto.thrift.Span toThrift() {
com.profiler.common.dto.thrift.Span span = new com.profiler.common.dto.thrift.Span();
span.setAgentID(Agent.getInstance().getAgentId());
span.setTimestamp(createTime);
span.setMostTraceID(traceID.getId().getMostSignificantBits());
span.setLeastTraceID(traceID.getId().getLeastSignificantBits());
span.setName(name);
span.setServiceName(serviceName);
span.setSpanID(traceID.getSpanId());
span.setParentSpanId(traceID.getParentSpanId());
List<com.profiler.common.dto.thrift.Annotation> annotationList = new ArrayList<com.profiler.common.dto.thrift.Annotation>(annotations.size());
for (HippoAnnotation a : annotations) {
annotationList.add(a.toThrift());
}
span.setAnnotations(annotationList);
List<com.profiler.common.dto.thrift.BinaryAnnotation> binaryAnnotationList = new ArrayList<com.profiler.common.dto.thrift.BinaryAnnotation>(binaryAnnotations.size());
for (HippoBinaryAnnotation a : binaryAnnotations) {
binaryAnnotationList.add(a.toThrift());
}
span.setBinaryAnnotations(binaryAnnotationList);
span.setFlag(traceID.getFlags());
return span;
}
}
|
package com.technoirarts;
import org.apache.solr.client.solrj.beans.Field;
import org.springframework.data.annotation.Id;
import org.springframework.data.solr.core.mapping.SolrDocument;
@SolrDocument(solrCoreName = "collection1")
public class SolrUser {
@Id
@Field
private String id;
@Field("userId_l")
private Long userId;
@Field("surname_s")
private String surname;
@Field("name_s")
private String name;
@Field("age_i")
private Integer age;
@Field("city_s")
private String city;
@Field("extra_en")
private String extra;
static public SolrUser fromUser(User user) {
SolrUser solrUser = new SolrUser();
solrUser.setUserId(user.getId());
solrUser.setSurname(user.getSurname());
solrUser.setName(user.getName());
solrUser.setAge(user.getAge());
solrUser.setCity(user.getCity());
solrUser.setExtra(user.getExtra());
return solrUser;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public Long getUserId() {
return userId;
}
public void setUserId(Long userId) {
this.userId = userId;
}
public String getSurname() {
return surname;
}
public void setSurname(String surname) {
this.surname = surname;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getExtra() {
return extra;
}
public void setExtra(String extra) {
this.extra = extra;
}
}
|
package com.yq.user.dao;
import com.google.common.base.Strings;
import com.sr178.common.jdbc.SqlParameter;
import com.sr178.common.jdbc.bean.IPage;
import com.yq.common.dao.YqDaoBase;
import com.yq.user.bo.Tduser;
public class TduserDao extends YqDaoBase<Tduser>{
public Tduser get(String tdName,String tdUserId){
String sql = "select * from "+super.getTable()+" where gai=0 and (tdname=? or tduserid=?) limit 1";
SqlParameter parameter = new SqlParameter();
parameter.setString(tdName);
parameter.setString(tdUserId);
return super.getJdbc().get(sql, Tduser.class, parameter);
}
public IPage<Tduser> getPage(String userName,int pageIndex,int pageSize){
String sql = "select * from "+super.getTable();
SqlParameter parameter = new SqlParameter();
if(Strings.isNullOrEmpty(userName)){
sql = sql + " where gai=1";
}else{
sql = sql +" where gai=1 and (tdname=? or tduserid=? or tduser=? or tdcall=? or tdqq=?)";
parameter.setString(userName);
parameter.setString(userName);
parameter.setString(userName);
parameter.setString(userName);
parameter.setString(userName);
}
return super.getJdbc().getListPage(sql, Tduser.class, parameter, pageSize, pageIndex);
}
public IPage<Tduser> getTduserPageList(String param,int pageIndex,int pageSize){
String sql = "select * from "+super.getTable();
sql = sql +" where gai=0 and (tdname=? or tduserid=? or tduser=? or tdcall=? or tdqq=?)";
SqlParameter parameter = new SqlParameter();
parameter.setString(param);
parameter.setString(param);
parameter.setString(param);
parameter.setString(param);
parameter.setString(param);
return super.getJdbc().getListPage(sql, Tduser.class, parameter, pageSize, pageIndex);
}
public boolean update(Integer id,String tdname,String tduserid,String tduser,String tdcall,String tdqq){
String sql = "update "+super.getTable();
sql = sql +" set tdname=? , tduserid=? , tduser=? , tdcall=? , tdqq=? where id=?";
SqlParameter parameter = new SqlParameter();
parameter.setString(tdname);
parameter.setString(tduserid);
parameter.setString(tduser);
parameter.setString(tdcall);
parameter.setString(tdqq);
parameter.setInt(id);
return super.getJdbc().update(sql, parameter)>0;
}
}
|
package controller;
import java.util.Calendar;
import java.util.Date;
import java.util.Timer;
import java.util.UUID;
import javax.ejb.EJBException;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.ws.rs.*;
import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.core.Application;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Request;
import javax.ws.rs.core.Response;
import io.swagger.annotations.Api;
import model.User;
import session.UserSession;
@Stateless
@ApplicationPath("/api")
@Path("/user")
@Api("user")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public class UserController extends ApiController {
@PersistenceContext(unitName="myPU")
private EntityManager entityManager;
@Context private HttpServletRequest request;
@GET
@Secured
@Path("/logout")
@Produces(MediaType.APPLICATION_JSON)
public Response logout (@Context HttpHeaders httpHeaders) {
try {
String token = httpHeaders.getHeaderString(HttpHeaders.AUTHORIZATION).substring("Bearer".length()).trim();
User user = (User) entityManager.createQuery("FROM User WHERE token = :token")
.setParameter("token", token)
.getSingleResult();
user.setToken(null);
user.setTokenExpiration(null);
entityManager.merge(user);
entityManager.flush();
request.getSession(false);
String json = "logout successfull";
return Response.ok(json, MediaType.APPLICATION_JSON).build();
} catch (javax.persistence.NoResultException ex) {
return Response.status(Response.Status.FORBIDDEN).build();
} catch (Exception ex) {
return Response.status(Response.Status.FORBIDDEN).build();
}
}
@GET
@Path("/authenticate/{login}/{password}")
@Produces(MediaType.APPLICATION_JSON)
public Response authenticate (@PathParam("login") String login,
@PathParam("password") String password) {
try {
User user = (User) entityManager.createQuery("FROM User WHERE login = :user AND password = :pass")
.setParameter("user", login)
.setParameter("pass", password)
.getSingleResult();
request.getSession(true);
Date date = new Date();
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.add(Calendar.DATE, 2);
date = calendar.getTime();
user.setTokenExpiration(date);
String token = UUID.randomUUID().toString();
user.setToken(token);
request.getSession().setAttribute("token", token);
String json = token;
entityManager.merge(user);
entityManager.flush();
return Response.ok(json, MediaType.APPLICATION_JSON).build();
}catch (javax.persistence.NoResultException ex) {
return Response.status(401).build();
}
}
@GET
@Path("/create/{login}/{username}/{password}/{mail}/{phone}/{role}/{firstname}/{lastname}")
@Produces(MediaType.APPLICATION_JSON)
public User createUser (@PathParam("login") String login,
@PathParam("username") String username,
@PathParam("password") String password,
@PathParam("mail") String mail,
@PathParam("phone") String phone,
@PathParam("role") String role,
@PathParam("firstname") String firstname,
@PathParam("lastname") String lastname) {
User userRet = new User();
userRet.setUserName(username);
userRet.setLogin(login);
userRet.setMailAddress(mail);
userRet.setPassword(password);
userRet.setPhoneNum(phone);
userRet.setRole(role);
userRet.setUserFirstName(firstname);
userRet.setUserName(lastname);
userRet.setStatus(true);
entityManager.persist(userRet);
entityManager.flush();
return userRet;
}
@GET
@Secured
@Path("/edit/{id}/{login}/{username}/{password}/{mail}/{phone}/{role}/{firstname}/{lastname}/{agencyId}")
@Produces(MediaType.APPLICATION_JSON)
public User editUser (@PathParam("id") Integer id,
@PathParam("login") String login,
@PathParam("username") String username,
@PathParam("password") String password,
@PathParam("mail") String mail,
@PathParam("phone") String phone,
@PathParam("role") String role,
@PathParam("firstname") String firstname,
@PathParam("lastname") String lastname,
@PathParam("agencyId") Integer agencyId) {
User userRet = entityManager.find(User.class, id);
userRet.setUserName(username);
userRet.setLogin(login);
userRet.setMailAddress(mail);
userRet.setPassword(password);
userRet.setPhoneNum(phone);
userRet.setRole(role);
userRet.setUserFirstName(firstname);
userRet.setUserName(lastname);
userRet.setStatus(true);
entityManager.merge(userRet);
entityManager.flush();
return userRet;
}
@GET
@Secured
@Path("/view/{id}")
@Produces(MediaType.APPLICATION_JSON)
public User consultUser (@PathParam("id") Integer id) {
User userRet = entityManager.find(User.class, id);
return userRet;
}
@GET
@Path("/disable/{id}")
@Produces(MediaType.APPLICATION_JSON)
public String disableUser (@PathParam("id") Integer id) {
User userRet = entityManager.find(User.class, id);
userRet.setStatus(false);
entityManager.merge(userRet);
entityManager.flush();
return ("User successfully disabled");
}
}
|
package craterdog.core;
import java.util.Iterator;
/**
* This interface should be implemented by classes that define a sequence of
* elements that can be iterated over in a sequential manner.
*
* @author Derk Norton
* @param <E> The type of element that makes up the sequence.
*/
public interface Sequential<E> extends Iterable<E> {
/**
* This method checks to see if the sequence is empty.
*
* @return Whether or not the sequence is empty.
*/
boolean isEmpty();
/**
* This method returns the number of elements in the sequence.
*
* @return The number of elements in the sequence.
*/
int getNumberOfElements();
/**
* This method returns an array containing the elements in the sequence.
*
* @return array An array containing the elements from the sequence.
*/
E[] toArray();
/**
* This method fills the specified array with as many elements from the sequence as
* will fit in the array. If the array is larger than the sequence, the remaining
* elements in the array remain unchanged.
*
* @param array An array to be used to hold the elements of the sequence.
*/
@Deprecated
void toArray(E[] array);
@Override
Iterator<E> iterator();
}
|
package example;
import ev3dev.hardware.display.SystemDisplay;
import ev3dev.utils.JarResource;
import lejos.hardware.lcd.GraphicsLCD;
import lejos.robotics.Color;
import lejos.utility.Delay;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
public class LCDDrawImagesTest {
public static GraphicsLCD lcd = SystemDisplay.initializeRealLCD();
public static void main(final String[] args) throws IOException {
System.out.println("EV3 LCD Example");
clear();
BufferedImage cross = ImageIO.read(JarResource.stream("cross.gif"));
BufferedImage nought = ImageIO.read(JarResource.stream("nought.gif"));
//lcd.setColor(Color.BLACK);
lcd.setColor(0,0,0);
//LCD.drawImage(img, new AffineTransform(1f, 0f, 0f, 1f, 0, 0), null);
//LCD.drawImage(image, 40,40, null);
lcd.drawImage(cross,40,40,0);
//LCD.drawImage(img, 0,0, Color.WHITE, null);
lcd.drawImage(nought, 0,0,0);
lcd.refresh();
Delay.msDelay(5000);
}
public static void clear() {
//lcd.setColor(Color.WHITE);
lcd.setColor(255, 255, 255);
lcd.fillRect(0, 0, lcd.getWidth(), lcd.getHeight());
}
}
|
package filter.expression;
public class SortKey {
public final String key;
public final boolean inverted;
public SortKey(String key, boolean inverted) {
this.key = key;
this.inverted = inverted;
}
@Override
public String toString() {
return (inverted ? "~" : "") + key;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
SortKey sortKey = (SortKey) o;
if (inverted != sortKey.inverted) return false;
if (key != null ? !key.equals(sortKey.key) : sortKey.key != null) return false;
return true;
}
@Override
public int hashCode() {
int result = key != null ? key.hashCode() : 0;
result = 31 * result + (inverted ? 1 : 0);
return result;
}
}
|
package io.scif.img;
import io.scif.FormatException;
import io.scif.ImageMetadata;
import io.scif.Metadata;
import io.scif.img.cell.SCIFIOCellImg;
import java.io.IOException;
import net.imagej.ImgPlus;
import net.imagej.ImgPlusMetadata;
import net.imagej.axis.AxisType;
import net.imagej.axis.CalibratedAxis;
import net.imglib2.display.ColorTable;
import net.imglib2.img.Img;
import org.scijava.Disposable;
/**
* SCIFIO extension of {@link ImgPlus} that adds
* {@link #getColorTable(int, int)} API for specifying both the plane and image
* index.
* <p>
* Also provides direct access to the {@link Metadata} object associated with
* the underlying dataset.
* </p>
*
* @author Mark Hiner
*/
public class SCIFIOImgPlus<T> extends ImgPlus<T> implements Disposable {
// -- Constants --
public static final String GLOBAL_META = "scifio.metadata.global";
public static final String IMAGE_META = "scifio.metadata.image";
// -- Constructors --
public SCIFIOImgPlus(final Img<T> img) {
super(img);
}
public SCIFIOImgPlus(final Img<T> img, final String name) {
super(img, name);
}
public SCIFIOImgPlus(final Img<T> img, final String name,
final AxisType[] axes)
{
super(img, name, axes);
}
public SCIFIOImgPlus(final Img<T> img, final ImgPlusMetadata metadata) {
super(img, metadata);
}
public SCIFIOImgPlus(final Img<T> img, final String name,
final AxisType[] axes, final double[] cal)
{
super(img, name, axes, cal);
}
public SCIFIOImgPlus(final ImgPlus<T> imgPlus) {
this(imgPlus.getImg(), imgPlus.getName(), getTypes(imgPlus));
}
// -- SCIFIOImgPlus Methods --
/**
* @return The SCIFIO {@link Metadata} object attached to this ImgPlus.
*/
public Metadata getMetadata() {
return (Metadata) getProperties().get(GLOBAL_META);
}
/**
* Sets the {@link Metadata} object for this ImgPlus.
*/
public void setMetadata(final Metadata meta) {
getProperties().put(GLOBAL_META, meta);
}
/**
* @return The SCIFIO {@link ImageMetadata} object attached to this ImgPlus.
*/
public ImageMetadata getImageMetadata() {
return (ImageMetadata) getProperties().get(IMAGE_META);
}
/**
* Sets the {@link ImageMetadata} object for this ImgPlus.
*/
public void setImageMetadata(final ImageMetadata imageMeta) {
getProperties().put(IMAGE_META, imageMeta);
}
// -- ImgPlus Methods --
@Override
public ColorTable getColorTable(final int planeIndex) {
return getColorTable(0, planeIndex);
}
/**
* @param imageIndex - Image index to look up the color table
* @param planeIndex - Plane index of the desired color table
* @return The ColorTable of the underlying dataset at the specified indices.
*/
public ColorTable getColorTable(final int imageIndex, final int planeIndex) {
ColorTable table = super.getColorTable(planeIndex);
if (table == null &&
SCIFIOCellImg.class.isAssignableFrom(getImg().getClass()))
{
try {
table =
((SCIFIOCellImg<?, ?, ?>) getImg()).getColorTable(imageIndex,
planeIndex);
}
catch (final FormatException e) {
return null;
}
catch (final IOException e) {
return null;
}
setColorTable(table, planeIndex);
}
return table;
}
@Override
public SCIFIOImgPlus<T> copy() {
final SCIFIOImgPlus<T> copy = new SCIFIOImgPlus<T>(getImg().copy(), this);
copy.setMetadata(getMetadata());
return copy;
}
// -- Disposable methods --
@Override
public void dispose() {
if (getImg() instanceof SCIFIOCellImg) {
((SCIFIOCellImg) getImg()).dispose();
}
}
// -- Helper methods --
/**
* @return An array of {@link AxisType} corresponding to the axes of the
* provided {@link ImgPlus}.
*/
private static AxisType[] getTypes(final ImgPlus<?> imgPlus) {
final AxisType[] types = new AxisType[imgPlus.numDimensions()];
for (int i = 0; i < types.length; i++) {
types[i] = imgPlus.axis(i).type();
}
return types;
}
}
|
package org.cactoos.scalar;
import java.io.IOException;
import java.util.Iterator;
import org.cactoos.Func;
import org.cactoos.Scalar;
import org.cactoos.text.FormattedText;
/**
* Element from position in {@link Iterator}
* or fallback value if iterator hasn't this position.
*
* <p>There is no thread-safety guarantee.
*
* @author Ilia Rogozhin (ilia.rogozhin@gmail.com)
* @version $Id$
* @param <T> Scalar type
* @since 0.7
*/
public final class ItemAt<T> implements Scalar<T> {
/**
* {@link StickyScalar} that holds the value of the iterator
* at the position specified in the constructor.
*/
private final Scalar<T> saved;
/**
* Ctor.
*
* @param source Iterable
*/
public ItemAt(final Iterable<T> source) {
this(
source,
itr -> {
throw new IOException("The iterable is empty");
}
);
}
/**
* Ctor.
*
* @param fallback Fallback value
* @param source Iterable
*/
public ItemAt(final T fallback, final Iterable<T> source) {
this(source, itr -> fallback);
}
/**
* Ctor.
*
* @param fallback Fallback value
* @param source Iterable
*/
public ItemAt(
final Iterable<T> source,
final Func<Iterable<T>, T> fallback
) {
this(source, 0, fallback);
}
/**
* Ctor.
*
* @param position Position
* @param source Iterable
*/
public ItemAt(final int position, final Iterable<T> source) {
this(
source,
position,
itr -> {
throw new IOException(
new FormattedText(
"The iterable doesn't have the position
position
).asString()
);
}
);
}
/**
* Ctor.
*
* @param position Position
* @param source Iterable
* @since 0.21
*/
public ItemAt(final int position, final Iterator<T> source) {
this(position, () -> source);
}
/**
* Ctor.
*
* @param source Iterable
* @param position Position
* @param fallback Fallback value
*/
public ItemAt(
final Iterable<T> source,
final int position,
final Func<Iterable<T>, T> fallback
) {
this(new StickyScalar<>(source::iterator), position, fallback);
}
/**
* Ctor.
*
* @param iterator Iterator
*/
public ItemAt(final Iterator<T> iterator) {
this(
iterator,
itr -> {
throw new IOException("Iterator is empty");
}
);
}
/**
* Ctor.
*
* @param iterator Iterator
* @param fallback Fallback value
*/
public ItemAt(final Iterator<T> iterator, final T fallback) {
this(iterator, itr -> fallback);
}
/**
* Ctor.
*
* @param iterator Iterator
* @param fallback Fallback value
*/
public ItemAt(
final Iterator<T> iterator,
final Func<Iterable<T>, T> fallback
) {
this(iterator, 0, fallback);
}
/**
* Ctor.
*
* @param iterator Iterator
* @param position Position
*/
public ItemAt(final Iterator<T> iterator, final int position) {
this(
iterator,
position,
itr -> {
throw new IOException(
new FormattedText(
"Iterator doesn't have an element at #%d position",
position
).asString()
);
}
);
}
/**
* Ctor.
*
* @param iterator Iterator
* @param position Position
* @param fallback Fallback value
*/
public ItemAt(
final Iterator<T> iterator,
final int position,
final Func<Iterable<T>, T> fallback
) {
this(new StickyScalar<>(() -> iterator), position, fallback);
}
/**
* Ctor.
*
* @param iterator Iterator
* @param position Position
* @param fallback Fallback value
*/
private ItemAt(
final Scalar<Iterator<T>> iterator,
final int position,
final Func<Iterable<T>, T> fallback
) {
this.saved = new StickyScalar<T>(
() -> {
final T ret;
if (position < 0) {
throw new IOException(
new FormattedText(
"The position must be non-negative: %d",
position
).asString()
);
}
final Iterator<T> src = iterator.value();
int cur;
for (cur = 0; cur < position && src.hasNext(); ++cur) {
src.next();
}
if (cur == position && src.hasNext()) {
ret = src.next();
} else {
ret = fallback.apply(() -> src);
}
return ret;
}
);
}
@Override
public T value() throws Exception {
return this.saved.value();
}
}
|
package org.jfree.data.time;
import org.jfree.chart.date.MonthConstants;
import org.jfree.chart.date.SerialDate;
import java.io.Serializable;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;
/**
* Represents a single month. This class is immutable, which is a requirement
* for all {@link RegularTimePeriod} subclasses.
*/
public class Month extends RegularTimePeriod implements Serializable {
/** For serialization. */
private static final long serialVersionUID = -5090216912548722570L;
/** The month (1-12). */
private int month;
/** The year in which the month falls. */
private int year;
/** The first millisecond. */
private long firstMillisecond;
/** The last millisecond. */
private long lastMillisecond;
/**
* Constructs a new Month, based on the current system time.
*/
public Month() {
this(new Date());
}
/**
* Constructs a new month instance.
*
* @param month the month (in the range 1 to 12).
* @param year the year.
*/
public Month(int month, int year) {
if ((month < 1) || (month > 12)) {
throw new IllegalArgumentException("Month outside valid range.");
}
this.month = month;
this.year = year;
peg(Calendar.getInstance());
}
/**
* Constructs a new month instance.
*
* @param month the month (in the range 1 to 12).
* @param year the year.
*/
public Month(int month, Year year) {
if ((month < 1) || (month > 12)) {
throw new IllegalArgumentException("Month outside valid range.");
}
this.month = month;
this.year = year.getYear();
peg(Calendar.getInstance());
}
/**
* Constructs a new <code>Month</code> instance, based on a date/time and
* the default time zone.
*
* @param time the date/time (<code>null</code> not permitted).
*
* @see #Month(Date, TimeZone, Locale)
*/
public Month(Date time) {
this(time, TimeZone.getDefault(), Locale.getDefault());
}
/**
* Creates a new <code>Month</code> instance, based on the specified time,
* zone and locale.
*
* @param time the current time.
* @param zone the time zone.
* @param locale the locale.
*
* @since 1.0.12
*/
public Month(Date time, TimeZone zone, Locale locale) {
Calendar calendar = Calendar.getInstance(zone, locale);
calendar.setTime(time);
this.month = calendar.get(Calendar.MONTH) + 1;
this.year = calendar.get(Calendar.YEAR);
peg(calendar);
}
/**
* Returns the year in which the month falls.
*
* @return The year in which the month falls (as a Year object).
*/
public Year getYear() {
return new Year(this.year);
}
/**
* Returns the year in which the month falls.
*
* @return The year in which the month falls (as an int).
*/
public int getYearValue() {
return this.year;
}
/**
* Returns the month. Note that 1=JAN, 2=FEB, ...
*
* @return The month.
*/
public int getMonth() {
return this.month;
}
/**
* Returns the first millisecond of the month. This will be determined
* relative to the time zone specified in the constructor, or in the
* calendar instance passed in the most recent call to the
* {@link #peg(Calendar)} method.
*
* @return The first millisecond of the month.
*
* @see #getLastMillisecond()
*/
@Override
public long getFirstMillisecond() {
return this.firstMillisecond;
}
/**
* Returns the last millisecond of the month. This will be
* determined relative to the time zone specified in the constructor, or
* in the calendar instance passed in the most recent call to the
* {@link #peg(Calendar)} method.
*
* @return The last millisecond of the month.
*
* @see #getFirstMillisecond()
*/
@Override
public long getLastMillisecond() {
return this.lastMillisecond;
}
/**
* Recalculates the start date/time and end date/time for this time period
* relative to the supplied calendar (which incorporates a time zone).
*
* @param calendar the calendar (<code>null</code> not permitted).
*
* @since 1.0.3
*/
@Override
public void peg(Calendar calendar) {
this.firstMillisecond = getFirstMillisecond(calendar);
this.lastMillisecond = getLastMillisecond(calendar);
}
/**
* Returns the month preceding this one. Note that the returned
* {@link Month} is "pegged" using the default time-zone, irrespective of
* the time-zone used to peg of the current month (which is not recorded
* anywhere). See the {@link #peg(Calendar)} method.
*
* @return The month preceding this one.
*/
@Override
public RegularTimePeriod previous() {
Month result;
if (this.month != MonthConstants.JANUARY) {
result = new Month(this.month - 1, this.year);
}
else {
if (this.year > 1900) {
result = new Month(MonthConstants.DECEMBER, this.year - 1);
}
else {
result = null;
}
}
return result;
}
/**
* Returns the month following this one. Note that the returned
* {@link Month} is "pegged" using the default time-zone, irrespective of
* the time-zone used to peg of the current month (which is not recorded
* anywhere). See the {@link #peg(Calendar)} method.
*
* @return The month following this one.
*/
@Override
public RegularTimePeriod next() {
Month result;
if (this.month != MonthConstants.DECEMBER) {
result = new Month(this.month + 1, this.year);
}
else {
if (this.year < 9999) {
result = new Month(MonthConstants.JANUARY, this.year + 1);
}
else {
result = null;
}
}
return result;
}
/**
* Returns a serial index number for the month.
*
* @return The serial index number.
*/
@Override
public long getSerialIndex() {
return this.year * 12L + this.month;
}
/**
* Returns a string representing the month (e.g. "January 2002").
* <P>
* To do: look at internationalisation.
*
* @return A string representing the month.
*/
@Override
public String toString() {
return SerialDate.monthCodeToString(this.month) + " " + this.year;
}
/**
* Tests the equality of this Month object to an arbitrary object.
* Returns true if the target is a Month instance representing the same
* month as this object. In all other cases, returns false.
*
* @param obj the object (<code>null</code> permitted).
*
* @return <code>true</code> if month and year of this and object are the
* same.
*/
@Override
public boolean equals(Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof Month)) {
return false;
}
Month that = (Month) obj;
if (this.month != that.month) {
return false;
}
if (this.year != that.year) {
return false;
}
return true;
}
@Override
public int hashCode() {
int result = 17;
result = 37 * result + this.month;
result = 37 * result + this.year;
return result;
}
/**
* Returns an integer indicating the order of this Month object relative to
* the specified
* object: negative == before, zero == same, positive == after.
*
* @param o1 the object to compare.
*
* @return negative == before, zero == same, positive == after.
*/
@Override
public int compareTo(TimePeriod o1) {
int result;
// CASE 1 : Comparing to another Month object
if (o1 instanceof Month) {
Month m = (Month) o1;
result = this.year - m.getYearValue();
if (result == 0) {
result = this.month - m.getMonth();
}
}
// CASE 2 : Comparing to another TimePeriod object
else {
// more difficult case - evaluate later...
result = 0;
}
return result;
}
/**
* Returns the first millisecond of the month, evaluated using the supplied
* calendar (which determines the time zone).
*
* @param calendar the calendar (<code>null</code> not permitted).
*
* @return The first millisecond of the month.
*
* @throws NullPointerException if <code>calendar</code> is
* <code>null</code>.
*/
@Override
public long getFirstMillisecond(Calendar calendar) {
calendar.set(this.year, this.month - 1, 1, 0, 0, 0);
calendar.set(Calendar.MILLISECOND, 0);
return calendar.getTimeInMillis();
}
/**
* Returns the last millisecond of the month, evaluated using the supplied
* calendar (which determines the time zone).
*
* @param calendar the calendar (<code>null</code> not permitted).
*
* @return The last millisecond of the month.
*
* @throws NullPointerException if <code>calendar</code> is
* <code>null</code>.
*/
@Override
public long getLastMillisecond(Calendar calendar) {
int eom = SerialDate.lastDayOfMonth(this.month, this.year);
calendar.set(this.year, this.month - 1, eom, 23, 59, 59);
calendar.set(Calendar.MILLISECOND, 999);
return calendar.getTimeInMillis();
}
/**
* Parses the string argument as a month. This method is required to
* accept the format "YYYY-MM". It will also accept "MM-YYYY". Anything
* else, at the moment, is a bonus.
*
* @param s the string to parse (<code>null</code> permitted).
*
* @return <code>null</code> if the string is not parseable, the month
* otherwise.
*/
public static Month parseMonth(String s) {
Month result = null;
if (s == null) {
return result;
}
// trim whitespace from either end of the string
s = s.trim();
int i = Month.findSeparator(s);
String s1, s2;
boolean yearIsFirst;
// if there is no separator, we assume the first four characters
// are YYYY
if (i == -1) {
yearIsFirst = true;
s1 = s.substring(0, 5);
s2 = s.substring(5);
}
else {
s1 = s.substring(0, i).trim();
s2 = s.substring(i + 1, s.length()).trim();
// now it is trickier to determine if the month or year is first
Year y1 = Month.evaluateAsYear(s1);
if (y1 == null) {
yearIsFirst = false;
}
else {
Year y2 = Month.evaluateAsYear(s2);
if (y2 == null) {
yearIsFirst = true;
}
else {
yearIsFirst = (s1.length() > s2.length());
}
}
}
Year year;
int month;
if (yearIsFirst) {
year = Month.evaluateAsYear(s1);
month = SerialDate.stringToMonthCode(s2);
}
else {
year = Month.evaluateAsYear(s2);
month = SerialDate.stringToMonthCode(s1);
}
if (month == -1) {
throw new TimePeriodFormatException("Can't evaluate the month.");
}
if (year == null) {
throw new TimePeriodFormatException("Can't evaluate the year.");
}
result = new Month(month, year);
return result;
}
/**
* Finds the first occurrence of '-', or if that character is not found,
* the first occurrence of ',', or the first occurrence of ' ' or '.'
*
* @param s the string to parse.
*
* @return The position of the separator character, or <code>-1</code> if
* none of the characters were found.
*/
private static int findSeparator(String s) {
int result = s.indexOf('-');
if (result == -1) {
result = s.indexOf(',');
}
if (result == -1) {
result = s.indexOf(' ');
}
if (result == -1) {
result = s.indexOf('.');
}
return result;
}
/**
* Creates a year from a string, or returns <code>null</code> (format
* exceptions suppressed).
*
* @param s the string to parse.
*
* @return <code>null</code> if the string is not parseable, the year
* otherwise.
*/
private static Year evaluateAsYear(String s) {
Year result = null;
try {
result = Year.parseYear(s);
}
catch (TimePeriodFormatException e) {
// suppress
}
return result;
}
}
|
package org.lantern;
import java.io.IOException;
import java.net.InetAddress;
import java.util.Collection;
import org.apache.commons.lang.StringUtils;
import org.lastbamboo.common.stun.client.PublicIpAddress;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.collect.Sets;
import com.maxmind.geoip.Country;
public class CensoredUtils {
private static final Logger LOG =
LoggerFactory.getLogger(CensoredUtils.class);
/**
* Censored country codes, in order of population.
*/
/*
private static final Collection<String> CENSORED =
Sets.newHashSet(
// Asia
"CN",
"VN",
"MM",
//Mideast:
"IR",
"BH", // Bahrain
"YE", // Yemen
"SA", // Saudi Arabia
"SY",
//Eurasia:
"UZ", // Uzbekistan
"TM", // Turkmenistan
//Africa:
"ET", // Ethiopia
"ER", // Eritrea
// LAC:
"CU");
*/
// These country codes have US export restrictions, and therefore cannot
// access App Engine sites.
private static final Collection<String> EXPORT_RESTRICTED =
Sets.newHashSet(
"SY");
private static String countryCode;
public static String countryCode() {
if (StringUtils.isNotBlank(countryCode)) {
LOG.info("Returning cached country code: {}", countryCode);
return countryCode;
}
LOG.info("Returning country code: {}", countryCode);
countryCode = countryCode(new PublicIpAddress().getPublicIpAddress());
return countryCode;
}
public static String countryCode(final InetAddress address) {
final Country country = LanternHub.getGeoIpLookup().getCountry(address);
LOG.info("Country is: {}", country.getName());
return country.getCode().trim();
}
public static boolean isCensored() {
return isCensored(new PublicIpAddress().getPublicIpAddress());
}
public static boolean isCensored(final InetAddress address) {
return isMatch(address, StatsTracker.CENSORED);
}
public static boolean isCensored(final String address) throws IOException {
return isCensored(InetAddress.getByName(address));
}
public static boolean isExportRestricted() {
return isExportRestricted(new PublicIpAddress().getPublicIpAddress());
}
public static boolean isExportRestricted(final InetAddress address) {
return isMatch(address, EXPORT_RESTRICTED);
}
public static boolean isExportRestricted(final String address)
throws IOException {
return isExportRestricted(InetAddress.getByName(address));
}
public static boolean isMatch(final InetAddress address,
final Collection<String> countries) {
final Country country = LanternHub.getGeoIpLookup().getCountry(address);
LOG.info("Country is: {}", country.getName());
final String cc = country.getCode().trim();
return countries.contains(cc);
}
public static boolean isCensored(final Country country) {
final String cc = country.getCode().trim();
return StatsTracker.CENSORED.contains(cc);
}
public static boolean isForceCensored() {
final boolean force =
LanternUtils.getBooleanProperty(LanternConstants.FORCE_CENSORED);
LOG.info("Forcing proxy: "+force);
return force;
}
public static void forceCensored() {
LanternUtils.setBooleanProperty(LanternConstants.FORCE_CENSORED, true);
}
public static void unforceCensored() {
LanternUtils.setBooleanProperty(LanternConstants.FORCE_CENSORED, false);
}
}
|
package org.lantern.pubsub;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;
import java.nio.ByteBuffer;
import java.nio.charset.Charset;
import java.security.KeyStore;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.util.Collections;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManagerFactory;
import org.msgpack.core.MessageFormat;
import org.msgpack.core.MessagePack;
import org.msgpack.core.MessagePacker;
import org.msgpack.core.MessageUnpacker;
/**
* A client for Lantern's pubsub infrastructure.
*/
public class Client implements Runnable {
private static final Charset UTF8 = Charset.forName("UTF-8");
private static final Runnable NOOP = new Runnable() {
public void run() {
};
};
private final ClientConfig cfg;
private final LinkedBlockingQueue<Runnable> outQueue =
new LinkedBlockingQueue<Runnable>(1);
private final LinkedBlockingQueue<Message> in =
new LinkedBlockingQueue<Message>(1);
private final ScheduledExecutorService scheduledExecutor = Executors
.newSingleThreadScheduledExecutor();
private final Set<ByteBuffer> subscriptions = Collections
.newSetFromMap(new ConcurrentHashMap<ByteBuffer, Boolean>());
private volatile Socket socket;
private volatile MessagePacker packer;
private volatile ScheduledFuture<?> nextKeepalive;
private final AtomicBoolean forceReconnect = new AtomicBoolean();
public static class ClientConfig {
private final String host;
private final int port;
public String authenticationKey;
public long backoffBase;
public long maxBackoff;
public long keepalivePeriod;
public ClientConfig(String host, int port) {
this.host = host;
this.port = port;
}
private Socket dial() throws IOException {
return sslContext.getSocketFactory().createSocket(host, port);
}
}
public Client(ClientConfig cfg) {
// Apply sensible defaults
if (cfg.backoffBase == 0) {
cfg.backoffBase = 1000; // 1 second
}
if (cfg.maxBackoff == 0) {
cfg.maxBackoff = 60 * 1000; // 1 minute
}
if (cfg.keepalivePeriod == 0) {
cfg.keepalivePeriod = 20 * 1000; // 20 seconds
}
this.cfg = cfg;
Thread thread = new Thread(this, "Client");
thread.setDaemon(true);
thread.start();
}
public static byte[] utf8(String str) {
return str == null ? null : str.getBytes(UTF8);
}
public static String fromUTF8(byte[] bytes) {
return bytes == null ? null : new String(bytes, UTF8);
}
public Message read() throws InterruptedException {
return in.take();
}
public Message readTimeout(long timeout, TimeUnit unit)
throws InterruptedException {
return in.poll(timeout, unit);
}
public void subscribe(byte[] topic) throws InterruptedException {
subscriptions.add(ByteBuffer.wrap(topic));
new Sendable(this, new Message(Type.Subscribe, topic, null)).send();
}
public void unsubscribe(byte[] topic) throws InterruptedException {
subscriptions.remove(ByteBuffer.wrap(topic));
new Sendable(this, new Message(Type.Unsubscribe, topic, null)).send();
}
public void publish(byte[] topic, byte[] body) throws InterruptedException {
new Sendable(this, new Message(Type.Publish, topic, body)).send();
}
public void run() {
forceConnect();
try {
process();
} catch (InterruptedException ie) {
throw new RuntimeException("Interrupted while processing", ie);
}
}
private void process() throws InterruptedException {
while (true) {
doWithConnection(outQueue.take());
}
}
private void doWithConnection(Runnable op) throws InterruptedException {
for (int numFailures = 0; numFailures < Integer.MAX_VALUE; numFailures++) {
// Back off if necessary
if (numFailures > 0) {
long backoff = (long) (Math.pow(cfg.backoffBase, numFailures));
backoff = Math.min(backoff, cfg.maxBackoff);
Thread.sleep(backoff);
}
boolean force = forceReconnect.compareAndSet(true, false);
boolean socketNull = socket == null;
if (force || socketNull) {
close();
// Dial
try {
// Dial
socket = cfg.dial();
packer = MessagePack
.newDefaultPacker(new BufferedOutputStream(socket
.getOutputStream()));
sendInitialMessages();
final InputStream in = socket.getInputStream();
// Start read loop
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
readLoop(MessagePack.newDefaultUnpacker(in));
}
}, "Client-ReadLoop");
thread.setDaemon(true);
thread.start();
// Success
return;
} catch (Exception e) {
e.printStackTrace();
close();
continue;
}
}
try {
// Run the op
op.run();
// Success
return;
} catch (Exception e) {
e.printStackTrace();
close();
}
}
}
private void sendInitialMessages() throws IOException, InterruptedException {
if (cfg.authenticationKey != null) {
new Sendable(this, new Message(Type.Authenticate, null,
utf8(cfg.authenticationKey))).sendImmediate();
}
for (ByteBuffer topic : subscriptions) {
new Sendable(this, new Message(Type.Subscribe, topic.array(), null))
.sendImmediate();
}
}
private void readLoop(MessageUnpacker in) {
try {
doReadLoop(in);
} catch (Exception e) {
e.printStackTrace();
forceReconnect.set(true);
forceConnect();
}
}
private void doReadLoop(MessageUnpacker in) throws IOException,
InterruptedException {
while (in.hasNext()) {
if (in.getNextFormat() == MessageFormat.NIL) {
in.skipValue();
continue;
}
byte type = in.unpackByte();
if (type == Type.KeepAlive) {
// KeepAlive messages only contain the type, and we ignore them
continue;
}
Message msg = new Message();
msg.setType(type);
msg.setTopic(unpackByteArray(in));
msg.setBody(unpackByteArray(in));
this.in.put(msg);
}
}
private void forceConnect() {
outQueue.offer(NOOP);
}
private final Runnable sendKeepalive = new Runnable() {
public void run() {
outQueue.offer(new Sendable(Client.this, new Message(
Type.KeepAlive, null, null)));
}
};
private synchronized void resetKeepalive() {
if (nextKeepalive != null) {
nextKeepalive.cancel(false);
}
nextKeepalive = scheduledExecutor.schedule(sendKeepalive,
cfg.keepalivePeriod,
TimeUnit.MILLISECONDS);
}
private void close() {
if (socket != null) {
try {
packer.close();
} catch (Exception e) {
// ignore exception on close
}
socket = null;
packer = null;
}
}
private static class Sendable implements Runnable {
private final Client client;
private final Message msg;
public Sendable(Client client, Message msg) {
super();
this.client = client;
this.msg = msg;
}
private void send() throws InterruptedException {
client.outQueue.put(this);
}
public void run() {
try {
sendImmediate();
} catch (IOException ioe) {
throw new RuntimeException("Unable to send message: "
+ ioe.getMessage(), ioe);
}
}
private void sendImmediate() throws IOException {
client.resetKeepalive();
client.packer.packByte(msg.getType());
if (msg.getType() != Type.KeepAlive) {
// Only non-KeepAlive messages contain a topic and body
packByteArray(msg.getTopic());
packByteArray(msg.getBody());
}
client.packer.flush();
}
private void packByteArray(byte[] bytes) throws IOException {
if (bytes == null) {
client.packer.packNil();
} else {
client.packer.packBinaryHeader(bytes.length);
client.packer.writePayload(bytes);
}
}
}
private static byte[] unpackByteArray(MessageUnpacker in)
throws IOException {
if (MessageFormat.NIL == in.getNextFormat()) {
in.skipValue();
return null;
}
int length = in.unpackBinaryHeader();
byte[] result = new byte[length];
in.readPayload(result);
return result;
}
// pubsub.lantern.io uses a certificate from letsencrypt. The root
// certificates for letsencrypt are not part of Java's standard trust store,
// so we're loading it explicitly.
// See
// See
private static final SSLContext sslContext;
static {
try {
KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
ks.load(null, null);
addCertificate(ks, "isrgrootx1", "isrgrootx1.pem");
addCertificate(ks, "letsencryptauthorityx1",
"letsencryptauthorityx1.der");
addCertificate(ks, "letsencryptauthorityx2",
"letsencryptauthorityx2.der");
addCertificate(ks, "lets-encrypt-x2-cross-signed",
"lets-encrypt-x2-cross-signed.der");
TrustManagerFactory tmf = TrustManagerFactory
.getInstance(TrustManagerFactory.getDefaultAlgorithm());
tmf.init(ks);
sslContext = SSLContext.getInstance("TLS");
sslContext.init(null, tmf.getTrustManagers(), null);
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException("Unable to initialize sslContext: "
+ e.getMessage(), e);
}
}
private static void addCertificate(KeyStore ks, String alias, String file)
throws Exception {
InputStream in = Client.class.getResourceAsStream(file);
X509Certificate cert = (X509Certificate) CertificateFactory
.getInstance("X.509")
.generateCertificate(in);
ks.setCertificateEntry(alias, cert);
}
}
|
package org.lantern.state;
import java.io.File;
import java.io.IOException;
import java.security.GeneralSecurityException;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.json.simple.JSONObject;
import org.json.simple.JSONValue;
import org.lantern.Cli;
import org.lantern.Country;
import org.lantern.CountryService;
import org.lantern.LanternClientConstants;
import org.lantern.LanternUtils;
import org.lantern.event.Events;
import org.lantern.event.RefreshTokenEvent;
import org.lantern.privacy.EncryptedFileService;
import org.lantern.privacy.InvalidKeyException;
import org.lantern.privacy.LocalCipherProvider;
import org.lastbamboo.common.offer.answer.IceConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.inject.Inject;
import com.google.inject.Singleton;
@Singleton
public class ModelIo extends Storage<Model> {
private final Logger log = LoggerFactory.getLogger(getClass());
private final CountryService countryService;
private final CommandLine commandLine;
private LocalCipherProvider localCipherProvider;
/**
* Creates a new instance with all the default operations.
*/
@Inject
public ModelIo(final EncryptedFileService encryptedFileService,
final Transfers transfers, final CountryService countryService,
final CommandLine commandLine,
final LocalCipherProvider lcp) {
this(LanternClientConstants.DEFAULT_MODEL_FILE, encryptedFileService,
transfers, countryService, commandLine, lcp);
}
/**
* Creates a new instance with custom settings typically used only in
* testing.
*
* @param modelFile The file where settings are stored.
* @param commandLine The command line arguments.
* @param localCipherProvider The local cipher provider for accessing
* encrypted data on disk.
*/
public ModelIo(final File modelFile,
final EncryptedFileService encryptedFileService, Transfers transfers,
final CountryService countryService, final CommandLine commandLine,
final LocalCipherProvider localCipherProvider) {
super(encryptedFileService, modelFile, Model.class);
this.countryService = countryService;
this.commandLine = commandLine;
this.localCipherProvider = localCipherProvider;
obj = read();
obj.setTransfers(transfers);
log.info("Loaded module");
}
/**
* Reads the state model from disk.
*
* @return The {@link Model} instance as read from disk.
*/
@Override
public Model read() {
try {
final Model read = super.read();
read.setCountryService(countryService);
if (!LanternUtils.persistCredentials()) {
if (read.getModal() != Modal.welcome) {
read.setModal(Modal.authorize);
}
}
// Make sure all peers are considered offline at startup.
final Peers peers = read.getPeerCollector();
peers.reset();
if (read.getModal() == Modal.settingsLoadFailure) {
read.setModal(Modal.none);
}
boolean isCensored = false;
String countryCode = read.getLocation().getCountry();
if (countryCode != null) {
Country country = countryService.getCountryByCode(countryCode);
if (country != null) {
isCensored = country.isCensors();
}
}
if (!isCensored && read.getModal() == Modal.giveModeForbidden) {
read.setModal(Modal.none);
}
LanternUtils.setModel(read);
processCommandLine(this.commandLine, read);
return read;
} catch (final ModelReadFailedException e) {
log.error("Failed to read model", e);
Model blank = blank();
blank.setModal(Modal.settingsLoadFailure);
return blank;
} catch (final Exception e) {
log.error("Failed to read model for some other reason", e);
Model blank = blank();
return blank;
}
}
/**
* We need to make sure to set the server port before anything is
* injected -- otherwise we run the risk of running on a completely
* different port than what is passed on the command line!
*
* @param cmd The command line.
* @param read The model
*/
private void processCommandLine(final CommandLine cmd, final Model model) {
if (cmd == null) {
// Can be true for testing.
log.error("No command line?");
return;
}
final Settings set = model.getSettings();
if (cmd.hasOption(Cli.OPTION_SERVER_PORT)) {
final String serverPortStr =
cmd.getOptionValue(Cli.OPTION_SERVER_PORT);
log.debug("Using command-line proxy port: "+serverPortStr);
final int serverPort = Integer.parseInt(serverPortStr);
set.setServerPort(serverPort);
} else {
final int existing = set.getServerPort();
if (existing < 1024) {
log.debug("Using random give mode proxy port...");
set.setServerPort(LanternUtils.randomPort());
}
}
log.info("Running give mode proxy on port: {}", set.getServerPort());
if (cmd.hasOption(Cli.OPTION_KEYSTORE)) {
LanternUtils.setFallbackKeystorePath(cmd.getOptionValue(Cli.OPTION_KEYSTORE));
}
final String ctrlOpt = Cli.OPTION_CONTROLLER_ID;
if (cmd.hasOption(ctrlOpt)) {
LanternClientConstants.setControllerId(
cmd.getOptionValue(ctrlOpt));
}
final String insOpt = Cli.OPTION_INSTANCE_ID;
if (cmd.hasOption(insOpt)) {
model.setInstanceId(cmd.getOptionValue(insOpt));
}
final String fbOpt = Cli.OPTION_AS_FALLBACK;
if (cmd.hasOption(fbOpt)) {
LanternUtils.setFallbackProxy(true);
}
final String secOpt = Cli.OPTION_OAUTH2_CLIENT_SECRETS_FILE;
if (cmd.hasOption(secOpt)) {
loadOAuth2ClientSecretsFile(cmd.getOptionValue(secOpt), set);
}
final String credOpt = Cli.OPTION_OAUTH2_USER_CREDENTIALS_FILE;
if (cmd.hasOption(credOpt)) {
loadOAuth2UserCredentialsFile(cmd.getOptionValue(credOpt), set);
}
final String ripOpt = Cli.OPTION_REPORT_IP;
if (cmd.hasOption(ripOpt)) {
model.setReportIp(cmd.getOptionValue(ripOpt));
}
//final Settings set = LanternHub.settings();
set.setUseTrustedPeers(parseOptionDefaultTrue(cmd, Cli.OPTION_TRUSTED_PEERS));
set.setUseAnonymousPeers(parseOptionDefaultTrue(cmd, Cli.OPTION_ANON_PEERS));
set.setUseLaeProxies(parseOptionDefaultTrue(cmd, Cli.OPTION_LAE));
set.setUseCentralProxies(parseOptionDefaultTrue(cmd, Cli.OPTION_CENTRAL));
set.setUdpProxyPriority(cmd.getOptionValue(Cli.OPTION_UDP_PROXY_PRIORITY, "lower").toUpperCase());
final boolean tcp = parseOptionDefaultTrue(cmd, Cli.OPTION_TCP);
final boolean udp = parseOptionDefaultTrue(cmd, Cli.OPTION_UDP);
IceConfig.setTcp(tcp);
IceConfig.setUdp(udp);
set.setTcp(tcp);
set.setUdp(udp);
/*
if (cmd.hasOption(OPTION_USER)) {
set.setUserId(cmd.getOptionValue(OPTION_USER));
}
if (cmd.hasOption(OPTION_PASS)) {
set.(cmd.getOptionValue(OPTION_PASS));
}
*/
if (cmd.hasOption(Cli.OPTION_ACCESS_TOK)) {
set.setAccessToken(cmd.getOptionValue(Cli.OPTION_ACCESS_TOK));
}
if (cmd.hasOption(Cli.OPTION_REFRESH_TOK)) {
final String refresh = cmd.getOptionValue(Cli.OPTION_REFRESH_TOK);
set.setRefreshToken(refresh);
Events.asyncEventBus().post(new RefreshTokenEvent(refresh));
}
// option to disable use of keychains in local privacy
if (cmd.hasOption(Cli.OPTION_DISABLE_KEYCHAIN)) {
log.info("Disabling use of system keychains");
set.setKeychainEnabled(false);
}
else {
set.setKeychainEnabled(true);
}
if (cmd.hasOption(Cli.OPTION_PASSWORD_FILE)) {
loadLocalPasswordFile(cmd.getOptionValue(Cli.OPTION_PASSWORD_FILE));
}
if (cmd.hasOption(Cli.OPTION_PUBLIC_API)) {
set.setBindToLocalhost(false);
}
log.info("Running API on port: {}", StaticSettings.getApiPort());
if (cmd.hasOption(Cli.OPTION_LAUNCHD)) {
log.debug("Running from launchd or launchd set on command line");
model.setLaunchd(true);
} else {
model.setLaunchd(false);
}
if (cmd.hasOption(Cli.OPTION_GIVE)) {
model.getSettings().setMode(Mode.give);
} else if (cmd.hasOption(Cli.OPTION_GET)) {
model.getSettings().setMode(Mode.get);
}
}
private void loadOAuth2ClientSecretsFile(final String filename, final Settings set) {
if (StringUtils.isBlank(filename)) {
log.error("No filename specified");
throw new NullPointerException("No filename specified!");
}
final File file = new File(filename);
if (!(file.exists() && file.canRead())) {
log.error("Unable to read user credentials from {}", filename);
throw new IllegalArgumentException("File does not exist! "+filename);
}
log.debug("Reading client secrets from file \"{}\"", filename);
try {
final String json = FileUtils.readFileToString(file, "US-ASCII");
JSONObject obj = (JSONObject)JSONValue.parse(json);
final JSONObject ins;
final JSONObject temp = (JSONObject)obj.get("installed");
if (temp == null) {
ins = (JSONObject)obj.get("web");
} else {
ins = temp;
}
//JSONObject ins = (JSONObject)obj.get("installed");
final String clientID = (String)ins.get("client_id");
final String clientSecret = (String)ins.get("client_secret");
if (StringUtils.isBlank(clientID) ||
StringUtils.isBlank(clientSecret)) {
log.error("Failed to parse client secrets file \"{}\"", file);
throw new Error("Failed to parse client secrets file: "+ file);
} else {
set.setClientID(clientID);
set.setClientSecret(clientSecret);
}
} catch (final IOException e) {
log.error("Failed to read file \"{}\"", filename);
throw new Error("Could not load oauth file"+file, e);
}
}
public void loadOAuth2UserCredentialsFile(final String filename,
final Settings set) {
if (StringUtils.isBlank(filename)) {
log.error("No filename specified");
throw new NullPointerException("No filename specified!");
}
final File file = new File(filename);
if (!(file.exists() && file.canRead())) {
log.error("Unable to read user credentials from {}", filename);
throw new IllegalArgumentException("File does not exist! "+filename);
}
log.info("Reading user credentials from file \"{}\"", filename);
try {
final String json = FileUtils.readFileToString(file, "US-ASCII");
final JSONObject obj = (JSONObject)JSONValue.parse(json);
final String username = (String)obj.get("username");
final String accessToken = (String)obj.get("access_token");
final String refreshToken = (String)obj.get("refresh_token");
// Access token is not strictly necessary, so we allow it to be
// null.
if (StringUtils.isBlank(username) ||
StringUtils.isBlank(refreshToken)) {
log.error("Failed to parse user credentials file \"{}\"", filename);
throw new Error("Could not load username or refresh_token");
} else {
set.setAccessToken(accessToken);
set.setRefreshToken(refreshToken);
set.setUseGoogleOAuth2(true);
// We have to be careful here because classes simply haven't
// registered as listeners at this point, so listeners have
// to make sure to also check for an existing refresh token
// in the settings.
Events.asyncEventBus().post(new RefreshTokenEvent(refreshToken));
}
} catch (final IOException e) {
log.error("Failed to read file \"{}\"", filename);
throw new Error("Could not load oauth credentials", e);
}
}
private boolean parseOptionDefaultTrue(final CommandLine cmd,
final String option) {
if (cmd.hasOption(option)) {
log.info("Found option: "+option);
return false;
}
// DEFAULTS TO TRUE!!
return true;
}
private void loadLocalPasswordFile(final String pwFilename) {
//final LocalCipherProvider lcp = localCipherProvider;
if (!localCipherProvider.requiresAdditionalUserInput()) {
log.error("Settings do not require a password to unlock.");
System.exit(1);
}
if (StringUtils.isBlank(pwFilename)) {
log.error("No filename specified to --{}", Cli.OPTION_PASSWORD_FILE);
System.exit(1);
}
final File pwFile = new File(pwFilename);
if (!(pwFile.exists() && pwFile.canRead())) {
log.error("Unable to read password from {}", pwFilename);
System.exit(1);
}
log.info("Reading local password from file \"{}\"", pwFilename);
try {
final String pw = FileUtils.readLines(pwFile, "US-ASCII").get(0);
final boolean init = !localCipherProvider.isInitialized();
localCipherProvider.feedUserInput(pw.toCharArray(), init);
}
catch (final IndexOutOfBoundsException e) {
log.error("Password in file \"{}\" was incorrect", pwFilename);
System.exit(1);
}
catch (final InvalidKeyException e) {
log.error("Password in file \"{}\" was incorrect", pwFilename);
System.exit(1);
}
catch (final GeneralSecurityException e) {
log.error("Failed to initialize using password in file \"{}\": {}", pwFilename, e);
System.exit(1);
}
catch (final IOException e) {
log.error("Failed to initialize using password in file \"{}\": {}", pwFilename, e);
System.exit(1);
}
}
@Override
protected Model blank() {
log.info("Loading empty model!!");
final Model mod = new Model(countryService);
processCommandLine(this.commandLine, mod);
return mod;
}
/**
* Serializes the specified model -- useful for testing.
*/
@Override
public synchronized void write(final Model toWrite) {
final Settings set = toWrite.getSettings();
final String refresh = set.getRefreshToken();
final String access = set.getAccessToken();
final boolean useOauth = set.isUseGoogleOAuth2();
final boolean gtalk = toWrite.getConnectivity().isGtalkAuthorized();
if (!LanternUtils.persistCredentials()) {
set.setRefreshToken("");
set.setAccessToken("");
set.setUseGoogleOAuth2(false);
toWrite.getConnectivity().setGtalkAuthorized(false);
}
super.write(toWrite);
if (!LanternUtils.persistCredentials()) {
set.setRefreshToken(refresh);
set.setAccessToken(access);
set.setUseGoogleOAuth2(useOauth);
toWrite.getConnectivity().setGtalkAuthorized(gtalk);
}
}
public boolean reload() {
Model newModel = read();
newModel.setCountryService(countryService);
if (newModel.getModal() == Modal.welcome) {
//if modal is welcome, then we are dealing with fresh settings
return false;
}
obj.loadFrom(newModel);
return true;
}
}
|
package org.minimalj.util;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.logging.Logger;
/**
* Every main entity in a minimal-j model must have a public field named <code>id</code>.<p>
*
* This class provides get and set for this special field. It caches the
* reflection calls. Mostly it's used for minimal-j internal stuff.
*/
public class IdUtils {
private static final Logger logger = Logger.getLogger(IdUtils.class.getName());
private static final Map<Class<?>, Field> idFieldOfClass = new HashMap<>(200);
private static Field getIdField(Class<?> clazz) {
if (idFieldOfClass.containsKey(clazz)) {
return idFieldOfClass.get(clazz);
}
try {
Field idField = clazz.getField("id");
idFieldOfClass.put(clazz, idField);
return idField;
} catch (NoSuchFieldException e) {
idFieldOfClass.put(clazz, null);
return null;
} catch (SecurityException e) {
throw new LoggingRuntimeException(e, logger, "getting Id failed");
}
}
/**
* Check if a class has an <code>id</code> field
*
* @param clazz class to check. Must not be <code>null</code>
* @return true if the given class has a field named <code>id</code>
*/
public static boolean hasId(Class<?> clazz) {
return getIdField(clazz) != null;
}
/**
* Get the value of the <code>id</code> field
*
* @param object object containing the id. Must not be <code>null</code>
* @return the value of the <code>id</code> field
*/
public static Object getId(Object object) {
if (object != null) {
try {
Field idField = getIdField(object.getClass());
if (idField == null) throw new IllegalArgumentException(object.getClass().getName() + " has no id field to get");
Object id = idField.get(object);
return id;
} catch (SecurityException | IllegalAccessException e) {
throw new LoggingRuntimeException(e, logger, "getting Id failed");
}
} else {
throw new IllegalArgumentException("object must not be null");
}
}
/**
* Set the value of the <code>id</code> in the given object
*
* @param object object containing a public <code>id</code> field. Must not be <code>null</code>
* @param id the new value. Can be <code>null</code>.
*/
public static void setId(Object object, Object id) {
try {
Field idField = getIdField(object.getClass());
if (idField != null) {
idField.set(object, id);
}
} catch (IllegalAccessException | IllegalArgumentException e) {
throw new LoggingRuntimeException(e, logger, "setting Id failed");
}
}
/**
* Set the value of the <code>version</code> in the given object
*
* @param object object containing a public <code>version</code> field. Must not be <code>null</code>
* @param id the new value. Can be <code>null</code>.
*/
public static void setVersion(Object object, int id) {
try {
Field versionField = object.getClass().getField("version");
if (versionField.getType() == Integer.TYPE) versionField.set(object, id);
else throw new IllegalArgumentException("Cannot set version on field with " + versionField.getType());
} catch (NoSuchFieldException | SecurityException | IllegalAccessException e) {
// throw new LoggingRuntimeException(e, logger, "setting Version failed");
}
}
/**
* Get the value of the <code>id</code> field as String
*
* @param object object containing the id. Must not be <code>null</code>
* @return the value of the <code>id</code> field as String
*/
public static String getIdString(Object object) {
if (object == null) {
throw new NullPointerException();
}
return String.valueOf(getId(object));
}
/**
* Get the value of the <code>id</code> field as String.
* Leaves out all 'filler' characters. For an UUID this would
* be the '-' characters
*
* @param object object containing the id. Must not be <code>null</code>
* @return the value of the <code>id</code> field as String
*/
public static String getCompactIdString(Object object) {
return getIdString(object).replace("-", "");
}
/**
* Note: Do not depend on the class of the returned id. It
* could be changed.
*
* @return a new unique id
*/
public static Object createId() {
return UUID.randomUUID().toString();
}
}
|
package org.rcsb.project6;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import javax.vecmath.Point3d;
import org.apache.hadoop.io.ArrayWritable;
import org.apache.hadoop.io.Text;
import org.apache.spark.SparkConf;
import org.apache.spark.api.java.JavaSparkContext;
import org.rcsb.hadoop.io.Demo;
import org.rcsb.hadoop.io.HadoopToSimpleChainMapper;
import org.rcsb.hadoop.io.SimplePolymerChain;
import org.rcsb.structuralAlignment.SuperPositionQCP;
import org.rcsb.structuralSimilarity.GapFilter;
import org.rcsb.structuralSimilarity.LengthFilter;
import scala.Tuple2;
import scala.Tuple3;
/**
*
* This class creates a library of unique fragments categorized by length.
* Output PDBID as a string, length as a string, and the points as a point3d[].
*
* @author Grant Summers
*
*/
public class Library
{
private static int NUM_THREADS = 4;
private static int NUM_TASKS_PER_THREAD = 3;
// make the data structure to store unique fragments
public static void main(String[] args) throws FileNotFoundException, UnsupportedEncodingException
{
// arguments
String path = "/Users/grantsummers/Desktop/School/Internship/main/QuickStructureSearch/src/main/java/org/rcsb/project1/protein_chains_All_20150629_002251.seq";
// String outputfilename = "output.txt";
int length = 8;
// Spark setup
SparkConf conf = new SparkConf().setMaster("local[" + NUM_THREADS + "]")
.setAppName(Demo.class.getSimpleName())
.set("spark.serializer", "org.apache.spark.serializer.KryoSerializer");
JavaSparkContext sc = new JavaSparkContext(conf);
// start time
// long start = System.nanoTime();
// map sequence file to pairs (id, points)
List<Tuple2<String, Point3d[]>> chains = sc
.sequenceFile(path, Text.class, ArrayWritable.class,NUM_THREADS*NUM_TASKS_PER_THREAD)
.sample(false, 0.0003, 123)
.mapToPair(new HadoopToSimpleChainMapper()) // convert input to <pdbId.chainId, SimplePolymerChain> pairs
.filter(t -> t._2.isProtein())
.mapToPair(t -> new Tuple2<String, Point3d[]>(t._1, t._2.getCoordinates()))
.filter(new GapFilter(0, 0)) // keep protein chains with gap size <= 0 and 0 gaps
.filter(new LengthFilter(50,500)) // keep protein chains with 50 - 500 residues
.collect();
List<Tuple3<String, String, Point3d[]>> lib = new ArrayList<>();
// boolean for whether or not to add a fragment to the library
boolean bool = true;
// instantiate the SPQCP object
SuperPositionQCP qcp = new SuperPositionQCP(true);
for (Tuple2<String, Point3d[]> t: chains) {
for(int star=0; star<t._2.length-length; star++)
{
// System.out.println(t._1 + "." + star + ": " + Arrays.toString(Arrays.copyOfRange(t._2, star, star + length)));
// Create a Tuple3 for each fragment
Tuple3<String, String, Point3d[]> tup =
new Tuple3<String, String, Point3d[]>
(t._1 + "." + star,
lengthy(Arrays.copyOfRange(t._2, star, star+length)),
Arrays.copyOfRange(t._2, star, star+length));
// center each fragment
SuperPositionQCP.center(tup._3());
if(!lib.isEmpty()){
check: for(Tuple3<String, String, Point3d[]> l: lib){
if(l._2() == tup._2()){
qcp.set(l._3(), tup._3());
double q = qcp.getRmsd();
if(q<1){
bool = false;
break check;
}
}
}
}
if(bool == true){
lib.add(tup);
// System.out.println("[" + tup._2() + "] - " + (lib.size()-1) + ": " + Arrays.toString(tup._3()));
}
bool = true;
}
}
sc.close();
// Write the lib list to a text or csv file
// PrintWriter writer = new PrintWriter("library.tsv", "UTF-8");
// for(Tuple3<String, String, Point3d[]> l: lib){
// writer.println(l._1() + "\t [" + l._2() + "]\t " + Arrays.toString(l._3()));
// alternate write-out
PrintWriter writer = new PrintWriter("library.csv", "UTF-8");
for(Tuple3<String, String, Point3d[]> l: lib){
writer.print(l._1() + ", [" + l._2() + "]");
for(Point3d p: l._3()){
writer.print(", \"" + p + "\"");
}
writer.println();
}
writer.close();
// prints time
// System.out.println("Time: " + (System.nanoTime() - start)/1E9 + " sec.");
}
public static String lengthy(Point3d[] p){
int round = 2;
double i = Math.abs(p[p.length-1].distance(p[0]));
i /= round;
int base = (int) i * round;
int top = ((int) i + 1) * round;
return Integer.toString(base) + " - " + Integer.toString(top);
}
}
|
package org.takes.http;
import java.io.IOException;
import java.net.Socket;
import lombok.EqualsAndHashCode;
/**
* Back decorator with lifetime.
* <p>The class is immutable and thread-safe.
* @author Aleksey Kurochka (eg04lt3r@gmail.com)
* @version $Id$
*/
@EqualsAndHashCode(of = { "origin", "latency", "start" })
public final class BkTimeable implements Back {
/**
* Origin back.
*/
private final transient Back origin;
/**
* Latency in milliseconds.
*/
private final transient long latency;
/**
* Start time of instance creation.
*/
private final transient long start;
/**
* Ctor.
* @param back Original back
* @param lat Latency delay
*/
public BkTimeable(final Back back, final long lat) {
this.origin = back;
this.latency = lat;
this.start = System.currentTimeMillis();
}
@Override
public void accept(final Socket socket) throws IOException {
if (this.latencyExceeded()) {
Thread.currentThread().interrupt();
} else {
this.origin.accept(socket);
}
}
/**
* Check is latency exceeded.
* @return True if exceeded
*/
private boolean latencyExceeded() {
return System.currentTimeMillis() - this.start > this.latency;
}
}
|
package ru.r2cloud.ssl;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.security.KeyPair;
import java.security.cert.X509Certificate;
import java.util.Date;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.shredzone.acme4j.Authorization;
import org.shredzone.acme4j.Certificate;
import org.shredzone.acme4j.Registration;
import org.shredzone.acme4j.Registration.EditableRegistration;
import org.shredzone.acme4j.RegistrationBuilder;
import org.shredzone.acme4j.Session;
import org.shredzone.acme4j.Status;
import org.shredzone.acme4j.challenge.Challenge;
import org.shredzone.acme4j.challenge.Http01Challenge;
import org.shredzone.acme4j.exception.AcmeConflictException;
import org.shredzone.acme4j.exception.AcmeException;
import org.shredzone.acme4j.exception.AcmeRetryAfterException;
import org.shredzone.acme4j.exception.AcmeUnauthorizedException;
import org.shredzone.acme4j.util.CSRBuilder;
import org.shredzone.acme4j.util.CertificateUtils;
import org.shredzone.acme4j.util.KeyPairUtils;
import ru.r2cloud.ddns.DDNSType;
import ru.r2cloud.uitl.Configuration;
import ru.r2cloud.uitl.NamingThreadFactory;
import ru.r2cloud.uitl.SafeRunnable;
import ru.r2cloud.uitl.Util;
public class AcmeClient {
private final static Logger LOG = Logger.getLogger(AcmeClient.class.getName());
private final static long INITIAL_RETRY = 3000L;
private ScheduledExecutorService executor;
private final AtomicBoolean running = new AtomicBoolean(false);
private final Configuration config;
private final File basepath;
private final File challengePath;
private final Messages messages = new Messages();
public AcmeClient(Configuration config) {
this.config = config;
this.basepath = Util.initDirectory(config.getProperty("acme.basepath"));
this.challengePath = Util.initDirectory(config.getProperty("acme.webroot") + "/.well-known/acme-challenge/");
}
public void start() {
executor = Executors.newSingleThreadScheduledExecutor(new NamingThreadFactory("acme-client"));
if (isSSLEnabled()) {
try (FileInputStream fis = new FileInputStream(new File(basepath, "domain-chain.crt"))) {
X509Certificate certificate = CertificateUtils.readX509Certificate(fis);
scheduleRenew(certificate);
} catch (IOException e) {
LOG.log(Level.SEVERE, "unable to load certificate for renewal", e);
}
}
}
private void scheduleRenew(X509Certificate certificate) {
long delay = certificate.getNotAfter().getTime() - System.currentTimeMillis() - TimeUnit.DAYS.toMillis(7);
messages.add("Schedule certificate renewal. NotAfter: " + certificate.getNotAfter() + " Renew at: " + new Date(certificate.getNotAfter().getTime() - TimeUnit.DAYS.toMillis(7)), LOG);
executor.schedule(new SafeRunnable() {
@Override
public void doRun() {
if (!running.compareAndSet(false, true)) {
LOG.info("acmeclient is already running. skip renew");
return;
}
messages.clear();
renew();
running.set(false);
}
}, delay, TimeUnit.MILLISECONDS);
}
private void renew() {
Registration reg = loadOrCreateRegistration();
if (reg == null) {
return;
}
byte[] csr;
try (FileInputStream fis = new FileInputStream(new File(basepath, "domain.csr"))) {
csr = CertificateUtils.readCSR(fis).getEncoded();
} catch (Exception e) {
LOG.log(Level.SEVERE, "unable to load csr. trying to create new", e);
CSRBuilder csrb = createCSR(reg);
if (csrb == null) {
return;
}
try {
csr = csrb.getEncoded();
} catch (IOException e1) {
LOG.log(Level.SEVERE, "unable to encode csr", e1);
return;
}
}
Certificate certificate;
try {
certificate = reg.requestCertificate(csr);
} catch (AcmeUnauthorizedException e) {
LOG.info("authorizations expired. create new csr");
CSRBuilder csrb = createCSR(reg);
if (csrb == null) {
return;
}
try {
certificate = reg.requestCertificate(csrb.getEncoded());
} catch (Exception e1) {
LOG.log(Level.SEVERE, "unable to renew certificate with new csr", e1);
return;
}
} catch (AcmeException e) {
LOG.log(Level.SEVERE, "unable to renew certificate", e);
return;
}
downloadCertificate(certificate);
}
public void setup() {
if (!running.compareAndSet(false, true)) {
return;
}
messages.clear();
executor.submit(new SafeRunnable() {
@Override
public void doRun() {
doSetup();
running.set(false);
}
});
}
private void doSetup() {
messages.add("starting up...", LOG);
Registration reg = loadOrCreateRegistration();
if (reg == null) {
return;
}
CSRBuilder csrb = createCSR(reg);
if (csrb == null) {
return;
}
messages.add("requesting certificate", LOG);
Certificate certificate;
try {
certificate = reg.requestCertificate(csrb.getEncoded());
} catch (Exception e) {
String message = "unable to request certificate";
messages.add(message);
LOG.log(Level.SEVERE, message, e);
return;
}
downloadCertificate(certificate);
}
private void downloadCertificate(Certificate certificate) {
messages.add("downloading certificate", LOG);
X509Certificate cert;
try {
cert = certificate.download();
} catch (AcmeException e) {
String message = "unable to download certificate";
messages.add(message);
LOG.log(Level.SEVERE, message, e);
return;
}
scheduleRenew(cert);
messages.add("downloading certificate chain", LOG);
X509Certificate[] chain;
try {
chain = certificate.downloadChain();
} catch (AcmeException e) {
String message = "unable to download certificate chain";
messages.add(message);
LOG.log(Level.SEVERE, message, e);
return;
}
messages.add("saving certificate", LOG);
try (FileWriter fw = new FileWriter(new File(basepath, "domain-chain.crt"))) {
CertificateUtils.writeX509CertificateChain(fw, cert, chain);
} catch (IOException e) {
String message = "unable to save certificate";
messages.add(message);
LOG.log(Level.SEVERE, message, e);
return;
}
messages.add("reloading nginx configuration", LOG);
try {
new ProcessBuilder().inheritIO().command(new String[] { "sudo", config.getProperty("nginx.location"), "-s", "reload" }).start();
} catch (IOException e) {
String message = "unable to reload configuration";
messages.add(message);
LOG.log(Level.SEVERE, message, e);
return;
}
config.setProperty("acme.ssl.enabled", "true");
config.update();
}
private CSRBuilder createCSR(Registration reg) {
String domain = getSslDomain();
try {
authorize(reg, domain);
} catch (Exception e) {
String message = "unable to authorize domain";
messages.add(message);
LOG.log(Level.SEVERE, message, e);
return null;
} finally {
messages.add("cleanup challenge data", LOG);
for (File cur : challengePath.listFiles()) {
if (cur.isFile() && !cur.delete()) {
LOG.info("unable to cleanup: " + cur.getAbsolutePath());
}
}
}
KeyPair domainKeyPair;
try {
File domainKeyFile = new File(basepath, "domain.key");
//if domain.csr doesn't exist then this is first time execution
//and domain.key contains self-signed private key stored in git
if (new File(basepath, "domain.csr").exists()) {
domainKeyPair = loadOrCreateKeyPair(domainKeyFile);
} else {
domainKeyPair = createKeyPair(domainKeyFile);
}
} catch (IOException e) {
String message = "unable to load domain keypair";
messages.add(message);
LOG.log(Level.SEVERE, message, e);
return null;
}
messages.add("creating csr", LOG);
CSRBuilder csrb = new CSRBuilder();
csrb.addDomain(domain);
try {
csrb.sign(domainKeyPair);
} catch (IOException e) {
String message = "unable to sign csr";
messages.add(message);
LOG.log(Level.SEVERE, message, e);
return null;
}
messages.add("saving csr for future use", LOG);
try (Writer out = new FileWriter(new File(basepath, "domain.csr"))) {
csrb.write(out);
} catch (IOException e) {
String message = "unable to save csr";
messages.add(message);
LOG.log(Level.SEVERE, message, e);
return null;
}
return csrb;
}
private Registration loadOrCreateRegistration() {
KeyPair userKeyPair;
try {
userKeyPair = loadOrCreateKeyPair(new File(basepath, "user.key"));
} catch (IOException e) {
String message = "unable to load user keypair";
messages.add(message);
LOG.log(Level.SEVERE, message, e);
return null;
}
messages.add("creating session", LOG);
Session session = new Session(config.getProperty("acme.ca.url"), userKeyPair);
Registration reg;
try {
reg = loadOrRegisterAccount(session);
} catch (AcmeException e) {
String message = "unable to setup account";
messages.add(message);
LOG.log(Level.SEVERE, message, e);
return null;
}
return reg;
}
private KeyPair loadOrCreateKeyPair(File file) throws IOException {
if (file.exists()) {
messages.add("loading keypair", LOG);
try (FileReader fr = new FileReader(file)) {
return KeyPairUtils.readKeyPair(fr);
}
} else {
return createKeyPair(file);
}
}
private KeyPair createKeyPair(File file) throws IOException {
messages.add("creating keypair", LOG);
KeyPair keyPair = KeyPairUtils.createKeyPair(2048);
try (FileWriter fw = new FileWriter(file)) {
KeyPairUtils.writeKeyPair(keyPair, fw);
}
return keyPair;
}
private Registration loadOrRegisterAccount(Session session) throws AcmeException {
Registration reg;
try {
messages.add("registering new user", LOG);
reg = new RegistrationBuilder().create(session);
URI agreement = reg.getAgreement();
messages.add("accepting terms of service", LOG);
EditableRegistration editableReg = reg.modify();
editableReg.setAgreement(agreement);
editableReg.addContact("mailto:" + config.getProperty("server.login"));
editableReg.commit();
} catch (AcmeConflictException ex) {
messages.add("account already exists. use it", LOG);
reg = Registration.bind(session, ex.getLocation());
}
return reg;
}
private void authorize(Registration reg, String domain) throws AcmeException, FileNotFoundException, IOException {
messages.add("authorizing domain: " + domain, LOG);
Authorization auth = reg.authorizeDomain(domain);
messages.add("find http challenge", LOG);
Http01Challenge challenge1 = auth.findChallenge(Http01Challenge.TYPE);
if (challenge1 == null) {
throw new AcmeException("Found no " + Http01Challenge.TYPE + " challenge, don't know what to do...");
}
messages.add("saving challenge request", LOG);
try (FileOutputStream fos = new FileOutputStream(new File(challengePath, challenge1.getToken()))) {
fos.write(challenge1.getAuthorization().getBytes(StandardCharsets.UTF_8));
}
Challenge challenge = challenge1;
if (challenge.getStatus() == Status.VALID) {
messages.add("challenge already successeded", LOG);
return;
}
messages.add("trigger challenge", LOG);
challenge.trigger();
// Poll for the challenge to complete.
try {
long retryTimeout = INITIAL_RETRY;
while (challenge.getStatus() != Status.VALID) {
// Did the authorization fail?
if (challenge.getStatus() == Status.INVALID) {
throw new AcmeException("Challenge failed... Giving up.");
}
Thread.sleep(retryTimeout);
try {
messages.add("update challenge", LOG);
challenge.update();
} catch (AcmeRetryAfterException e) {
retryTimeout = e.getRetryAfter().toEpochMilli() - System.currentTimeMillis();
messages.add("not ready. retry after: " + retryTimeout + " millis", LOG);
}
}
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
}
// All reattempts are used up and there is still no valid authorization?
if (challenge.getStatus() != Status.VALID) {
throw new AcmeException("Failed to pass the challenge for domain " + domain + ", ... Giving up.");
}
}
public void stop() {
if (executor != null) {
executor.shutdown();
}
}
public boolean isSSLEnabled() {
return config.getBoolean("acme.ssl.enabled");
}
public boolean isRunning() {
return running.get();
}
public List<String> getMessages() {
return messages.get();
}
public String getSslDomain() {
String result = config.getProperty("acme.ssl.domain");
if (result == null || result.trim().length() == 0) {
DDNSType type = config.getDdnsType("ddns.type");
if (type != null && type.equals(DDNSType.NOIP)) {
result = config.getProperty("ddns.noip.domain");
}
}
return result;
}
}
|
package rusk.domain.task;
import java.util.Date;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.Validate;
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.apache.commons.lang3.time.DurationFormatUtils;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
@JsonIgnoreProperties(ignoreUnknown=true)
public class WorkTime {
private long id;
private long startTime;
private Long endTime; // null Long
/**
*
*
* @param startTime
* @return
*/
public static WorkTime createInWorkingTime(Date startTime) {
return new WorkTime(startTime);
}
private WorkTime(Date startTime) {
this.setStartTime(startTime);
}
private void setStartTime(Date startTime) {
Validate.notNull(startTime, "");
this.startTime = startTime.getTime();
}
/**
*
*
* @param id ID
* @param startTime
* @return
*/
public static WorkTime deserializeInWorkingTime(long id, Date startTime) {
return new WorkTime(id, startTime);
}
private WorkTime(long id, Date startTime) {
this.id = id;
this.setStartTime(startTime);
}
/**
*
*
* @param startTime
* @param endTime
* @return
*/
public static WorkTime createConcludedWorkTime(Date startTime, Date endTime) {
return new WorkTime(startTime, endTime);
}
private WorkTime(Date startTime, Date endTime) {
this.setStartTime(startTime);
this.setEndTime(endTime);
}
void setEndTime(Date endTime) {
Validate.notNull(endTime, "");
this.validateStartEndTimeRelation(this.startTime, endTime.getTime());
this.endTime = endTime.getTime();
}
private void validateStartEndTimeRelation(long startTime, long endTime) {
if (endTime <= startTime) {
throw new IllegalArgumentException("=" + startTime + ", =" + endTime);
}
}
/**
*
*
* @param id ID
* @param startTime
* @param endTime
* @return
*/
public static WorkTime deserializeConcludedWorkTime(long id, Date startTime, Date endTime) {
return new WorkTime(id, startTime, endTime);
}
private WorkTime(long id, Date startTime, Date endTime) {
this.id = id;
this.setStartTime(startTime);
this.setEndTime(endTime);
}
/**
*
* @param other
* @return true
*/
public boolean isDuplicate(WorkTime other) {
long otherEndTime = other.endTime != null ? other.endTime : Long.MAX_VALUE;
return this.includes(other.startTime) || this.includes(otherEndTime);
}
private boolean includes(long time) {
long endTime = ObjectUtils.defaultIfNull(this.endTime, Long.MAX_VALUE);
return this.startTime <= time && time <= endTime;
}
/**
*
* @return
*/
public Date getStartTime() {
return new Date(this.startTime);
}
/**
*
* @return
*/
public Date getEndTime() {
return this.endTime == null ? null : new Date(this.endTime);
}
/**
*
*
* @return
*/
public long getDuration() {
return this.endTime == null ? 0L : this.endTime - this.startTime;
}
/**
*
*
* @return true
*/
public boolean hasEndTime() {
return this.endTime != null;
}
public long getId() {
return id;
}
@Override
public int hashCode() {
return new HashCodeBuilder().append(this.startTime).append(this.endTime).toHashCode();
}
@Override
public boolean equals(Object other) {
if (other == null || !(other instanceof WorkTime)) return false;
WorkTime o = (WorkTime)other;
return new EqualsBuilder().append(this.startTime, o.startTime).append(this.endTime, o.endTime).isEquals();
}
@Override
public String toString() {
return DurationFormatUtils.formatDuration(this.getDuration(), "HH:mm:ss.SSS");
}
@Deprecated
public WorkTime() {
this.startTime = Long.MIN_VALUE;
this.endTime = Long.MIN_VALUE;
}
}
|
package seedu.tache.ui;
import java.util.logging.Logger;
import org.controlsfx.control.textfield.AutoCompletionBinding;
import org.controlsfx.control.textfield.TextFields;
import javafx.fxml.FXML;
import javafx.scene.control.SplitPane;
import javafx.scene.control.TextField;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.Region;
import seedu.tache.commons.core.LogsCenter;
import seedu.tache.commons.events.ui.NewResultAvailableEvent;
import seedu.tache.commons.util.FxViewUtil;
import seedu.tache.logic.Logic;
import seedu.tache.logic.commands.CommandResult;
import seedu.tache.logic.commands.exceptions.CommandException;
public class CommandBox extends UiPart<Region> {
private final Logger logger = LogsCenter.getLogger(CommandBox.class);
private static final String FXML = "CommandBox.fxml";
public static final String ERROR_STYLE_CLASS = "error";
private final Logic logic;
@FXML
private TextField commandTextField;
public CommandBox(AnchorPane commandBoxPlaceholder, Logic logic) {
super(FXML);
this.logic = logic;
addToPlaceholder(commandBoxPlaceholder);
setAutocomplete();
}
private void addToPlaceholder(AnchorPane placeHolderPane) {
SplitPane.setResizableWithParent(placeHolderPane, false);
placeHolderPane.getChildren().add(commandTextField);
FxViewUtil.applyAnchorBoundaryParameters(getRoot(), 0.0, 0.0, 0.0, 0.0);
FxViewUtil.applyAnchorBoundaryParameters(commandTextField, 0.0, 0.0, 0.0, 0.0);
}
@FXML
private void handleCommandInputChanged() {
try {
CommandResult commandResult = logic.execute(commandTextField.getText());
// process result of the command
setStyleToIndicateCommandSuccess();
commandTextField.setText("");
logger.info("Result: " + commandResult.feedbackToUser);
raise(new NewResultAvailableEvent(commandResult.feedbackToUser));
} catch (CommandException e) {
// handle command failure
setStyleToIndicateCommandFailure();
logger.info("Invalid command: " + commandTextField.getText());
raise(new NewResultAvailableEvent(e.getMessage()));
}
}
/**
* Sets autocomplete functionality for user commands.
* Uses ControlsFX Autocomplete TextField function.
*/
private void setAutocomplete() {
String[] possibleCommands = {"add ", "clear", "complete ", "delete ", "edit ", "exit", "find ",
"help", "list", "save ", "select ", "undo" };
AutoCompletionBinding<String> binding = TextFields.bindAutoCompletion(commandTextField, possibleCommands);
binding.setMaxWidth(70);
}
/**
* Sets the command box style to indicate a successful command.
*/
private void setStyleToIndicateCommandSuccess() {
commandTextField.getStyleClass().remove(ERROR_STYLE_CLASS);
}
/**
* Sets the command box style to indicate a failed command.
*/
private void setStyleToIndicateCommandFailure() {
commandTextField.getStyleClass().add(ERROR_STYLE_CLASS);
}
}
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package service;
//import be.luckycode.projetawebservice.DummyProject;
import be.luckycode.projetawebservice.*;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.security.RolesAllowed;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.ws.rs.*;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.SecurityContext;
import org.codehaus.jackson.map.ObjectMapper;
/**
*
* @author michael
*/
@Stateless
@Path("projects")
public class ProjectFacadeREST extends AbstractFacade<Project> {
@PersistenceContext(unitName = "be.luckycode_projeta-webservice_war_1.0-SNAPSHOTPU")
private EntityManager em;
@Context
SecurityContext security;
public ProjectFacadeREST() {
super(Project.class);
}
@POST
@Path("create")
@RolesAllowed("administrator")
@Consumes("application/json")
@Produces("application/json")
public String createNewProject(Project entity) {
em.persist(entity);
initDefaultProgressForNewProject(entity);
em.flush();
List<Project> prjList = new ArrayList<Project>();
prjList.add(entity);
ObjectMapper mapper = new ObjectMapper();
List<Map> projectList = new ArrayList<Map>();
//getProjects(prjList, projectList, "Project.getChildProjects", "");
getProjects(prjList, projectList, em.createNamedQuery("Project.getChildProjects"), null);
String retVal = "";
HashMap<String, Object> retProjects = new HashMap<String, Object>();
retProjects.put("project", projectList);
try {
retVal = mapper.writeValueAsString(retProjects);
} catch (IOException ex) {
Logger.getLogger(ProjectFacadeREST.class.getName()).log(Level.SEVERE, null, ex);
}
return retVal;
}
private void initDefaultProgressForNewProject(Project entity) {
Progress progress = new Progress();
progress.setPercentageComplete((short) 0);
progress.setProgressComment("Projet créé.");
progress.setStatusId(new Status(1));
progress.setUserCreated(getAuthenticatedUser());
progress.setProjectId(entity);
em.persist(progress);
}
@PUT
@Override
@Consumes("application/json")
public void edit(Project entity) {
super.edit(entity);
}
@DELETE
@Path("{id}")
public void remove(@PathParam("id") Integer id) {
super.remove(super.find(id));
}
@POST
@Path("delete/{id}")
public void deleteProjectById(@PathParam("id") Integer id) {
Project project = super.find(id);
project.setDeleted(Boolean.TRUE);
// enregistrer en DB.
super.edit(project);
}
@POST
@Path("delete")
public void deleteProject(Project entity) {
Project project = super.find(entity.getProjectId());
project.setDeleted(Boolean.TRUE);
// enregistrer en DB.
super.edit(project);
}
@GET
@Path("{id}")
@Produces("application/json")
public Project find(@PathParam("id") Integer id) {
return super.find(id);
}
@GET
@Path("wsprojects")
public ProjectDummy findProjectsPOJO() {
ProjectDummy projDummy = new ProjectDummy();
List<ProjectSimpleWebSite> listProj = new ArrayList<ProjectSimpleWebSite>();
if (security.isUserInRole("administrator")) {
Query q = em.createNamedQuery("Project.getParentProjects");
List<Project> prjList = new ArrayList<Project>();
prjList = q.getResultList();
for (Project p_tmp : prjList) {
ProjectSimpleWebSite p = new ProjectSimpleWebSite();
p.setProjectTitle(p_tmp.getProjectTitle());
p.setProjectId(p_tmp.getProjectId());
if (p_tmp.getStartDate() != null) {
p.setStartDate(p_tmp.getStartDate());
}
if (p_tmp.getEndDate() != null) {
p.setEndDate(p_tmp.getEndDate());
}
// statut
p.setProjectStatus(getStatusForProjectId(p_tmp.getProjectId()));
getChildProjectsWebSite(p, "Project.getChildProjects", null);
listProj.add(p);
}
} else {
Query q = em.createNativeQuery("SELECT DISTINCT project.project_id as PROJECT_ID, project.project_title as PROJECT_TITLE, project.flag_public as FLAG_PUBLIC, project.project_description as PROJECT_DESCRIPTION, project.user_created as USER_CREATED, project.date_created as DATE_CREATED, project.start_date as START_DATE, project.end_date as END_DATE, project.start_date_real as START_DATE_REAL, project.end_date_real as END_DATE_REAL, project.parent_project_id as PARENT_PROJECT_ID, project.completed as COMPLETED, project.canceled as CANCELED, project.deleted as DELETED, project.user_assigned as USER_ASSIGNED FROM project LEFT OUTER JOIN project_user_visible ON project.project_id = project_user_visible.project_id LEFT OUTER JOIN project_usergroup_visible ON project_usergroup_visible.project_id = project.project_id LEFT OUTER JOIN project_client ON project_client.project_id = project.project_id LEFT OUTER JOIN client ON project_client.client_id = client.client_id LEFT OUTER JOIN client_user ON client_user.client_id = client.client_id LEFT OUTER JOIN usergroup ON usergroup.usergroup_id = project_usergroup_visible.usergroup_id LEFT OUTER JOIN user_usergroup ON usergroup.usergroup_id = user_usergroup.usergroup_id WHERE (project.deleted = false or project.deleted IS NULL) AND ((project.flag_public = TRUE) OR (user_usergroup.user_id = ?1) OR (client_user.user_id = ?1) OR (project_user_visible.user_id = ?1) OR (project.user_created = ?1) OR (project.user_assigned = ?1)) AND project.parent_project_id IS NULL", Project.class);
q.setParameter(1, getAuthenticatedUser().getUserId());
List<Project> prjList = new ArrayList<Project>();
prjList = q.getResultList();
Query subquery = em.createNativeQuery("SELECT DISTINCT project.project_id as PROJECT_ID, project.project_title as PROJECT_TITLE, project.flag_public as FLAG_PUBLIC, project.project_description as PROJECT_DESCRIPTION, project.user_created as USER_CREATED, project.date_created as DATE_CREATED, project.start_date as START_DATE, project.end_date as END_DATE, project.start_date_real as START_DATE_REAL, project.end_date_real as END_DATE_REAL, project.parent_project_id as PARENT_PROJECT_ID, project.completed as COMPLETED, project.canceled as CANCELED, project.deleted as DELETED, project.user_assigned as USER_ASSIGNED FROM project LEFT OUTER JOIN project_user_visible ON project.project_id = project_user_visible.project_id LEFT OUTER JOIN project_usergroup_visible ON project_usergroup_visible.project_id = project.project_id LEFT OUTER JOIN project_client ON project_client.project_id = project.project_id LEFT OUTER JOIN client ON project_client.client_id = client.client_id LEFT OUTER JOIN client_user ON client_user.client_id = client.client_id LEFT OUTER JOIN usergroup ON usergroup.usergroup_id = project_usergroup_visible.usergroup_id LEFT OUTER JOIN user_usergroup ON usergroup.usergroup_id = user_usergroup.usergroup_id WHERE project.parent_project_id = ?1 AND (project.deleted = false or project.deleted IS NULL) AND ((project.flag_public = TRUE) OR (user_usergroup.user_id = ?2) OR (client_user.user_id = ?2) OR (project_user_visible.user_id = ?2) OR (project.user_created = ?1) OR (project.user_assigned = ?1))", Project.class);
subquery.setParameter(2, getAuthenticatedUser().getUserId());
for (Project p_tmp : prjList) {
ProjectSimpleWebSite p = new ProjectSimpleWebSite();
p.setProjectTitle(p_tmp.getProjectTitle());
p.setProjectId(p_tmp.getProjectId());
if (p_tmp.getStartDate() != null) {
p.setStartDate(p_tmp.getStartDate());
}
if (p_tmp.getEndDate() != null) {
p.setEndDate(p_tmp.getEndDate());
}
// statut
p.setProjectStatus(getStatusForProjectId(p_tmp.getProjectId()));
getChildProjectsWebSite(p, null, subquery);
listProj.add(p);
}
// get projects. Pas des sous-projets.
//getProjects(prjList, projectList, null, subquery);
}
projDummy.setListProject(listProj);
return projDummy;
}
@GET
@Path("wsprojectspublic")
public ProjectDummy findPublicProjectsPOJO() {
ProjectDummy projDummy = new ProjectDummy();
Query q = em.createNamedQuery("Project.getParentPublicProjects");
List<Project> prjList = new ArrayList<Project>();
prjList = q.getResultList();
List<ProjectSimpleWebSite> listProj = new ArrayList<ProjectSimpleWebSite>();
for (Project p_tmp : prjList) {
ProjectSimpleWebSite p = new ProjectSimpleWebSite();
p.setProjectTitle(p_tmp.getProjectTitle());
p.setProjectId(p_tmp.getProjectId());
if (p_tmp.getStartDate() != null) {
p.setStartDate(p_tmp.getStartDate());
}
if (p_tmp.getEndDate() != null) {
p.setEndDate(p_tmp.getEndDate());
}
// statut
p.setProjectStatus(getStatusForProjectId(p_tmp.getProjectId()));
getChildProjectsWebSite(p, "Project.getChildPublicProjects", null);
listProj.add(p);
}
projDummy.setListProject(listProj);
return projDummy;
}
private void getChildProjectsWebSite(ProjectSimpleWebSite p, String namedQuery, Query nativeSubQuery) {
Query qry_child_projects;
List<Project> childPrjList = new ArrayList<Project>();
// get child projects
if (namedQuery != null) {
qry_child_projects = em.createNamedQuery(namedQuery);
Project p_qry = new Project(p.getProjectId());
qry_child_projects.setParameter(1, p_qry);
childPrjList = qry_child_projects.getResultList();
} else {
qry_child_projects = nativeSubQuery;
qry_child_projects.setParameter(1, p.getProjectId());
childPrjList = qry_child_projects.getResultList();
// get child projects
//getProjects(childPrjList, childProjectList, null, qry_child_projects);
}
List<ProjectSimpleWebSite> listSubProject = new ArrayList<ProjectSimpleWebSite>();
for (Project p_tmp : childPrjList) {
ProjectSimpleWebSite p_sub = new ProjectSimpleWebSite();
p_sub.setProjectTitle(p_tmp.getProjectTitle());
p_sub.setProjectId(p_tmp.getProjectId());
if (p_tmp.getStartDate() != null) {
p_sub.setStartDate(p_tmp.getStartDate());
}
if (p_tmp.getEndDate() != null) {
p_sub.setEndDate(p_tmp.getEndDate());
}
// statut.
p_sub.setProjectStatus(getStatusForProjectId(p_tmp.getProjectId()));
if (namedQuery != null) {
getChildProjectsWebSite(p_sub, namedQuery, null);
} else {
getChildProjectsWebSite(p_sub, null, nativeSubQuery);
}
listSubProject.add(p_sub);
}
p.setChildProject(listSubProject);
}
// retourne le statut actuel du projet.
private String getStatusForProjectId(Integer projectId) {
// liste des 'Progress' pour le projet.
Query qryStatus = em.createNamedQuery("Progress.findByProjectId");
qryStatus.setParameter("projectId", projectId);
qryStatus.setMaxResults(1); // top 1 result
// lire en liste.
List<Progress> listProgress = new ArrayList<Progress>();
listProgress = qryStatus.getResultList();
// retourner le statut, s'il y'en a un.
if (listProgress.size() > 0) {
String status = "";
if (listProgress.get(0).getPercentageComplete() != null) {
status += listProgress.get(0).getPercentageComplete().toString() + "% - ";
}
return status + listProgress.get(0).getStatusId().getStatusName();
} else {
return "-";
}
}
// retourne le statut actuel du projet.
private Short getPercentageCompleteForProjectId(Integer projectId) {
// liste des 'Progress' pour le projet.
Query qryPercentage = em.createNamedQuery("Progress.findByProjectId");
qryPercentage.setParameter("projectId", projectId);
qryPercentage.setMaxResults(1); // top 1 result
// lire en liste.
List<Progress> listProgress = new ArrayList<Progress>();
listProgress = qryPercentage.getResultList();
// retourner le statut, s'il y'en a un.
if (listProgress.size() > 0) {
return listProgress.get(0).getPercentageComplete();
} else {
return 0;
}
}
// retourne le statut actuel du projet.
private Progress getProgressForProjectId(Integer projectId) {
// liste des 'Progress' pour le projet.
Query qryPercentage = em.createNamedQuery("Progress.findByProjectId");
qryPercentage.setParameter("projectId", projectId);
qryPercentage.setMaxResults(1); // top 1 result
// lire en liste.
List<Progress> listProgress = new ArrayList<Progress>();
listProgress = qryPercentage.getResultList();
// retourner le statut, s'il y'en a un.
if (listProgress.size() > 0) {
return listProgress.get(0);
} else {
return null;
}
}
// returns parent objects including its children
@GET
@Produces("application/json")
public String findAllProjects() {
String retVal = "";
ObjectMapper mapper = new ObjectMapper();
List<Map> projectList = new ArrayList<Map>();
if (security.isUserInRole("administrator")) {
Query q = em.createNamedQuery("Project.getParentProjects");
List<Project> prjList = new ArrayList<Project>();
prjList = q.getResultList();
// get projects and its children
//getProjects(prjList, projectList, "Project.getChildProjects", "");
getProjects(prjList, projectList, em.createNamedQuery("Project.getChildProjects"), null);
} else {
Query q = em.createNativeQuery("SELECT DISTINCT project.project_id as PROJECT_ID, project.project_title as PROJECT_TITLE, project.flag_public as FLAG_PUBLIC, project.project_description as PROJECT_DESCRIPTION, project.user_created as USER_CREATED, project.date_created as DATE_CREATED, project.start_date as START_DATE, project.end_date as END_DATE, project.start_date_real as START_DATE_REAL, project.end_date_real as END_DATE_REAL, project.parent_project_id as PARENT_PROJECT_ID, project.completed as COMPLETED, project.canceled as CANCELED, project.deleted as DELETED, project.user_assigned as USER_ASSIGNED FROM project LEFT OUTER JOIN project_user_visible ON project.project_id = project_user_visible.project_id LEFT OUTER JOIN project_usergroup_visible ON project_usergroup_visible.project_id = project.project_id LEFT OUTER JOIN project_client ON project_client.project_id = project.project_id LEFT OUTER JOIN client ON project_client.client_id = client.client_id LEFT OUTER JOIN client_user ON client_user.client_id = client.client_id LEFT OUTER JOIN usergroup ON usergroup.usergroup_id = project_usergroup_visible.usergroup_id LEFT OUTER JOIN user_usergroup ON usergroup.usergroup_id = user_usergroup.usergroup_id WHERE (project.deleted = false or project.deleted IS NULL) AND ((project.flag_public = TRUE) OR (user_usergroup.user_id = ?1) OR (client_user.user_id = ?1) OR (project_user_visible.user_id = ?1) OR (project.user_created = ?1) OR (project.user_assigned = ?1)) AND project.parent_project_id IS NULL", Project.class);
q.setParameter(1, getAuthenticatedUser().getUserId());
List<Project> prjList = new ArrayList<Project>();
prjList = q.getResultList();
Query subquery = em.createNativeQuery("SELECT DISTINCT project.project_id as PROJECT_ID, project.project_title as PROJECT_TITLE, project.flag_public as FLAG_PUBLIC, project.project_description as PROJECT_DESCRIPTION, project.user_created as USER_CREATED, project.date_created as DATE_CREATED, project.start_date as START_DATE, project.end_date as END_DATE, project.start_date_real as START_DATE_REAL, project.end_date_real as END_DATE_REAL, project.parent_project_id as PARENT_PROJECT_ID, project.completed as COMPLETED, project.canceled as CANCELED, project.deleted as DELETED, project.user_assigned as USER_ASSIGNED FROM project LEFT OUTER JOIN project_user_visible ON project.project_id = project_user_visible.project_id LEFT OUTER JOIN project_usergroup_visible ON project_usergroup_visible.project_id = project.project_id LEFT OUTER JOIN project_client ON project_client.project_id = project.project_id LEFT OUTER JOIN client ON project_client.client_id = client.client_id LEFT OUTER JOIN client_user ON client_user.client_id = client.client_id LEFT OUTER JOIN usergroup ON usergroup.usergroup_id = project_usergroup_visible.usergroup_id LEFT OUTER JOIN user_usergroup ON usergroup.usergroup_id = user_usergroup.usergroup_id WHERE project.parent_project_id = ?1 AND (project.deleted = false or project.deleted IS NULL) AND ((project.flag_public = TRUE) OR (user_usergroup.user_id = ?2) OR (client_user.user_id = ?2) OR (project_user_visible.user_id = ?2) OR (project.user_created = ?1) OR (project.user_assigned = ?1))", Project.class);
subquery.setParameter(2, getAuthenticatedUser().getUserId());
// get projects. Pas des sous-projets.
getProjects(prjList, projectList, null, subquery);
}
HashMap<String, Object> retProjects = new HashMap<String, Object>();
retProjects.put("project", projectList);
try {
retVal = mapper.writeValueAsString(retProjects);
} catch (IOException ex) {
Logger.getLogger(ProjectFacadeREST.class.getName()).log(Level.SEVERE, null, ex);
}
return retVal;
}
private void getProjects(List<Project> prjList, List<Map> projectList, Query namedsubquery, Query nativesubquery) {
// if list is not empty
if (prjList.isEmpty() == false) {
for (Project p : prjList) {
if (p.getDeleted() == null || p.getDeleted() == false) {
Map<String, Object> projectData = new HashMap<String, Object>();
Map<String, Object> userStruct = new HashMap<String, Object>();
if (p.getUserCreated() != null) {
userStruct.put("userId", p.getUserCreated().getUserId().toString());
userStruct.put("username", p.getUserCreated().getUsername());
projectData.put("userCreated", userStruct);
}
if (p.getUserAssigned() != null) {
userStruct.put("userId", p.getUserAssigned().getUserId().toString());
userStruct.put("username", p.getUserAssigned().getUsername());
if (p.getUserAssigned().getFirstName() != null) {
userStruct.put("firstName", p.getUserAssigned().getFirstName());
}
if (p.getUserAssigned().getLastName() != null) {
userStruct.put("lastName", p.getUserAssigned().getLastName());
}
projectData.put("userAssigned", userStruct);
}
if (p.getDateCreated() != null) {
projectData.put("dateCreated", CommonMethods.convertDate(p.getDateCreated()));
}
if (p.getFlagPublic() != null) {
projectData.put("flagPublic", p.getFlagPublic());
}
if (p.getEndDate() != null) {
projectData.put("endDate", CommonMethods.convertDate(p.getEndDate()));
}
if (p.getStartDate() != null) {
projectData.put("startDate", CommonMethods.convertDate(p.getStartDate()));
}
projectData.put("projectDescription", p.getProjectDescription());
projectData.put("projectId", p.getProjectId().toString());
projectData.put("projectTitle", p.getProjectTitle());
// new/optional
if (p.getCompleted() != null) {
projectData.put("completed", p.getCompleted());
} else {
projectData.put("completed", false);
}
if (p.getCanceled() != null) {
projectData.put("canceled", p.getCanceled());
} else {
projectData.put("canceled", false);
}
if (p.getStartDateReal() != null) {
projectData.put("startDateReal", CommonMethods.convertDate(p.getStartDateReal()));
}
if (p.getEndDateReal() != null) {
projectData.put("endDateReal", CommonMethods.convertDate(p.getEndDateReal()));
}
Progress progress = getProgressForProjectId(p.getProjectId());
if (progress != null) {
if (progress.getStatusId() != null && progress.getStatusId().getStatusName() != null) {
projectData.put("projectStatus", progress.getStatusId().getStatusName());
}
// pourcentage.
if (progress.getPercentageComplete() != null) {
projectData.put("projectPercentage", progress.getPercentageComplete().toString());
}
}
// get child projects, if any
if (namedsubquery != null || nativesubquery != null) {
getChildProjects(p, userStruct, projectData, namedsubquery, nativesubquery);
}
// if (namedQuery.length() > 0) {
// getChildProjects(p, userStruct, projectData, namedQuery, "");
// // get child projects, if any
// if (nativeQuery.length() > 0) {
// getChildProjects(p, userStruct, projectData, "", nativeQuery);
projectList.add(projectData);
}
}
}
}
private void getChildProjects(Project p, Map<String, Object> userStruct, Map<String, Object> projectData, Query namedSubQuery, Query nativeSubQuery) {
List<Map> childProjectList = new ArrayList<Map>();
Query qry_child_projects;
// get child projects
if (namedSubQuery != null) {
//Query qry_child_projects = em.createNamedQuery(namedSubQuery);
qry_child_projects = namedSubQuery;
qry_child_projects.setParameter(1, p);
List<Project> childPrjList = new ArrayList<Project>();
childPrjList = qry_child_projects.getResultList();
// get child projects
getProjects(childPrjList, childProjectList, qry_child_projects, null);
} else {
qry_child_projects = nativeSubQuery;
qry_child_projects.setParameter(1, p.getProjectId());
List<Project> childPrjList = new ArrayList<Project>();
childPrjList = qry_child_projects.getResultList();
// get child projects
getProjects(childPrjList, childProjectList, null, qry_child_projects);
}
//List<Project> childPrjList = new ArrayList<Project>();
//childPrjList = qry_child_projects.getResultList();
//// get child projects
//getProjects(childPrjList, childProjectList, qry_child_projects, null);
if (childProjectList.isEmpty() == false) {
projectData.put("childProject", childProjectList);
}
}
@GET
@Path("{from}/{to}")
@Produces("application/json")
public List<Project> findRange(@PathParam("from") Integer from, @PathParam("to") Integer to) {
return super.findRange(new int[]{from, to});
}
@GET
@Path("count")
@Produces("text/plain")
public String countREST() {
return String.valueOf(super.count());
}
@java.lang.Override
protected EntityManager getEntityManager() {
return em;
}
@PUT
@Path("update")
@RolesAllowed("administrator")
@Consumes("application/json")
@Produces("application/json")
public String updateProject(Project entity) {
// fetch user to be updated.
Project project = super.find(entity.getProjectId());
if (entity.getProjectTitle() != null) {
project.setProjectTitle(entity.getProjectTitle());
}
if (entity.getProjectDescription() != null) {
project.setProjectDescription(entity.getProjectDescription());
}
if (entity.getStartDate() != null) {
project.setStartDate(entity.getStartDate());
}
if (entity.getEndDate() != null) {
project.setEndDate(entity.getEndDate());
}
super.edit(project);
List<Project> prjList = new ArrayList<Project>();
prjList.add(super.find(project.getProjectId()));
ObjectMapper mapper = new ObjectMapper();
List<Map> projectList = new ArrayList<Map>();
//getProjects(prjList, projectList, "Project.getChildProjects");
getProjects(prjList, projectList, em.createNamedQuery("Project.getChildProjects"), null);
String retVal = "";
HashMap<String, Object> retProjects = new HashMap<String, Object>();
retProjects.put("project", projectList);
try {
retVal = mapper.writeValueAsString(retProjects);
} catch (IOException ex) {
Logger.getLogger(ProjectFacadeREST.class.getName()).log(Level.SEVERE, null, ex);
}
return retVal;
}
// returns user ID of the authenticated user.
public User getAuthenticatedUser() {
String username;
username = security.getUserPrincipal().getName();
Query q = em.createNamedQuery("User.findByUsername");
q.setParameter("username", username);
List<User> userList = new ArrayList<User>();
userList = q.getResultList();
if (userList.size() == 1) {
return userList.get(0);
} else {
return null;
}
}
// returns parent objects including its children
@GET
@Path("public")
@RolesAllowed({"user", "administrator", "developer"})
@Produces("application/json")
public String findAllPublicProjects() {
String retVal = "";
ObjectMapper mapper = new ObjectMapper();
List<Map> projectList = new ArrayList<Map>();
// get root public projects (projects which have no parent)
Query q = em.createNamedQuery("Project.getParentPublicProjects");
List<Project> prjList = new ArrayList<Project>();
prjList = q.getResultList();
// get projects and its children
//getProjects(prjList, projectList, "Project.getChildPublicProjects", "");
getProjects(prjList, projectList, em.createNamedQuery("Project.getChildPublicProjects"), null);
HashMap<String, Object> retProjects = new HashMap<String, Object>();
retProjects.put("project", projectList);
try {
retVal = mapper.writeValueAsString(retProjects);
} catch (IOException ex) {
Logger.getLogger(ProjectFacadeREST.class.getName()).log(Level.SEVERE, null, ex);
}
return retVal;
}
@PUT
@RolesAllowed({"administrator", "developer"})
@Path("updateUsersVisibleForProject")
@Consumes("application/json")
public void updateUsersVisibleForProject(@QueryParam("projectId") Integer projectId, ArrayList<User> users) {
Query q;
if (projectId != null && security.isUserInRole("administrator")) {
q = em.createNamedQuery("Project.findByProjectId");
q.setParameter("projectId", projectId);
List<Project> projectList = new ArrayList<Project>();
projectList = q.getResultList();
if (projectList.size() == 1) {
// user
Project project = projectList.get(0);
if (users.get(0).getUserId() == null) {
ArrayList<User> list = new ArrayList<User>();
project.setUserCollection(list);
} else {
project.setUserCollection(users);
}
em.merge(project);
if (project.getParentProjectId() != null) {
updateUsersVisibleForParentProject(project);
}
} else {
}
}
}
private void updateUsersVisibleForParentProject(Project p) {
Query q = em.createNamedQuery("Project.findByProjectId");
q.setParameter("projectId", p.getParentProjectId().getProjectId());
List<Project> projectList = q.getResultList();
Project parentProject = projectList.get(0);
Boolean found = false;
for (User u : p.getUserCollection()) {
found = false;
for (User uParent : parentProject.getUserCollection()) {
if (uParent.getUserId() == u.getUserId()) {
found = true;
break;
}
}
if (found == false) {
parentProject.getUserCollection().add(u);
em.merge(parentProject);
}
}
if (parentProject.getParentProjectId() != null) {
updateUsersVisibleForParentProject(parentProject);
}
}
@PUT
@RolesAllowed({"administrator", "developer"})
@Path("updateUsergroupsVisibleForProject")
@Consumes("application/json")
public void updateUsergroupsVisibleForProject(@QueryParam("projectId") Integer projectId, ArrayList<Usergroup> usergroups) {
Query q;
if (projectId != null && security.isUserInRole("administrator")) {
q = em.createNamedQuery("Project.findByProjectId");
q.setParameter("projectId", projectId);
List<Project> projectList = new ArrayList<Project>();
projectList = q.getResultList();
if (projectList.size() == 1) {
// user
Project project = projectList.get(0);
if (usergroups.get(0).getUsergroupId() == null) {
ArrayList<Usergroup> list = new ArrayList<Usergroup>();
project.setUsergroupCollection(list);
} else {
project.setUsergroupCollection(usergroups);
}
em.merge(project);
if (project.getParentProjectId() != null) {
updateUsergroupsVisibleForParentProject(project);
}
} else {
}
}
}
private void updateUsergroupsVisibleForParentProject(Project p) {
Query q = em.createNamedQuery("Project.findByProjectId");
q.setParameter("projectId", p.getParentProjectId().getProjectId());
List<Project> projectList = q.getResultList();
Project parentProject = projectList.get(0);
Boolean found = false;
for (Usergroup ug : p.getUsergroupCollection()) {
found = false;
for (Usergroup ugParent : parentProject.getUsergroupCollection()) {
if (ugParent.getUsergroupId() == ug.getUsergroupId()) {
found = true;
break;
}
}
if (found == false) {
parentProject.getUsergroupCollection().add(ug);
em.merge(parentProject);
}
}
if (parentProject.getParentProjectId() != null) {
updateUsergroupsVisibleForParentProject(parentProject);
}
}
@PUT
@RolesAllowed({"administrator", "developer"})
@Path("updateClientsVisibleForProject")
@Consumes("application/json")
public void updateClientsVisibleForProject(@QueryParam("projectId") Integer projectId, ArrayList<Client> clients) {
Query q;
if (projectId != null && security.isUserInRole("administrator")) {
q = em.createNamedQuery("Project.findByProjectId");
q.setParameter("projectId", projectId);
List<Project> projectList = new ArrayList<Project>();
projectList = q.getResultList();
if (projectList.size() == 1) {
// user
Project project = projectList.get(0);
if (clients.get(0).getClientId() == null) {
ArrayList<Client> clientList = new ArrayList<Client>();
project.setClientCollection(clientList);
} else {
project.setClientCollection(clients);
}
em.merge(project);
if (project.getParentProjectId() != null) {
updateClientsVisibleForParentProject(project);
}
} else {
}
}
}
private void updateClientsVisibleForParentProject(Project p) {
Query q = em.createNamedQuery("Project.findByProjectId");
q.setParameter("projectId", p.getParentProjectId().getProjectId());
List<Project> projectList = q.getResultList();
Project parentProject = projectList.get(0);
Boolean found = false;
for (Client c : p.getClientCollection()) {
found = false;
for (Client cParent : parentProject.getClientCollection()) {
if (cParent.getClientId() == c.getClientId()) {
found = true;
break;
}
}
if (found == false) {
parentProject.getClientCollection().add(c);
em.merge(parentProject);
}
}
if (parentProject.getParentProjectId() != null) {
updateClientsVisibleForParentProject(parentProject);
}
}
@GET
@RolesAllowed({"administrator", "developer"})
@Path("assigned")
@Produces("application/json")
public String findAllAssignedProjects() {
String retVal = "";
ObjectMapper mapper = new ObjectMapper();
List<Map> projectList = new ArrayList<Map>();
Query q = em.createNamedQuery("Project.getAssignedProjects");
q.setParameter("userAssignedId", getAuthenticatedUser().getUserId());
List<Project> prjList = new ArrayList<Project>();
prjList = q.getResultList();
// get projects. Pas des sous-projets.
getProjects(prjList, projectList, null, null);
HashMap<String, Object> retProjects = new HashMap<String, Object>();
retProjects.put("project", projectList);
try {
retVal = mapper.writeValueAsString(retProjects);
} catch (IOException ex) {
Logger.getLogger(ProjectFacadeREST.class.getName()).log(Level.SEVERE, null, ex);
}
return retVal;
}
// TEST METHOD. CAN BE REMOVED!!!
@GET
@RolesAllowed({"administrator", "developer"})
@Path("testproj")
@Produces("application/json")
public String findAllProjectsTEST() {
String retVal = "";
ObjectMapper mapper = new ObjectMapper();
List<Map> projectList = new ArrayList<Map>();
//Query q = em.createNamedQuery("Project.findAllProjectsUser");
// WORKS !!!
//Query q = em.createNativeQuery("SELECT DISTINCT project.project_id as PROJECT_ID, project.project_title as PROJECT_TITLE, project.flag_public as FLAG_PUBLIC FROM project_user_visible LEFT OUTER JOIN project ON project_user_visible.project_id = project.project_id", Project.class);
Query q = em.createNativeQuery("SELECT DISTINCT project.project_id as PROJECT_ID, project.project_title as PROJECT_TITLE, project.flag_public as FLAG_PUBLIC, project.project_description as PROJECT_DESCRIPTION, project.user_created as USER_CREATED, project.date_created as DATE_CREATED, project.start_date as START_DATE, project.end_date as END_DATE, project.start_date_real as START_DATE_REAL, project.end_date_real as END_DATE_REAL, project.parent_project_id as PARENT_PROJECT_ID, project.completed as COMPLETED, project.canceled as CANCELED, project.deleted as DELETED, project.user_assigned as USER_ASSIGNED FROM project LEFT OUTER JOIN project_user_visible ON project.project_id = project_user_visible.project_id LEFT OUTER JOIN project_usergroup_visible ON project_usergroup_visible.project_id = project.project_id LEFT OUTER JOIN project_client ON project_client.project_id = project.project_id LEFT OUTER JOIN client ON project_client.client_id = client.client_id LEFT OUTER JOIN client_user ON client_user.client_id = client.client_id LEFT OUTER JOIN usergroup ON usergroup.usergroup_id = project_usergroup_visible.usergroup_id LEFT OUTER JOIN user_usergroup ON usergroup.usergroup_id = user_usergroup.usergroup_id WHERE (project.deleted = false or project.deleted IS NULL) AND ((project.flag_public = TRUE) OR (user_usergroup.user_id = ?1) OR (client_user.user_id = ?1) OR (project_user_visible.user_id = ?1) OR (project.user_created = ?1) OR (project.user_assigned = ?1)) AND project.parent_project_id IS NULL", Project.class);
q.setParameter(1, getAuthenticatedUser().getUserId());
//q.setParameter(2, getAuthenticatedUser().getUserId());
//q.setParameter(3, getAuthenticatedUser().getUserId());
//Query q = em.createNativeQuery("SELECT DISTINCT project as PROJECT FROM project_user_visible LEFT OUTER JOIN project ON project_user_visible.project_id = project.project_id", Project.class);
//q.setParameter("userAssignedId", getAuthenticatedUser().getUserId());
List<Project> prjList = new ArrayList<Project>();
prjList = q.getResultList();
Query subquery = em.createNativeQuery("SELECT DISTINCT project.project_id as PROJECT_ID, project.project_title as PROJECT_TITLE, project.flag_public as FLAG_PUBLIC, project.project_description as PROJECT_DESCRIPTION, project.user_created as USER_CREATED, project.date_created as DATE_CREATED, project.start_date as START_DATE, project.end_date as END_DATE, project.start_date_real as START_DATE_REAL, project.end_date_real as END_DATE_REAL, project.parent_project_id as PARENT_PROJECT_ID, project.completed as COMPLETED, project.canceled as CANCELED, project.deleted as DELETED, project.user_assigned as USER_ASSIGNED FROM project LEFT OUTER JOIN project_user_visible ON project.project_id = project_user_visible.project_id LEFT OUTER JOIN project_usergroup_visible ON project_usergroup_visible.project_id = project.project_id LEFT OUTER JOIN project_client ON project_client.project_id = project.project_id LEFT OUTER JOIN client ON project_client.client_id = client.client_id LEFT OUTER JOIN client_user ON client_user.client_id = client.client_id LEFT OUTER JOIN usergroup ON usergroup.usergroup_id = project_usergroup_visible.usergroup_id LEFT OUTER JOIN user_usergroup ON usergroup.usergroup_id = user_usergroup.usergroup_id WHERE project.parent_project_id = ?1 AND (project.deleted = false or project.deleted IS NULL) AND ((project.flag_public = TRUE) OR (user_usergroup.user_id = ?2) OR (client_user.user_id = ?2) OR (project_user_visible.user_id = ?2) OR (project.user_created = ?1) OR (project.user_assigned = ?1))", Project.class);
subquery.setParameter(2, getAuthenticatedUser().getUserId());
// get projects. Pas des sous-projets.
getProjects(prjList, projectList, null, subquery);
HashMap<String, Object> retProjects = new HashMap<String, Object>();
retProjects.put("project", projectList);
try {
retVal = mapper.writeValueAsString(retProjects);
} catch (IOException ex) {
Logger.getLogger(ProjectFacadeREST.class.getName()).log(Level.SEVERE, null, ex);
}
return retVal;
}
// returns parent objects including its children
@GET
@Path("filter")
@Produces("application/json")
public String findAllProjectsFilter(@QueryParam("status") String statusId, @QueryParam("minDate") String minDate, @QueryParam("maxDate") String maxDate) {
String retVal = "";
ObjectMapper mapper = new ObjectMapper();
List<Map> projectList = new ArrayList<Map>();
Query q;
String filterQuery = "";
if (statusId != null) {
filterQuery += " AND (" + statusId + "= (SELECT status_id FROM Progress p WHERE p.project_id = project.project_id order by p.date_created DESC LIMIT 1))";
}
// if (minDate != null && maxDate != null) {
// filterQuery += " AND (project.start_date BETWEEN " + minDate + " and " + maxDate + ")";
// } else {
if (minDate != null) {
filterQuery += " AND (project.start_date >= " + minDate + ")";
}
if (maxDate != null) {
filterQuery += " AND (project.end_date <= " + maxDate + ")";
}
if (security.isUserInRole("administrator")) {
//q = em.createNamedQuery("Project.getParentProjects");
q = em.createNativeQuery("SELECT DISTINCT project.project_id as PROJECT_ID, project.project_title as PROJECT_TITLE, project.flag_public as FLAG_PUBLIC, project.project_description as PROJECT_DESCRIPTION, project.user_created as USER_CREATED, project.date_created as DATE_CREATED, project.start_date as START_DATE, project.end_date as END_DATE, project.start_date_real as START_DATE_REAL, project.end_date_real as END_DATE_REAL, project.parent_project_id as PARENT_PROJECT_ID, project.completed as COMPLETED, project.canceled as CANCELED, project.deleted as DELETED, project.user_assigned as USER_ASSIGNED FROM project WHERE project.parent_project_id IS NULL" + filterQuery, Project.class);
List<Project> prjList = new ArrayList<Project>();
prjList = q.getResultList();
// get projects and its children
//getProjects(prjList, projectList, "Project.getChildProjects", "");
getProjects(prjList, projectList, em.createNamedQuery("Project.getChildProjects"), null);
} else {
q = em.createNativeQuery("SELECT DISTINCT project.project_id as PROJECT_ID, project.project_title as PROJECT_TITLE, project.flag_public as FLAG_PUBLIC, project.project_description as PROJECT_DESCRIPTION, project.user_created as USER_CREATED, project.date_created as DATE_CREATED, project.start_date as START_DATE, project.end_date as END_DATE, project.start_date_real as START_DATE_REAL, project.end_date_real as END_DATE_REAL, project.parent_project_id as PARENT_PROJECT_ID, project.completed as COMPLETED, project.canceled as CANCELED, project.deleted as DELETED, project.user_assigned as USER_ASSIGNED FROM project LEFT OUTER JOIN project_user_visible ON project.project_id = project_user_visible.project_id LEFT OUTER JOIN project_usergroup_visible ON project_usergroup_visible.project_id = project.project_id LEFT OUTER JOIN project_client ON project_client.project_id = project.project_id LEFT OUTER JOIN client ON project_client.client_id = client.client_id LEFT OUTER JOIN client_user ON client_user.client_id = client.client_id LEFT OUTER JOIN usergroup ON usergroup.usergroup_id = project_usergroup_visible.usergroup_id LEFT OUTER JOIN user_usergroup ON usergroup.usergroup_id = user_usergroup.usergroup_id WHERE (project.deleted = false or project.deleted IS NULL) AND ((project.flag_public = TRUE) OR (user_usergroup.user_id = ?1) OR (client_user.user_id = ?1) OR (project_user_visible.user_id = ?1) OR (project.user_created = ?1) OR (project.user_assigned = ?1)) AND project.parent_project_id IS NULL" + filterQuery, Project.class);
//Query q = em.createNativeQuery("SELECT DISTINCT project.project_id as PROJECT_ID, project.project_title as PROJECT_TITLE, project.flag_public as FLAG_PUBLIC, project.project_description as PROJECT_DESCRIPTION, project.user_created as USER_CREATED, project.date_created as DATE_CREATED, project.start_date as START_DATE, project.end_date as END_DATE, project.start_date_real as START_DATE_REAL, project.end_date_real as END_DATE_REAL, project.parent_project_id as PARENT_PROJECT_ID, project.completed as COMPLETED, project.canceled as CANCELED, project.deleted as DELETED, project.user_assigned as USER_ASSIGNED FROM project LEFT OUTER JOIN project_user_visible ON project.project_id = project_user_visible.project_id LEFT OUTER JOIN project_usergroup_visible ON project_usergroup_visible.project_id = project.project_id LEFT OUTER JOIN project_client ON project_client.project_id = project.project_id LEFT OUTER JOIN client ON project_client.client_id = client.client_id LEFT OUTER JOIN client_user ON client_user.client_id = client.client_id LEFT OUTER JOIN usergroup ON usergroup.usergroup_id = project_usergroup_visible.usergroup_id LEFT OUTER JOIN user_usergroup ON usergroup.usergroup_id = user_usergroup.usergroup_id WHERE (project.deleted = false or project.deleted IS NULL) AND ((project.flag_public = TRUE) OR (((user_usergroup.user_id = ?1) OR (client_user.user_id = ?1) OR (project_user_visible.user_id = ?1) OR (project.user_created = ?1) OR (project.user_assigned = ?1)) " + filterQuery + ")) AND project.parent_project_id IS NULL" + filterQuery, Project.class);
q.setParameter(1, getAuthenticatedUser().getUserId());
List<Project> prjList = new ArrayList<Project>();
prjList = q.getResultList();
Query subquery = em.createNativeQuery("SELECT DISTINCT project.project_id as PROJECT_ID, project.project_title as PROJECT_TITLE, project.flag_public as FLAG_PUBLIC, project.project_description as PROJECT_DESCRIPTION, project.user_created as USER_CREATED, project.date_created as DATE_CREATED, project.start_date as START_DATE, project.end_date as END_DATE, project.start_date_real as START_DATE_REAL, project.end_date_real as END_DATE_REAL, project.parent_project_id as PARENT_PROJECT_ID, project.completed as COMPLETED, project.canceled as CANCELED, project.deleted as DELETED, project.user_assigned as USER_ASSIGNED FROM project LEFT OUTER JOIN project_user_visible ON project.project_id = project_user_visible.project_id LEFT OUTER JOIN project_usergroup_visible ON project_usergroup_visible.project_id = project.project_id LEFT OUTER JOIN project_client ON project_client.project_id = project.project_id LEFT OUTER JOIN client ON project_client.client_id = client.client_id LEFT OUTER JOIN client_user ON client_user.client_id = client.client_id LEFT OUTER JOIN usergroup ON usergroup.usergroup_id = project_usergroup_visible.usergroup_id LEFT OUTER JOIN user_usergroup ON usergroup.usergroup_id = user_usergroup.usergroup_id WHERE project.parent_project_id = ?1 AND (project.deleted = false or project.deleted IS NULL) AND ((project.flag_public = TRUE) OR (user_usergroup.user_id = ?2) OR (client_user.user_id = ?2) OR (project_user_visible.user_id = ?2) OR (project.user_created = ?1) OR (project.user_assigned = ?1))", Project.class);
subquery.setParameter(2, getAuthenticatedUser().getUserId());
// get projects. Pas des sous-projets.
getProjects(prjList, projectList, null, subquery);
}
HashMap<String, Object> retProjects = new HashMap<String, Object>();
retProjects.put("project", projectList);
try {
retVal = mapper.writeValueAsString(retProjects);
} catch (IOException ex) {
Logger.getLogger(ProjectFacadeREST.class.getName()).log(Level.SEVERE, null, ex);
}
return retVal;
//return q.toString();
}
}
|
package tars.ui;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.logging.Logger;
import com.google.common.eventbus.Subscribe;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.scene.Node;
import javafx.scene.control.Label;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.HBox;
import javafx.stage.Stage;
import tars.commons.core.LogsCenter;
import tars.commons.events.model.TarsChangedEvent;
import tars.commons.util.DateTimeUtil;
import tars.commons.util.FxViewUtil;
import tars.model.task.ReadOnlyTask;
/**
* A Ui for the information header of the application
*/
public class InformationHeader extends UiPart {
private static final Logger logger = LogsCenter.getLogger(StatusBarFooter.class);
public static final String INFORMATION_HEADER_ID = "informationHeader";
private static final String INFO_HEADER_STYLE_SHEET = "info-header";
private static final String FXML = "InformationHeader.fxml";
private static final DateFormat df = new SimpleDateFormat("E d, MMM");
private static final String STATUS_UNDONE = "Undone";
private static ObservableList<ReadOnlyTask> list;
private AnchorPane placeHolder;
private AnchorPane mainPane;
@FXML
private HBox header;
@FXML
private Label date;
@FXML
private Label numUpcoming;
@FXML
private Label numOverdue;
public static InformationHeader load(Stage primaryStage, AnchorPane placeHolder
, ObservableList<ReadOnlyTask> taskList) {
InformationHeader infoHeader = UiPartLoader.loadUiPart(primaryStage, placeHolder, new InformationHeader());
list = taskList;
infoHeader.configure();
return infoHeader;
}
public void configure() {
header.getStyleClass().add(INFO_HEADER_STYLE_SHEET);
setDate();
setUpcoming();
setOverdue();
FxViewUtil.applyAnchorBoundaryParameters(header, 0.0, 0.0, 0.0, 0.0);
FxViewUtil.applyAnchorBoundaryParameters(mainPane, 0.0, 0.0, 0.0, 0.0);
placeHolder.getChildren().add(mainPane);
registerAsAnEventHandler(this);
}
private void setDate() {
Date today = new Date();
date.setText(df.format(today));
}
private void setUpcoming() {
int count = 0;
for (ReadOnlyTask t : list) {
if (DateTimeUtil.isWithinWeek(t.getDateTime().getEndDate())
&& t.getStatus().toString().equals(STATUS_UNDONE)) {
count++;
}
}
numUpcoming.setText(String.valueOf(count));
}
private void setOverdue() {
int count = 0;
for (ReadOnlyTask t : list) {
if (DateTimeUtil.isOverDue(t.getDateTime().getEndDate())
&& t.getStatus().toString().equals(STATUS_UNDONE)) {
count++;
}
}
numOverdue.setText(String.valueOf(count));
}
@Subscribe
public void handleTarsChangedEvent(TarsChangedEvent event) {
logger.info(LogsCenter.getEventHandlingLogMessage(event, "Update information header"));
setUpcoming();
setOverdue();
}
@Override
public void setNode(Node node) {
mainPane = (AnchorPane) node;
}
@Override
public void setPlaceholder(AnchorPane placeholder) {
this.placeHolder = placeholder;
}
@Override
public String getFxmlPath() {
return FXML;
}
}
|
package vontus.magicbottle;
import java.util.HashSet;
import java.util.UUID;
import org.bukkit.Material;
import org.bukkit.enchantments.Enchantment;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.block.Action;
import org.bukkit.event.inventory.CraftItemEvent;
import org.bukkit.event.inventory.InventoryClickEvent;
import org.bukkit.event.inventory.InventoryType;
import org.bukkit.event.inventory.PrepareItemCraftEvent;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.event.player.PlayerItemDamageEvent;
import org.bukkit.event.player.PlayerKickEvent;
import org.bukkit.event.player.PlayerQuitEvent;
import org.bukkit.inventory.CraftingInventory;
import org.bukkit.inventory.ItemStack;
import org.bukkit.scheduler.BukkitRunnable;
import vontus.magicbottle.config.Config;
import vontus.magicbottle.config.Messages;
import vontus.magicbottle.effects.SoundEffect;
import vontus.magicbottle.util.Exp;
import vontus.magicbottle.util.Utils;
public class Events implements Listener {
private HashSet<UUID> wait;
private Plugin plugin;
public Events(Plugin plugin) {
this.plugin = plugin;
this.wait = new HashSet<>();
}
@EventHandler(priority = EventPriority.HIGHEST)
public void onClickInventory(InventoryClickEvent e) {
InventoryType invType = e.getView().getType();
if (invType == InventoryType.ANVIL || invType == InventoryType.BREWING) {
e.setCancelled(MagicBottle.isMagicBottle(e.getCurrentItem()));
}
}
@EventHandler(priority = EventPriority.HIGHEST)
public void onInteract(PlayerInteractEvent event) {
Player player = event.getPlayer();
Action act = event.getAction();
ItemStack item = event.getItem();
if (MagicBottle.isMagicBottle(item)) {
MagicBottle mb = new MagicBottle(item);
if (item.getAmount() == 1 && timeOut(player)) {
if (act == Action.LEFT_CLICK_AIR || act == Action.LEFT_CLICK_BLOCK) {
onInteractDeposit(mb, player);
} else if (act == Action.RIGHT_CLICK_AIR || act == Action.RIGHT_CLICK_BLOCK) {
onInteractWithdraw(mb, player);
}
}
event.setCancelled(true);
player.updateInventory();
}
}
@EventHandler(priority = EventPriority.HIGHEST)
public void onPrepareCraft(PrepareItemCraftEvent event) {
if (event.getRecipe() != null) {
ItemStack r = event.getRecipe().getResult();
if (MagicBottle.isMagicBottle(r)) {
MagicBottle result = new MagicBottle(r);
if (MagicBottle.isMagicBottle(getFirstIngredient(event.getInventory()))) {
if (result.isEmpty()) {
onPrepareRecipeWithdraw(event);
} else {
onPrepareRecipeDeposit(event);
}
} else {
if (!isEmptyBottleRecipe(event.getInventory())) {
event.getInventory().setResult(null);
}
}
}
}
}
@EventHandler(priority = EventPriority.HIGHEST)
public void onCraft(CraftItemEvent e) {
if (MagicBottle.isMagicBottle(e.getRecipe().getResult())) {
MagicBottle result = new MagicBottle(e.getRecipe().getResult());
if (MagicBottle.isMagicBottle(getFirstIngredient(e.getInventory()))) {
if (result.isEmpty()) {
onRecipeWithdraw(e);
} else {
onRecipeDeposit(e);
}
} else {
if (MagicBottle.isMagicBottle(e.getRecipe().getResult())) {
if (isEmptyBottleRecipe(e.getInventory())) {
Player player = (Player) e.getView().getPlayer();
if (player.hasPermission(Config.permCraft)) {
if (chargeNewBottleMoney(player)) {
e.getInventory().setResult(new MagicBottle(0).getItem());
SoundEffect.newBottle(player);
} else {
SoundEffect.forbidden(player);
player.sendMessage(Messages.msgNotEnoughMoney.replace(Messages.moneyReplacer,
Double.toString(Config.costMoneyCraftNewBottle)));
e.setCancelled(true);
}
} else {
player.sendMessage(Messages.msgUnauthorizedToCraft);
e.setCancelled(true);
}
}
}
}
}
}
@EventHandler(priority = EventPriority.HIGHEST)
public void onItemUse(PlayerItemDamageEvent e) {
Player p = e.getPlayer();
if (Config.repairAutoEnabled && timeOut(p)) {
ItemStack i = e.getItem();
if (plugin.autoEnabled.contains(p) && i.containsEnchantment(Enchantment.MENDING)
&& i.getDurability() % 2 != 0) {
MagicBottle mb = MagicBottle.getUsableMBInToolsbar(p);
if (mb != null && !e.isCancelled()) {
i.setDurability((short) (i.getDurability() + e.getDamage()));
mb.repair(i);
e.setCancelled(true);
p.updateInventory();
}
}
}
}
@EventHandler
public void onPlayerLeave(PlayerQuitEvent e) {
plugin.autoEnabled.remove(e.getPlayer());
}
@EventHandler
public void onPlayerKicked(PlayerKickEvent e) {
plugin.autoEnabled.remove(e.getPlayer());
}
private void onInteractDeposit(MagicBottle bottle, Player p) {
if (Exp.getPoints(p) > 0) {
if (p.hasPermission(Config.permDeposit)) {
int round = p.isSneaking() ? 1 : 0;
int targetPlayerLevel = Exp.floorLevel(p, round);
int expToDeposit = Exp.getExpToLevel(p, targetPlayerLevel) * -1;
bottle.deposit(p, expToDeposit);
} else
p.sendMessage(Messages.msgUnauthorizedToDeposit);
}
}
private void onInteractWithdraw(MagicBottle bottle, Player p) {
if (bottle.getExp() > 0) {
if (p.hasPermission(Config.permWithdraw)) {
int round = p.isSneaking() ? 1 : 0;
int targetPlayerLevel = Exp.ceilingLevel(p, round);
int expToWithdraw = Exp.getExpToLevel(p, targetPlayerLevel);
bottle.withdraw(p, expToWithdraw);
} else {
p.sendMessage(Messages.msgUnauthorizedToWithdraw);
}
}
}
private void onPrepareRecipeWithdraw(PrepareItemCraftEvent e) {
Player player = (Player) e.getView().getPlayer();
if (!Config.recipePour || !player.hasPermission(Config.permWithdraw)) {
e.getInventory().setResult(null);
}
}
private void onPrepareRecipeDeposit(PrepareItemCraftEvent e) {
Player player = (Player) e.getView().getPlayer();
if (Config.recipeFill && player.hasPermission(Config.permDeposit) && Exp.getPoints(player) > 0) {
MagicBottle bottle = new MagicBottle(0);
int playerPoints = Exp.getPoints(player);
int expCost = (int) Math.round(playerPoints * Config.costPercentageDeposit);
int maxPoints = bottle.getMaxFillablePoints(player, playerPoints - expCost);
bottle.setExp(maxPoints);
e.getInventory().setResult(bottle.getItem());
} else {
e.getInventory().setResult(null);
}
}
private void onRecipeWithdraw(CraftItemEvent e) {
Player player = (Player) e.getView().getPlayer();
ItemStack i = getFirstIngredient(e.getInventory());
if (i.getAmount() == 1 && Config.recipePour && player.hasPermission(Config.permWithdraw)) {
MagicBottle bottle = new MagicBottle(i);
bottle.withdraw(player, bottle.getExp());
e.getInventory().setResult(new MagicBottle(0).getItem());
} else {
e.setCancelled(true);
}
}
private void onRecipeDeposit(CraftItemEvent e) {
Player player = (Player) e.getView().getPlayer();
ItemStack ingr = getFirstIngredient(e.getInventory());
if (ingr.getAmount() == 1 && Exp.getPoints(player) > 0 && player.hasPermission(Config.permDeposit)
&& Config.recipeFill) {
MagicBottle bottle = new MagicBottle(0);
bottle.deposit(player, Exp.getPoints(player));
e.getInventory().setResult(bottle.getItem());
} else {
e.setCancelled(true);
}
}
private ItemStack getFirstIngredient(CraftingInventory inv) {
for (ItemStack i : inv.getMatrix()) {
if (Utils.getMaterial(i) != Material.AIR) {
return i;
}
}
return null;
}
private boolean timeOut(Player p) {
if (!wait.contains(p.getUniqueId())) {
wait.add(p.getUniqueId());
new BukkitRunnable() {
@Override
public void run() {
wait.remove(p.getUniqueId());
}
}.runTaskLater(this.plugin, 3);
return true;
} else {
return false;
}
}
private boolean isEmptyBottleRecipe(CraftingInventory inv) {
for (int i = 0; i < 9; i++) {
ItemStack item = inv.getMatrix()[i];
Material m = Config.getBottleRecipeIngredient(i + 1);
if (!Utils.getMaterial(item).equals(m) || MagicBottle.isMagicBottle(item)) {
return false;
}
}
return true;
}
private boolean chargeNewBottleMoney(Player p) {
if (Config.costMoneyCraftNewBottle != 0 && !p.hasPermission(Config.permCraftCostExempt)) {
return plugin.econ.withdrawPlayer(p, Config.costMoneyCraftNewBottle).transactionSuccess();
} else {
return true;
}
}
}
|
package water.api;
import water.MRTask2;
import water.Model;
import water.Request2;
import water.UKV;
import water.fvec.Chunk;
import water.fvec.Frame;
import water.fvec.TransfVec;
import water.fvec.Vec;
import water.util.Utils;
import java.util.Arrays;
import static water.util.Utils.printConfusionMatrix;
/**
* Compare two categorical columns, reporting a grid of co-occurrences.
*
* <p>The semantics follows R-approach - see R code:
* <pre>
* > l = c("A", "B", "C")
* > a = factor(c("A", "B", "C"), levels=l)
* > b = factor(c("A", "B", "A"), levels=l)
* > confusionMatrix(a,b)
*
* Reference
* Prediction A B C
* A 1 0 0
* B 0 1 0
* C 1 0 0
* </pre></p>
*
* <p>Note: By default we report zero rows and columns.</p>
*
* @author cliffc
*/
public class ConfusionMatrix extends Request2 {
static final int API_WEAVER = 1; // This file has auto-gen'd doc & json fields
static public DocGen.FieldDoc[] DOC_FIELDS; // Initialized from Auto-Gen code.
@API(help = "", required = true, filter = Default.class)
public Frame actual;
@API(help="Column of the actual results (will display vertically)", required=true, filter=actualVecSelect.class)
public Vec vactual;
class actualVecSelect extends VecClassSelect { actualVecSelect() { super("actual"); } }
@API(help = "", required = true, filter = Default.class)
public Frame predict;
@API(help="Column of the predicted results (will display horizontally)", required=true, filter=predictVecSelect.class)
public Vec vpredict;
class predictVecSelect extends VecClassSelect { predictVecSelect() { super("predict"); } }
@API(help="domain of the actual response")
String [] actual_domain;
@API(help="domain of the predicted response")
String [] predicted_domain;
@API(help="union of domains")
public
String [] domain;
@API(help="Confusion Matrix (or co-occurrence matrix)")
public long cm[][];
@API(help="Mean Squared Error")
public double mse = Double.NaN;
private boolean classification;
@Override public Response serve() {
Vec va = null,vp = null, avp = null;
classification = vactual.isInt() && vpredict.isInt();
// Input handling
if( vactual==null || vpredict==null )
throw new IllegalArgumentException("Missing actual or predict!");
if (vactual.length() != vpredict.length())
throw new IllegalArgumentException("Both arguments must have the same length!");
try {
if (classification) {
// Create a new vectors - it is cheap since vector are only adaptation vectors
va = vactual .toEnum(); // always returns TransfVec
actual_domain = va._domain;
vp = vpredict.toEnum(); // always returns TransfVec
predicted_domain = vp._domain;
if (!Arrays.equals(actual_domain, predicted_domain)) {
domain = Utils.domainUnion(actual_domain, predicted_domain);
int[][] vamap = Model.getDomainMapping(domain, actual_domain, true);
va = TransfVec.compose( (TransfVec) va, vamap, domain, false ); // delete original va
int[][] vpmap = Model.getDomainMapping(domain, predicted_domain, true);
vp = TransfVec.compose( (TransfVec) vp, vpmap, domain, false ); // delete original vp
} else domain = actual_domain;
// The vectors are from different groups => align them, but properly delete it after computation
if (!va.group().equals(vp.group())) {
avp = vp;
vp = va.align(vp);
}
cm = new CM(domain.length).doAll(va,vp)._cm;
} else {
if (vactual.isEnum())
throw new IllegalArgumentException("Actual vector cannot be categorical for regression scoring.");
if (vpredict.isEnum())
throw new IllegalArgumentException("Predicted vector cannot be categorical for regression scoring.");
mse = new CM(1).doAll(vactual,vpredict).mse();
}
return Response.done(this);
} catch( Throwable t ) {
return Response.error(t);
} finally { // Delete adaptation vectors
if (va!=null) UKV.remove(va._key);
if (vp!=null) UKV.remove(vp._key);
if (avp!=null) UKV.remove(avp._key);
}
}
// Compute the co-occurrence matrix
private static class CM extends MRTask2<CM> {
final int _c_len;
/* @OUT Classification */ long _cm[][];
/* @OUT Regression */ public double mse() { return _count > 0 ? _mse/_count : Double.POSITIVE_INFINITY; }
/* @OUT Regression Helper */ private double _mse;
/* @OUT Regression Helper */ private long _count;
CM(int c_len) { _c_len = c_len; }
@Override public void map( Chunk ca, Chunk cp ) {
//classification
if (_c_len > 1) {
_cm = new long[_c_len+1][_c_len+1];
int len = Math.min(ca._len,cp._len); // handle different lenghts, but the vectors should have been rejected already
for( int i=0; i < len; i++ ) {
int a=ca.isNA0(i) ? _c_len : (int)ca.at80(i);
int p=cp.isNA0(i) ? _c_len : (int)cp.at80(i);
_cm[a][p]++;
}
if( len < ca._len )
for( int i=len; i < ca._len; i++ )
_cm[ca.isNA0(i) ? _c_len : (int)ca.at80(i)][_c_len]++;
if( len < cp._len )
for( int i=len; i < cp._len; i++ )
_cm[_c_len][cp.isNA0(i) ? _c_len : (int)cp.at80(i)]++;
} else {
_cm = null;
_mse = 0;
assert(ca._len == cp._len);
int len = ca._len;
for( int i=0; i < len; i++ ) {
if (ca.isNA0(i) || cp.isNA0(i)) continue; //TODO: Improve
final double a=ca.at0(i);
final double p=cp.at0(i);
_mse += (p-a)*(p-a);
_count++;
}
}
}
@Override public void reduce( CM cm ) {
if (_cm != null && cm._cm != null) {
Utils.add(_cm,cm._cm);
} else {
assert(_mse != Double.NaN && cm._mse != Double.NaN);
assert(_cm == null && cm._cm == null);
_mse += cm._mse;
_count += cm._count;
}
}
}
@Override public boolean toHTML( StringBuilder sb ) {
if (classification) {
DocGen.HTML.section(sb,"Confusion Matrix");
if( cm == null ) return true;
printConfusionMatrix(sb, cm, domain, true);
} else{
DocGen.HTML.section(sb,"Mean Squared Error");
if( mse == Double.NaN ) return true;
DocGen.HTML.arrayHead(sb);
sb.append("<tr class='warning'><td>" + mse + "</td></tr>");
DocGen.HTML.arrayTail(sb);
}
return true;
}
public void toASCII( StringBuilder sb ) {
if (classification) {
if(cm == null) return;
printConfusionMatrix(sb, cm, domain, false);
} else {
sb.append("MSE: " + mse);
}
}
}
|
package lombok.ast.grammar;
import lombok.ast.Node;
import org.parboiled.BaseParser;
import org.parboiled.Rule;
public class TypesParser extends BaseParser<Node> {
final ParserGroup group;
final TypesActions actions;
public TypesParser(ParserGroup group) {
actions = new TypesActions(group.getSource());
this.group = group;
}
public Rule nonArrayType() {
return firstOf(primitiveType(), referenceType());
}
public Rule type() {
return sequence(
nonArrayType(),
SET(),
zeroOrMore(sequence(
ch('['), group.basics.optWS(), ch(']'), group.basics.optWS())),
SET(actions.setArrayDimensionsOfType(VALUE(), TEXTS("zeroOrMore/sequence")))).label("type");
}
public Rule primitiveType() {
return enforcedSequence(
firstOf(
sequence(string("boolean"), group.basics.testLexBreak()),
sequence(string("int"), group.basics.testLexBreak()),
sequence(string("long"), group.basics.testLexBreak()),
sequence(string("double"), group.basics.testLexBreak()),
sequence(string("float"), group.basics.testLexBreak()),
sequence(string("short"), group.basics.testLexBreak()),
sequence(string("char"), group.basics.testLexBreak()),
sequence(string("byte"), group.basics.testLexBreak()),
sequence(string("void"), group.basics.testLexBreak())),
SET(actions.createPrimitiveType(TEXT("firstOf/sequence"))),
group.basics.optWS());
}
public Rule referenceType() {
return sequence(
referenceTypePart().label("head"),
zeroOrMore(dotReferenceTypePart().label("tail")),
SET(actions.createReferenceType(VALUE("head"), VALUES("zeroOrMore/tail"))));
}
Rule dotReferenceTypePart() {
return sequence(
ch('.'), group.basics.optWS(),
group.basics.identifier().label("partName"),
optional(typeArguments()),
SET(actions.createTypeReferencePart(NODE("partName"), VALUE("optional/typeArguments"))),
group.basics.optWS());
}
Rule referenceTypePart() {
return sequence(
group.basics.identifier().label("partName"),
optional(typeArguments()),
SET(actions.createTypeReferencePart(NODE("partName"), VALUE("optional/typeArguments"))),
group.basics.optWS());
}
public Rule plainReferenceType() {
return sequence(
plainReferenceTypePart().label("head"),
zeroOrMore(dotPlainReferenceTypePart().label("tail")),
SET(actions.createReferenceType(VALUE("head"), VALUES("zeroOrMore/tail"))));
}
Rule plainReferenceTypePart() {
return sequence(
group.basics.identifier().label("partName"),
SET(actions.createTypeReferencePart(NODE("partName"), null)),
group.basics.optWS());
}
Rule dotPlainReferenceTypePart() {
return sequence(
ch('.'), group.basics.optWS(),
group.basics.identifier().label("partName"),
SET(actions.createTypeReferencePart(NODE("partName"), null)),
group.basics.optWS());
}
public Rule typeVariables() {
return optional(enforcedSequence(
ch('<'),
group.basics.optWS(),
optional(enforcedSequence(
typeVariable().label("head"),
zeroOrMore(enforcedSequence(
ch(','),
group.basics.optWS(),
typeVariable().label("tail"))))),
ch('>'),
SET(actions.createTypeVariables(VALUE("optional/enforcedSequence/head"), VALUES("optional/enforcedSequence/zeroOrMore/enforcedSequence/tail"))),
group.basics.optWS()));
}
Rule typeVariable() {
return sequence(
group.basics.identifier(),
optional(enforcedSequence(
sequence(
string("extends"),
group.basics.testLexBreak(),
group.basics.optWS()),
type(),
zeroOrMore(sequence(
ch('&'), group.basics.optWS(),
type())))),
SET(actions.createTypeVariable(VALUE("identifier"), VALUE("optional/enforcedSequence/type"), VALUES("optional/enforcedSequence/zeroOrMore/sequence/type"))));
}
public Rule typeArguments() {
return optional(sequence(
ch('<'),
group.basics.optWS(),
optional(sequence(
typeArgument().label("head"),
zeroOrMore(sequence(
ch(','),
group.basics.optWS(),
typeArgument().label("tail"))))),
ch('>'),
SET(actions.createTypeArguments(VALUE("optional/sequence/head"), VALUES("optional/sequence/zeroOrMore/sequence/tail"))),
group.basics.optWS())).label("typeArguments");
}
public Rule typeArgument() {
return firstOf(
type(),
sequence(
ch('?').label("qmark"),
group.basics.optWS(),
firstOf(string("extends"), string("super")).label("boundType"),
group.basics.testLexBreak(),
group.basics.optWS(),
type(),
SET(actions.createWildcardedType(NODE("qmark"), NODE("boundType"), TEXT("boundType"), VALUE("type")))),
sequence(
ch('?').label("qmark"),
SET(actions.createUnboundedWildcardType(NODE("qmark"))),
group.basics.optWS()));
}
}
|
package org.greip.color;
import java.util.function.Consumer;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.GC;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.ImageData;
import org.eclipse.swt.graphics.PaletteData;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.graphics.RGB;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.greip.common.Util;
public class ColorButton extends Button {
private RGB rgb;
private Image image;
private IColorChooserFactory factory;
private Consumer<RGB> consumer;
public ColorButton(final Composite parent) {
super(parent, SWT.PUSH);
addListener(SWT.Resize, e -> changeImage());
addListener(SWT.Dispose, e -> disposeImage());
addListener(SWT.Selection, e -> {
if (factory != null && consumer != null) {
Util.whenNotNull(chooseRGB(factory), consumer);
}
});
setRGB(new RGB(255, 255, 255));
}
@Override
protected void checkSubclass() {
// allow subclassing
}
public RGB chooseRGB(final IColorChooserFactory factory) {
final ColorChooserPopup colorChooserPopup = new ColorChooserPopup(this);
colorChooserPopup.createContent(factory);
colorChooserPopup.setRGB(rgb);
colorChooserPopup.open();
final RGB newRGB = colorChooserPopup.getRGB();
Util.whenNotNull(newRGB, this::setRGB);
return newRGB;
}
@Override
public Point computeSize(final int wHint, final int hHint, final boolean changed) {
final Point size = super.computeSize(wHint, hHint, changed);
return new Point(Math.max(wHint, getTextSize().x + 30), size.y);
}
public void setRGB(final RGB rgb) {
this.rgb = rgb;
changeImage();
}
public RGB getRGB() {
return rgb;
}
@Override
public void setText(final String string) {
super.setText(string);
changeImage();
}
private Point getTextSize() {
final Point size = Util.getTextSize(this, getText(), SWT.DRAW_MNEMONIC);
if (size.x > 0) {
size.x += 6;
}
return size;
}
private void changeImage() {
final Point size = getSize();
if (size.x == 0 || size.y == 0) {
return;
}
final int height = size.y - 16;
final int width = getText().isEmpty() ? size.x - 21 : height;
if (height <= 0 || width <= 0) {
return;
}
final PaletteData palette = new PaletteData(0xFF, 0xFF00, 0xFF0000);
final ImageData source = new ImageData(width, height, 24, palette);
source.transparentPixel = 0;
disposeImage();
image = new Image(getDisplay(), source);
final GC gc = new GC(image);
if (rgb != null && isEnabled()) {
final Color color = new Color(gc.getDevice(), rgb);
gc.setBackground(color);
gc.fillRectangle(0, 0, width, height);
color.dispose();
}
gc.setForeground(getDisplay().getSystemColor(isEnabled() ? SWT.COLOR_DARK_GRAY : SWT.COLOR_GRAY));
gc.drawRectangle(0, 0, width - 1, height - 1);
gc.dispose();
setImage(image);
}
private void disposeImage() {
Util.whenNotNull(image, image::dispose);
}
public void setColorChooserFactory(final IColorChooserFactory factory) {
this.factory = factory;
}
public void setColorConsumer(final Consumer<RGB> consumer) {
this.consumer = consumer;
}
}
|
package be.ibridge.kettle.core;
import java.util.Hashtable;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.Font;
import org.eclipse.swt.graphics.GC;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Listener;
import be.ibridge.kettle.trans.StepLoader;
import be.ibridge.kettle.trans.StepPlugin;
/**
* This is a singleton class that contains allocated Fonts, Colors, etc.
* All colors etc. are allocated once and released once at the end of the program.
*
* @author Matt
* @since 27/10/2005
*
*/
public class GUIResource
{
private static GUIResource guiResource;
private Display display;
// 33 resources
/* * * Colors * * */
private Color colorBackground;
private Color colorGraph;
private Color colorTab;
private Color colorRed;
private Color colorGreen;
private Color colorBlue;
private Color colorOrange;
private Color colorYellow;
private Color colorMagenta;
private Color colorBlack;
private Color colorGray;
private Color colorDarkGray;
private Color colorLightGray;
private Color colorDemoGray;
private Color colorWhite;
private Color colorDirectory;
/* * * Fonts * * */
private Font fontGraph;
private Font fontNote;
// private Font fontGrid;
// private Font fontDefault;
private Font fontFixed;
/* * * Images * * */
private Hashtable imagesSteps;
private Hashtable imagesStepsSmall;
private Image imageHop;
private Image imageConnection;
private Image imageBol;
private Image imageKettle;
private Image imageCredits;
private Image imageStart;
private Image imageDummy;
private Image imageSpoon;
private GUIResource(Display display)
{
this.display = display;
getResources(false);
display.addListener(SWT.Dispose, new Listener()
{
public void handleEvent(Event event)
{
dispose();
}
}
);
}
public static final GUIResource getInstance()
{
if (guiResource!=null) return guiResource;
guiResource = new GUIResource(Props.getInstance().getDisplay());
return guiResource;
}
public void reload()
{
dispose();
getResources(true);
}
private void getResources(boolean reload)
{
Props props = Props.getInstance();
if (props.getBackgroundRGB()!=null) colorBackground = new Color(display, props.getBackgroundRGB() );
if (props.getGraphColorRGB()!=null) colorGraph = new Color(display, props.getGraphColorRGB() );
if (props.getTabColorRGB() !=null) colorTab = new Color(display, props.getTabColorRGB() );
colorRed = new Color(display, 255, 0, 0 );
colorGreen = new Color(display, 0, 255, 0 );
colorBlue = new Color(display, 0, 0, 255 );
colorGray = new Color(display, 100, 100, 100 );
colorYellow = new Color(display, 255, 255, 0 );
colorMagenta = new Color(display, 255, 0, 255);
colorOrange = new Color(display, 255, 165, 0 );
colorWhite = new Color(display, 255, 255, 255 );
colorDemoGray = new Color(display, 248, 248, 248 );
colorLightGray = new Color(display, 225, 225, 225 );
colorDarkGray = new Color(display, 100, 100, 100 );
colorBlack = new Color(display, 0, 0, 0 );
colorDirectory = new Color(display, 0, 0, 255 );
if (props.getGraphFont() != null) fontGraph = new Font(display, props.getGraphFont());
if (props.getNoteFont() != null) fontNote = new Font(display, props.getNoteFont());
// if (props.getGridFont() != null) fontGrid = new Font(display, props.getGridFont());
// if (props.getDefaultFont() != null) fontDefault = new Font(display, props.getDefaultFont());
if (props.getFixedFont() != null) fontFixed = new Font(display, props.getFixedFont());
// Load all images from files...
if (!reload) loadStepImages();
}
private void dispose()
{
// Colors
if (colorBackground!=null) colorBackground.dispose();
if (colorGraph !=null) colorGraph .dispose();
if (colorTab !=null) colorTab .dispose();
colorRed .dispose();
colorGreen .dispose();
colorBlue .dispose();
colorGray .dispose();
colorYellow .dispose();
colorMagenta .dispose();
colorOrange .dispose();
colorWhite .dispose();
colorDemoGray .dispose();
colorLightGray.dispose();
colorDarkGray .dispose();
colorBlack .dispose();
colorDirectory.dispose();
// Fonts
if (fontGraph !=null) fontGraph .dispose();
if (fontNote !=null) fontNote .dispose();
// if (fontGrid !=null) fontGrid .dispose();
// if (fontDefault!=null) fontDefault.dispose();
if (fontFixed !=null) fontFixed .dispose();
// Images
/*
Enumeration en = imagesStepsSmall.elements();
while (en.hasMoreElements())
{
Image im = (Image) en.nextElement();
im.dispose();
}
en = imagesSteps.elements();
while (en.hasMoreElements())
{
Image im = (Image) en.nextElement();
im.dispose();
}
imageHop.dispose();
imageBol.dispose();
imageConnection.dispose();
imageCredits.dispose();
imageKettle.dispose();
imageStart.dispose();
imageDummy.dispose();
imageSpoon.dispose();
*/
}
/**
* Load all step/jobentry images from files.
*
*/
private void loadStepImages()
{
imagesSteps = new Hashtable();
imagesStepsSmall = new Hashtable();
LogWriter log = LogWriter.getInstance();
//// STEP IMAGES TO LOAD
StepLoader steploader = StepLoader.getInstance();
StepPlugin steps[] = steploader.getStepsWithType(StepPlugin.TYPE_ALL);
for (int i = 0; i < steps.length; i++)
{
Image image = null;
Image small_image = null;
if (steps[i].isNative())
{
String filename = steps[i].getIconFilename();
try
{
image = new Image(display, getClass().getResourceAsStream(filename));
}
catch(Exception e)
{
log.logError("Kettle", "Unable to find required image file ["+(Const.IMAGE_DIRECTORY + filename)+" : "+e.toString());
image = new Image(display, Const.ICON_SIZE, Const.ICON_SIZE);
GC gc = new GC(image);
gc.drawRectangle(0,0,Const.ICON_SIZE, Const.ICON_SIZE);
gc.drawLine(0,0,Const.ICON_SIZE, Const.ICON_SIZE);
gc.drawLine(Const.ICON_SIZE, 0, 0, Const.ICON_SIZE);
gc.dispose();
}
}
else
{
String filename = steps[i].getIconFilename();
try
{
image = new Image(display, filename);
}
catch(Exception e)
{
log.logError("Kettle", "Unable to find required image file ["+(Const.IMAGE_DIRECTORY + filename)+" : "+e.toString());
image = new Image(display, Const.ICON_SIZE, Const.ICON_SIZE);
GC gc = new GC(image);
gc.drawRectangle(0,0,Const.ICON_SIZE, Const.ICON_SIZE);
gc.drawLine(0,0,Const.ICON_SIZE, Const.ICON_SIZE);
gc.drawLine(Const.ICON_SIZE, 0, 0, Const.ICON_SIZE);
gc.dispose();
}
}
// Calculate the smaller version of the image @ 16x16...
// Perhaps we should make this configurable?
if (image != null)
{
int xsize = image.getBounds().width;
int ysize = image.getBounds().height;
small_image = new Image(display, 16, 16);
GC gc = new GC(small_image);
gc.drawImage(image, 0, 0, xsize, ysize, 0, 0, 16, 16);
gc.dispose();
}
imagesSteps.put(steps[i].getID(), image);
imagesStepsSmall.put(steps[i].getID(), small_image);
}
imageHop = new Image(display, getClass().getResourceAsStream(Const.IMAGE_DIRECTORY + "HOP.png"));
imageConnection = new Image(display, getClass().getResourceAsStream(Const.IMAGE_DIRECTORY + "CNC.png"));
imageBol = new Image(display, getClass().getResourceAsStream(Const.IMAGE_DIRECTORY + "BOL.png"));
imageKettle = new Image(display, getClass().getResourceAsStream(Const.IMAGE_DIRECTORY + "kettle_logo.png"));
imageCredits = new Image(display, getClass().getResourceAsStream(Const.IMAGE_DIRECTORY + "credits.png"));
imageStart = new Image(display, getClass().getResourceAsStream(Const.IMAGE_DIRECTORY + "STR.png"));
imageDummy = new Image(display, getClass().getResourceAsStream(Const.IMAGE_DIRECTORY + "DUM.png"));
imageSpoon = new Image(display, getClass().getResourceAsStream(Const.IMAGE_DIRECTORY + "spoon32.png"));
}
/**
* @return Returns the colorBackground.
*/
public Color getColorBackground()
{
Color retval = colorBackground;
if (retval==null) retval = display.getSystemColor(SWT.COLOR_WIDGET_BACKGROUND);
if (retval.isDisposed()) throw new RuntimeException("Color can not be disposed!!");
return retval;
}
/**
* @return Returns the colorBlack.
*/
public Color getColorBlack()
{
Color retval = colorBlack;
if (retval.isDisposed()) throw new RuntimeException("Color can not be disposed!!");
return retval;
}
/**
* @return Returns the colorBlue.
*/
public Color getColorBlue()
{
Color retval = colorBlue;
if (retval.isDisposed()) throw new RuntimeException("Color can not be disposed!!");
return retval;
}
/**
* @return Returns the colorDarkGray.
*/
public Color getColorDarkGray()
{
Color retval = colorDarkGray;
if (retval.isDisposed()) throw new RuntimeException("Color can not be disposed!!");
return retval;
}
/**
* @return Returns the colorDemoGray.
*/
public Color getColorDemoGray()
{
Color retval = colorDemoGray;
if (retval.isDisposed()) throw new RuntimeException("Color can not be disposed!!");
return retval;
}
/**
* @return Returns the colorDirectory.
*/
public Color getColorDirectory()
{
Color retval = colorDirectory;
if (retval.isDisposed()) throw new RuntimeException("Color can not be disposed!!");
return retval;
}
/**
* @return Returns the colorGraph.
*/
public Color getColorGraph()
{
Color retval = colorGraph;
if (retval==null) retval = display.getSystemColor(SWT.COLOR_WIDGET_BACKGROUND);
if (retval.isDisposed()) throw new RuntimeException("Color can not be disposed!!");
return retval;
}
/**
* @return Returns the colorGray.
*/
public Color getColorGray()
{
Color retval = colorGray;
if (retval.isDisposed()) throw new RuntimeException("Color can not be disposed!!");
return retval;
}
/**
* @return Returns the colorGreen.
*/
public Color getColorGreen()
{
Color retval = colorGreen;
if (retval.isDisposed()) throw new RuntimeException("Color can not be disposed!!");
return retval;
}
/**
* @return Returns the colorLightGray.
*/
public Color getColorLightGray()
{
Color retval = colorLightGray;
if (retval.isDisposed()) throw new RuntimeException("Color can not be disposed!!");
return retval;
}
/**
* @return Returns the colorMagenta.
*/
public Color getColorMagenta()
{
Color retval = colorMagenta;
if (retval.isDisposed()) throw new RuntimeException("Color can not be disposed!!");
return retval;
}
/**
* @return Returns the colorOrange.
*/
public Color getColorOrange()
{
Color retval = colorOrange;
if (retval.isDisposed()) throw new RuntimeException("Color can not be disposed!!");
return retval;
}
/**
* @return Returns the colorRed.
*/
public Color getColorRed()
{
Color retval = colorRed;
if (retval.isDisposed()) throw new RuntimeException("Color can not be disposed!!");
return retval;
}
/**
* @return Returns the colorTab.
*/
public Color getColorTab()
{
Color retval = colorTab;
if (retval==null) retval = display.getSystemColor(SWT.COLOR_WIDGET_FOREGROUND);
if (retval.isDisposed()) throw new RuntimeException("Color can not be disposed!!");
return retval;
}
/**
* @return Returns the colorWhite.
*/
public Color getColorWhite()
{
Color retval = colorWhite;
if (retval.isDisposed()) throw new RuntimeException("Color can not be disposed!!");
return retval;
}
/**
* @return Returns the colorYellow.
*/
public Color getColorYellow()
{
Color retval = colorYellow;
if (retval.isDisposed()) throw new RuntimeException("Color can not be disposed!!");
return retval;
}
/**
* @return Returns the display.
*/
public Display getDisplay()
{
return display;
}
/*
* @return Returns the fontDefault.
*
public Font getFontDefault()
{
if (fontDefault==null) return display.getSystemFont();
return fontDefault;
}
*/
/**
* @return Returns the fontFixed.
*/
public Font getFontFixed()
{
if (fontFixed==null) return display.getSystemFont();
return fontFixed;
}
/**
* @return Returns the fontGraph.
*/
public Font getFontGraph()
{
if (fontGraph==null) return display.getSystemFont();
return fontGraph;
}
/*
* @return Returns the fontGrid.
*
public Font getFontGrid()
{
if (fontGrid==null) return display.getSystemFont();
return fontGrid;
}
*/
/**
* @return Returns the fontNote.
*/
public Font getFontNote()
{
if (fontNote==null) return display.getSystemFont();
return fontNote;
}
/**
* @return Returns the imageBol.
*/
public Image getImageBol()
{
return imageBol;
}
/**
* @return Returns the imageConnection.
*/
public Image getImageConnection()
{
return imageConnection;
}
/**
* @return Returns the imageCredits.
*/
public Image getImageCredits()
{
return imageCredits;
}
/**
* @return Returns the imageDummy.
*/
public Image getImageDummy()
{
return imageDummy;
}
/**
* @return Returns the imageHop.
*/
public Image getImageHop()
{
return imageHop;
}
/**
* @return Returns the imageKettle.
*/
public Image getImageKettle()
{
return imageKettle;
}
/**
* @return Returns the imageSpoon.
*/
public Image getImageSpoon()
{
return imageSpoon;
}
/**
* @return Returns the imagesSteps.
*/
public Hashtable getImagesSteps()
{
return imagesSteps;
}
/**
* @return Returns the imagesStepsSmall.
*/
public Hashtable getImagesStepsSmall()
{
return imagesStepsSmall;
}
/**
* @return Returns the imageStart.
*/
public Image getImageStart()
{
return imageStart;
}
}
|
package burlap.behavior.singleagent;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import burlap.behavior.singleagent.options.Option;
import burlap.debugtools.RandomFactory;
import burlap.oomdp.core.AbstractGroundedAction;
import burlap.oomdp.core.Domain;
import burlap.oomdp.core.State;
import burlap.oomdp.core.TerminalFunction;
import burlap.oomdp.singleagent.Action;
import burlap.oomdp.singleagent.GroundedAction;
import burlap.oomdp.singleagent.RewardFunction;
import burlap.oomdp.singleagent.common.NullAction;
import burlap.oomdp.singleagent.environment.Environment;
import burlap.oomdp.singleagent.environment.EnvironmentOutcome;
import com.sun.tools.javac.comp.Env;
/**
* This abstract class is used to store a policy for a domain that can be queried and perform common operations with the policy.
* This class provides a number of important methods for working with and defining policies. To implement this class
* you must implement the methods:
* {@link #getAction(burlap.oomdp.core.State)},
* {@link #getActionDistributionForState(burlap.oomdp.core.State)},
* {@link #isStochastic()}, and
* {@link #isDefinedFor(burlap.oomdp.core.State)}.
* <br/><br/>
* The {@link #getAction(burlap.oomdp.core.State)} should return the action (specified by an
* {@link burlap.oomdp.core.AbstractGroundedAction}; e.g., a {@link burlap.oomdp.singleagent.GroundedAction} for
* single agent domains) this policy defines for the
* input {@link burlap.oomdp.core.State}. If this {@link burlap.behavior.singleagent.Policy} is a stochastic policy,
* then the {@link #getAction(burlap.oomdp.core.State)} method should sample an action from its probability distribution
* and return it.
* <br/><br/>
* The {@link #getActionDistributionForState(burlap.oomdp.core.State)} should return this {@link burlap.behavior.singleagent.Policy}'s
* action selection probability distribution for the input {@link burlap.oomdp.core.State}. The probability distribution is
* specified by returning a {@link java.util.List} of {@link burlap.behavior.singleagent.Policy.ActionProb} instances.
* An {@link burlap.behavior.singleagent.Policy.ActionProb} is a pair consisting of an {@link burlap.oomdp.core.AbstractGroundedAction}
* specifying the action and a double specifying the probability that this {@link burlap.behavior.singleagent.Policy} would
* select that action.
* <br/><br/>
* The {@link #isStochastic()} method should return true if this {@link burlap.behavior.singleagent.Policy} is
* stochastic and false if it is deterministic.
* <br/><br/>
* The {@link #isDefinedFor(burlap.oomdp.core.State)} method should return true if this {@link burlap.behavior.singleagent.Policy}
* is defined for the input {@link burlap.oomdp.core.State} and false if it is not.
* <br/><br/>
* This abstract class also has some pre-implemented methods that can be used to help define these required methods. For example,
* if the {@link #getActionDistributionForState(burlap.oomdp.core.State)} is implemented and stochastic, then the
* {@link #getAction(burlap.oomdp.core.State)} can be trivially implemented by having it return the result of the
* superclass method {@link #sampleFromActionDistribution(burlap.oomdp.core.State)}, which will get the probability
* distribution from the {@link #getActionDistributionForState(burlap.oomdp.core.State)}, roll a random number
* and return an action based on the fully define action distribution. Inversely, if the policy is deterministic and
* the {@link #getAction(burlap.oomdp.core.State)} is implemented, then the
* {@link #getActionDistributionForState(burlap.oomdp.core.State)} method can be trivially implemented by having it
* return the result of {@link #getDeterministicPolicy(burlap.oomdp.core.State)}, which will call {@link #getAction(burlap.oomdp.core.State)}
* and wrap the result in an {@link burlap.behavior.singleagent.Policy.ActionProb} object with assigned probability of 1.0.
* <br/><br/><br/><br/>
* <b>Superclass method</b><br/>
* This class also has many superclass methods for interacting with policy. These include
* {@link #getProbOfAction(burlap.oomdp.core.State, burlap.oomdp.core.AbstractGroundedAction)},
* {@link #evaluateBehavior(burlap.oomdp.core.State, burlap.oomdp.singleagent.RewardFunction, burlap.oomdp.core.TerminalFunction)}
* (and other variants of the method signature), and {@link #evaluateBehavior(burlap.oomdp.singleagent.environment.Environment)} (and
* other variants of the method signature).
* <br/><br/>
* The {@link #getProbOfAction(burlap.oomdp.core.State, burlap.oomdp.core.AbstractGroundedAction)} method
* takes as input a {@link burlap.oomdp.core.State} and {@link burlap.oomdp.core.AbstractGroundedAction} and returns
* the probability of this {@link burlap.behavior.singleagent.Policy} selecting that action. It uses the result of the
* {@link #getActionDistributionForState(burlap.oomdp.core.State)} method to determine the full distribution, finds
* the matching {@link burlap.oomdp.core.AbstractGroundedAction} in the returned list, and then returns its assigned probability.
* It may be possible to return this value in a more efficient way than enumerating the full probability distribution,
* in which case you may want to consider overriding the method.
* <br/><br/>
* The {@link #evaluateBehavior(burlap.oomdp.core.State, burlap.oomdp.singleagent.RewardFunction, burlap.oomdp.core.TerminalFunction)},
* {@link #evaluateBehavior(burlap.oomdp.core.State, burlap.oomdp.singleagent.RewardFunction, int)}, and
* {@link #evaluateBehavior(burlap.oomdp.core.State, burlap.oomdp.singleagent.RewardFunction, burlap.oomdp.core.TerminalFunction, int)}
* methods will all evaluate this policy by rolling it out from the input {@link burlap.oomdp.core.State} or until
* it reaches a terminal state or executes for the maximum number of steps (depending on which version of the method you use).
* The resulting behavior will be saved in an {@link burlap.behavior.singleagent.EpisodeAnalysis} object that is returned.
* Note that this method requires that the returned {@link burlap.oomdp.core.AbstractGroundedAction} instances are
* able to be executed using the action's defined transition dynamics. For single agent domains in which the actions
* are {@link burlap.oomdp.singleagent.GroundedAction} instances, this will work as long as the corresponding
* {@link burlap.oomdp.singleagent.Action#performAction(burlap.oomdp.core.State, String[])} method is implemented. If this
* policy defines the policy for an agent in a stochastic game, returning {@link burlap.oomdp.stochasticgames.GroundedSingleAction} instances
* for the action, then the policy cannot be rolled out since the outcome state would depend on the action selection of
* other agents.
* <br/><br/>
* The {@link #evaluateBehavior(burlap.oomdp.singleagent.environment.Environment)} and
* {@link #evaluateBehavior(burlap.oomdp.singleagent.environment.Environment, int)}
* methods will execute this policy in some input {@link burlap.oomdp.singleagent.environment.Environment} until either
* the {@link burlap.oomdp.singleagent.environment.Environment} reaches a terminal state or the maximum number of
* steps are taken (depending on which method signature is used). This method is useful if a policy was computed
* with a planning algorithm using some model of the world and then needs to be executed in an environment which may
* have slightly different transitions; for example, planning a policy for a robot using a model of the world and then
* executing it on the actual robot by following the policy in an {@link burlap.oomdp.singleagent.environment.Environment}.
* <br/><br/>
* All of the evaluateBehavior methods also know how to work with {@link burlap.behavior.singleagent.options.Option}s.
* In particular, they also are able to record
* the option execution in the returned {@link burlap.behavior.singleagent.EpisodeAnalysis} object in verbose ways
* for better debugging. By default, when an option is selected in an evaluateBehavior method, each primitive step
* will be recorded in the {@link burlap.behavior.singleagent.EpisodeAnalysis} object, rather than only recording that
* the option was taken. Additionally, in the returned {@link burlap.behavior.singleagent.EpisodeAnalysis}, each primitive
* step by default will be annotated with the option the executed and which step in the option execution that it was.
* If you would like to disable option decomposition and/or the option annotation, you can do so with the
* {@link #evaluateMethodsShouldDecomposeOption(boolean)} and {@link #evaluateMethodsShouldAnnotateOptionDecomposition(boolean)}
* methods.
*
*
* @author James MacGlashan
*
*/
public abstract class Policy {
protected boolean evaluateDecomposesOptions = true;
protected boolean annotateOptionDecomposition = true;
/**
* This method will return an action sampled by the policy for the given state. If the defined policy is
* stochastic, then multiple calls to this method for the same state may return different actions. The sampling
* should be with respect to defined action distribution that is returned by getActionDistributionForState
* @param s the state for which an action should be returned
* @return a sample action from the action distribution; null if the policy is undefined for s
*/
public abstract AbstractGroundedAction getAction(State s);
/**
* This method will return action probability distribution defined by the policy. The action distribution is represented
* by a list of ActionProb objects, each which specifies a grounded action and a probability of that grounded action being
* taken. The returned list does not have to include actions with probability 0.
* @param s the state for which an action distribution should be returned
* @return a list of possible actions taken by the policy and their probability.
*/
public abstract List<ActionProb> getActionDistributionForState(State s); //returns null when policy is undefined for s
/**
* Indicates whether the policy is stochastic or deterministic.
* @return true when the policy is stochastic; false when it is deterministic.
*/
public abstract boolean isStochastic();
/**
* Specifies whether this policy is defined for the input state.
* @param s the input state to test for whether this policy is defined
* @return true if this policy is defined for {@link burlap.oomdp.core.State} s, false otherwise.
*/
public abstract boolean isDefinedFor(State s);
/**
* Will return the probability of this policy taking action ga in state s
* @param s the state in which the action would be taken
* @param ga the action being queried
* @return the probability of this policy taking action ga in state s
*/
public double getProbOfAction(State s, AbstractGroundedAction ga){
List <ActionProb> probs = this.getActionDistributionForState(s);
if(probs == null || probs.size() == 0){
throw new PolicyUndefinedException();
}
for(ActionProb ap : probs){
if(ap.ga.equals(ga)){
return ap.pSelection;
}
}
return 0.;
}
/**
* Don't use this, the input state is not necessary; instead use {@link #getProbOfActionGivenDistribution(burlap.oomdp.core.AbstractGroundedAction, java.util.List)}.
*/
@Deprecated
public static double getProbOfActionGivenDistribution(State s, AbstractGroundedAction ga, List<ActionProb> distribution){
if(distribution == null || distribution.size() == 0){
throw new RuntimeException("Distribution is null or empty, cannot return probability for given action.");
}
for(ActionProb ap : distribution){
if(ap.ga.equals(ga)){
return ap.pSelection;
}
}
return 0.;
}
/**
* Searches the input distribution for the occurrence of the input action and returns its probability.
* @param ga the {@link burlap.oomdp.core.AbstractGroundedAction} for which its probability in specified distribution should be returned.
* @param distribution the probability distribution over actions.
* @return the probability of selecting action ga according to the probability specified in distribution.
*/
public static double getProbOfActionGivenDistribution(AbstractGroundedAction ga, List<ActionProb> distribution){
if(distribution == null || distribution.size() == 0){
throw new RuntimeException("Distribution is null or empty, cannot return probability for given action.");
}
for(ActionProb ap : distribution){
if(ap.ga.equals(ga)){
return ap.pSelection;
}
}
return 0.;
}
/**
* A helper method for defining deterministic policies. This method relies on the getAction method being
* implemented and will return a list of ActionProb objects with a single instance: the result of
* the getAction method with assigned probability 1. This method simplifies the definition of
* deterministic policies because the getActionDistributionForState method can just retunr this method.
* @param s the state for which the action distribution should be returned.
* @return a deterministic action distribution for the action returned by the getAction method.
*/
protected List <ActionProb> getDeterministicPolicy(State s){
AbstractGroundedAction ga = this.getAction(s);
if(ga == null){
throw new PolicyUndefinedException();
}
ActionProb ap = new ActionProb(ga, 1.);
List <ActionProb> aps = new ArrayList<Policy.ActionProb>();
aps.add(ap);
return aps;
}
/**
* This is a helper method for stochastic policies. If the policy is stochastic, then rather than
* having the subclass policy define both the {@link #getAction(burlap.oomdp.core.State)} method and
* {@link #getActionDistributionForState(burlap.oomdp.core.State)} method,
* the subclass needs to only define the {@link #getActionDistributionForState(burlap.oomdp.core.State)} method and
* the {@link #getAction(burlap.oomdp.core.State)} method can simply
* call this method to return an action.
* @param s the input state from which an action should be selected.
* @return an {@link AbstractGroundedAction} to take
*/
protected AbstractGroundedAction sampleFromActionDistribution(State s){
Random rand = RandomFactory.getMapped(0);
double roll = rand.nextDouble();
List <ActionProb> probs = this.getActionDistributionForState(s);
if(probs == null || probs.size() == 0){
throw new PolicyUndefinedException();
}
double sump = 0.;
for(ActionProb ap : probs){
sump += ap.pSelection;
if(roll < sump){
return ap.ga;
}
}
throw new RuntimeException("Tried to sample policy action distribution, but it did not sum to 1.");
}
/**
* Sets whether the primitive actions taken during an options will be included as steps in produced EpisodeAnalysis objects.
* The default value is true. If this is set to false, then EpisodeAnalysis objects returned from evaluating a policy will record options
* as a single "action" and the steps taken by the option will be hidden.
* @param toggle whether to decompose options into the primitive actions taken by them or not.
*/
public void evaluateMethodsShouldDecomposeOption(boolean toggle){
this.evaluateDecomposesOptions = toggle;
}
/**
* Sets whether options that are decomposed into primitives will have the option that produced them and listed.
* The default value is true. If option decomposition is not enabled, changing this value will do nothing. When it
* is enabled and this is set to true, primitive actions taken by an option in EpisodeAnalysis objects will be
* recorded with a special action name that indicates which option was called to produce the primitive action
* as well as which step of the option the primitive action is. When set to false, recorded names of primitives
* will be only the primitive aciton's name it will be unclear which option was taken to generate it.
* @param toggle whether to annotate the primitive actions of options with the calling option's name.
*/
public void evaluateMethodsShouldAnnotateOptionDecomposition(boolean toggle){
this.annotateOptionDecomposition = toggle;
}
/**
* This method will return the an episode that results from following this policy from state s. The episode will terminate
* when the policy reaches a terminal state defined by tf.
* @param s the state from which to roll out the policy
* @param rf the reward function used to track rewards accumulated during the episode
* @param tf the terminal function defining when the policy should stop being followed.
* @return an EpisodeAnalysis object that records the events from following the policy.
*/
public EpisodeAnalysis evaluateBehavior(State s, RewardFunction rf, TerminalFunction tf){
EpisodeAnalysis res = new EpisodeAnalysis();
res.addState(s); //add initial state
State cur = s;
while(!tf.isTerminal(cur)){
cur = this.followAndRecordPolicy(res, cur, rf);
}
return res;
}
/**
* This method will return the an episode that results from following this policy from state s. The episode will terminate
* when the policy reaches a terminal state defined by tf or when the number of steps surpasses maxSteps.
* @param s the state from which to roll out the policy
* @param rf the reward function used to track rewards accumulated during the episode
* @param tf the terminal function defining when the policy should stop being followed.
* @param maxSteps the maximum number of steps to take before terminating the policy rollout.
* @return an EpisodeAnalysis object that records the events from following the policy.
*/
public EpisodeAnalysis evaluateBehavior(State s, RewardFunction rf, TerminalFunction tf, int maxSteps){
EpisodeAnalysis res = new EpisodeAnalysis();
res.addState(s); //add initial state
State cur = s;
int nSteps = 0;
while(!tf.isTerminal(cur) && nSteps < maxSteps){
cur = this.followAndRecordPolicy(res, cur, rf);
nSteps = res.numTimeSteps();
}
return res;
}
/**
* This method will return the an episode that results from following this policy from state s. The episode will terminate
* when the number of steps taken is >= numSteps.
* @param s the state from which to roll out the policy
* @param rf the reward function used to track rewards accumulated during the episode
* @param numSteps the number of steps to take before terminating the policy rollout
* @return an EpisodeAnalysis object that records the events from following the policy.
*/
public EpisodeAnalysis evaluateBehavior(State s, RewardFunction rf, int numSteps){
EpisodeAnalysis res = new EpisodeAnalysis();
res.addState(s);
State cur = s;
int nSteps = 0;
while(nSteps < numSteps){
cur = this.followAndRecordPolicy(res, cur, rf);
nSteps = res.numTimeSteps();
}
return res;
}
/**
* Evaluates this policy in the provided {@link burlap.oomdp.singleagent.environment.Environment}. The policy will stop being evaluated once a terminal state
* in the environment is reached.
* @param env The {@link burlap.oomdp.singleagent.environment.Environment} in which this policy is to be evaluated.
* @return An {@link burlap.behavior.singleagent.EpisodeAnalysis} object specifying the interaction with the environment.
*/
public EpisodeAnalysis evaluateBehavior(Environment env){
EpisodeAnalysis ea = new EpisodeAnalysis(env.getCurState());
do{
this.followAndRecordPolicy(env, ea);
}while(!env.curStateIsTerminal());
return ea;
}
/**
* Evaluates this policy in the provided {@link burlap.oomdp.singleagent.environment.Environment}. The policy will stop being evaluated once a terminal state
* in the environment is reached or when the provided number of steps has been taken.
* @param env The {@link burlap.oomdp.singleagent.environment.Environment} in which this policy is to be evaluated.
* @param numSteps the maximum number of steps to take in the environment.
* @return An {@link burlap.behavior.singleagent.EpisodeAnalysis} object specifying the interaction with the environment.
*/
public EpisodeAnalysis evaluateBehavior(Environment env, int numSteps){
EpisodeAnalysis ea = new EpisodeAnalysis(env.getCurState());
int nSteps = 0;
do{
this.followAndRecordPolicy(env, ea);
nSteps = ea.numTimeSteps();
}while(!env.curStateIsTerminal() && nSteps < numSteps);
return ea;
}
/**
* Follows this policy for one time step in the provided {@link burlap.oomdp.singleagent.environment.Environment} and
* records the interaction in the provided {@link burlap.behavior.singleagent.EpisodeAnalysis} object. If the policy
* selects an {@link burlap.behavior.singleagent.options.Option}, then how the option's interaction in the environment
* is recorded depends on this object's {@link #evaluateDecomposesOptions} and {@link #annotateOptionDecomposition} flags.
* If {@link #evaluateDecomposesOptions} is false, then the option is recorded as a single action. If it is true, then
* the individual primitive actions selected by the environment are recorded. If {@link #annotateOptionDecomposition} is
* also true, then each primitive action selected but the option is also given a unique name specifying the option
* which controlled it and its step in the option's execution.
* @param env The {@link burlap.oomdp.singleagent.environment.Environment} in which this policy should be followed.
* @param ea The {@link burlap.behavior.singleagent.EpisodeAnalysis} object to which the action selection will be recorded.
*/
protected void followAndRecordPolicy(Environment env, EpisodeAnalysis ea){
//follow policy
AbstractGroundedAction aga = this.getAction(env.getCurState());
if(aga == null){
throw new PolicyUndefinedException();
}
if(!(aga instanceof GroundedAction)){
throw new RuntimeException("cannot folow policy for non-single agent actions");
}
GroundedAction ga = (GroundedAction)aga;
if(ga.action.isPrimitive()|| !this.evaluateDecomposesOptions){
EnvironmentOutcome eo = ga.executeIn(env);
ea.recordTransitionTo(ga, eo.sp, eo.r);
}
else{
//then we need to decompose the option
State cur = env.getCurState();
Option o = (Option)ga.action;
o.initiateInState(cur, ga.params);
int ns = 0;
do{
//do step of option
GroundedAction cga = o.oneStepActionSelection(cur, ga.params);
EnvironmentOutcome eo = cga.executeIn(env);
State next = eo.sp;
double r = eo.r;
if(annotateOptionDecomposition){
//setup a null action to record the option and primitive action taken
NullAction annotatedPrimitive = new NullAction(o.getName() + "(" + ns + ")-" + cga.action.getName());
GroundedAction annotatedPrimitiveGA = new GroundedAction(annotatedPrimitive, cga.params);
//record it
ea.recordTransitionTo(annotatedPrimitiveGA, next, r);
}
else{
//otherwise just record the primitive that was taken
ea.recordTransitionTo(cga, next, r);
}
cur = env.getCurState();
ns++;
}while(o.continueFromState(cur, ga.params));
}
}
/**
* Follows this policy for one time step from the provided {@link burlap.oomdp.core.State} and
* records the interaction in the provided {@link burlap.behavior.singleagent.EpisodeAnalysis} object. If the policy
* selects an {@link burlap.behavior.singleagent.options.Option}, then how the option's interaction in the environment
* is recorded depends on this object's {@link #evaluateDecomposesOptions} and {@link #annotateOptionDecomposition} flags.
* If {@link #evaluateDecomposesOptions} is false, then the option is recorded as a single action. If it is true, then
* the individual primitive actions selected by the environment are recorded. If {@link #annotateOptionDecomposition} is
* also true, then each primitive action selected but the option is also given a unique name specifying the option
* which controlled it and its step in the option's execution.
* @param ea The {@link burlap.behavior.singleagent.EpisodeAnalysis} object to which the action selection will be recorded.
* @param cur The {@link burlap.oomdp.core.State} from which the policy will be followed
* @param rf The {@link burlap.oomdp.singleagent.RewardFunction} to keep track of reward
* @return the next {@link State} that is a consequence of following this policy for one action selection.
*/
protected State followAndRecordPolicy(EpisodeAnalysis ea, State cur, RewardFunction rf){
State next = null;
//follow policy
AbstractGroundedAction aga = this.getAction(cur);
if(aga == null){
throw new PolicyUndefinedException();
}
if(!(aga instanceof GroundedAction)){
throw new RuntimeException("cannot folow policy for non-single agent actions");
}
GroundedAction ga = (GroundedAction)aga;
if(ga.action.isPrimitive() || !this.evaluateDecomposesOptions){
next = ga.executeIn(cur);
double r = rf.reward(cur, ga, next);
//record result
ea.recordTransitionTo(ga, next, r);
}
else{
//then we need to decompose the option
Option o = (Option)ga.action;
o.initiateInState(cur, ga.params);
int ns = 0;
do{
//do step of option
GroundedAction cga = o.oneStepActionSelection(cur, ga.params);
next = cga.executeIn(cur);
double r = rf.reward(cur, cga, next);
if(annotateOptionDecomposition){
//setup a null action to record the option and primitive action taken
NullAction annotatedPrimitive = new NullAction(o.getName() + "(" + ns + ")-" + cga.action.getName());
GroundedAction annotatedPrimitiveGA = new GroundedAction(annotatedPrimitive, cga.params);
//record it
ea.recordTransitionTo(annotatedPrimitiveGA, next, r);
}
else{
//otherwise just record the primitive that was taken
ea.recordTransitionTo(cga, next, r);
}
cur = next;
ns++;
}while(o.continueFromState(cur, ga.params));
}
//return outcome state
return next;
}
/**
* Class for storing an action and probability tuple. The probability represents the probability that the action will be selected.
* @author James MacGlashan
*
*/
public static class ActionProb{
/**
* The action to be considered.
*/
public AbstractGroundedAction ga;
/**
* The probability of the action being selected.
*/
public double pSelection;
/**
* Initializes the action, probability tuple.
* @param ga the action to be considered
* @param p the probability of the action being selected.
*/
public ActionProb(AbstractGroundedAction ga, double p){
this.ga = ga;
this.pSelection = p;
}
}
/**
* RuntimeException to be thrown when a Policy is queried for a state in which the policy is undefined.
* @author James MacGlashan
*
*/
public static class PolicyUndefinedException extends RuntimeException{
private static final long serialVersionUID = 1L;
public PolicyUndefinedException(){
super("Policy is undefined for provided state");
}
}
/**
* A uniform random policy for single agent domains. You may set the actions between which it randomly
* selects by providing a domain (from which the domains primitive actions are copied into an internal list)
* or from a list of Action objects (from which the action references are copied into an internal list).
* You may also add additional actions with the {@link #addAction(burlap.oomdp.singleagent.Action)} method
* or remove or clear the actions.
* <br/>
* Upon action selection, all applicable grounded actions for the state are generated and an action is selected
* uniformly randomly from them. The policy is not defined if there are no applicable actions.
*/
public static class RandomPolicy extends Policy{
/**
* The actions from which selection is performed
*/
protected List<Action> actions;
/**
* The random factory used to randomly select actions.
*/
protected Random rand = RandomFactory.getMapped(0);
/**
* Initializes by copying all the primitive actions references defined for the domain into an internal action
* list for this policy.
* @param domain the domain containing all the primitive actions.
*/
public RandomPolicy(Domain domain){
this.actions = new ArrayList<Action>(domain.getActions());
}
/**
* Initializes by copying all the actions references defined in the provided list into an internal action
* list for this policy.
* @param acitons the actions to select between.
*/
public RandomPolicy(List<Action> acitons){
this.actions = new ArrayList<Action>(actions);
}
/**
* Adds an aciton to consider in selection.
* @param action an action to consider in selection
*/
public void addAction(Action action){
this.actions.add(action);
}
/**
* Clears the action list used in action selection. Note that if no actions are added to this policy after
* calling this method then the policy will be undefined everywhere.
*/
public void clearActions(){
this.actions.clear();
}
/**
* Removes an action from consideration.
* @param actionName the name of the action to remove.
*/
public void removeAction(String actionName){
Action toRemove = null;
for(Action a : this.actions){
if(a.getName().equals(actionName)){
toRemove = a;
break;
}
}
if(toRemove != null){
this.actions.remove(toRemove);
}
}
/**
* Returns of the list of actions that can be randomly selected.
* @return the list of actions that can be randomly selected.
*/
public List<Action> getSelectionActions(){
return this.actions;
}
/**
* Returns the random generator used for action selection.
* @return the random generator used for action selection.
*/
public Random getRandomGenerator(){
return this.rand;
}
/**
* Sets the random generator used for action selection.
* @param rand the random generator used for action selection.
*/
public void setRandomGenerator(Random rand){
this.rand = rand;
}
@Override
public AbstractGroundedAction getAction(State s) {
List<GroundedAction> gas = Action.getAllApplicableGroundedActionsFromActionList(this.actions, s);
if(gas.size() == 0){
throw new PolicyUndefinedException();
}
GroundedAction selection = gas.get(this.rand.nextInt(this.actions.size()));
return selection;
}
@Override
public List<ActionProb> getActionDistributionForState(State s) {
List<GroundedAction> gas = Action.getAllApplicableGroundedActionsFromActionList(this.actions, s);
if(gas.size() == 0){
throw new PolicyUndefinedException();
}
double p = 1./gas.size();
List<ActionProb> aps = new ArrayList<ActionProb>(gas.size());
for(GroundedAction ga : gas){
ActionProb ap = new ActionProb(ga, p);
aps.add(ap);
}
return aps;
}
@Override
public boolean isStochastic() {
return true;
}
@Override
public boolean isDefinedFor(State s) {
return Action.getAllApplicableGroundedActionsFromActionList(this.actions, s).size() > 0;
}
}
}
|
package com.ericelsken.android.web;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.ProtocolException;
import java.net.URI;
import java.net.URL;
import java.util.LinkedList;
import java.util.List;
import android.content.Context;
import android.os.Build;
import com.ericelsken.android.web.content.ResponseLoader;
public class Request {
static {
//Work around pre-Froyo bugs in HTTP connection reuse.
if(Build.VERSION.SDK_INT < Build.VERSION_CODES.FROYO) {
System.setProperty("http.keepAlive", "false");
}
}
/**
* The default buffer size to use when reading/writing requests.
*/
public static final int DEFAULT_BUFFER_SIZE = 1 << 10;
private static final int DELETE = 0;
private static final int GET = 1;
private static final int POST = 2;
private static final int PUT = 3;
/**
* All object fields of this class must be immutable or deep-copied into Request objects.
*/
private static class Params {
private final URI uri;
private String data;
private int method;
private int bufferSize;
private List<String[]> headers;
private Params(URI uri) {
this.uri = uri;
data = null;
method = GET;
bufferSize = DEFAULT_BUFFER_SIZE;
headers = new LinkedList<String[]>();
}
}
/**
* The Response obtained from this Request in execute().
*/
private Response response;
//The following should be an exact copy of Params fields, all final, and all deep copied from a Params object.
private final URI uri;
private final String data;
private final int method;
private final int bufferSize;
private final List<String[]> headers;
/**
* Deep-copy all fields from p into this class' fields.
* @param p the Params object from which to copy values into this instance.
*/
private Request(Params p) {
uri = p.uri;
data = p.data;
method = p.method;
bufferSize = p.bufferSize;
//deep-copy the headers.
headers = new LinkedList<String[]>();
for(String[] pair : p.headers) {
headers.add(new String[] {pair[0], pair[1]});
}
}
/**
* Creates, starts, and returns a new RequestHandler with the given id, Context, and RequestCallback.
* Creates the RequestHandler via new RequestHandler(context, id, this, callback), starts the handler, and returns it.
* @param context the Context of the RequestHandler.
* @param id the id of the RequestHandler.
* @param callback the RequestCallback object that receives callbacks from the RequestHandler.
* @return the new, started RequestHandler now handling this Request.
*/
public RequestHandler handle(Context context, int id, RequestCallbacks callback) {
RequestHandler handler = new RequestHandler(context, id, this, callback);
handler.start();
return handler;
}
/**
* Creates and returns a new ResponseLoader that loads its Response from this Request.
* @param context the Context of the ResponseLoader.
* @return the newly created ResponseLoader.
*/
public ResponseLoader newLoader(Context context) {
ResponseLoader loader = new ResponseLoader(context, this);
return loader;
}
/**
* Executes this Request and returns the Response object obtained from the Request.
* This method makes networking calls and thus CANNOT be called on the main-UI thread.
* Multiple, successive calls to this method on the same instance will return the Response from the first call.
* @return the Response object obtained from executing this Request.
*/
public Response execute() {
if(response != null) {
return response;
}
HttpURLConnection conn = null;
String body = null;
Exception caught = null;
try {
if(uri.getScheme() == null || uri.getScheme().indexOf("http") != 0) {
throw new SchemeException(uri.getScheme());
}
URL url = uri.toURL();
conn = (HttpURLConnection) url.openConnection();
body = executeForBody(conn);
} catch (Exception ex) {
caught = ex;
}
response = new Response(conn, body, caught);
return response;
}
/**
* Actually makes the networking request and returns the response body returned from the request.
* @param conn connection used in making the request.
* @return the response body returned from the request.
* @throws IOException if an IO problem occurs while making the request.
* @throws HttpException if the response status code is not 2xx.
*/
private String executeForBody(HttpURLConnection conn) throws IOException, HttpException {
String body = null;
try {
apply(conn);
if(data != null) {
writeData(conn);
}
body = inputToString(conn);
}
finally {
conn.disconnect();
}
int statusCode = conn.getResponseCode();
if(statusCode / 100 != 2) {
throw new HttpException(statusCode, conn.getResponseMessage(), body);
}
return body;
}
/**
* Applies the settings of this request to the connection being used to make the request.
* @param conn connection used in making the request.
* @throws ProtocolException see ProtocolException documentation.
*/
private void apply(HttpURLConnection conn) throws ProtocolException {
switch(method) {
case DELETE: conn.setRequestMethod("DELETE"); break;
case GET: conn.setRequestMethod("GET"); break;
case POST: conn.setRequestMethod("POST"); break;
case PUT: conn.setRequestMethod("PUT"); break;
}
for(String[] pair : headers) {
conn.setRequestProperty(pair[0], pair[1]);
}
}
private String inputToString(HttpURLConnection conn) throws IOException {
ByteArrayOutputStream out = new ByteArrayOutputStream(bufferSize);
InputStream in = new BufferedInputStream(conn.getInputStream(), bufferSize);
copyStreams(in, out);
return out.toString();
}
private void writeData(HttpURLConnection conn) throws IOException {
conn.setDoOutput(true);
byte[] bytes = data.getBytes();
conn.setFixedLengthStreamingMode(bytes.length);
OutputStream out = new BufferedOutputStream(conn.getOutputStream(), bufferSize);
InputStream in = new BufferedInputStream(new ByteArrayInputStream(bytes), bufferSize);
copyStreams(in, out);
}
private void copyStreams(InputStream in, OutputStream out) throws IOException {
int tempRead = 0;
byte[] buffer = new byte[bufferSize];
while(tempRead != -1) {
tempRead = in.read(buffer, 0, buffer.length);
if(tempRead != -1) {
out.write(buffer, 0, tempRead);
}
}
in.close();
out.close();
}
/**
* Utility class for building Request objects.
* All Requests must be created through this class.
* All calls on this class will reflect the settings of the Request object
* returned by create().
* All methods of this class return a reference to this so that method call
* chaining is easy.
*
* @author Eric Elsken
*
*/
public static class Builder {
private final Params p;
/**
* Creates a new Builder with the provided URI.
* Without any further calls, the built Request will be a GET request
* to the given URI with the default buffer size and no headers.
* @param uri the URI of the Request.
*/
public Builder(URI uri) {
p = new Params(uri);
}
/**
* Sets the built Request to be a DELETE Request.
* @return this
*/
public Builder delete() {
p.method = DELETE;
return this;
}
/**
* Sets the built Request to be a GET Request.
* If there is any data already associated with the Request, then it is
* removed.
* @return this
*/
public Builder get() {
p.method = GET;
p.data = null;
return this;
}
/**
* Sets the built Request to be a POST Request.
* @return this
*/
public Builder post() {
p.method = POST;
return this;
}
/**
* Sets the built Request to be a PUT Request.
* @return this
*/
public Builder put() {
p.method = PUT;
return this;
}
/**
* Sets the data to be sent in the Request for DELETE, POST, and PUT
* requests.
* @param data the data to send as part of the Request.
* @return this
*/
public Builder setData(String data) {
p.data = data;
return this;
}
/**
* Sets the size of the buffer to use when writing/reading the Request/
* Response.
* @param bufferSize the new buffer size. If negative or zero, this is
* a no-op.
* @return this
*/
public Builder setBufferSize(int bufferSize) {
bufferSize = bufferSize <= 0 ? p.bufferSize : bufferSize;
p.bufferSize = bufferSize;
return this;
}
/**
* Sets the header value to be associated with the field name.
* @param field the name of the header.
* @param newValue the new value of the header to be associated with field.
* @return this.
*/
public Builder setHeader(String field, String newValue) {
if(field == null || newValue == null) {
throw new NullPointerException("field and newValue cannot be null.");
}
p.headers.add(new String[] {field, newValue});
return this;
}
/**
* Creates and returns a new Request with the settings provided by all
* the calls on this object.
* @return the newly created Request.
*/
public Request create() {
return new Request(p);
}
}
}
|
package com.guisehn.main;
import com.guisehn.crossover.Crossover2;
import com.guisehn.crossover.CrossoverOperator;
import com.guisehn.crossover.CrossoverResult;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashSet;
import java.util.List;
import java.util.Random;
import java.util.Set;
public class MagicSquareFinder {
public static final int LOG_EVENT = 0;
public static final int MAGIC_SQUARE_FOUND_EVENT = 1;
public static final int SEARCH_ENDED_EVENT = 2;
private final int size;
private final int arraySize;
private final int populationSize;
private final int eliteSize;
private final int eliteDeathPeriod;
private final int minimumCrossoverPoint;
private final int maximumCrossoverPoint;
private final double mutationProbability;
private final boolean allowDuplicates;
private final boolean showGenerationDetails;
private final MagicSquareFitnessCalculator fitnessCalculator;
private final RandomMagicSquareGenerator randomGenerator;
private final IndividualComparator comparator;
private final CrossoverOperator crossoverOperator;
private final ActionListener listener;
private final Random random = new Random();
private final Set<Individual> magicSquaresFound;
private final List<Individual> population;
private final StringBuilder log;
private Thread thread;
private int generationCount;
private int amountOfGenerationsSinceLastNewMagicSquare;
public MagicSquareFinder(int size, int populationSize, int eliteSize,
int eliteDeathPeriod, double mutationProbability,
boolean allowDuplicates, int minimumCrossoverPoint,
int maximumCrossoverPoint, boolean showGenerationDetails,
ActionListener listener) {
this.size = size;
this.arraySize = (int)Math.pow(size, 2);
this.populationSize = populationSize;
this.eliteSize = eliteSize;
this.eliteDeathPeriod = eliteDeathPeriod;
this.mutationProbability = mutationProbability;
this.allowDuplicates = allowDuplicates;
this.minimumCrossoverPoint = minimumCrossoverPoint;
this.maximumCrossoverPoint = maximumCrossoverPoint;
this.showGenerationDetails = showGenerationDetails;
this.fitnessCalculator = new MagicSquareFitnessCalculator(size);
this.randomGenerator = new RandomMagicSquareGenerator(size);
this.crossoverOperator = new Crossover2();
this.comparator = new IndividualComparator();
this.magicSquaresFound = new HashSet<>();
this.population = new ArrayList<>();
this.log = new StringBuilder();
this.listener = listener;
}
public void start() {
stop();
thread = new Thread() {
@Override
public void run() {
startGeneticAlgorithm();
}
};
thread.start();
}
public void stop() {
if (thread != null) {
thread.interrupt();
}
}
public int getGenerationCount() {
return generationCount;
}
private void startGeneticAlgorithm() {
generationCount = amountOfGenerationsSinceLastNewMagicSquare = 0;
log.setLength(0);
generateInitialPopulation();
boolean published;
while (!thread.isInterrupted()) {
sortPopulation();
addCurrentGenerationToLog();
if (generationCount == 0 || generationCount % 200 == 0) {
publishAndClearLog();
published = true;
} else {
published = false;
}
addAndPublishMagicSquares();
if (checkForCompletion(published)) {
break;
}
createNewGeneration();
}
stop();
}
private void sortPopulation() {
Collections.sort(population, comparator);
}
private void generateInitialPopulation() {
population.clear();
for (int i = 0; i < populationSize; i++) {
population.add(new Individual(randomGenerator.generate(),
null, null, null, "", fitnessCalculator));
}
}
/**
* Checks if there are new magic squares on the current generation.
* If there are new ones, add them to the magic square list and publishes
* them to the action listener.
*/
private void addAndPublishMagicSquares() {
Individual[] magicSquares = population.stream()
.filter(i -> i.getFitness() == 0)
.toArray(Individual[]::new);
for (Individual magicSquare : magicSquares) {
boolean added = magicSquaresFound.add(magicSquare);
if (added) {
amountOfGenerationsSinceLastNewMagicSquare = 0;
publishMagicSquare(magicSquare);
}
}
}
private boolean checkForCompletion(boolean published) {
int amountFound = magicSquaresFound.size();
if (!thread.isInterrupted() && (
(size == 1 && amountFound == 1) ||
(size == 3 && amountFound == 8) ||
amountFound >= 10)
) {
listener.actionPerformed(new ActionEvent(this, SEARCH_ENDED_EVENT,
null));
if (!published) {
publishAndClearLog();
}
return true;
}
return false;
}
private void addCurrentGenerationToLog() {
log.append("======================\nGeneration ").append(generationCount)
.append("\n======================");
int i = 0;
for (Individual individual : population) {
if (showGenerationDetails) {
log.append("\nIndividual #").append(++i);
}
log.append("\n").append(individual.toString(true));
if (showGenerationDetails) {
log.append("\n").append(individual.getGenerationDetails(true))
.append("\n
}
}
log.append("\n");
}
/**
* Outputs the log
*/
private void publishAndClearLog() {
listener.actionPerformed(new ActionEvent(this, LOG_EVENT, log.toString()));
log.setLength(0);
}
private void publishMagicSquare(Individual magicSquare) {
StringBuilder sb = new StringBuilder();
sb.append(SquareFormatter.format(magicSquare.getSquare()));
sb.append("\n");
sb.append("\nGeneration number: ").append(generationCount);
sb.append("\n").append(magicSquare.getGenerationDetails(false));
listener.actionPerformed(new ActionEvent(this, MAGIC_SQUARE_FOUND_EVENT,
sb.toString()));
}
private List<Individual> createMatingPool() {
List<Individual> matingPool = new ArrayList<>();
int poolSize = populationSize / 2;
while (matingPool.size() < poolSize) {
Individual i1 = Utils.getRandom(population);
Individual i2 = Utils.getRandom(population);
if (i1 == i2) {
continue;
}
matingPool.add(i1.getFitness() > i2.getFitness() ? i1 : i2);
}
return matingPool;
}
private void createNewGeneration() {
generationCount++;
// Applies the elite death period
if (eliteDeathPeriod != 0 && amountOfGenerationsSinceLastNewMagicSquare > eliteDeathPeriod) {
population.subList(0, eliteSize).clear();
amountOfGenerationsSinceLastNewMagicSquare = 0;
} else {
amountOfGenerationsSinceLastNewMagicSquare++;
}
List<Individual> matingPool = createMatingPool();
// Elitism. Transfers the N best individuals to the next generation.
try {
population.subList(eliteSize, populationSize).clear();
population.stream().forEach(individual -> {
individual.setBelongsToElite(true);
});
} catch (java.lang.IndexOutOfBoundsException e) { }
while (population.size() < populationSize) {
Individual i1 = Utils.getRandom(matingPool);
Individual i2 = Utils.getRandom(matingPool);
Individual[] children = crossoverAndMutate(i1, i2);
if (allowDuplicates) {
population.addAll(Arrays.asList(children));
} else {
for (Individual child : children) {
String representation = child.toString();
boolean duplicate = false;
for (Individual individual : population) {
if (representation.equals(individual.toString())) {
duplicate = true;
break;
}
}
if (!duplicate) {
population.add(child);
}
}
}
}
}
/**
* Performs the crossover of two individuals and (possibily) mutation
* @param parent1 1st parent
* @param parent2 2nd parent
* @return children
*/
private Individual[] crossoverAndMutate(Individual parent1, Individual parent2) {
CrossoverResult result = crossoverOperator.crossover(parent1.getSquare(),
parent2.getSquare(), minimumCrossoverPoint, maximumCrossoverPoint);
int[][] children = result.getChildren();
int[][] mutationPoints = new int[children.length][];
// Mutation
for (int i = 0; i < children.length; i++) {
int[] child = children[i];
if (Math.random() <= mutationProbability) {
int index1, index2;
do {
index1 = random.nextInt(arraySize);
index2 = random.nextInt(arraySize);
}
while (index1 == index2);
int aux = child[index1];
child[index1] = child[index2];
child[index2] = aux;
mutationPoints[i] = new int[] { index1, index2 };
} else {
mutationPoints[i] = null;
}
}
// Transforms the int arrays to Individual objects
Individual[] individuals = new Individual[children.length];
for (int i = 0; i < individuals.length; i++) {
individuals[i] = new Individual(children[i], parent1.getSquare(),
parent2.getSquare(), mutationPoints[i], result.getDetails(),
fitnessCalculator);
}
return individuals;
}
}
class IndividualComparator implements Comparator<Individual> {
@Override
public int compare(Individual o1, Individual o2) {
int f1 = o1.getFitness();
int f2 = o2.getFitness();
if (f1 > f2) {
return 1;
}
if (f1 == f2) {
return 0;
}
return -1;
}
}
|
package com.haxademic.core.system;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileFilter;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.channels.FileChannel;
import java.util.ArrayList;
import com.haxademic.core.app.P;
import com.haxademic.core.debug.DebugUtil;
import com.haxademic.core.math.MathUtil;
public class FileUtil {
public static String DATA_PATH = null;
public static String OUTPUT_PATH = null;
public static String BIN_PATH = null;
public static String HAX_PATH = null;
public static String getProjectAbsolutePath() {
return new java.io.File("").getAbsolutePath();
}
public static String getHaxademicPath() {
if( HAX_PATH != null ) return HAX_PATH;
String binPath = getProjectAbsolutePath();
Boolean hasBin = ( binPath.lastIndexOf("/bin") != -1 ) ? true : false;
HAX_PATH = ( hasBin == true ) ? binPath.substring(0, binPath.lastIndexOf("/bin") ) : binPath;
return HAX_PATH;
}
public static String getHaxademicBinPath() {
if( BIN_PATH != null ) return BIN_PATH;
BIN_PATH = getHaxademicPath().concat("/bin/");
return BIN_PATH;
}
public static String getHaxademicDataPath() {
if( DATA_PATH != null ) return DATA_PATH;
DATA_PATH = getHaxademicPath().concat("/data/");
return DATA_PATH;
}
public static String getHaxademicOutputPath() {
if( OUTPUT_PATH != null ) return OUTPUT_PATH;
OUTPUT_PATH = getHaxademicPath().concat("/output/");
return OUTPUT_PATH;
}
public static Boolean fileOrPathExists( String path ) {
File f = new File( path );
return f.exists();
}
public static Boolean fileExists( String path ) {
return new File( path ).isFile();
}
/**
* Creates a new directory on the machine's filesystem
* @param path Directory to create
*/
public static void createDir( String path ) {
File f = new File( path );
try {
if( f.mkdir() ) {
P.println("Directory created: "+path);
} else {
P.println("Directory was not created"+path);
}
} catch(Exception e){
e.printStackTrace();
}
}
/**
* Finds files of a specific type within a directory
* @param path Directory to search
* @param type File extension to search for
*/
public static ArrayList<String> getFilesInDirOfType( String directory, String type ) {
type = "."+type;
File dir = new File( directory );
String[] children = dir.list();
ArrayList<String> filesOfType = new ArrayList<String>();
if (children == null) {
P.println("FileUtil error: couldn't find file or directory");
} else {
for (int i=0; i < children.length; i++) {
String filename = children[i];
if( filename.indexOf( type ) != -1 ) {
P.println(filename);
filesOfType.add( filename );
}
}
}
return filesOfType;
}
public static void shuffleFileList( ArrayList<String> files ) {
String cur = null;
String temp = null;
int swapIndex = 0;
for( int i=0; i < files.size(); i++ ) {
swapIndex = MathUtil.randRange(0, files.size() - 1);
temp = files.get( swapIndex );
cur = files.get( i );
files.set( swapIndex, cur );
files.set( i, temp );
}
}
public static void getFilesInDir( String directory ) {
File dir = new File( directory );
String[] children = dir.list();
if (children == null) {
// Either dir does not exist or is not a directory
} else {
for (int i=0; i<children.length; i++) {
// Get filename of file or directory
String filename = children[i];
DebugUtil.print( filename );
}
}
// It is also possible to filter the list of returned files.
// This example does not return any files that start with `.'.
FilenameFilter filter = new FilenameFilter() {
public boolean accept(File dir, String name) {
return !name.startsWith(".");
}
};
children = dir.list(filter);
// The list of files can also be retrieved as File objects
// File[] files = dir.listFiles();
// This filter only returns directories
FileFilter fileFilter = new FileFilter() {
public boolean accept(File file) {
return file.isDirectory();
}
};
File[] files = dir.listFiles(fileFilter);
P.println( files.length );
}
/**
* Simple method to write text to a file
* @param file The filename (with full path) to write to
* @param text Text to write to the file
*/
public static final void writeTextToFile( String file, String text ) {
try {
BufferedWriter writer = new BufferedWriter(new FileWriter(file));
writer.write( text );
writer.close();
} catch (IOException e) { e.printStackTrace(); }
}
/**
* Simple method to append text to a file
* @param file The filename (with full path) to write to
* @param text Text to appendto the file
*/
public static final void appendTextToFile( String file, String text ) {
try {
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(file, true)));
out.print(text);
out.close();
} catch (IOException e) { e.printStackTrace(); }
}
public static void copyFile( String sourcePath, String destPath ) throws IOException {
File sourceFile = new File( sourcePath );
File destFile = new File( destPath );
if(!destFile.exists()) {
destFile.createNewFile();
}
FileChannel source = null;
FileChannel destination = null;
try {
source = new FileInputStream(sourceFile).getChannel();
destination = new FileOutputStream(destFile).getChannel();
destination.transferFrom(source, 0, source.size());
}
finally {
if(source != null) {
source.close();
}
if(destination != null) {
destination.close();
}
}
}
}
|
package com.humbughq.mobile;
import java.util.ArrayList;
import java.util.HashMap;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.util.SparseArray;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.webkit.WebView;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
public class HumbugActivity extends Activity {
public static final String USER_AGENT = "ZulipMobile 1.0";
ListView listView;
SparseArray<Message> messageIndex;
MessageAdapter adapter;
AsyncPoller current_poll;
boolean suspended = false;
boolean logged_in = false;
String api_key;
View bottom_list_spacer;
HumbugActivity that = this; // self-ref
SharedPreferences settings;
String client_id;
protected int mIDSelected;
private Menu menu;
public Person you;
private View composeView;
protected HashMap<String, Bitmap> gravatars = new HashMap<String, Bitmap>();
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
settings = getPreferences(Activity.MODE_PRIVATE);
this.you = new Person(null, settings.getString("email", null));
this.api_key = settings.getString("api_key", null);
if (this.api_key == null) {
this.openLogin();
} else {
this.openHomeView();
}
return;
}
public boolean onPrepareOptionsMenu(Menu menu) {
/*
* We want to show a menu only when we're logged in, so this function is
* called by both Android and our own app when we encounter state
* changes where we might want to update the menu.
*/
if (menu == null) {
// We were called by a function before the menu had been
// initialised, so we should bail.
return false;
}
this.menu = menu;
menu.clear();
if (this.logged_in) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.options, menu);
}
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case R.id.compose_stream:
openCompose(MessageType.STREAM_MESSAGE);
break;
case R.id.compose_pm:
openCompose(MessageType.PRIVATE_MESSAGE);
break;
case R.id.refresh:
Log.w("menu", "Refreshed manually by user. We shouldn't need this.");
onResume();
break;
case R.id.logout:
logout();
break;
case R.id.legal:
openLegal();
break;
default:
return super.onOptionsItemSelected(item);
}
return true;
}
/**
* Switches the compose window's state to compose a personal message.
*/
protected void switchToPersonal() {
EditText recipient = (EditText) composeView
.findViewById(R.id.composeRecipient);
EditText subject = (EditText) composeView
.findViewById(R.id.composeSubject);
subject.setVisibility(View.GONE);
recipient.setGravity(Gravity.FILL_HORIZONTAL);
recipient.setHint(R.string.pm_prompt);
}
/**
* Switches the compose window's state to compose a stream message.
*/
protected void switchToStream() {
EditText recipient = (EditText) composeView
.findViewById(R.id.composeRecipient);
EditText subject = (EditText) composeView
.findViewById(R.id.composeSubject);
subject.setVisibility(View.VISIBLE);
recipient.setGravity(Gravity.NO_GRAVITY);
recipient.setHint(R.string.stream);
}
protected void openCompose(Message msg) {
openCompose(msg, null);
}
protected void openCompose(MessageType type) {
openCompose(null, type);
}
private void openCompose(Message msg, MessageType type) {
openCompose(msg, type, false);
}
private void openCompose(Message msg, MessageType type, boolean to_sender) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
LayoutInflater inflater = this.getLayoutInflater();
composeView = inflater.inflate(R.layout.compose, null);
AlertDialog composeWindow = builder
.setView(composeView)
.setTitle("Compose")
.setPositiveButton(R.string.send,
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface d, int id) {
EditText recipient = (EditText) composeView
.findViewById(R.id.composeRecipient);
EditText subject = (EditText) composeView
.findViewById(R.id.composeSubject);
EditText body = (EditText) composeView
.findViewById(R.id.composeText);
// If the subject field is hidden, we have a
// personal
// message.
boolean subjectFilledIfRequired = subject
.getVisibility() == View.GONE
|| requireFilled(subject, "subject");
if (!(requireFilled(recipient, "recipient")
&& subjectFilledIfRequired && requireFilled(
body, "message body"))) {
return;
}
Message msg = new Message();
msg.setSender(that.you);
if (subject.getVisibility() == View.GONE) {
msg.setType(MessageType.PRIVATE_MESSAGE);
msg.setRecipient(recipient.getText()
.toString().split(","));
} else {
msg.setType(MessageType.STREAM_MESSAGE);
msg.setStream(recipient.getText()
.toString());
msg.setSubject(subject.getText().toString());
}
msg.setContent(body.getText().toString());
AsyncSend sender = new AsyncSend(that, msg);
sender.execute();
}
})
.setNegativeButton(android.R.string.cancel,
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface d, int id) {
d.dismiss();
}
}).create();
EditText recipient = (EditText) composeView
.findViewById(R.id.composeRecipient);
EditText subject = (EditText) composeView
.findViewById(R.id.composeSubject);
EditText body = (EditText) composeView.findViewById(R.id.composeText);
if (type == MessageType.STREAM_MESSAGE
|| (msg != null && msg.getType() == MessageType.STREAM_MESSAGE && !to_sender)) {
this.switchToStream();
} else {
this.switchToPersonal();
}
if (msg != null) {
if (msg.getType() == MessageType.STREAM_MESSAGE && !to_sender) {
recipient.setText(msg.getStream());
subject.setText(msg.getSubject());
} else if (msg.getType() == MessageType.PRIVATE_MESSAGE
&& !to_sender) {
recipient.setText(msg.getReplyTo());
} else {
recipient.setText(msg.getSender().getEmail());
}
body.requestFocus();
} else {
// Focus the stream, zero out stream/subject
recipient.requestFocus();
recipient.setText("");
subject.setText("");
}
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.toggleSoftInput(InputMethodManager.SHOW_FORCED,
InputMethodManager.HIDE_IMPLICIT_ONLY);
composeWindow
.setOnDismissListener(new DialogInterface.OnDismissListener() {
@Override
public void onDismiss(DialogInterface dialog) {
// Hide physical keyboard if present.
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.toggleSoftInput(InputMethodManager.SHOW_IMPLICIT, 0);
}
});
composeWindow.show();
}
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
private void copyMessage(Message msg) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
android.content.ClipboardManager clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
clipboard.setPrimaryClip(ClipData.newPlainText("Zulip Message",
msg.getContent()));
} else {
// TODO: implement a pre-Honeycomb version
// using the older android.text.ClipboardManager API
}
}
/**
* Check if a field is nonempty and mark fields as invalid if they are.
*
* @param field
* The field to check
* @param fieldName
* The human-readable name of the field
* @return Whether the field correctly validated.
*/
protected boolean requireFilled(EditText field, String fieldName) {
if (field.getText().toString().equals("")) {
field.setError("You must specify a " + fieldName);
field.requestFocus();
return false;
}
return true;
}
/**
* Log the user out of the app, clearing our cache of their credentials.
*/
private void logout() {
this.logged_in = false;
if (this.current_poll != null) {
this.current_poll.cancel(true);
}
Editor ed = this.settings.edit();
ed.remove("email");
ed.remove("api_key");
ed.commit();
this.openLogin();
}
/**
* Switch to the login view.
*/
protected void openLogin() {
this.logged_in = false;
this.onPrepareOptionsMenu(menu);
setContentView(R.layout.login);
((Button) findViewById(R.id.login))
.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
TextView errorText = (TextView) findViewById(R.id.error_text);
errorText.setText("Logging in...");
(new AsyncLogin(that,
((EditText) findViewById(R.id.username))
.getText().toString(),
((EditText) findViewById(R.id.password))
.getText().toString())).execute();
}
});
((TextView) findViewById(R.id.legalTextView))
.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
openLegal();
}
});
}
protected void openLegal() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
WebView legalView = new WebView(this);
legalView.loadUrl("file:
builder.setView(legalView)
.setTitle(R.string.legal)
.setPositiveButton(R.string.close,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.dismiss();
}
});
AlertDialog dialog = builder.create();
dialog.show();
}
private void size_bottom_spacer() {
@SuppressWarnings("deprecation")
// needed for compat with API <13
int windowHeight = ((WindowManager) this
.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay()
.getHeight();
AbsListView.LayoutParams params = new AbsListView.LayoutParams(0, 0);
params.height = windowHeight / 2;
this.bottom_list_spacer.setLayoutParams(params);
}
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// our display has changed, lets recalculate the spacer
this.size_bottom_spacer();
}
/**
* Open the home view, where the message list is displayed.
*/
protected void openHomeView() {
this.onPrepareOptionsMenu(menu);
this.logged_in = true;
messageIndex = new SparseArray<Message>();
setContentView(R.layout.main);
listView = (ListView) findViewById(R.id.listview);
this.bottom_list_spacer = new ImageView(this);
this.size_bottom_spacer();
listView.addFooterView(this.bottom_list_spacer);
adapter = new MessageAdapter(this, new ArrayList<Message>());
listView.setAdapter(adapter);
// We want blue highlights when you longpress
listView.setDrawSelectorOnTop(true);
registerForContextMenu(listView);
listView.setOnScrollListener(new OnScrollListener() {
@Override
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
// pass
}
@Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
try {
// Scrolling messages isn't meaningful unless we have
// messages to scroll.
int mID = ((Message) view.getItemAtPosition(view
.getFirstVisiblePosition())).getID();
if (mIDSelected != mID) {
Log.i("scrolling", "Now at " + mID);
(new AsyncPointerUpdate(that)).execute(mID);
mIDSelected = mID;
}
} catch (NullPointerException e) {
Log.w("scrolling",
"Could not find a location to scroll to!");
}
}
});
listView.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
try {
openCompose(adapter.getItem(position));
} catch (IndexOutOfBoundsException e) {
// We can ignore this because its probably before the data
// has been fetched.
}
}
});
listView.setOnItemSelectedListener(new OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view,
int position, long id) {
try {
int mID = (Integer) view.getTag(R.id.messageID);
if (mIDSelected != mID) {
Log.i("keyboard", "Now at " + mID);
(new AsyncPointerUpdate(that)).execute(mID);
mIDSelected = mID;
}
} catch (NullPointerException e) {
Log.e("selected", "None, because we couldn't find the tag.");
}
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
// pass
}
});
(new AsyncPointerUpdate(this)).execute();
}
protected void onPause() {
super.onPause();
Log.i("status", "suspend");
this.suspended = true;
if (this.current_poll != null) {
this.current_poll.cancel(true);
}
}
protected void onResume() {
super.onResume();
Log.i("status", "resume");
this.suspended = false;
if (this.logged_in) {
if (this.adapter.getCount() != 0) {
AsyncPointerUpdate apu = new AsyncPointerUpdate(this);
apu.execute();
}
}
}
/**
* Determines the server URI applicable for the user.
*
* @return either the production or staging server's URI
*/
public String getServerURI() {
if (you.getRealm().equals("zulip.com")
|| you.getRealm().equals("humbughq.com")) {
return "https://staging.zulip.com/api/";
}
return "https://api.zulip.com/";
}
@Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
// Using menuInfo, determine which menu to show (stream or private)
AdapterContextMenuInfo info = (AdapterContextMenuInfo) menuInfo;
Message msg = messageIndex.get((int) info.id);
if (msg == null) {
return;
}
if (msg.getType().equals(MessageType.STREAM_MESSAGE)) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.context_stream, menu);
} else if (msg.getReplyToArray().length > 1) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.context_private, menu);
} else {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.context_single_private, menu);
}
}
@Override
public boolean onContextItemSelected(MenuItem item) {
AdapterContextMenuInfo info = (AdapterContextMenuInfo) item
.getMenuInfo();
Message message = messageIndex.get((int) info.id);
switch (item.getItemId()) {
case R.id.reply_to_stream:
openCompose(message, message.getType());
return true;
case R.id.reply_to_private:
openCompose(message, message.getType());
return true;
case R.id.reply_to_sender:
openCompose(message, MessageType.PRIVATE_MESSAGE, true);
return true;
case R.id.copy_message:
copyMessage(message);
return true;
default:
return super.onContextItemSelected(item);
}
}
}
|
package com.icecondor.nest.ui;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.res.Configuration;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.app.Fragment;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import com.icecondor.nest.Condor;
import com.icecondor.nest.Condor.LocalBinder;
import com.icecondor.nest.Constants;
import com.icecondor.nest.Prefs;
import com.icecondor.nest.R;
import com.icecondor.nest.ui.alist.ActivityListFragment;
import com.icecondor.nest.ui.alist.SettingsFragment;
abstract public class BaseActivity extends ActionBarActivity
implements ServiceConnection,
UiActions, OnItemClickListener {
protected Prefs prefs;
private LocalBinder localBinder;
protected Condor condor;
protected Intent condorIntent;
private Handler handler;
private DrawerLayout drawerLayout;
private ActionBarDrawerToggle drawerToggle;
private ListView drawerList;
private SettingsFragment settingsFragment;
protected ActivityListFragment actListFragment;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d(Constants.APP_TAG, "BaseActivity("+this.getClass().getName()+"): onCreate data "+getIntent().getData());
prefs = new Prefs(this);
condorIntent = new Intent(this, Condor.class);
handler = new Handler();
setContentView(R.layout.activity_main);
ActionBar bar = getSupportActionBar();
drawerSetup(bar);
settingsFragment = new SettingsFragment();
actListFragment = new ActivityListFragment();
}
@Override
protected void onStart() {
super.onStart();
Log.d(Constants.APP_TAG, "BaseActivity("+this.getClass().getName()+"): onStart");
startService(condorIntent); // keep this for STICKY result
}
@Override
protected void onResume() {
super.onResume();
Log.d(Constants.APP_TAG, "BaseActivity("+this.getClass().getName()+"): onResume");
bindService(condorIntent, this, BIND_AUTO_CREATE);
}
@Override
protected void onPause() {
super.onPause();
Log.d(Constants.APP_TAG, "BaseActivity("+this.getClass().getName()+"): onPause");
if(condor != null) {
condor = null;
unbindService(this);
}
}
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
log("onServiceConnected "+name.flattenToShortString());
localBinder = (Condor.LocalBinder)service;
enableServiceHandler();
condor = localBinder.getService();
}
protected void enableServiceHandler() {
if(localBinder != null) {
localBinder.setHandler(handler, this);
}
}
protected void disableServiceHandler() {
if(localBinder != null) {
localBinder.clearHandler();
}
}
@Override
public void onServiceDisconnected(ComponentName name) {
log("onServiceDisconnected "+name.flattenToShortString());
}
public void drawerSetup(ActionBar bar) {
drawerList = (ListView) findViewById(R.id.left_drawer);
ArrayList<Map<String, ?>> list = new ArrayList<Map<String, ?>>();
populateDrawer(list);
drawerList.setAdapter(new SimpleAdapter(this, list,
R.layout.drawer_list_item,
new String[]{"icon", "name"},
new int[]{R.id.drawer_row_icon, R.id.drawer_row_name}){
});
drawerList.setOnItemClickListener(BaseActivity.this);
drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
drawerToggle = new ActionBarDrawerToggle(this,
drawerLayout,
R.drawable.ic_navigation_drawer,
R.string.drawer_open,
R.string.drawer_closed)
{
/** Called when a drawer has settled in a completely closed state. */
@Override
public void onDrawerClosed(View view) {
super.onDrawerClosed(view);
}
/** Called when a drawer has settled in a completely open state. */
@Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
}
};
drawerLayout.setDrawerListener(drawerToggle);
bar.setDisplayHomeAsUpEnabled(true);
bar.setHomeButtonEnabled(true);
}
public void populateDrawer(ArrayList<Map<String, ?>> list) {
HashMap<String, Object> item;
item = new HashMap<String, Object>();
item.put("icon",R.drawable.ic_person);
item.put("name", prefs.getAuthenticatedUsername());
list.add(item);
item = new HashMap<String, Object>();
item.put("icon",R.drawable.ic_bar_blue);
item.put("name", "Activity");
list.add(item);
item = new HashMap<String, Object>();
item.put("icon",R.drawable.ic_bar_blue);
item.put("name", "Settings");
list.add(item);
}
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Log.d(Constants.APP_TAG, "BaseActivity: onItemClick position:"+position+" id:"+id);
if(position == 0) {
// User
String url = "https://icecondor.com/"+prefs.getAuthenticatedUsername();
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url));
startActivity(i);
}
if(position == 1) {
// Activity List
switchFragment(actListFragment);
drawerLayout.closeDrawers();
}
if(position == 2) {
// Settings
switchFragment(settingsFragment);
drawerLayout.closeDrawers();
}
}
protected void switchFragment(Fragment fragment) {
getSupportFragmentManager().beginTransaction()
.replace(R.id.container, fragment, "frags").commit();
}
@Override
public void onBackPressed() {
Fragment fragment = getSupportFragmentManager().findFragmentByTag("frags");
if(fragment instanceof SettingsFragment && fragment.isVisible()){
switchFragment(actListFragment);
} else {
super.onBackPressed();
}
}
@Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
drawerToggle.syncState();
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
drawerToggle.onConfigurationChanged(newConfig);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Pass the event to ActionBarDrawerToggle, if it returns
// true, then it has handled the app icon touch event
if (drawerToggle.onOptionsItemSelected(item)) {
return true;
}
// Handle your other action bar items...
return super.onOptionsItemSelected(item);
}
public void authCheck() {
if(prefs.getAuthenticatedUserId() == null) {
startActivity(new Intent(this, com.icecondor.nest.ui.login.Main.class));
return;
}
}
protected void log(String msg){
Log.d(Constants.APP_TAG, "BaseActivity("+this.getClass().getName()+"): "+msg);
}
}
|
package com.ilearnrw.reader;
import ilearnrw.annotation.UserBasedAnnotatedWord;
import ilearnrw.annotation.UserBasedAnnotatedWordsSet;
import ilearnrw.textclassification.SeverityOnWordProblemInfo;
import ilearnrw.textclassification.StringMatchesInfo;
import ilearnrw.textclassification.Word;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Locale;
import com.ilearnrw.reader.R;
import com.ilearnrw.reader.interfaces.OnTextToSpeechComplete;
import com.ilearnrw.reader.interfaces.TTSHighlightCallback;
import com.ilearnrw.reader.interfaces.TTSReadingCallback;
import com.ilearnrw.reader.popups.ModeActivity;
import com.ilearnrw.reader.popups.SearchActivity;
import com.ilearnrw.reader.popups.WordActivity;
import com.ilearnrw.reader.texttospeech.TextToSpeechReader;
import com.ilearnrw.reader.texttospeech.TextToSpeechUtils;
import com.ilearnrw.reader.types.Pair;
import com.ilearnrw.reader.types.singleton.AnnotatedWordsSet;
import com.ilearnrw.reader.utils.AppLocales;
import com.ilearnrw.reader.utils.FileHelper;
import com.ilearnrw.reader.utils.Helper;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.graphics.Rect;
import android.graphics.drawable.GradientDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.webkit.JavascriptInterface;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageButton;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.SeekBar.OnSeekBarChangeListener;
public class ReaderActivity
extends
Activity
implements
OnClickListener,
OnLongClickListener,
OnSeekBarChangeListener,
TTSHighlightCallback,
TTSReadingCallback,
OnTextToSpeechComplete {
private final String TAG = getClass().getName();
private TextView tvTitle;
private WebView reader;
private ImageButton ibtnLib, ibtnSearch, ibtnMode, ibtnPrev, ibtnPlay, ibtnNext, ibtnSettings, ibtnSearchForward, ibtnSearchBack;
private RelativeLayout bottom, searchbar, rlHighlightSpeed;
private SeekBar sbHighLightSpeed;
private ReaderMode reader_mode;
private ReaderStatus reader_status;
private HighlightRunnable highlightRunnable;
private Handler highlightHandler;
public HashMap<String, Pair<String>> highlightParts;
private SharedPreferences sp;
private SharedPreferences.Editor spEditor;
private TextToSpeechReader ttsReader;
public String CURR_SENT;
public String CURR_WORD;
public final String SENTENCE_TAG = "sen";
public final String WORD_TAG = "w";
private ArrayList<String> sentenceIds, wordIds;
private String defaultSentence = "", defaultWord = "";
private int currSentPos, currWordPos;
private String touchedId;
private static String html, bundleJSON, bundleHtml, cleanHtml;
private String libraryTitle;
private double highlightSpeed;
private boolean isHighlighting;
private UserBasedAnnotatedWordsSet annotationData;
private ArrayList<Word> trickyWords;
public final static int FLAG_SEARCH = 10000;
public final static int FLAG_MODE = 10001;
public final static int FLAG_REFRESH_WEBVIEW = 10002;
public final static int FLAG_WORD_POPUP = 10004;
public static enum ReaderMode {
Listen("Listen", 0),
Guidance("Guidance", 1);
private String name;
private int value;
private ReaderMode(String name, int value){
this.name = name;
this.value = value;
}
@Override
public String toString() {
return name;
}
public int getValue(){
return value;
}
public String getName(){
return name;
}
}
public static enum HighlightMode{
Sentence("Sentence", 1),
Word("Word", 2);
private String name;
private int value;
private HighlightMode(String name, int value){
this.name = name;
this.value = value;
}
@Override
public String toString() {
return name;
}
public int getValue(){
return value;
}
public String getName(){
return name;
}
}
public static enum ReaderStatus {
Enabled,
Disabled
}
@SuppressWarnings("unchecked")
@SuppressLint("SetJavaScriptEnabled")
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_reader);
sp = PreferenceManager.getDefaultSharedPreferences(this);
AppLocales.setLocales(getApplicationContext(), sp.getString(getString(R.string.sp_user_language), "en"));
Bundle libBundle = getIntent().getExtras();
String htmlName = libBundle.getString("html");
libraryTitle = libBundle.getString("title");
boolean isRulesAct = libBundle.getBoolean("annotated");
annotationData = AnnotatedWordsSet.getInstance(this.getApplicationContext()).getUserBasedAnnotatedWordsSet();
trickyWords = (ArrayList<Word>) libBundle.get("trickyWords");
Pair<File> libItems = FileHelper.getFilesFromLocation(this, htmlName, getString(R.string.library_location));
Pair<File> f = FileHelper.getFilesFromLocation(this, "annotatedData.txt", getString(R.string.temp_location));
bundleHtml = isRulesAct ? FileHelper.readFromFile(f.first()) : FileHelper.readFromFile(libItems.first());
bundleJSON = FileHelper.readFromFile(libItems.second());
spEditor = sp.edit();
Pair<String> bookTitle = Helper.splitFileName(libraryTitle);
CURR_SENT = bookTitle.first() + "_" + bookTitle.second().substring(1) + "_sent";
CURR_WORD = bookTitle.first() + "_" + bookTitle.second().substring(1) + "_word";
tvTitle = (TextView) findViewById(R.id.tv_book_title_reader);
if(libraryTitle.endsWith(".txt"))
libraryTitle = libraryTitle.substring(0, libraryTitle.length()-4);
tvTitle.setText(libraryTitle);
sbHighLightSpeed = (SeekBar) findViewById(R.id.seekbar_highLight_speed);
sbHighLightSpeed.setOnSeekBarChangeListener(this);
highlightSpeed = Double.longBitsToDouble(sp.getLong(getString(R.string.pref_highlighter_speed), Double.doubleToLongBits(5.5)));
int hlSpeed = (int) (highlightSpeed * 10);
int flipValue = sbHighLightSpeed.getMax() - hlSpeed;
sbHighLightSpeed.setProgress(flipValue);
ibtnLib = (ImageButton) findViewById(R.id.ibtn_lib_reader);
ibtnSearch = (ImageButton) findViewById(R.id.ibtn_search_reader);
ibtnMode = (ImageButton) findViewById(R.id.ibtn_mode_reader);
ibtnPrev = (ImageButton) findViewById(R.id.ibtn_prev_reader);
ibtnPlay = (ImageButton) findViewById(R.id.ibtn_play_reader);
ibtnNext = (ImageButton) findViewById(R.id.ibtn_next_reader);
ibtnSettings = (ImageButton) findViewById(R.id.ibtn_settings_reader);
searchbar = (RelativeLayout) findViewById(R.id.search_buttons_layout);
ibtnSearchForward = (ImageButton) findViewById(R.id.ibtn_search_forward);
ibtnSearchBack = (ImageButton) findViewById(R.id.ibtn_search_back);
bottom = (RelativeLayout) findViewById(R.id.reader_bottom);
rlHighlightSpeed = (RelativeLayout) findViewById(R.id.reader_body_highlight_speed);
ibtnLib.setOnClickListener(this);
ibtnSearch.setOnClickListener(this);
ibtnMode.setOnClickListener(this);
ibtnPrev.setOnClickListener(this);
ibtnPlay.setOnClickListener(this);
ibtnNext.setOnClickListener(this);
ibtnSettings.setOnClickListener(this);
ibtnSearchForward.setOnClickListener(this);
ibtnSearchBack.setOnClickListener(this);
ibtnPlay.setEnabled(false);
ibtnNext.setEnabled(false);
ibtnPrev.setEnabled(false);
searchbar.setVisibility(RelativeLayout.GONE);
//TextToSpeechUtils.checkLanguageData(this);
ttsReader = TextToSpeechReader.getInstance(getApplicationContext());
//ttsReader = new TextToSpeechReaderId(this, this, Locale.UK, SENTENCE_TAG, this, this);
reader = (WebView) findViewById(R.id.webview_reader);
reader.setOnLongClickListener(this);
reader.setLongClickable(false);
reader.getSettings().setJavaScriptEnabled(true);
reader.addJavascriptInterface(new ReaderWebInterface(this), "ReaderInterface");
reader.getSettings().setDefaultFontSize(22);
reader.setWebViewClient(new MyWebViewClient());
html = updateHtml(bundleHtml);
reader.loadDataWithBaseURL("file:///android_asset/", html, "text/html", "UTF-8", "about:blank");
reader_status = ReaderStatus.Disabled;
ibtnPlay.setImageResource(R.drawable.image_selector_play);
touchedId = "w0";
currSentPos = sp.getInt(CURR_SENT, 0);
currWordPos = sp.getInt(CURR_WORD, 0);
isHighlighting = sp.getBoolean(getString(R.string.sp_highlighting), true);
highlightParts = new HashMap<String, Pair<String>>();
int mode = sp.getInt(getString(R.string.sp_reader_mode), -1);
if(mode==-1){
reader_mode = ReaderMode.Listen;
mode = reader_mode.getValue();
spEditor.putInt(getString(R.string.sp_reader_mode), mode).apply();
rlHighlightSpeed.setVisibility(View.GONE);
Toast.makeText(this, "No reader mode set. Listen mode is selected", Toast.LENGTH_LONG).show();
} else {
switch(mode){
case 0:
reader_mode = ReaderMode.Listen;
rlHighlightSpeed.setVisibility(View.GONE);
break;
case 1:
reader_mode = ReaderMode.Guidance;
rlHighlightSpeed.setVisibility(View.VISIBLE);
break;
}
}
highlightRunnable = new HighlightRunnable();
highlightHandler = new Handler();
ibtnPlay.setEnabled(true);
ibtnNext.setEnabled(true);
ibtnPrev.setEnabled(true);
updateGUI();
}
@Override
protected void onResume() {
ttsReader.activateIdDrive(this, this, this);
super.onResume();
}
@Override
protected void onPause() {
turnOffHandler();
ttsReader.deactivateIdDrive();
super.onPause();
}
@Override
protected void onDestroy() {
//ttsReader.destroy();
super.onDestroy();
}
@SuppressWarnings("unchecked")
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case TextToSpeechUtils.FLAG_CHECK_TTS_DATA:
//if(tts==null){
// tts = new TextToSpeechIdDriven(ReaderActivity.this, this, CURR_SENT, cbHighlight, cbSpoken, requestCode, resultCode, data);
// setTTS();
break;
case FLAG_SEARCH:
{
if(resultCode == RESULT_OK){
String searchString = data.getStringExtra("searchString");
searchbar.setVisibility(RelativeLayout.VISIBLE);
reader.findAllAsync(searchString);
}
}
break;
case FLAG_WORD_POPUP:
{
if(resultCode == RESULT_OK){
trickyWords = (ArrayList<Word>) data.getExtras().get("trickyWords");
}
}
break;
case FLAG_MODE:
{
if(resultCode == RESULT_OK){
int mode = data.getExtras().getInt("chosenMode");
switch(mode){
case 0:
reader_mode = ReaderMode.Listen;
rlHighlightSpeed.setVisibility(View.GONE);
currSentPos = sp.getInt(CURR_SENT, 0);
highlight(sentenceIds.get(currSentPos));
removeHighlight(wordIds.get(currWordPos));
break;
case 1:
reader_mode = ReaderMode.Guidance;
rlHighlightSpeed.setVisibility(View.VISIBLE);
currWordPos = sp.getInt(CURR_WORD, 0);
highlight(wordIds.get(currWordPos));
removeHighlight(sentenceIds.get(currSentPos));
break;
}
spEditor.putInt(getString(R.string.sp_reader_mode), mode).apply();
}
}
break;
case FLAG_REFRESH_WEBVIEW:
{
if(data!=null){
Bundle b = data.getExtras();
if(b.containsKey("showGUI")){
boolean show = b.getBoolean("showGUI", false);
if(show){
Intent i = new Intent(this, ActiveRules.class);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP|Intent.FLAG_ACTIVITY_SINGLE_TOP);
startActivity(i);
return;
} else {
Intent intent = new Intent(ReaderActivity.this, ActiveRules.class);
intent.putExtra("html", bundleHtml);
intent.putExtra("json", bundleJSON);
intent.putExtra("cleanHtml", cleanHtml);
intent.putExtra("title", libraryTitle);
intent.putExtra("loadFiles", false);
intent.putExtra("showGUI", true);
startActivity(intent);
return;
}
}
}
updateGUI();
html = updateHtml(bundleHtml);
reader.loadDataWithBaseURL("file:///android_asset/", html, "text/html", "UTF-8", "about:blank");
setTTS();
}
default:
break;
}
super.onActivityResult(requestCode, resultCode, data);
}
private void turnOffHandler(){
highlightHandler.removeCallbacks(highlightRunnable);
}
@Override
public void onBackPressed() {
Intent i = new Intent(this, LibraryActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP|Intent.FLAG_ACTIVITY_SINGLE_TOP);
startActivity(i);
finish();
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.ibtn_lib_reader:
Intent lib_intent = new Intent(this, LibraryActivity.class);
lib_intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP|Intent.FLAG_ACTIVITY_SINGLE_TOP);
startActivity(lib_intent);
finish();
break;
case R.id.ibtn_search_reader:
Intent search_intent = new Intent(this, SearchActivity.class);
search_intent.putExtra("posX", ibtnSearch.getX());
search_intent.putExtra("posY", (ibtnSearch.getY()+ibtnSearch.getHeight()));
search_intent.putExtra("imageHeight", ibtnSearch.getHeight());
startActivityForResult(search_intent, FLAG_SEARCH);
break;
case R.id.ibtn_mode_reader:
if(reader_status == ReaderStatus.Enabled)
setPlayStatus(ReaderStatus.Disabled, true);
else if(reader_status == ReaderStatus.Disabled)
setPlayStatus(ReaderStatus.Disabled, false);
highlightHandler.removeCallbacks(highlightRunnable);
if(reader_mode == ReaderMode.Listen)
ttsReader.stop();
Intent mode_intent = new Intent(this, ModeActivity.class);
mode_intent.putExtra("posX", ibtnMode.getX());
mode_intent.putExtra("posY", (bottom.getY()-ibtnMode.getHeight()));
mode_intent.putExtra("imageHeight", ibtnMode.getHeight());
mode_intent.putExtra("readerMode", reader_mode);
startActivityForResult(mode_intent, FLAG_MODE);
break;
case R.id.ibtn_settings_reader:
highlightHandler.removeCallbacks(highlightRunnable);
if(reader_status == ReaderStatus.Enabled)
setPlayStatus(ReaderStatus.Disabled, true);
if(ttsReader.isSpeaking())
ttsReader.stop();
Intent i = new Intent(this, SettingsActivity.class);
i.putExtra("setting", "reader");
startActivityForResult(i, FLAG_REFRESH_WEBVIEW);
break;
case R.id.ibtn_prev_reader:
stepReader(false);
break;
case R.id.ibtn_play_reader:
if(reader_mode == ReaderMode.Listen){
if(reader_status == ReaderStatus.Disabled){
setPlayStatus(ReaderStatus.Enabled, true);
currSentPos = sp.getInt(CURR_SENT, 0);
String c = sentenceIds.get(currSentPos);
speakFromSentence(c);
} else {
setPlayStatus(ReaderStatus.Disabled, true);
spEditor.putInt(CURR_SENT, currSentPos).apply();
ttsReader.stop();
ttsReader.rehighlight();
}
} else if(reader_mode == ReaderMode.Guidance){
if(reader_status == ReaderStatus.Disabled){
setPlayStatus(ReaderStatus.Enabled, true);
resetGuidance();
} else {
setPlayStatus(ReaderStatus.Disabled, true);
highlightHandler.removeCallbacks(highlightRunnable);
}
}
break;
case R.id.ibtn_next_reader:
stepReader(true);
break;
case R.id.ibtn_search_forward:
reader.findNext(true);
break;
case R.id.ibtn_search_back:
reader.findNext(false);
break;
default:
break;
}
}
private void stepReader(boolean forward){
boolean isSpeaking =ttsReader.isSpeaking();
boolean doHighlight=true;
int direction = forward ? -1 : 1;
if(reader_mode == ReaderMode.Listen){
spEditor.putBoolean(getString(R.string.sp_tts_reader_is_stepping), true).apply();
ttsReader.stop();
if(isSpeaking){
setPlayStatus(ReaderStatus.Disabled, false);
}
if(!forward){
currSentPos
if(currSentPos<0){
currSentPos=0;
doHighlight = false;
}
} else {
currSentPos++;
if(currSentPos>sentenceIds.size()-1){
currSentPos=sentenceIds.size()-1;
doHighlight = false;
}
}
String current = sentenceIds.get(currSentPos);
String other = sentenceIds.get(currSentPos+direction);
if(doHighlight){
removeHighlight(other);
highlight(current);
}
spEditor.putInt(CURR_SENT, currSentPos).apply();
if(isSpeaking)
setPlayStatus(ReaderStatus.Enabled, false);
reader.loadUrl("javascript:updateCurrentPosition('"+sentenceIds.get(currSentPos)+"', 0);");
if(reader_status == ReaderStatus.Enabled)
speakFromSentence(current);
} else if(reader_mode == ReaderMode.Guidance){
if(!forward){
currWordPos
if(currWordPos<0){
currWordPos = 0;
doHighlight = false;
}
} else{
currWordPos++;
if(currWordPos>wordIds.size()-1){
currWordPos = wordIds.size()-1;
doHighlight = false;
}
}
String current = wordIds.get(currWordPos);
String other = wordIds.get(currWordPos+direction);
spEditor.putInt(CURR_WORD, currWordPos).apply();
if(doHighlight){
removeHighlight(other);
highlight(current);
}
reader.loadUrl("javascript:updateCurrentPosition('"+wordIds.get(currWordPos)+"', 1);");
if(reader_status == ReaderStatus.Enabled)
resetGuidance();
}
}
@Override
public boolean onLongClick(View v) {
removeSearches();
reader.loadUrl("javascript:longClick('"+touchedId+"');");
return true;
};
@Override
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
switch(seekBar.getId()){
case R.id.seekbar_highLight_speed:
int flipValue = seekBar.getMax() - seekBar.getProgress();
highlightSpeed = (flipValue * 0.1) + 0.5; // Slider values goes from 0.5 to 10.5
break;
default:
break;
}
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
switch (seekBar.getId()) {
case R.id.seekbar_highLight_speed:
highlightHandler.removeCallbacks(highlightRunnable);
break;
default:
break;
}
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
switch (seekBar.getId()) {
case R.id.seekbar_highLight_speed:
int flipValue = seekBar.getMax() - seekBar.getProgress();
highlightSpeed = (flipValue * 0.1);
spEditor.putLong(getString(R.string.pref_highlighter_speed), Double.doubleToRawLongBits(highlightSpeed)).apply();
highlightSpeed += 0.5;
if(reader_status == ReaderStatus.Enabled) {
long millis = (long) (highlightSpeed * 1000);
highlightHandler.postDelayed(highlightRunnable, millis);
}
break;
default:
break;
}
}
public void removeSearches(){
reader.clearMatches();
searchbar.setVisibility(View.GONE);
}
private void updateGUI(){
int sliderProgressColor = 0xff555555;
int backgroundColor = sp.getInt("pref_background_color", 0xffffffff);
int colors[] = new int[3];
colors[0] = Helper.darkenColor(sliderProgressColor, 0.1f);
colors[1] = sliderProgressColor;
colors[2] = Helper.lightenColor(sliderProgressColor, 0.9f);
GradientDrawable shape = new GradientDrawable(GradientDrawable.Orientation.LEFT_RIGHT, colors);
shape.setCornerRadius(5.0f);
shape.setStroke((int)getResources().getDimension(R.dimen.slider_stroke), 0x50999999);
Rect bounds = sbHighLightSpeed.getProgressDrawable().getBounds();
sbHighLightSpeed.setProgressDrawable(shape);
sbHighLightSpeed.getProgressDrawable().setBounds(bounds);
int sliderColor = Helper.darkenColor(backgroundColor, 0.95f);
sbHighLightSpeed.setBackgroundColor(sliderColor);
rlHighlightSpeed.setBackgroundColor(sliderColor);
}
public void highlight(String id){
id = checkId(id);
if(id != null){
//reader.loadUrl("javascript:scrollToElement('" + id + "');");
String highlightColor = "#" + Integer.toHexString(sp.getInt(getString(R.string.pref_highlight_color_title), Color.argb(255, 255, 255, 0))).substring(2);
reader.loadUrl("javascript:highlight('" + id + "', '" + highlightColor + "');");
}
}
public void highlight(String id, String hexColor){
id = checkId(id);
if(id != null)
reader.loadUrl("javascript:highlight('" + id + "', '" + hexColor + "');");
}
public void highlightPart(String id, final int start, final int end, final String hexColor){
final String fId = checkId(id);
if(fId == null)
return;
runOnUiThread(new Runnable() {
@Override
public void run() {
reader.loadUrl("javascript:highlightPart('" + fId + "', '" + start + "', '" + end + "', '" + hexColor + "');");
}
});
}
public void removeHighlight(String id){
id = checkId(id);
if(id != null){
reader.loadUrl("javascript:removeHighlight('" + id + "');");
}
}
public void removeHighlightPart(String id, final Pair<String> span){
final String fId = checkId(id);
if(fId == null)
return;
runOnUiThread(new Runnable() {
@Override
public void run() {
reader.loadUrl("javascript:unhighlight('" + fId + "', '" + span.first() + "', '" + span.second() + "');");
}
});
}
private String checkId(String id){
if(id == null || id.isEmpty()){
if(reader_mode == ReaderMode.Listen){
if(!defaultSentence.isEmpty())
return defaultSentence;
else
return null;
} else if(reader_mode == ReaderMode.Guidance){
if(!defaultWord.isEmpty())
return defaultWord;
else
return null;
}
}
return id;
}
private void resetGuidance(){
highlightHandler.removeCallbacks(highlightRunnable);
long millis = (long) (highlightSpeed * 1000);
highlightHandler.postDelayed(highlightRunnable, millis);
}
private void setPlayStatus(ReaderStatus status, boolean changeImage){
if(changeImage){
if(status == ReaderStatus.Enabled)
ibtnPlay.setImageResource(R.drawable.image_selector_pause);
else
ibtnPlay.setImageResource(R.drawable.image_selector_play);
}
reader_status = status;
}
private void setTTS(){
int pitchRate = sp.getInt(getString(R.string.pref_pitch_title), 9);
int speechRate = sp.getInt(getString(R.string.pref_speech_rate_title), 9);
double pitch = ((pitchRate + 1.0) / 10.0);
ttsReader.setPitch((float)pitch);
double speech = ((speechRate + 1.0) / 10.0);
ttsReader.setSpeechRate((float)speech);
//tts.setLanguage(Locale.UK);
}
private void speakFromSentence(String id){
id = checkId(id);
if(id==null)
return;
final String _id = id;
this.runOnUiThread(new Runnable() {
@Override
public void run() {
reader.loadUrl("javascript:speakSentence('" + _id + "');");
}
});
}
private String updateHtml(String html){
boolean hasHead = true;
StringBuilder builder = new StringBuilder(html);
int insertPos = builder.indexOf("<head");
if(insertPos == -1){
insertPos = builder.indexOf("<html");
hasHead = false;
}
insertPos = builder.indexOf(">", insertPos) + 1;
if(!hasHead){
builder.insert(insertPos, "<head></head>");
insertPos += 6;
} else {
int headEnd = html.indexOf("</head>");
builder.delete(insertPos, headEnd);
}
String startScripts = "<script type=\"text/javascript\">";
String stopScripts = "</script>";
String showToast =
"function showToast(toast){" +
"ReaderInterface.showToast(toast);" +
"}";
String retrieveBodyContent =
"function getBodyContent(str) {" +
" var bodyHTML = document.body.innerHTML;" +
" ReaderInterface.splitSentencesSpeak(bodyHTML, 0, 'button');" +
"}";
String scrollToElement =
"function scrollToElement(id){" +
"var elem = document.getElementById(id);" +
"var x = 0;" +
"var y = 0;" +
"" +
"while(elem != null) {" +
"x += elem.offsetLeft;" +
"y += elem.offsetTop;" +
"elem = elem.offsetParent" +
"}" +
"window.scrollTo(x,y);" +
"}";
String highlightSentence =
"function highlight(id, color){" +
"var element = document.getElementById(id);" +
"element.style.backgroundColor=color;" +
"" +
"return true;" +
"}";
String removeHighlight =
"function removeHighlight(id){" +
"var element = document.getElementById(id);" +
"element.style.backgroundColor='transparent';" +
"" +
"return true;" +
"}";
String highlightPart =
"function highlightPart(id, start, end, color){" +
"var node = document.getElementById(id);" +
"var range = document.createRange();" +
"range.setStart(node.firstChild, start);" +
"range.setEnd(node.firstChild, end);" +
"" +
"var span = document.createElement('span');" +
"span.className = id;" +
"span.style.backgroundColor = color;" +
"" +
"range.surroundContents(span);" +
"range.detach();" +
"ReaderInterface.saveHighlightInformation(id, start, end);" +
"" +
"return true;" +
"}";
String unhighlightPart =
"function unhighlight(id, start, end){" +
"var spans = document.getElementsByTagName(\"span\");" +
"for(var i=0; i<spans.length; i++){" +
"if(spans[i].className == id){" +
"var container = spans[i].parentNode;" +
"var node = spans[i].firstChild;" +
"container.insertBefore(node, spans[i]);" +
"container.removeChild(spans[i]);" +
"ReaderInterface.removeHighlightInformation(id);" +
"}" +
"}" +
"}";
String getSentences =
"function getSentences(){" +
"var sents = document.getElementsByTagName('" + SENTENCE_TAG + "');" +
"var result = '';" +
"for(var i=0; i<sents.length; i++){" +
"if(i+1==sents.length){" +
"result += sents[i].id;" +
"} else {" +
"result += sents[i].id + ',';" +
"}" +
"sents[i].onclick = function() {" +
"var body = document.body.innerHTML;" +
"var index = body.indexOf(this.id);" +
"var part = body.substring(0, index);" +
"var lastIndex = part.lastIndexOf('<');" +
"part = part.substring(lastIndex);" +
"body = body.substring(body.indexOf(this.id));" +
"body = part + body;" +
"ReaderInterface.clickSentence(body, this.id);" +
"};" +
"}" +
"ReaderInterface.getSentences(result);" +
"}";
String getWords =
"function getWords(){" +
"var words = document.getElementsByTagName('" + WORD_TAG + "');" +
"var result = '';" +
"for(var i=0; i<words.length; i++){" +
"words[i].ontouchstart = function(){" +
"ReaderInterface.touchWord(this.id);" +
"};" +
"if(i+1==words.length){" +
"result += words[i].id;" +
"} else {" +
"result += words[i].id + ',';" +
"}" +
"words[i].onclick = function() {" +
"var body = document.body.innerHTML;" +
"var index = body.indexOf(this.id);" +
"var part = body.substring(0, index);" +
"var lastIndex = part.lastIndexOf('<');" +
"part = part.substring(lastIndex);" +
"body = body.substring(body.indexOf(this.id));" +
"body = part + body;" +
"ReaderInterface.clickWord(body, this.id);" +
"};" +
"}" +
"ReaderInterface.getWords(result);" +
"}";
String updatePosition =
"function updateCurrentPosition(id, checkParent){" +
"var node = document.getElementById(id);" +
"var other = '';" +
"if(checkParent==1) {" +
"other = node.parentNode.id;" +
"} else {" +
"other = node.childNodes[0].id;" +
"}" +
"ReaderInterface.updateCurrentPosition(other, checkParent);" +
"}";
String speakSentence =
"function speakSentence(id){" +
"var element = document.getElementById(id);" +
"ReaderInterface.speakSentence(element.innerText);" +
"}";
String longClick =
"function longClick(id) {" +
"var word = document.getElementById(id);" +
"ReaderInterface.longClick(word.innerHTML);" +
"}";
String setCSSLink = "<link rel='stylesheet' href='css/default.css' type='text/css'>";
String backgroundColor = Integer.toHexString(sp.getInt(getString(R.string.pref_background_color_title), Color.argb(255,255,255,255)));
String textColor = Integer.toHexString(sp.getInt(getString(R.string.pref_text_color_title), Color.argb(255,0,0,0)));
backgroundColor = "#" + backgroundColor.substring(2);
textColor = "#" + textColor.substring(2);
String lineHeight = sp.getString(getString(R.string.pref_line_height_title), "125");
int fSize = sp.getInt(getString(R.string.pref_font_size_title), 20);
String fontSize;
String letterSpacing = sp.getString(getString(R.string.pref_letter_spacing_title), "0");
String margin = sp.getString(getString(R.string.pref_margin_title), "5");
String fontFamily = sp.getString(getString(R.string.pref_font_face_title), "default");
lineHeight = lineHeight.equals("0") ? "line-height: normal;" : "line-height: " + lineHeight + "%;";
fontSize = fSize==0 ? "font-size: 20pt;" : "font-size: " + fSize + "pt;";
fontFamily = fontFamily.indexOf(".") == -1 ? fontFamily : fontFamily.substring(0, fontFamily.lastIndexOf("."));
String cssBody = "" +
"<style type='text/css'>" +
"body " +
"{ " +
"font-family:" + fontFamily +", sans-serif; "+
fontSize +
"background-color:" + backgroundColor + "!important; " +
"color:" + textColor +"; " +
lineHeight +
"letter-spacing: " + letterSpacing + "pt;" +
"margin: " + margin + "%; " +
"outline-style: none;" +
"-webkit-touch-callout: none;" +
"-webkit-tap-highlight-color: rgba(0,0,0,0);" +
"}" +
"</style>" +
"";
builder = builder
.insert(insertPos, cssBody)
.insert(insertPos, setCSSLink)
.insert(insertPos, stopScripts)
.insert(insertPos, longClick)
.insert(insertPos, showToast)
.insert(insertPos, updatePosition)
.insert(insertPos, speakSentence)
.insert(insertPos, getWords)
.insert(insertPos, getSentences)
.insert(insertPos, scrollToElement)
.insert(insertPos, retrieveBodyContent)
.insert(insertPos, unhighlightPart)
.insert(insertPos, removeHighlight)
.insert(insertPos, highlightPart)
.insert(insertPos, highlightSentence)
.insert(insertPos, startScripts);
return builder.toString();
}
private class MyWebViewClient extends WebViewClient{
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
Log.e(TAG + " WebViewClient", "shouldOverrideUrlLoading");
return true;
}
@Override
public void onPageFinished(WebView view, String url) {
reader.loadUrl("javascript:getSentences();");
reader.loadUrl("javascript:getWords();");
}
};
private class ReaderWebInterface {
Context context;
public ReaderWebInterface(Context c){
context = c;
}
@JavascriptInterface
public void showHTML(String html){
new AlertDialog.Builder(context)
.setTitle("Show HTML")
.setMessage(html)
.setPositiveButton(android.R.string.ok, null)
.setCancelable(false)
.create()
.show();
}
@JavascriptInterface
public void showToast(String text){
Toast.makeText(context, text, Toast.LENGTH_SHORT).show();
}
@JavascriptInterface
public void logMessage(String tag, String text){
Log.d(tag, text);
}
@JavascriptInterface
public void saveHighlightInformation(String id, String startPos, String endPos){
Pair<String> span = new Pair<String>(startPos, endPos);
highlightParts.put(id, span);
}
@JavascriptInterface
public void removeHighlightInformation(String id){
highlightParts.remove(id);
}
@JavascriptInterface
public void getSentences(String sentences){
sentenceIds = new ArrayList<String>(Arrays.asList(sentences.split(",")));
defaultSentence = sentenceIds.get(0);
if(currSentPos>=sentenceIds.size()-1)
currSentPos=sentenceIds.size()-1;
final String current = sentenceIds.get(currSentPos);
runOnUiThread(new Runnable() {
@Override
public void run() {
if(isHighlighting && reader_mode==ReaderMode.Listen)
highlight(current);
}
});
}
@JavascriptInterface
public void getWords(String words){
wordIds = new ArrayList<String>(Arrays.asList(words.split(",")));
defaultWord = wordIds.get(0);
if(currWordPos >= wordIds.size()-1)
currWordPos = wordIds.size()-1;
final String current = wordIds.get(currWordPos);
runOnUiThread(new Runnable() {
@Override
public void run() {
if(isHighlighting && reader_mode==ReaderMode.Guidance)
highlight(current);
}
});
}
@JavascriptInterface
public void speakSentence(String text){
if(currSentPos==sentenceIds.size()-1)
ttsReader.speak(text, currSentPos, true);
else
ttsReader.speak(text, currSentPos, false);
}
@JavascriptInterface
public void touchWord(String id){
touchedId = id;
}
@JavascriptInterface
public void longClick(String jsWord){
ArrayList<UserBasedAnnotatedWord> words = annotationData.getWords();
String _word = "";
_word = jsWord.toLowerCase(Locale.getDefault());
_word = _word.replace("\n", "");
_word = _word.trim();
_word = Helper.removeSpans(new StringBuilder(_word)).toString();
ArrayList<Integer> values = new ArrayList<Integer>();
ArrayList<String> datas = new ArrayList<String>();
for(int i=0; i<words.size(); i++){
UserBasedAnnotatedWord word = words.get(i);
if(_word.equals(word.getWord())){
Intent in = new Intent(getBaseContext(), WordActivity.class);
in.putExtra("word", word.getWord());
in.putExtra("stem", word.getStem());
in.putExtra("phoneme", word.getPhonetics());
in.putExtra("wordInSyllables", word.getWordInToSyllables());
in.putExtra("trickyWords", trickyWords);
ArrayList<SeverityOnWordProblemInfo> problems = word.getUserSeveritiesOnWordProblems();
for(int j=0; j<problems.size(); j++){
SeverityOnWordProblemInfo problem = problems.get(j);
problem.getCategory();
problem.getIndex();
ArrayList<StringMatchesInfo> infos = problem.getMatched();
for(int k=0; k<infos.size(); k++){
StringMatchesInfo info = infos.get(k);
values.add(j);
values.add(info.getStart());
values.add(info.getEnd());
datas.add(null);
datas.add(Integer.toString(problem.getCategory()));
datas.add(Integer.toString(problem.getIndex()));
}
}
in.putIntegerArrayListExtra("problems", values);
in.putStringArrayListExtra("data", datas);
startActivityForResult(in, FLAG_WORD_POPUP);
break;
}
}
}
@JavascriptInterface
public void clickSentence(String html, final String id){
if(reader_mode != ReaderMode.Listen)
return;
runOnUiThread(new Runnable() {
@Override
public void run() {
removeSearches();
spEditor.putBoolean(getString(R.string.sp_tts_reader_is_stepping), false).apply();
String curr = sentenceIds.get(currSentPos);
removeHighlight(curr);
for(int i=0;i<sentenceIds.size(); i++){
if(sentenceIds.get(i).equals(id)){
currSentPos = i;
break;
}
}
if(!isHighlighting || !curr.equals(id)){
highlight(id);
spEditor.putInt(CURR_SENT, currSentPos).apply();
isHighlighting = true;
if(reader_status == ReaderStatus.Enabled)
speakFromSentence(id);
} else {
spEditor.putInt(CURR_SENT, currSentPos).apply();
isHighlighting = false;
}
spEditor.putBoolean("highlighting", isHighlighting).apply();
reader.loadUrl("javascript:updateCurrentPosition('"+sentenceIds.get(currSentPos)+"', 0);");
}
});
}
@JavascriptInterface
public void clickWord(String html, final String id){
if(reader_mode != ReaderMode.Guidance)
return;
runOnUiThread(new Runnable() {
@Override
public void run() {
removeSearches();
String curr = wordIds.get(currWordPos);
removeHighlight(curr);
for(int i=0;i<wordIds.size(); i++){
if(wordIds.get(i).equals(id)){
currWordPos = i;
break;
}
}
if(!isHighlighting || !curr.equals(id)){
highlight(id);
spEditor.putInt(CURR_WORD, currWordPos);
isHighlighting = true;
if(reader_status == ReaderStatus.Enabled){
highlightHandler.removeCallbacks(highlightRunnable);
long millis = (long) (highlightSpeed * 1000);
highlightHandler.postDelayed(highlightRunnable, millis);
}
} else {
spEditor.putInt(CURR_WORD, currWordPos);
isHighlighting = false;
}
spEditor.putBoolean(getString(R.string.sp_highlighting), isHighlighting);
spEditor.apply();
reader.loadUrl("javascript:updateCurrentPosition('"+wordIds.get(currWordPos)+"', 1);");
}
});
}
@JavascriptInterface
public void updateCurrentPosition(String other, int isParent){
switch (isParent) {
case 0:
for(int i=0; i<wordIds.size(); i++){
if(currWordPos != i && wordIds.get(i).equals(other)){
spEditor.putInt(CURR_WORD, i).apply();
break;
}
}
break;
case 1:
for(int i=0; i<sentenceIds.size(); i++){
if(currSentPos != i && sentenceIds.get(i).equals(other)){
spEditor.putInt(CURR_SENT, i).apply();
break;
}
}
break;
}
}
}
@Override
public void OnHighlight(int id) {
final String curr = sentenceIds.get(id);
this.runOnUiThread(new Runnable(){
@Override
public void run() {
highlight(curr);
}
});
}
@Override
public void OnRemoveHighlight(int id, boolean read) {
final String curr = sentenceIds.get(id);
if(read){
if(reader_status == ReaderStatus.Enabled){
int next = ++id;
if(next==++currSentPos){
spEditor.putInt(CURR_SENT, next).apply();
currSentPos = next;
runOnUiThread(new Runnable() {
@Override
public void run() {
reader.loadUrl("javascript:updateCurrentPosition('"+sentenceIds.get(currSentPos)+"', 0);");
}
});
speakFromSentence(sentenceIds.get(next));
}
}
}
this.runOnUiThread(new Runnable(){
@Override
public void run() {
removeHighlight(curr);
}
});
}
@Override
public void OnFinishedReading() {
this.runOnUiThread(new Runnable(){
@Override
public void run() {
if(reader_status != ReaderStatus.Disabled)
setPlayStatus(ReaderStatus.Disabled, true);
}
});
}
@Override
public void OnStartedReading() {
this.runOnUiThread(new Runnable(){
@Override
public void run() {
if(reader_status != ReaderStatus.Enabled)
setPlayStatus(ReaderStatus.Enabled, true);
}
});
}
@Override
public void onTextToSpeechInitialized() {
this.runOnUiThread(new Runnable() {
@Override
public void run() {
ibtnPlay.setEnabled(true);
ibtnNext.setEnabled(true);
ibtnPrev.setEnabled(true);
}
});
}
@Override
public void onTextToSpeechInstall() {
onBackPressed();
}
private class HighlightRunnable implements Runnable{
@Override
public void run() {
String prev = "", current = "";
if(reader_mode == ReaderMode.Listen){
if(currSentPos==sentenceIds.size()-1){
ibtnPlay.callOnClick();
return;
}
prev = sentenceIds.get(currSentPos++);
current = sentenceIds.get(currSentPos);
spEditor.putInt(CURR_SENT, currSentPos).apply();
runOnUiThread(new Runnable() {
public void run() {
reader.loadUrl("javascript:updateCurrentPosition('"+sentenceIds.get(currSentPos)+"', 0);");
}
});
} else if(reader_mode == ReaderMode.Guidance){
if(currWordPos==wordIds.size()-1){
ibtnPlay.callOnClick();
return;
}
prev = wordIds.get(currWordPos++);
current = wordIds.get(currWordPos);
spEditor.putInt(CURR_WORD, currWordPos).apply();
runOnUiThread(new Runnable() {
public void run() {
reader.loadUrl("javascript:updateCurrentPosition('"+wordIds.get(currWordPos)+"', 1);");
}
});
}
removeHighlight(prev);
highlight(current);
long millis = (long) (highlightSpeed * 1000);
highlightHandler.postDelayed(this, millis);
}
}
}
|
package com.jme.input.action;
import com.jme.input.Mouse;
import com.jme.input.MouseInput;
import com.jme.math.Vector3f;
import com.jme.scene.Spatial;
/**
* <code>NodeMouseLook</code> defines a mouse action that detects mouse
* movement and converts it into node rotations and node tilts.
*
* @author Mark Powell
* @version $Id$
*/
public class NodeMouseLook extends MouseInputAction {
//the actions that handle looking up, down, left and right.
private KeyNodeLookDownAction lookDown;
private KeyNodeLookUpAction lookUp;
private KeyNodeRotateLeftAction rotateLeft;
private KeyNodeRotateRightAction rotateRight;
//the axis to lock
private Vector3f lockAxis;
//the node to control
private Spatial node;
//the event to distribute to the look actions.
private static InputActionEvent event;
private boolean buttonPressRequired = false;
private int mouseButtonForRequired = 0;
/**
* Constructor creates a new <code>NodeMouseLook</code> object. It takes
* the mouse, node and speed of the looking.
*
* @param mouse
* the mouse to calculate view changes.
* @param node
* the node to move.
* @param speed
* the speed at which to alter the camera.
*/
public NodeMouseLook(Mouse mouse, Spatial node, float speed) {
this.mouse = mouse;
this.speed = speed;
this.node = node;
lookDown = new KeyNodeLookDownAction(this.node, speed);
lookUp = new KeyNodeLookUpAction(this.node, speed);
rotateLeft = new KeyNodeRotateLeftAction(this.node, speed);
rotateRight = new KeyNodeRotateRightAction(this.node, speed);
event = new InputActionEvent();
}
/**
*
* <code>setLockAxis</code> sets the axis that should be locked down. This
* prevents "rolling" about a particular axis. Typically, this is set to the
* mouse's up vector.
*
* @param lockAxis
* the axis that should be locked down to prevent rolling.
*/
public void setLockAxis(Vector3f lockAxis) {
this.lockAxis = lockAxis;
rotateLeft.setLockAxis(lockAxis);
rotateRight.setLockAxis(lockAxis);
}
/**
* Returns the axis that is currently locked.
*
* @return The currently locked axis
* @see #setLockAxis(com.jme.math.Vector3f)
*/
public Vector3f getLockAxis() {
return lockAxis;
}
/**
*
* <code>setSpeed</code> sets the speed of the mouse look.
*
* @param speed
* the speed of the mouse look.
*/
public void setSpeed(float speed) {
super.setSpeed( speed );
lookDown.setSpeed(speed);
lookUp.setSpeed(speed);
rotateRight.setSpeed(speed);
rotateLeft.setSpeed(speed);
}
/**
* Sets the option for requiring the user to click the mouse
* button specified by <code>mouseButtonForRequired</code> in
* order to rotate the node.
* @param buttonPressRequired the buttonPressRequired to set
*/
public void setButtonPressRequired(boolean buttonPressRequired) {
this.buttonPressRequired = buttonPressRequired;
}
/**
* Sets which mouse button needs to be pressed in order to rotate
* the node (that is, assuming <code>buttonPressRequired</code> is
* set to true).
* @param mouseButtonForRequired the mouseButtonForRequired to set
*/
public void setMouseButtonForRequired(int mouseButtonForRequired) {
this.mouseButtonForRequired = mouseButtonForRequired;
}
/**
* <code>performAction</code> checks for any movement of the mouse, and
* calls the appropriate method to alter the node's orientation when
* applicable.
*
* @see com.jme.input.action.MouseInputAction#performAction(InputActionEvent)
*/
public void performAction(InputActionEvent evt) {
float time = 0.01f * speed;
if (buttonPressRequired && MouseInput.get().isButtonDown(mouseButtonForRequired) || !buttonPressRequired)
{
if (mouse.getLocalTranslation().x > 0) {
event.setTime(time * mouse.getLocalTranslation().x);
rotateRight.performAction(event);
} else if (mouse.getLocalTranslation().x < 0) {
event.setTime(time * mouse.getLocalTranslation().x * -1);
rotateLeft.performAction(event);
}
if (mouse.getLocalTranslation().y > 0) {
event.setTime(time * mouse.getLocalTranslation().y);
lookUp.performAction(event);
} else if (mouse.getLocalTranslation().y < 0) {
event.setTime(time * mouse.getLocalTranslation().y * -1);
lookDown.performAction(event);
}
}
}
}
|
package com.opencms.file;
import java.util.*;
import javax.servlet.http.*;
import com.opencms.core.*;
public class CmsRequestContext implements I_CmsConstants {
/**
* The rb to get access to the OpenCms.
*/
private I_CmsResourceBroker m_rb;
/**
* The current CmsRequest.
*/
private I_CmsRequest m_req;
/**
* The current CmsResponse.
*/
private I_CmsResponse m_resp;
/**
* The current user.
*/
private CmsUser m_user;
/**
* The current group of the user.
*/
private CmsGroup m_currentGroup;
/**
* The current project.
*/
private CmsProject m_currentProject;
/**
* The default constructor.
*
*/
public CmsRequestContext() {
super();
}
/**
* Returns the current folder object.
*
* @return the current folder object.
*
* @exception CmsException if operation was not successful.
*/
public CmsFolder currentFolder() throws CmsException {
// truncate the filename from the pathinformation
String folderName = getUri().substring(0, getUri().lastIndexOf("/") + 1);
return (m_rb.readFolder(currentUser(), currentProject(), folderName, ""));
}
/**
* Returns the current group of the current user.
*
* @return the current group of the current user.
*/
public CmsGroup currentGroup() {
return(m_currentGroup);
}
/**
* Returns the current project of the current user.
*
* @return the current project of the current user.
*/
public CmsProject currentProject() {
return m_currentProject;
}
/**
* Returns the current user object.
*
* @return the current user object.
*/
public CmsUser currentUser() {
return(m_user);
}
/**
* Gets the name of the requested file without any path-information.
*
* @return the requested filename.
*/
public String getFileUri() {
String uri = m_req.getRequestedResource();
uri=uri.substring(uri.lastIndexOf("/")+1);
return uri;
}
/**
* Gets the current request, if availaible.
*
* @return the current request, if availaible.
*/
public I_CmsRequest getRequest() {
return( m_req );
}
/**
* Gets the current response, if availaible.
*
* @return the current response, if availaible.
*/
public I_CmsResponse getResponse() {
return( m_resp );
}
/**
* Gets the Session for this request.
* <br>
* This method should be used instead of the originalRequest.getSession() method.
* @param value indicates, if a session should be created when a session for the particular client does not already exist.
* @return the CmsSession, or <code>null</code> if no session already exists and value was set to <code>false</code>
*
*/
public I_CmsSession getSession(boolean value) {
HttpSession session = ((HttpServletRequest)m_req.getOriginalRequest()).getSession(value);
if(session != null) {
return (I_CmsSession) new CmsSession(session);
} else {
return null;
}
}
public String getUri() {
if( m_req != null ) {
return( m_req.getRequestedResource() );
} else {
return( C_ROOT );
}
}
/**
* Initializes this RequestContext.
*
* @param req the CmsRequest.
* @param resp the CmsResponse.
* @param user the current user for this request.
* @param currentGroup the current group for this request.
* @param currentProjectId the id of the current project for this request.
*
* @exception CmsException if operation was not successful.
*/
void init(I_CmsResourceBroker rb, I_CmsRequest req, I_CmsResponse resp,
String user, String currentGroup, int currentProjectId)
throws CmsException {
m_rb = rb;
m_req = req;
m_resp = resp;
try {
m_user = m_rb.readUser(null, null, user);
} catch (CmsException ex){
}
// if no user found try to read webUser
if (m_user == null) {
m_user = m_rb.readWebUser(null, null, user);
}
// check, if the user is disabled
if( m_user.getDisabled() == true ) {
m_user = null;
}
// set current project and group for this request
setCurrentProject(currentProjectId);
m_currentGroup = m_rb.readGroup(m_user, m_currentProject, currentGroup);
}
/**
* Determines if the users is in the admin-group.
*
* @return <code>true</code> if the users current group is the admin-group; <code>false</code> otherwise.
*
* @exception CmsException if operation was not successful.
*/
public boolean isAdmin()
throws CmsException {
return( m_rb.isAdmin(m_user, m_currentProject) );
}
/**
* Determines if the users current group is the projectmanager-group.
* <BR>
* All projectmanagers can create new projects, or close their own projects.
*
* @return <code>true</code> if the users current group is the projectleader-group; <code>false</code> otherwise.
*
* @exception CmsException if operation was not successful.
*/
public boolean isProjectManager()
throws CmsException {
return( m_rb.isProjectManager(m_user, m_currentProject) );
}
/**
* Sets the current group of the current user.
*
* @param groupname the name of the group to be set as current group.
*
* @exception CmsException if operation was not successful.
*/
public void setCurrentGroup(String groupname)
throws CmsException {
// is the user in that group?
if(m_rb.userInGroup(m_user, m_currentProject, m_user.getName(), groupname)) {
// Yes - set it to the current Group.
m_currentGroup = m_rb.readGroup(m_user, m_currentProject, groupname);
} else {
// No - throw exception.
throw new CmsException("[" + this.getClass().getName() + "] " + groupname,
CmsException.C_NO_ACCESS);
}
}
/**
* Sets the current project for the user.
*
* @param projectId the id of the project to be set as current project.
* @exception CmsException if operation was not successful.
*/
public CmsProject setCurrentProject(int projectId)
throws CmsException {
CmsProject newProject = m_rb.readProject(m_user,
m_currentProject,
projectId);
if( newProject != null ) {
m_currentProject = newProject;
}
return( m_currentProject );
}
}
|
package com.worizon.jsonrpc;
import java.io.Serializable;
import java.util.List;
import java.util.Map;
import com.google.gson.Gson;
/**
* This class is the representation of a JSON-RPC request. The id field of the JSON-RPC
* message is generated with a timestamp value as returned by
*
* @author enric
* @since 1.0.0
*/
@SuppressWarnings("serial")
public class JsonRpcRequest extends JsonRpcBase implements Serializable {
/**
* Remote procedure method name.
*/
private final String method;
/**
* Remote procedure parameters, this object might be both a List or a
* Map.
*/
private Object params;
JsonRpcRequest( String method, Object params){
super("2.0",IDGenerator.getInstance().generate());
this.method = method;
this.params = params;
}
/**
* Copy constructor.
*/
public JsonRpcRequest( JsonRpcRequest req ){
super("2.0", req.getId());
this.method = req.getMethod();
this.params = req.getParams();
}
public JsonRpcRequest( String method ){
this(method, (Object)null);
}
public JsonRpcRequest( String method, Map<String, Object> params ){
this(method, (Object)params);
}
public JsonRpcRequest( String method, List<Object> params){
this(method, (Object)params);
}
/**
* Returns remote method name at which the call will be targeted.
* @return The remote name.
*/
public String getMethod() {
return method;
}
/**
* Returns arguments supplied to the remote procedure, might be Map or List.
*/
public Object getParams() {
return params;
}
@Override
public boolean equals( Object obj ){
if(obj == null)
return false;
else if(obj == this)
return true;
else if( !(obj instanceof JsonRpcRequest) )
return false;
JsonRpcRequest req = (JsonRpcRequest)obj;
return id.equals(req.getId());
/*
boolean retval = req.method.equals(this.method);
if(!retval)
return false;
retval = req.id.longValue() == id.longValue();
if(!retval)
return false;
if( params instanceof Map){
for( Object key: ((Map)params).keySet() ){
retval = ((Map) params).get(key).equals( ((Map)req.params).get(key) );
if(!retval)
return false;
}
}
return retval;
*/
}
/**
* This Helper method turns a String representing a JSON-RPC request into a JsonRpcRequest object.
*
* Ex:
* "{\"method\":\"test\",\"params\":{\"a\":10,\"n\":20},\"jsonrpc\":\"2.0\",id:887237382}"
*
* @return The object which holds the request information.
*/
public static JsonRpcRequest parse( String request ){
JsonRpcRequest req = getDeserializeHelper().fromJson(request, JsonRpcRequest.class);
if(req.getId() == null || req.getMethod() == null || req.getVersion() == null)
throw new IllegalArgumentException("Missing fields in this request");
return req;
}
/**
* Converts this object to a readable String.
* @return The string representation of this request object.
* @see java.lang.Object#toString()
*/
public String toString(){
Gson gson = getSerializeHelper();
return gson.toJson(this);
}
}
|
package de.lmu.ifi.dbs.elki.utilities;
import java.io.PrintStream;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.BitSet;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Set;
import java.util.SortedSet;
import java.util.StringTokenizer;
import java.util.TreeSet;
import java.util.regex.Pattern;
import de.lmu.ifi.dbs.elki.data.ClassLabel;
import de.lmu.ifi.dbs.elki.data.DatabaseObject;
import de.lmu.ifi.dbs.elki.data.RealVector;
import de.lmu.ifi.dbs.elki.database.AssociationID;
import de.lmu.ifi.dbs.elki.database.Database;
import de.lmu.ifi.dbs.elki.distance.Distance;
import de.lmu.ifi.dbs.elki.logging.AbstractLoggable;
import de.lmu.ifi.dbs.elki.logging.LoggingConfiguration;
import de.lmu.ifi.dbs.elki.math.linearalgebra.Matrix;
import de.lmu.ifi.dbs.elki.math.linearalgebra.Vector;
import de.lmu.ifi.dbs.elki.utilities.optionhandling.Flag;
import de.lmu.ifi.dbs.elki.utilities.optionhandling.NumberParameter;
import de.lmu.ifi.dbs.elki.utilities.optionhandling.Option;
import de.lmu.ifi.dbs.elki.utilities.optionhandling.OptionHandler;
import de.lmu.ifi.dbs.elki.utilities.optionhandling.OptionID;
import de.lmu.ifi.dbs.elki.utilities.optionhandling.Parameter;
/**
* @version 0.1
*/
public final class Util extends AbstractLoggable {
static {
if (LoggingConfiguration.isChangeable()) {
LoggingConfiguration.configureRoot(LoggingConfiguration.CLI);
}
}
private Util() {
super(LoggingConfiguration.DEBUG);
}
/**
* Returns the maximum of the given Distances or the first, if none is
* greater than the other one.
*
* @param d1 first Distance
* @param d2 second Distance
* @return Distance the maximum of the given Distances or the first, if
* neither is greater than the other one
*/
public static <D extends Distance<D>> D max(D d1, D d2) {
if (d1.compareTo(d2) > 0) {
return d1;
}
else if (d2.compareTo(d1) > 0) {
return d2;
}
else {
return d1;
}
}
/**
* Returns the minimum of the given Distances or the first, if none is less
* than the other one.
*
* @param d1 first Distance
* @param d2 second Distance
* @return Distance the minimum of the given Distances or the first, if
* neither is less than the other one
*/
public static <D extends Distance<D>> D min(D d1, D d2) {
if (d1.compareTo(d2) < 0) {
return d1;
}
else if (d2.compareTo(d1) < 0) {
return d2;
}
else {
return d1;
}
}
/**
* Formats the double d with 2 fraction digits.
*
* @param d the double to be formatted
* @return a String representing the double d
*/
public static String format(final double d) {
return format(d, 2);
}
/**
* Formats the double d with the specified fraction digits.
*
* @param d the double array to be formatted
* @param digits the number of fraction digits
* @return a String representing the double d
*/
public static String format(final double d, int digits) {
final NumberFormat nf = NumberFormat.getInstance(Locale.US);
nf.setMaximumFractionDigits(digits);
nf.setMinimumFractionDigits(digits);
nf.setGroupingUsed(false);
return nf.format(d);
}
/**
* Formats the double d with the specified number format.
*
* @param d the double array to be formatted
* @param nf the number format to be used for formatting
* @return a String representing the double d
*/
public static String format(final double d, NumberFormat nf) {
return nf.format(d);
}
/**
* Formats the double array d with ',' as separator and 2 fraction digits.
*
* @param d the double array to be formatted
* @return a String representing the double array d
*/
public static String format(double[] d) {
return format(d, ", ", 2);
}
/**
* Formats the double array d with ',' as separator and 2 fraction digits.
*
* @param d the double array to be formatted
* @return a String representing the double array d
*/
public static String format(double[][] d) {
StringBuffer buffer = new StringBuffer();
for (double[] array : d) {
buffer.append(format(array, ", ", 2)).append("\n");
}
return buffer.toString();
}
/**
* Formats the array of double arrays d with 'the specified separators and fraction digits.
*
* @param d the double array to be formatted
* @param sep1 the first separator of the outer array
* @param sep2 the second separator of the inner array
* @param digits the number of fraction digits
* @return a String representing the double array d
*/
public static String format(double[][] d, String sep1, String sep2, int digits) {
StringBuffer buffer = new StringBuffer();
for (int i = 0; i < d.length; i++) {
if (i < d.length - 1) {
buffer.append(format(d[i], sep2, digits)).append(sep1);
}
else {
buffer.append(format(d[i], sep2, digits));
}
}
return buffer.toString();
}
/**
* Formats the double array d with the specified separator.
*
* @param d the double array to be formatted
* @param sep the separator between the single values of the double array,
* e.g. ','
* @return a String representing the double array d
*/
public static String format(double[] d, String sep) {
StringBuffer buffer = new StringBuffer();
for (int i = 0; i < d.length; i++) {
if (i < d.length - 1) {
buffer.append(d[i]).append(sep);
}
else {
buffer.append(d[i]);
}
}
return buffer.toString();
}
/**
* Formats the double array d with the specified separator and the specified
* fraction digits.
*
* @param d the double array to be formatted
* @param sep the separator between the single values of the double array,
* e.g. ','
* @param digits the number of fraction digits
* @return a String representing the double array d
*/
public static String format(double[] d, String sep, int digits) {
StringBuffer buffer = new StringBuffer();
for (int i = 0; i < d.length; i++) {
if (i < d.length - 1) {
buffer.append(format(d[i], digits)).append(sep);
}
else {
buffer.append(format(d[i], digits));
}
}
return buffer.toString();
}
/**
* Formats the double array d with the specified number format.
*
* @param d the double array to be formatted
* @param nf the number format to be used for formatting
* @return a String representing the double array d
*/
public static String format(double[] d, NumberFormat nf) {
return format(d, " ", nf);
}
/**
* Formats the double array d with the specified number format.
*
* @param d the double array to be formatted
* @param sep the separator between the single values of the double array,
* e.g. ','
* @param nf the number format to be used for formatting
* @return a String representing the double array d
*/
public static String format(double[] d, String sep, NumberFormat nf) {
StringBuffer buffer = new StringBuffer();
for (int i = 0; i < d.length; i++) {
if (i < d.length - 1) {
buffer.append(format(d[i], nf)).append(sep);
}
else {
buffer.append(format(d[i], nf));
}
}
return buffer.toString();
}
/**
* Formats the float array f with the specified separator and the specified
* fraction digits.
*
* @param f the float array to be formatted
* @param sep the separator between the single values of the float array,
* e.g. ','
* @param digits the number of fraction digits
* @return a String representing the float array f
*/
public static String format(float[] f, String sep, int digits) {
StringBuffer buffer = new StringBuffer();
for (int i = 0; i < f.length; i++) {
if (i < f.length - 1) {
buffer.append(format(f[i], digits)).append(sep);
}
else {
buffer.append(format(f[i], digits));
}
}
return buffer.toString();
}
/**
* Formats the float array f with ',' as separator and 2 fraction digits.
*
* @param f the float array to be formatted
* @return a String representing the float array f
*/
public static String format(float[] f) {
return format(f, ", ", 2);
}
/**
* Formats the int array a for printing purposes.
*
* @param a the int array to be formatted
* @param sep the separator between the single values of the float array,
* e.g. ','
* @return a String representing the int array a
*/
public static String format(int[] a, String sep) {
StringBuffer buffer = new StringBuffer();
for (int i = 0; i < a.length; i++) {
if (i < a.length - 1) {
buffer.append(a[i]).append(sep);
}
else {
buffer.append(a[i]);
}
}
return buffer.toString();
}
/**
* Formats the int array a for printing purposes.
*
* @param a the int array to be formatted
* @return a String representing the int array a
*/
public static String format(int[] a) {
return format(a, ", ");
}
/**
* Formats the Integer array a for printing purposes.
*
* @param a the Integer array to be formatted
* @param sep the separator between the single values of the float array,
* e.g. ','
* @return a String representing the Integer array a
*/
public static String format(Integer[] a, String sep) {
StringBuffer buffer = new StringBuffer();
for (int i = 0; i < a.length; i++) {
if (i < a.length - 1) {
buffer.append(a[i]).append(sep);
}
else {
buffer.append(a[i]);
}
}
return buffer.toString();
}
/**
* Formats the Integer array a for printing purposes.
*
* @param a the Integer array to be formatted
* @return a String representing the Integer array a
*/
public static String format(Integer[] a) {
return format(a, ", ");
}
/**
* Formats the long array a for printing purposes.
*
* @param a the long array to be formatted
* @return a String representing the long array a
*/
public static String format(long[] a) {
StringBuffer buffer = new StringBuffer();
for (int i = 0; i < a.length; i++) {
if (i < a.length - 1) {
buffer.append(a[i]).append(", ");
}
else {
buffer.append(a[i]);
}
}
return buffer.toString();
}
/**
* Formats the byte array a for printing purposes.
*
* @param a the byte array to be formatted
* @return a String representing the byte array a
*/
public static String format(byte[] a) {
StringBuffer buffer = new StringBuffer();
for (int i = 0; i < a.length; i++) {
if (i < a.length - 1) {
buffer.append(a[i]).append(", ");
}
else {
buffer.append(a[i]);
}
}
return buffer.toString();
}
/**
* Formats the boolean b.
*
* @param b the boolean to be formatted
* @return a String representing of the boolean b
*/
public static String format(final boolean b) {
if (b) {
return "1";
}
return "0";
}
/**
* Formats the boolean array b with ',' as separator.
*
* @param b the boolean array to be formatted
* @param sep the separator between the single values of the double array,
* e.g. ','
* @return a String representing the boolean array b
*/
public static String format(boolean[] b, final String sep) {
StringBuffer buffer = new StringBuffer();
for (int i = 0; i < b.length; i++) {
if (i < b.length - 1) {
buffer.append(format(b[i])).append(sep);
}
else {
buffer.append(format(b[i]));
}
}
return buffer.toString();
}
/**
* Returns the prefix of the specidfied fileName (i.e. the name of the file
* without extension).
*
* @param fileName the name of the file
* @return the prefix of the specidfied fileName
*/
public static String getFilePrefix(final String fileName) {
final int index = fileName.lastIndexOf(Character.getNumericValue('.'));
if (index < 0) {
return fileName;
}
return fileName.substring(0, index);
}
/**
* Returns a new String array containing the same objects as are contained
* in the given array.
*
* @param array an array to copy
* @return the copied array
*/
public static String[] copy(String[] array) {
String[] copy = new String[array.length];
System.arraycopy(array, 0, copy, 0, array.length);
return copy;
}
/**
* Returns a new double array containng the same objects as are contained in
* the given array.
*
* @param array an array to copy
* @return the copied array
*/
public static double[] copy(double[] array) {
double[] copy = new double[array.length];
System.arraycopy(array, 0, copy, 0, array.length);
return copy;
}
/**
* Returns the unboxed double array of the given Object Double array.
*
* @param array the array to be unboxed
* @return the unboxed double array
*/
public static double[] unbox(Double[] array) {
double[] unboxed = new double[array.length];
// noinspection ManualArrayCopy
for (int i = 0; i < unboxed.length; i++) {
unboxed[i] = array[i];
}
return unboxed;
}
/**
* Returns the unboxed double array of the given Object Number array.
*
* @param array the array to be unboxed
* @return the unboxed double array
*/
public static double[] unbox(Number[] array) {
double[] unboxed = new double[array.length];
for (int i = 0; i < unboxed.length; i++) {
unboxed[i] = array[i].doubleValue();
}
return unboxed;
}
/**
* Returns the unboxed float array of the given Object Number array.
*
* @param array the array to be unboxed
* @return the unboxed float array
*/
public static float[] unboxToFloat(Number[] array) {
float[] unboxed = new float[array.length];
for (int i = 0; i < unboxed.length; i++) {
unboxed[i] = array[i].floatValue();
}
return unboxed;
}
public static <V extends RealVector<V, ?>> V centroid(Database<V> database, Collection<Integer> ids) {
if (ids.isEmpty()) {
throw new IllegalArgumentException("Cannot compute a centroid, because of empty list of ids!");
}
int dim = database.dimensionality();
double[] centroid = new double[dim];
for (int id : ids) {
V o = database.get(id);
for (int j = 1; j <= dim; j++) {
centroid[j - 1] += o.getValue(j).doubleValue();
}
}
double size = ids.size();
for (int i = 0; i < dim; i++) {
centroid[i] /= size;
}
V o = database.get(ids.iterator().next());
return o.newInstance(centroid);
}
public static <V extends RealVector<V, ?>> V centroid(Database<V> database, Collection<Integer> ids, BitSet bitSet) {
if (ids.isEmpty()) {
throw new IllegalArgumentException("Cannot compute a centroid, because of empty list of ids!");
}
int dim = database.dimensionality();
double[] centroid = new double[dim];
for (Integer id : ids) {
V o = database.get(id);
for (int j = 1; j <= dim; j++) {
if (bitSet.get(j - 1)) {
centroid[j - 1] += o.getValue(j).doubleValue();
}
}
}
double size = ids.size();
for (int i = 0; i < dim; i++) {
centroid[i] /= size;
}
V o = database.get(ids.iterator().next());
return o.newInstance(centroid);
}
public static <V extends RealVector<V, ?>> V centroid(Database<V> database, Iterator<Integer> iter, BitSet bitSet) {
if (! iter.hasNext()) {
throw new IllegalArgumentException("Cannot compute a centroid, because of empty list of ids!");
}
int dim = database.dimensionality();
double[] centroid = new double[dim];
int size = 0;
// we need to "cache" one o for the newInstance method, since we can't clone the iterator.
V o = null;
while (iter.hasNext()) {
Integer id = iter.next();
size++;
o = database.get(id);
for (int j = 1; j <= dim; j++) {
if (bitSet.get(j - 1)) {
centroid[j - 1] += o.getValue(j).doubleValue();
}
}
}
for (int i = 0; i < dim; i++) {
centroid[i] /= size;
}
return o.newInstance(centroid);
}
public static <O extends RealVector<O, ?>> O centroid(Database<O> database) {
if (database.size() == 0) {
throw new IllegalArgumentException("Database is empty!");
}
int dim = database.dimensionality();
double[] centroid = new double[dim];
Iterator<Integer> it = database.iterator();
while (it.hasNext()) {
RealVector<O, ?> o = database.get(it.next());
for (int j = 1; j <= dim; j++) {
centroid[j - 1] += o.getValue(j).doubleValue();
}
}
double size = database.size();
for (int i = 0; i < dim; i++) {
centroid[i] /= size;
}
O o = database.get(database.iterator().next());
return o.newInstance(centroid);
}
/**
* Returns the centroid as a Vector object of the specified data matrix.
*
* @param data the data matrix, where the data vectors are column vectors
* @return the centroid of the specified data matrix
*/
public static Vector centroid(Matrix data) {
int d = data.getRowDimensionality();
double n = data.getColumnDimensionality();
double[] centroid = new double[d];
for (int i = 0; i < n; i++) {
Vector x = data.getColumnVector(i);
for (int j = 0; j < d; j++) {
centroid[j] += x.get(j);
}
}
for (int j = 0; j < d; j++) {
centroid[j] /= n;
}
return new Vector(centroid);
}
/**
* Determines the covariance matrix of the objects stored in the given
* database.
*
* @param database the database storing the objects
* @param ids the ids of the objects
* @return the covarianvce matrix of the specified objects
*/
public static <V extends RealVector<V, ?>> Matrix covarianceMatrix(Database<V> database, Collection<Integer> ids) {
// centroid
V centroid = centroid(database, ids);
// covariance matrixArray
int columns = centroid.getDimensionality();
int rows = ids.size();
double[][] matrixArray = new double[rows][columns];
int i = 0;
for (Iterator<Integer> it = ids.iterator(); it.hasNext(); i++) {
RealVector<?, ?> obj = database.get(it.next());
for (int d = 0; d < columns; d++) {
matrixArray[i][d] = obj.getValue(d + 1).doubleValue() - centroid.getValue(d + 1).doubleValue();
}
}
Matrix centeredMatrix = new Matrix(matrixArray);
return centeredMatrix.transpose().times(centeredMatrix);
}
/**
* Determines the covariance matrix of the objects stored in the given
* database.
*
* @param database the database storing the objects
* @return the covarianvce matrix of the specified objects
*/
public static <O extends RealVector<O, ?>> Matrix covarianceMatrix(Database<O> database) {
// centroid
O centroid = centroid(database);
return covarianceMatrix(database, centroid);
}
/**
* <p>Determines the covariance matrix of the objects stored in the given
* database w.r.t. the given centroid.</p>
*
* @param database the database storing the objects
* @param centroid the dentroid of the database
* @return the covarianvce matrix of the specified objects
*/
public static <O extends RealVector<O, ?>> Matrix covarianceMatrix(Database<O> database, O centroid) {
// centered matrix
int columns = centroid.getDimensionality();
int rows = database.size();
double[][] matrixArray = new double[rows][columns];
Iterator<Integer> it = database.iterator();
int i = 0;
while (it.hasNext()) {
RealVector<?, ?> obj = database.get(it.next());
for (int d = 0; d < columns; d++) {
matrixArray[i][d] = obj.getValue(d + 1).doubleValue() - centroid.getValue(d + 1).doubleValue();
}
i++;
}
Matrix centeredMatrix = new Matrix(matrixArray);
// covariance matrix
Matrix cov = centeredMatrix.transpose().times(centeredMatrix);
cov = cov.times(1.0 / database.size());
return cov;
}
/**
* Determines the d x d covariance matrix of the given n x d data matrix.
*
* @param data the database storing the objects
* @return the covarianvce matrix of the given data matrix.
*/
public static Matrix covarianceMatrix(Matrix data) {
// centroid
Vector centroid = centroid(data);
// centered matrix
double[][] matrixArray = new double[data.getRowDimensionality()][data.getColumnDimensionality()];
for (int i = 0; i < data.getRowDimensionality(); i++) {
for (int j = 0; j < data.getColumnDimensionality(); j++) {
matrixArray[i][j] = data.get(i, j) - centroid.get(i);
}
}
Matrix centeredMatrix = new Matrix(matrixArray);
// covariance matrix
Matrix cov = centeredMatrix.times(centeredMatrix.transpose());
cov = cov.times(1.0 / data.getColumnDimensionality());
return cov;
}
/**
* Determines the variances in each dimension of all
* objects stored in the given database.
*
* @param database the database storing the objects
* @return the variances in each dimension of all objects stored in the given database
*/
public static <O extends RealVector<O, ?>> double[] variances(Database<O> database) {
O centroid = centroid(database);
double[] variances = new double[centroid.getDimensionality()];
for (int d = 1; d <= centroid.getDimensionality(); d++) {
double mu = centroid.getValue(d).doubleValue();
for (Iterator<Integer> it = database.iterator(); it.hasNext();) {
RealVector<?, ?> o = database.get(it.next());
double diff = o.getValue(d).doubleValue() - mu;
variances[d - 1] += diff * diff;
}
variances[d - 1] /= database.size();
}
return variances;
}
/**
* Determines the variances in each dimension of the specified
* objects stored in the given database.
* Returns <code>variances(database, centroid(database, ids), ids)</code>
*
* @param database the database storing the objects
* @param ids the ids of the objects
* @return the variances in each dimension of the specified objects
*/
public static <V extends RealVector<V, ?>> double[] variances(Database<V> database, Collection<Integer> ids) {
return variances(database, centroid(database, ids), ids);
}
/**
* Determines the variances in each dimension of the specified
* objects stored in the given database.
*
* @param database the database storing the objects
* @param ids the ids of the objects
* @param centroid the centroid or reference vector of the ids
* @return the variances in each dimension of the specified objects
*/
public static <V extends RealVector<V, ?>> double[] variances(Database<V> database, V centroid, Collection<Integer> ids) {
double[] variances = new double[centroid.getDimensionality()];
for (int d = 1; d <= centroid.getDimensionality(); d++) {
double mu = centroid.getValue(d).doubleValue();
for (Integer id : ids) {
V o = database.get(id);
double diff = o.getValue(d).doubleValue() - mu;
variances[d - 1] += diff * diff;
}
variances[d - 1] /= ids.size();
}
return variances;
}
/**
* Determines the variances in each dimension of the specified
* objects stored in the given database.
*
* @param database the database storing the objects
* @param ids the array of ids of the objects to be considered in each diemsnion
* @param centroid the centroid or reference vector of the ids
* @return the variances in each dimension of the specified objects
*/
public static double[] variances(Database<RealVector<?, ?>> database, RealVector<?, ?> centroid,
Collection<Integer>[] ids) {
double[] variances = new double[centroid.getDimensionality()];
for (int d = 1; d <= centroid.getDimensionality(); d++) {
double mu = centroid.getValue(d).doubleValue();
Collection<Integer> ids_d = ids[d - 1];
for (Integer neighborID : ids_d) {
RealVector<?, ?> neighbor = database.get(neighborID);
double diff = neighbor.getValue(d).doubleValue() - mu;
variances[d - 1] += diff * diff;
}
variances[d - 1] /= ids_d.size();
}
return variances;
}
/**
* Determines the minimum and maximum values in each dimension of all
* objects stored in the given database.
*
* @param database the database storing the objects
* @return an array consisting of an array of the minimum and an array of the maximum
* values in each dimension
* of all objects stored in the given database
*/
public static double[][] min_max(Database<RealVector<?, ?>> database) {
int dim = database.dimensionality();
double[] min = new double[dim];
double[] max = new double[dim];
Arrays.fill(min, Double.MAX_VALUE);
Arrays.fill(max, -Double.MAX_VALUE);
for (Iterator<Integer> it = database.iterator(); it.hasNext();) {
RealVector<?, ?> o = database.get(it.next());
for (int d = 1; d <= dim; d++) {
double v = o.getValue(d).doubleValue();
min[d] = Math.min(min[d], v);
max[d] = Math.min(max[d], v);
}
}
return new double[][]{min, max};
}
/**
* Returns a new <code>Double</code> array initialized to the values
* represented by the specified <code>String</code> and separated by
* comma, as performed by the <code>valueOf</code> method of class
* <code>Double</code>.
*
* @param s the string to be parsed.
* @return a new <code>Double</code> array represented by s
*/
public static double[] parseDoubles(String s) {
List<Double> result = new ArrayList<Double>();
StringTokenizer tokenizer = new StringTokenizer(s, ",");
while (tokenizer.hasMoreTokens()) {
String d = tokenizer.nextToken();
result.add(Double.parseDouble(d));
}
return unbox(result.toArray(new Double[result.size()]));
}
/**
* Returns a new <code>Float</code> array initialized to the values
* represented by the specified <code>String</code> and separated by
* comma, as performed by the <code>valueOf</code> method of class
* <code>Float</code>.
*
* @param s the string to be parsed.
* @return a new <code>Float</code> array represented by s
*/
public static float[] parseFloats(String s) {
List<Float> result = new ArrayList<Float>();
StringTokenizer tokenizer = new StringTokenizer(s, ",");
while (tokenizer.hasMoreTokens()) {
String d = tokenizer.nextToken();
result.add(Float.parseFloat(d));
}
return unboxToFloat(result.toArray(new Float[result.size()]));
}
/**
* Converts the specified list of double objects to a list of float objects.
*
* @param values the list of double objects to be converted
* @return the converted list of float objects
*/
public static List<Float> convertToFloat(List<Double> values) {
List<Float> result = new ArrayList<Float>(values.size());
for (Double value : values) {
result.add(new Float(value));
}
return result;
}
/**
* Converts the specified array of doubles to an array of floats.
*
* @param values the array of doubles to be converted
* @return the converted array of floats
*/
public static float[] convertToFloat(double[] values) {
float[] result = new float[values.length];
for (int i = 0; i < values.length; i++) {
//noinspection NumericCastThatLosesPrecision
result[i] = (float) values[i];
}
return result;
}
/**
* Converts the specified array of doubles to an array of floats.
*
* @param values the array of doubles to be converted
* @return the converted array of floats
*/
public static double[] convertToDoubles(float[] values) {
double[] result = new double[values.length];
for (int i = 0; i < values.length; i++) {
result[i] = values[i];
}
return result;
}
/**
* Converts the specified list of Double objects to an array of doubles.
*
* @param values the list of Double objects to be converted
* @return the converted array of doubles
*/
public static double[] convertToDoubles(List<Double> values) {
double[] result = new double[values.size()];
for (int i = 0; i < result.length; i++) {
result[i] = values.get(i);
}
return result;
}
/**
* Provides a script-text for a gnuplot script to use for transposed view of
* a specific file of given size of data set.
*
* @param filename the filename of the transposed file to be plotted
* @param datasetSize the size of the transposed data set
* @param dimensionality the dimensionality of the transposed data set
* @return a script-text for a gnuplot script to use for transposed view of
* a specific file of given size of data set
*/
public static String transposedGnuplotScript(String filename, int datasetSize, int dimensionality) {
StringBuffer script = new StringBuffer();
// script.append("set terminal pbm color;\n");
script.append("set nokey\n");
script.append("set data style linespoints\n");
script.append("set xlabel \"attribute\"\n");
script.append("show xlabel\n");
script.append("plot [0:");
script.append(datasetSize - 1).append("] []");
for (int p = 1; p <= dimensionality; p++) {
script.append("\"").append(filename).append("\" using ").append(p);
if (p < dimensionality) {
script.append(", ");
}
}
script.append("\npause -1");
return script.toString();
}
/**
* Returns a new instance of the given type for the specified className.
* <p/> If the Class for className is not found, the instantiation is tried
* using the package of the given type as package of the given className.
*
* @param type desired Class type of the Object to retrieve
* @param className name of the class to instantiate
* @return a new instance of the given type for the specified className
* @throws UnableToComplyException if the instantiation cannot be performed successfully
*/
public static <T> T instantiate(Class<T> type, String className) throws UnableToComplyException {
T instance;
try {
try {
instance = type.cast(Class.forName(className).newInstance());
}
catch (ClassNotFoundException e) {
// try package of type
instance = type.cast(Class.forName(type.getPackage().getName() + "." + className).newInstance());
}
}
catch (InstantiationException e) {
throw new UnableToComplyException("InstantiationException: " + e.getMessage(), e);
}
catch (IllegalAccessException e) {
throw new UnableToComplyException("IllegalAccessException: " + e.getMessage(), e);
}
catch (ClassNotFoundException e) {
throw new UnableToComplyException("ClassNotFoundException: " + e.getMessage(), e);
}
catch (ClassCastException e) {
throw new UnableToComplyException("ClassCastException: " + e.getMessage(), e);
}
return instance;
}
/**
* Returns a new instance of the given type for the specified className.
* <p/> If the Class for className is not found, the instantiation is tried
* using the package of the given type as package of the given className.
*
* This is a weaker type checked version of "instantiate" for use with generics.
*
* @param type desired Class type of the Object to retrieve
* @param className name of the class to instantiate
* @return a new instance of the given type for the specified className
* @throws UnableToComplyException if the instantiation cannot be performed successfully
*/
@SuppressWarnings("unchecked")
public static <T> T instantiateGenerics(Class<?> type, String className) throws UnableToComplyException {
T instance;
// TODO: can we do a verification that type conforms to T somehow?
// (probably not because generics are implemented via erasure.
try {
try {
instance = ((Class<T>) type).cast(Class.forName(className).newInstance());
}
catch (ClassNotFoundException e) {
// try package of type
instance = ((Class<T>) type).cast(Class.forName(type.getPackage().getName() + "." + className).newInstance());
}
}
catch (InstantiationException e) {
throw new UnableToComplyException("InstantiationException: " + e.getMessage(), e);
}
catch (IllegalAccessException e) {
throw new UnableToComplyException("IllegalAccessException: " + e.getMessage(), e);
}
catch (ClassNotFoundException e) {
throw new UnableToComplyException("ClassNotFoundException: " + e.getMessage(), e);
}
catch (ClassCastException e) {
throw new UnableToComplyException("ClassCastException: " + e.getMessage(), e);
}
return instance;
}
/**
* Provides a status report line with leading carriage return. Suitable for
* density based algorithms, since the number of found clusters is counted.
*
* @param progress the progress status
* @param clusters current number of clusters
* @return a status report line with leading carriage return
*/
public static String status(Progress progress, int clusters) {
StringBuffer status = new StringBuffer();
status.append("\r");
status.append(progress.toString());
status.append(" Number of clusters: ");
status.append(clusters);
status.append(". ");
return status.toString();
}
/**
* Provides a status report line with leading carriage return.
*
* @param progress the progress status
* @return a status report line with leading carriage return
*/
public static String status(Progress progress) {
StringBuffer status = new StringBuffer();
status.append("\r");
status.append(progress.toString());
status.append(" ");
return status.toString();
}
/**
* Prints the given list to the specified PrintStream. The list entries are
* separated by the specified separator. The last entry is not followed by a
* separator. Thus, if a newline is used as separator, it might make sense
* to print a newline to the PrintStream after calling this method.
*
* @param list the list to be printed
* @param separator the separator to separate entries of the list
* @param out the target PrintStream
*/
public static <O> void print(List<O> list, String separator, PrintStream out) {
for (Iterator<O> iter = list.iterator(); iter.hasNext();) {
out.print(iter.next());
if (iter.hasNext()) {
out.print(separator);
}
}
}
/**
* Returns the index of the maximum of the given values. If no value is
* bigger than the first, the index of the first entry is returned.
*
* @param values the values to find the index of the maximum
* @return the index of the maximum in the given values
* @throws ArrayIndexOutOfBoundsException if <code>values.length==0</code>
*/
public static int getIndexOfMaximum(double[] values) throws ArrayIndexOutOfBoundsException {
int index = 0;
double max = values[index];
for (int i = 0; i < values.length; i++) {
if (values[i] > max) {
max = values[i];
index = i;
}
}
return index;
}
/**
* Retrieves all class labels within the database.
*
* @param database the database to be scanned for class labels
* @return a set comprising all class labels that are currently set in the
* database
*/
public static SortedSet<ClassLabel> getClassLabels(Database<?> database) {
if (!database.isSetForAllObjects(AssociationID.CLASS)) {
throw new IllegalStateException("AssociationID " + AssociationID.CLASS.getName() + " is not set.");
}
SortedSet<ClassLabel> labels = new TreeSet<ClassLabel>();
for (Iterator<Integer> iter = database.iterator(); iter.hasNext();) {
//noinspection unchecked
labels.add(database.getAssociation(AssociationID.CLASS, iter.next()));
}
return labels;
}
public static String[] parameterDifference(String[] complete, String[] part) throws IllegalArgumentException {
if (complete.length < part.length) {
throw new IllegalArgumentException("First array must be at least as long as second array.\n" +
"First array: " + Arrays.asList(complete) + "\n" +
"Second array: " + Arrays.asList(part));
}
if (complete.length == 0) {
return new String[0];
}
List<String> completeArray = new ArrayList<String>();
for (int i = 0; i < complete.length; i++) {
String param = complete[i];
if (param.startsWith(OptionHandler.OPTION_PREFIX)) {
if (i < complete.length - 1) {
String key = complete[i + 1];
if (!key.startsWith(OptionHandler.OPTION_PREFIX)) {
completeArray.add(param + " " + key);
i++;
}
else {
completeArray.add(param);
}
}
}
}
List<String> partArray = new ArrayList<String>();
for (int i = 0; i < part.length; i++) {
String param = part[i];
if (param.startsWith(OptionHandler.OPTION_PREFIX)) {
if (i < part.length - 1) {
String key = part[i + 1];
if (!key.startsWith(OptionHandler.OPTION_PREFIX)) {
partArray.add(param + " " + key);
i++;
}
else {
partArray.add(param);
}
}
}
}
Pattern pattern = Pattern.compile(" ");
List<String> result = new ArrayList<String>();
int first = 0;
int second = 0;
while (first < completeArray.size() && second < partArray.size()) {
if (completeArray.get(first).equals(partArray.get(second))) {
first++;
second++;
}
else {
String[] params = pattern.split(completeArray.get(first));
for (String p : params) {
result.add(p);
}
first++;
}
}
if (second < partArray.size()) {
throw new IllegalArgumentException("second array contains entries that are not " +
"contained in the first array.\n" +
"First array: " + Arrays.asList(complete) + "\n" +
"Second array: " + Arrays.asList(part));
}
while (first < completeArray.size()) {
String[] params = pattern.split(completeArray.get(first));
for (String p : params) {
result.add(p);
}
first++;
}
String[] resultArray = new String[result.size()];
return result.toArray(resultArray);
}
// /**
// * Provides a string describing the restriction to implement or extend
// * the specified class.
// * <p/>
// * The message has a structure like follows:
// * <pre>
// * (implementing typeName -- available classes:
// * -->class1.name
// * -->class2.name
// * )
// * </pre>
// *
// * @param type the type restricting the possible classes
// * @return a description listing all available classes
// * restricted by the specified class
// */
// public static <T> String restrictionString(Class<T> type) {
// StringBuilder msg = new StringBuilder();
// msg.append('(');
// if (type.isInterface()) {
// msg.append("implementing ");
// else {
// msg.append("extending ");
// msg.append(type.getName());
// Class<? extends T>[] classes = implementingClasses(type);
// if (logger.debug()) {
// logger.debugFinest("Classes for " + type.getName() + ": " + Arrays.asList(classes).toString());
// if (classes.length > 0) {
// msg.append(" -- available classes:\n");
// for (Class<? extends T> c : classes) {
// msg.append("-->");
// msg.append(c.getName());
// msg.append('\n');
// msg.append(')');
// return msg.toString();
// /**
// * Provides all classes currently known by the Launcher
// * that are instance of the specified type
// * and that are instantiable by the default constructor.
// *
// * @param type the common superclass or interface
// * of the required classes
// * @return all classes currently known by the Launcher
// * that are instance of the specified type
// * and that are instantiable by the default constructor
// */
// public static <T> Class<? extends T>[] implementingClasses(Class<T> type) {
// List<Class<? extends T>> classes = new ArrayList<Class<? extends T>>();
// Package[] packages = Package.getPackages();
// if (logger.debug()) {
// logger.debugFinest("found packages: " + Arrays.asList(packages).toString());
// for (Package p : packages) {
// if (logger.debug()) {
// logger.debugFinest(p.getName());
// Class<?>[] classesInPackage = classesInPackage(p);
// int added = 0;
// for (Class<?> c : classesInPackage) {
// if (logger.debug()) {
// logger.debugFinest(type.getName() + " is assignable from " + c.getName());
// // noinspection unchecked
// classes.add((Class<? extends T>) c);
// added++;
// if (logger.debug()) {
// if (added != classesInPackage.length) {
// for (Class<?> c : classesInPackage) {
// //noinspection SuspiciousMethodCalls
// // noinspection unchecked
// Class<? extends T>[] result = new Class[classes.size()];
// return classes.toArray(result);
// /**
// * Provides all classes in the specified package
// * as currently present in the Launcher.
// * Only those classes are included
// * that can be instantiated per default constructor.
// *
// * @param p the package to retrieve classes for
// * @return all classes in the specified package
// */
// public static Class<?>[] classesInPackage(Package p) {
// List<Class<?>> classes = new ArrayList<Class<?>>();
// final String CLASS_SUFFIX = ".class";
// String pname = p.getName();
// URL url = Launcher.class.getResource(pname);
// if (url == null) {
// pname = pname.replace('.', '/');
// if (!pname.startsWith("/")) {
// pname = "/" + pname;
// url = Launcher.class.getResource(pname);
// if (url != null) {
// File dir = new File(url.getFile());
// if (dir.exists()) {
// String[] files = dir.list();
// for (String f : files) {
// if (f.endsWith(CLASS_SUFFIX)) {
// // remove the .class extension
// String classname = f.substring(0, f.length() - 6);
// try {
// if (logger.debug()) {
// logger.debugFinest("classname: " + classname);
// Class<?> c = Class.forName(p.getName() + "." + classname);
// if (logger.debug()) {
// logger.debugFinest("class: " + c.getName());
// Object o = c.newInstance();
// if (logger.debug()) {
// logger.debugFinest("object class: " + o.getClass().getName());
// catch (Exception e) {
// if (logger.debug()) {
// logger.debugFinest(e.getMessage() + "\n");
// else {
// if (logger.debug()) {
// logger.debugFinest("No resource available for name: \"" + pname + "\"\n");
// Class<?>[] result = new Class[classes.size()];
// return classes.toArray(result);
/**
* Returns a string representation of the specified bit set.
*
* @param bitSet the bitSet
* @param dim the overall dimensionality of the bit set
* @param sep the separator
* @return a string representation of the specified bit set.
*/
public static String format(BitSet bitSet, int dim, String sep) {
StringBuffer msg = new StringBuffer();
for (int d = 0; d < dim; d++) {
if (d > 0) {
msg.append(sep);
}
if (bitSet.get(d)) {
msg.append("1");
}
else {
msg.append("0");
}
}
return msg.toString();
}
/**
* Returns a string representation of the specified bit set.
*
* @param dim the overall dimensionality of the bit set
* @param bitSet the bitSet
* @return a string representation of the specified bit set.
*/
public static String format(int dim, BitSet bitSet) {
// TODO: removed whitespace - hierarchy reading to be adapted!
return format(bitSet, dim, ",");
}
/**
* Returns a new <code>BitSet</code> initialized to the values
* represented by the specified <code>String</code> only containing 0 and 1 values.
*
* @param s the string to be parsed.
* @return a new <code>BitSet</code> represented by s
*/
public static BitSet parseBitSet(String s) {
try {
return parseBitSet(s.toCharArray());
}
catch (IllegalArgumentException e) {
throw new IllegalArgumentException("The specified String does not represent a bit set " +
"containing only 0 and 1 values: " + s);
}
}
/**
* Returns a new <code>BitSet</code> initialized to the values
* represented by the specified <code>char</code> array only containing '0' and '1' values.
*
* @param s the char array to be parsed.
* @return a new <code>BitSet</code> represented by s
*/
public static BitSet parseBitSet(char[] s) {
BitSet result = new BitSet();
for (int i = 0; i < s.length; i++) {
if (s[i] == '1') {
result.set(i);
}
else if (s[i] != '0') {
throw new IllegalArgumentException("The specified String does not represent a bit set " +
"containing only 0 and 1 values: " + String.valueOf(s));
}
}
return result;
}
/**
* Returns a string that represents the selected bits of the
* specified <code>BitSet</code>, while the first bit starts with 1.
* The selected bits are separated
* by the specified separator <code>sep</code>.
*
* If <code>sep</code> is the empty String, the result is suitable as a parameter for an
* IntListParameter.
*
* @param b the bit set to be parsed
* @param sep the separator
* @return a string representing the selected bits of the
* specified <code>BitSet</code>
*/
public static String parseSelectedBits(BitSet b, String sep) {
StringBuffer result = new StringBuffer();
for (int i = b.nextSetBit(0); i >= 0; i = b.nextSetBit(i+1)) {
if (i > 0) {
result.append(sep).append(i + 1);
}
else{
result.append((i + 1));
}
}
return result.toString();
}
public static int indexOfNthSetBit(BitSet bitset, int nthSetBit) throws IllegalArgumentException {
if(nthSetBit < 1 || nthSetBit > bitset.cardinality()){
throw new IllegalArgumentException("Parameter nthSetBit out of range: nthSetBit="+nthSetBit+", bitset.cardinality="+bitset.cardinality());
}
int i = 0;
int index = -1;
for (int d = bitset.nextSetBit(0); d >= 0 && i < nthSetBit; d = bitset.nextSetBit(d + 1)) {
i++;
index = d;
}
return index;
}
/**
* Provides the intersection of the two specified sets in the given result set.
*
* @param s1 the first set
* @param s2 the second set
* @param result the result set
*/
public static <O> void intersection(Set<O> s1, Set<O> s2, Set<O> result) {
for (O object : s1) {
if (s2.contains(object)) {
result.add(object);
}
}
}
/**
* Converts the specified positive integer value into a bit representation,
* where bit 0 denotes 2<sup>0</sup>, bit 1 denotes 2<sup>1</sup> etc.
*
* @param n the positive integer value to be converted
* @return the specified integer value into a bit representation
*/
public static BitSet int2Bit(int n) {
if (n < 0) {
throw new IllegalArgumentException("Parameter n hast to be greater than or equal to zero!");
}
BitSet result = new BitSet();
int i = 0;
while (n > 0) {
boolean rest = (n % 2 == 1);
if (rest) {
result.set(i);
}
n = n / 2;
i++;
}
return result;
}
/**
* Returns a collection of the ids of the objects stored in the specified database.
*
* @param db the database storing the objects
* @return a collection of the ids of the objects stored in the specified database
*/
public static <O extends DatabaseObject> Collection<Integer> getDatabaseIDs(Database<O> db) {
Collection<Integer> ids = new ArrayList<Integer>(db.size());
for (Iterator<Integer> it = db.iterator(); it.hasNext();) {
ids.add(it.next());
}
return ids;
}
/**
* Adds the specified flag to the beginning of the given parameter list.
*
* @param parameters the list of parameters
* @param flag the flag to be added
*/
public static void addFlag(List<String> parameters, Flag flag) {
parameters.add(0, OptionHandler.OPTION_PREFIX + flag.getName());
}
/**
* Adds the specified optionID of a flag to the beginning of the given parameter list.
*
* @param parameters the list of parameters
* @param optionID the optionID to be added
*/
public static void addFlag(List<String> parameters, OptionID optionID) {
parameters.add(0, OptionHandler.OPTION_PREFIX + optionID.getName());
}
/**
* Adds the specified optionID and its value to the beginning of the given parameter list.
*
* @param parameters the list of parameters
* @param optionID the optionID of the parameter to be added
* @param value the value of the parameter to be added
*/
public static void addParameter(List<String> parameters, OptionID optionID, String value) {
parameters.add(0, OptionHandler.OPTION_PREFIX + optionID.getName());
parameters.add(1, value);
}
/**
* Adds the specified parameter and the specified value to the beginning of the given parameter list.
*
* @param parameters the list of parameters
* @param parameter the parameter to be added
* @param value the value of the parameter to be added
*/
public static void addParameter(List<String> parameters, Parameter<?, ?> parameter, String value) {
parameters.add(0, OptionHandler.OPTION_PREFIX + parameter.getName());
parameters.add(1, value);
}
/**
* Adds the specified optionID and its value to the beginning of the given parameter array.
*
* @param parameters the array of parameters
* @param optionID the optionID to be added
* @param value the value of the optionID to be added
* @return a new parameter array containing the values of <code>parameters</code> and
* the specified <code>optionID</code> and its <code>value</code>.
*/
public static String[] addParameter(String[] parameters, OptionID optionID, String value) {
String[] newParameters = new String[parameters.length + 2];
System.arraycopy(parameters, 0, newParameters, 2, parameters.length);
newParameters[0] = OptionHandler.OPTION_PREFIX + optionID.getName();
newParameters[1] = value;
return newParameters;
}
/**
* Returns a string representation of the specified list of
* options containing the names of the options.
*
* @param options the list of options
* @return the names of the options
*/
public static <O extends Option<?>> String optionsNamesToString(List<O> options) {
StringBuffer buffer = new StringBuffer();
buffer.append("[");
for (int i = 0; i < options.size(); i++) {
buffer.append(options.get(i).getName());
if (i != options.size() - 1) {
buffer.append(",");
}
}
buffer.append("]");
return buffer.toString();
}
/**
* Returns a string representation of the list of number
* parameters containing the names and the values of the parameters.
*
* @param parameters the list of number parameters
* @return the names and the values of the parameters
*/
public static <N extends NumberParameter<?>> String parameterNamesAndValuesToString(List<N> parameters) {
StringBuffer buffer = new StringBuffer();
buffer.append("[");
for (int i = 0; i < parameters.size(); i++) {
buffer.append(parameters.get(i).getName());
buffer.append(":");
buffer.append(parameters.get(i).getNumberValue().doubleValue());
if (i != parameters.size() - 1) {
buffer.append(", ");
}
}
buffer.append("]");
return buffer.toString();
}
/**
* Joins the specified arrays.
*
* @param array1 the first array
* @param array2 the second array
* @return a new array containing the entries of <code>array1</code> and
* the <code>array2</code>.
*/
public static String[] joinArray(String[] array1, String[] array2) {
String[] newArray = new String[array1.length + array2.length];
System.arraycopy(array1, 0, newArray, 0, array1.length);
System.arraycopy(array2, 0, newArray, array1.length, array2.length);
return newArray;
}
/**
* Adds the entries of the specified array
* to the end of the given list.
*
* @param list the list
* @param array the array containing the objects to be added to the list
*/
public static <O> void addToList(List<O> list, O[] array) {
for (O object : array) {
list.add(object);
}
}
/**
* Create an array of lists.
* This is a common cast we have to do due to Java generics limitations.
*
* @param <T> Type the list elements have
* @param len array size
* @return new array of lists
*/
@SuppressWarnings("unchecked")
public static <T> List<T>[] newArrayOfList(int len) {
List<?>[] result = new List<?>[len];
return (List<T>[]) result;
}
/**
* Create an array of ArrayLists.
* This is a common cast we have to do due to Java generics limitations.
*
* @param <T> Type the list elements have
* @param len array size
* @return new array of arraylists
*/
@SuppressWarnings("unchecked")
public static <T> ArrayList<T>[] newArrayOfArrayList(int len) {
ArrayList<?>[] result = new ArrayList<?>[len];
return (ArrayList<T>[]) result;
}
/**
* Create an array of sets.
* This is a common cast we have to do due to Java generics limitations.
*
* @param <T> Type the list elements have
* @param len array size
* @return new array of sets
*/
@SuppressWarnings("unchecked")
public static <T> Set<T>[] newArrayOfSet(int len) {
Set<?>[] result = new Set<?>[len];
return (Set<T>[]) result;
}
}
|
package de.sb.messenger.rest;
import static javax.ws.rs.core.MediaType.APPLICATION_JSON;
import static javax.ws.rs.core.MediaType.APPLICATION_XML;
import static javax.ws.rs.core.Response.Status.CONFLICT;
import static javax.ws.rs.core.Response.Status.NOT_FOUND;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.Persistence;
import javax.persistence.TypedQuery;
import javax.ws.rs.ClientErrorException;
import javax.ws.rs.GET;
import javax.ws.rs.HeaderParam;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import de.sb.messenger.persistence.Document;
import de.sb.messenger.persistence.Group;
import de.sb.messenger.persistence.Person;
import de.sb.toolbox.net.RestCredentials;
@Path("people")
public class PersonService {
@GET
@Produces({ APPLICATION_JSON, APPLICATION_XML })
public List<Person> queryPersons(@HeaderParam("Authorization") final String authentication,
@QueryParam("givenName") final String givenName, @QueryParam("familyName") final String familyName,
@QueryParam("mail") final String mail, @QueryParam("street") final String street,
@QueryParam("postcode") final String postcode, @QueryParam("city") final String city, @QueryParam("group") final Group group) {
final EntityManager messengerManager = Persistence.createEntityManagerFactory("messenger").createEntityManager();
TypedQuery<Person> query = messengerManager.createQuery("SELECT p FROM Person p WHERE "
+ "(:givenName is null OR p.name.given = :givenName) AND "
+ "(:familyName is null or p.name.family = :familyName) AND "
+ "(:mail IS null OR p.email = :mail) AND "
+ "(:street IS null OR p.address.street = :street) AND "
+ "(:postcode IS null OR p.address.postcode = :postcode) AND"
+ "(:city IS null OR p.address.city = :city) AND"
+ "(:group IS null OR p.group = :group)"
+ " ORDER BY p.name.family, p.name.given, p.email",
Person.class);
List<Person> results = query
.setParameter("mail", mail)
.setParameter("givenName", givenName)
.setParameter("familyName", familyName)
.setParameter("street", street)
.setParameter("postcode", postcode)
.setParameter("city", city)
.setParameter("group", group)
.getResultList();
if (results.isEmpty()) {
throw new ClientErrorException(NOT_FOUND);
}
return results;
}
@GET
@Path("{identity}")
@Produces({ APPLICATION_JSON, APPLICATION_XML })
public Person queryPerson(@HeaderParam("Authorization") final String authentication, @PathParam("identity") final long identity) {
final EntityManager messengerManager = Persistence.createEntityManagerFactory("messenger").createEntityManager();
Person person = messengerManager.find(Person.class, identity);
if (person == null) {
throw new ClientErrorException(NOT_FOUND);
}
return person;
}
@PUT
@Produces({ APPLICATION_JSON, APPLICATION_XML })
public long createPerson(final Person person) {
final EntityManager messengerManager = Persistence.createEntityManagerFactory("messenger").createEntityManager();
Person newPerson;
if (person.getIdentity() == 0) {
Document avatar = messengerManager.find(Document.class, 1L);
newPerson = new Person(avatar);
} else {
newPerson = messengerManager.find(Person.class, person.getIdentity());
}
newPerson.setMail(person.getMail());
newPerson.setGroup(person.getGroup());
newPerson.getAddress().setCity(person.getAddress().getCity());
newPerson.getAddress().setPostcode(person.getAddress().getPostcode());
newPerson.getAddress().setStreet(person.getAddress().getStreet());
newPerson.getName().setFamily(person.getName().getFamily());
newPerson.getName().setGiven(person.getName().getGiven());
messengerManager.getTransaction().begin();
messengerManager.merge(newPerson);
messengerManager.getTransaction().commit();
return newPerson.getIdentity();
}
@GET
@Path("{identity}/peopleObserving")
@Produces({ APPLICATION_JSON, APPLICATION_XML })
public List<Person> getPeopleObserving(@HeaderParam("Authorization") final String authentication, @PathParam("identity") final long identity){
Authenticator.authenticate(RestCredentials.newBasicInstance(authentication));
final EntityManager messengerManager = Persistence.createEntityManagerFactory("messenger").createEntityManager();
Person person = messengerManager.find(Person.class, identity);
if (person == null) {
throw new ClientErrorException(NOT_FOUND);
}
List<Person> peopleObserving = new ArrayList<>(person.getPeopleObserving());
// TODO sort this list
return peopleObserving;
}
@GET
@Path("{identity}/peopleObserved")
@Produces({ APPLICATION_JSON, APPLICATION_XML })
public List<Person> getPeopleObserved(@HeaderParam("Authorization") final String authentication, @PathParam("identity") final long identity){
Authenticator.authenticate(RestCredentials.newBasicInstance(authentication));
final EntityManager messengerManager = Persistence.createEntityManagerFactory("messenger").createEntityManager();
Person person = messengerManager.find(Person.class, identity);
if (person == null) {
throw new ClientErrorException(NOT_FOUND);
}
List<Person> peopleObserved = new ArrayList<>(person.getPeopleObserved());
// TODO sort this list
return peopleObserved;
}
}
|
package edu.agh.tunev.model;
import java.awt.geom.Point2D;
public abstract class AbstractPerson {
protected Point2D.Double position;
protected double orientation = 0;
/** Rodzaj ruchu. */
protected Movement movement = Movement.STANDING;
public static enum Movement {
STANDING, SQUATTING, CRAWLING
}
protected double width = 0.5;
protected double girth = 0.3;
protected double height = 1.7;
public AbstractPerson(Point2D.Double position) {
this.position = position;
}
public Point2D.Double getPosition() {
return position;
}
public void setPosition(Point2D.Double position) {
this.position = position;
}
public double getOrientation() {
return orientation;
}
public void setOrientation(double orientation) {
this.orientation = orientation;
}
public Movement getMovement() {
return movement;
}
public void setMovement(Movement movement) {
this.movement = movement;
}
public double getWidth() {
return width;
}
public double getGirth() {
return girth;
}
public double getHeight() {
return height;
}
}
|
package edu.ucsb.cs56.drawings.sswong;
import java.awt.geom.GeneralPath; // combinations of lines and curves
import java.awt.Shape; // general class for shapes
import java.awt.geom.Line2D;
import java.awt.geom.Rectangle2D;
import java.awt.geom.Ellipse2D;
import edu.ucsb.cs56.drawings.utilities.ShapeTransforms;
import edu.ucsb.cs56.drawings.utilities.GeneralPathWrapper;
/**
A vector drawing of a house that implements
the Shape interface, and so can be drawn, as well as
rotated, scaled, etc.
@author Simon Wong
@version for CS56, W16, UCSB
*/
public class Tree extends GeneralPathWrapper implements Shape
{
/**
Constructor
@param x x coord of top left corner of tree
@param y y coord of top left corner of tree
@param trunk_radius radius of tree leaves
@param trunk_width width of trunk
@param trunk_height height of trunk
*/
public Tree(double x, double y,
double leaves_radius,
double trunk_width,
double trunk_height)
{
// Rather than having to scale at the end, we can just
// draw things the right way to begin with, using the
// x, y, width and height. If you haven't already
// hard coded a particular drawing, this may be an easier
// way.
// Make the leaves
Ellipse2D.Double leaves =
new Ellipse2D.Double(x, y,leaves_radius*2, leaves_radius*2);
// Make the trunk
Rectangle2D.Double trunk =
new Rectangle2D.Double(x+2*leaves_radius,
y-trunk_height,
trunk_width, trunk_height);
// put the whole tree together
GeneralPath wholeTree = this.get();
wholeTree.append(leaves, false);
wholeTree.append(trunk, false);
}
}
|
package edu.wpi.first.wpilibj.templates;
import edu.wpi.first.wpilibj.DriverStationLCD;
public class UI
{
private DriverStationLCD outputBox;
private int printCounter;
public UI()
{
outputBox = DriverStationLCD.getInstance();
printCounter = 0;
}
public void printOutput()
{
printCounter++;
//clear, update, and reset printCounter
if (printCounter == 100)
{
//clear output box
outputBox.println(DriverStationLCD.Line.kUser1, 1, " ");
outputBox.println(DriverStationLCD.Line.kUser2, 1, " ");
outputBox.println(DriverStationLCD.Line.kUser3, 1, " ");
outputBox.println(DriverStationLCD.Line.kUser4, 1, " ");
outputBox.println(DriverStationLCD.Line.kUser5, 1, " ");
outputBox.println(DriverStationLCD.Line.kUser6, 1, " ");
//update the LCD
outputBox.updateLCD();
//reset printCounter
printCounter = 0;
}
outputBox.println(DriverStationLCD.Line.kUser1, 1, "UI test ");
outputBox.println(DriverStationLCD.Line.kUser2, 1, " ");
outputBox.println(DriverStationLCD.Line.kUser3, 1, " ");
outputBox.println(DriverStationLCD.Line.kUser4, 1, " ");
outputBox.println(DriverStationLCD.Line.kUser5, 1, " ");
outputBox.println(DriverStationLCD.Line.kUser6, 1, " ");
outputBox.updateLCD();
}
}
|
package org.voltdb;
import java.io.File;
import java.net.URI;
import java.nio.ByteBuffer;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Map;
import java.util.TreeMap;
import java.util.concurrent.Callable;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import org.apache.zookeeper_voltpatches.CreateMode;
import org.apache.zookeeper_voltpatches.KeeperException;
import org.apache.zookeeper_voltpatches.KeeperException.NodeExistsException;
import org.apache.zookeeper_voltpatches.WatchedEvent;
import org.apache.zookeeper_voltpatches.Watcher;
import org.apache.zookeeper_voltpatches.Watcher.Event.EventType;
import org.apache.zookeeper_voltpatches.Watcher.Event.KeeperState;
import org.apache.zookeeper_voltpatches.ZooDefs.Ids;
import org.apache.zookeeper_voltpatches.ZooKeeper;
import org.apache.zookeeper_voltpatches.data.Stat;
import org.json_voltpatches.JSONArray;
import org.json_voltpatches.JSONException;
import org.json_voltpatches.JSONObject;
import org.voltcore.logging.VoltLogger;
import org.voltcore.network.Connection;
import org.voltcore.utils.CoreUtils;
import org.voltdb.catalog.SnapshotSchedule;
import org.voltdb.client.ClientResponse;
import org.voltdb.client.ProcedureCallback;
import org.voltdb.dtxn.SiteTracker;
import org.voltdb.sysprocs.SnapshotSave;
import org.voltdb.sysprocs.saverestore.SnapshotUtil;
import com.google.common.base.Throwables;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.ListeningScheduledExecutorService;
import com.google.common.util.concurrent.MoreExecutors;
/**
* A scheduler of automated snapshots and manager of archived and retained snapshots.
* The new functionality for handling truncation snapshots operates separately from
* the old automated snapshots. They just share the same event processing threads. Future work
* should merge them.
*
*/
public class SnapshotDaemon implements SnapshotCompletionInterest {
private class TruncationSnapshotAttempt {
private String path;
private String nonce;
private boolean finished;
}
static int m_periodicWorkInterval = 2000;
public static volatile int m_userSnapshotRetryInterval = 30;
/*
* Something that initiates procedures for the snapshot daemon.
*/
public interface DaemonInitiator {
public void initiateSnapshotDaemonWork(final String procedureName, long clientData, Object params[]);
};
private static final VoltLogger SNAP_LOG = new VoltLogger("SNAPSHOT");
private static final VoltLogger loggingLog = new VoltLogger("LOGGING");
private final ScheduledThreadPoolExecutor m_esBase =
new ScheduledThreadPoolExecutor(1,
CoreUtils.getThreadFactory(null, "SnapshotDaemon", CoreUtils.SMALL_STACK_SIZE, false, null),
new java.util.concurrent.ThreadPoolExecutor.DiscardPolicy());
private final ListeningScheduledExecutorService m_es = MoreExecutors.listeningDecorator(m_esBase);
private ZooKeeper m_zk;
private DaemonInitiator m_initiator;
private long m_nextCallbackHandle;
private String m_truncationSnapshotPath;
/*
* Before doing truncation snapshot operations, wait a few seconds
* to give a few nodes a chance to get into the same state WRT to truncation
* so that a truncation snapshot will can service multiple truncation requests
* that arrive at the same time.
*/
int m_truncationGatheringPeriod = 10;
private final TreeMap<Long, TruncationSnapshotAttempt> m_truncationSnapshotAttempts =
new TreeMap<Long, TruncationSnapshotAttempt>();
private Future<?> m_truncationSnapshotScanTask;
private TimeUnit m_frequencyUnit;
private long m_frequencyInMillis;
private int m_frequency;
private int m_retain;
private String m_path;
private String m_prefix;
private String m_prefixAndSeparator;
private Future<?> m_snapshotTask;
private final HashMap<Long, ProcedureCallback> m_procedureCallbacks = new HashMap<Long, ProcedureCallback>();
private final SimpleDateFormat m_dateFormat = new SimpleDateFormat("'_'yyyy.MM.dd.HH.mm.ss");
// true if this SnapshotDaemon is the one responsible for generating
// snapshots
private boolean m_isActive = false;
private long m_nextSnapshotTime;
/**
* Don't invoke sysprocs too close together.
* Keep track of the last call and only do it after
* enough time has passed.
*/
private long m_lastSysprocInvocation = System.currentTimeMillis();
static long m_minTimeBetweenSysprocs = 3000;
/**
* List of snapshots on disk sorted by creation time
*/
final LinkedList<Snapshot> m_snapshots = new LinkedList<Snapshot>();
/**
* States the daemon can be in
*
*/
enum State {
/*
* Initial state
*/
STARTUP,
/*
* Invoked @SnapshotScan, waiting for results.
* Done once on startup to find number of snapshots on disk
* at path with prefix
*/
SCANNING,
/*
* Waiting in between snapshots
*/
WAITING,
/*
* Deleting snapshots that are no longer going to be retained.
*/
DELETING,
/*
* Initiated a snapshot. Will call snapshot scan occasionally to find out
* when it completes.
*/
SNAPSHOTTING,
/*
* Failure state. This state is entered when a sysproc
* fails and the snapshot Daemon can't recover. An error is logged
* and the Daemon stops working
*/
FAILURE;
}
private State m_state = State.STARTUP;
SnapshotDaemon() {
m_esBase.setContinueExistingPeriodicTasksAfterShutdownPolicy(false);
m_esBase.setExecuteExistingDelayedTasksAfterShutdownPolicy(false);
m_frequencyUnit = null;
m_retain = 0;
m_frequency = 0;
m_frequencyInMillis = 0;
m_prefix = null;
m_path = null;
m_prefixAndSeparator = null;
// Register the snapshot status to the StatsAgent
SnapshotStatus snapshotStatus = new SnapshotStatus();
VoltDB.instance().getStatsAgent().registerStatsSource(SysProcSelector.SNAPSHOTSTATUS,
0,
snapshotStatus);
VoltDB.instance().getSnapshotCompletionMonitor().addInterest(this);
}
public void init(DaemonInitiator initiator, ZooKeeper zk, Runnable threadLocalInit, GlobalServiceElector gse) {
m_initiator = initiator;
m_zk = zk;
try {
zk.create(VoltZK.nodes_currently_snapshotting, null, Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
} catch (Exception e) {}
try {
zk.create(VoltZK.completed_snapshots, null, Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
} catch (Exception e) {}
if (threadLocalInit != null) {
m_es.execute(threadLocalInit);
}
/*
* Really shouldn't leak this from a constructor, and twice to boot
* If IV2 is enabled leader election for the snapshot daemon is always tied to
* leader election for the MP coordinator so that they can't be partitioned
* from each other.
*/
if (gse == null) {
m_es.execute(new Runnable() {
@Override
public void run() {
leaderElection();
}
});
} else {
gse.registerService(new Promotable() {
@Override
public void acceptPromotion() throws InterruptedException,
ExecutionException, KeeperException {
m_es.submit(new Runnable() {
@Override
public void run() {
try {
electedTruncationLeader();
} catch (Exception e) {
VoltDB.crashLocalVoltDB("Exception in snapshot daemon electing master via ZK", true, e);
}
}
});
}
});
}
}
/*
* Search for truncation snapshots, after a failure there may be
* ones we don't know about, there may be ones from a previous instance etc.
* Do this every five minutes as an easy hack to make sure we don't leak them.
* Next time groom is called it will delete the old ones after a success.
*/
private void scanTruncationSnapshots() {
if (m_truncationSnapshotPath == null) {
try {
m_truncationSnapshotPath = new String(m_zk.getData(VoltZK.test_scan_path, false, null), "UTF-8");
} catch (Exception e) {
return;
}
}
Object params[] = new Object[1];
params[0] = m_truncationSnapshotPath;
long handle = m_nextCallbackHandle++;
m_procedureCallbacks.put(handle, new ProcedureCallback() {
@Override
public void clientCallback(final ClientResponse clientResponse)
throws Exception {
if (clientResponse.getStatus() != ClientResponse.SUCCESS){
SNAP_LOG.error(clientResponse.getStatusString());
return;
}
final VoltTable results[] = clientResponse.getResults();
if (results.length == 1) {
setState(State.FAILURE);
final VoltTable result = results[0];
boolean advanced = result.advanceRow();
assert(advanced);
assert(result.getColumnCount() == 1);
assert(result.getColumnType(0) == VoltType.STRING);
loggingLog.error("Snapshot scan failed with failure response: " + result.getString("ERR_MSG"));
return;
}
assert(results.length == 3);
final VoltTable snapshots = results[0];
assert(snapshots.getColumnCount() == 9);
TreeMap<Long, TruncationSnapshotAttempt> foundSnapshots =
new TreeMap<Long, TruncationSnapshotAttempt>();
while (snapshots.advanceRow()) {
final String path = snapshots.getString("PATH");
final String nonce = snapshots.getString("NONCE");
final Long txnId = snapshots.getLong("TXNID");
TruncationSnapshotAttempt snapshotAttempt = new TruncationSnapshotAttempt();
snapshotAttempt.path = path;
snapshotAttempt.nonce = nonce;
foundSnapshots.put(txnId, snapshotAttempt);
}
for (Map.Entry<Long, TruncationSnapshotAttempt> entry : foundSnapshots.entrySet()) {
if (!m_truncationSnapshotAttempts.containsKey(entry.getKey())) {
loggingLog.info("Truncation snapshot scan discovered new snapshot txnid " + entry.getKey() +
" path " + entry.getValue().path + " nonce " + entry.getValue().nonce);
m_truncationSnapshotAttempts.put(entry.getKey(), entry.getValue());
}
}
}
});
m_initiator.initiateSnapshotDaemonWork("@SnapshotScan", handle, params);
}
/*
* Delete all snapshots older then the last successful snapshot.
* This only effects snapshots used for log truncation
*/
private void groomTruncationSnapshots() {
ArrayList<TruncationSnapshotAttempt> toDelete = new ArrayList<TruncationSnapshotAttempt>();
boolean foundMostRecentSuccess = false;
Iterator<Map.Entry<Long, TruncationSnapshotAttempt>> iter =
m_truncationSnapshotAttempts.descendingMap().entrySet().iterator();
loggingLog.info("Snapshot daemon grooming truncation snapshots");
while (iter.hasNext()) {
Map.Entry<Long, TruncationSnapshotAttempt> entry = iter.next();
TruncationSnapshotAttempt snapshotAttempt = entry.getValue();
if (!foundMostRecentSuccess) {
if (snapshotAttempt.finished) {
loggingLog.info("Found most recent successful snapshot txnid " + entry.getKey()
+ " path " + entry.getValue().path + " nonce " + entry.getValue().nonce);
foundMostRecentSuccess = true;
} else {
loggingLog.info("Retaining possible partial snapshot txnid " + entry.getKey()
+ " path " + entry.getValue().path + " nonce " + entry.getValue().nonce);
}
} else {
loggingLog.info("Deleting old unecessary snapshot txnid " + entry.getKey()
+ " path " + entry.getValue().path + " nonce " + entry.getValue().nonce);
toDelete.add(entry.getValue());
iter.remove();
}
}
String paths[] = new String[toDelete.size()];
String nonces[] = new String[toDelete.size()];
int ii = 0;
for (TruncationSnapshotAttempt attempt : toDelete) {
paths[ii] = attempt.path;
nonces[ii++] = attempt.nonce;
}
Object params[] =
new Object[] {
paths,
nonces,
};
long handle = m_nextCallbackHandle++;
m_procedureCallbacks.put(handle, new ProcedureCallback() {
@Override
public void clientCallback(ClientResponse clientResponse)
throws Exception {
if (clientResponse.getStatus() != ClientResponse.SUCCESS) {
SNAP_LOG.error(clientResponse.getStatusString());
}
}
});
m_initiator.initiateSnapshotDaemonWork("@SnapshotDelete", handle, params);
}
/*
* If this cluster has per partition transactions ids carried over from
* previous instances, retrieve them from ZK and pass them to snapshot save so that it can
* include them in the snapshot
*/
private JSONArray retrievePerPartitionTransactionIds() {
JSONArray retval = new JSONArray();
try {
ByteBuffer values = ByteBuffer.wrap(m_zk.getData(VoltZK.perPartitionTxnIds, false, null));
int numKeys = values.getInt();
for (int ii = 0; ii < numKeys; ii++) {
retval.put(values.getLong());
}
} catch (KeeperException.NoNodeException e) {/*doesn't have to exist*/}
catch (Exception e) {
VoltDB.crashLocalVoltDB("Failed to retrieve per partition transaction ids for snapshot", false, e);
}
return retval;
}
/**
* Leader election for snapshots.
* Leader will watch for truncation and user snapshot requests
*/
private void leaderElection() {
loggingLog.info("Starting leader election for snapshot truncation daemon");
try {
while (true) {
Stat stat = m_zk.exists(VoltZK.snapshot_truncation_master, new Watcher() {
@Override
public void process(WatchedEvent event) {
switch(event.getType()) {
case NodeDeleted:
loggingLog.info("Detected the snapshot truncation leader's ephemeral node deletion");
m_es.execute(new Runnable() {
@Override
public void run() {
leaderElection();
}
});
break;
default:
break;
}
}
});
if (stat == null) {
try {
m_zk.create(VoltZK.snapshot_truncation_master, null, Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);
electedTruncationLeader();
return;
} catch (NodeExistsException e) {
}
} else {
loggingLog.info("Leader election concluded, a leader already exists");
break;
}
}
} catch (Exception e) {
VoltDB.crashLocalVoltDB("Exception in snapshot daemon electing master via ZK", true, e);
}
}
/*
* Invoked when this snapshot daemon has been elected as leader
*/
private void electedTruncationLeader() throws Exception {
loggingLog.info("This node was selected as the leader for snapshot truncation");
m_truncationSnapshotScanTask = m_es.scheduleWithFixedDelay(new Runnable() {
@Override
public void run() {
try {
scanTruncationSnapshots();
} catch (Exception e) {
loggingLog.error("Error during scan and group of truncation snapshots");
}
}
}, 0, 1, TimeUnit.HOURS);
try {
truncationRequestExistenceCheck();
userSnapshotRequestExistenceCheck(false);
} catch (Exception e) {
VoltDB.crashLocalVoltDB("Error while accepting snapshot daemon leadership", true, e);
}
}
/*
* Process the event generated when the node for a truncation request
* is created, reschedules it for a few seconds later
*/
private void processTruncationRequestEvent(final WatchedEvent event) {
if (event.getType() == EventType.NodeCreated) {
loggingLog.info("Scheduling truncation request processing 10 seconds from now");
/*
* Do it 10 seconds later because these requests tend to come in bunches
* and we want one truncation snapshot to do truncation for all nodes
* so we don't get them back to back
*/
m_es.schedule(new Runnable() {
@Override
public void run() {
try {
processSnapshotTruncationRequestCreated(event);
} catch (Exception e) {
VoltDB.crashLocalVoltDB("Error processing snapshot truncation request creation", true, e);
}
}
}, m_truncationGatheringPeriod, TimeUnit.SECONDS);
return;
} else {
loggingLog.info("Truncation request event was not type created: " + event.getType());
try {
truncationRequestExistenceCheck();
} catch (Exception e) {
VoltDB.crashLocalVoltDB("Error resetting truncation request existence check", true, e);
}
}
}
/*
* A ZK event occured requestion a truncation snapshot be taken
*/
private void processSnapshotTruncationRequestCreated(
final WatchedEvent event) {
loggingLog.info("Snapshot truncation leader received snapshot truncation request");
String snapshotPathTemp;
// Get the snapshot path.
try {
snapshotPathTemp = new String(m_zk.getData(VoltZK.truncation_snapshot_path, false, null), "UTF-8");
} catch (Exception e) {
loggingLog.error("Unable to retrieve truncation snapshot path from ZK, log can't be truncated");
return;
}
// Get the truncation request ID if provided.
final String truncReqId;
try {
byte[] data = m_zk.getData(event.getPath(), true, null);
if (data != null) {
truncReqId = new String(data, "UTF-8");
}
else {
truncReqId = "";
}
} catch (Exception e) {
loggingLog.error("Unable to retrieve truncation snapshot request ID from ZK, log can't be truncated");
return;
}
m_truncationSnapshotPath = snapshotPathTemp;
final String snapshotPath = snapshotPathTemp;
final long now = System.currentTimeMillis();
final String nonce = Long.toString(now);
//Allow nodes to check and see if the nonce incoming for a snapshot is
//for a truncation snapshot. In that case they will mark the completion node
//to be for a truncation snapshot. SnapshotCompletionMonitor notices the mark.
try {
ByteBuffer payload = ByteBuffer.allocate(8);
payload.putLong(0, now);
m_zk.setData(VoltZK.request_truncation_snapshot, payload.array(), -1);
} catch (Exception e) {
//Cause a cascading failure?
VoltDB.crashLocalVoltDB("Setting data on the truncation snapshot request in ZK should never fail", true, e);
}
JSONObject jsObj = new JSONObject();
try {
String sData = "";
if (truncReqId != null) {
JSONObject jsData = new JSONObject();
jsData.put("truncReqId", truncReqId);
sData = jsData.toString();
}
jsObj.put("path", snapshotPath );
jsObj.put("nonce", nonce);
jsObj.put("perPartitionTxnIds", retrievePerPartitionTransactionIds());
jsObj.put("data", sData);
} catch (JSONException e) {
/*
* Should never happen, so fail fast
*/
VoltDB.crashLocalVoltDB("", true, e);
}
long handle = m_nextCallbackHandle++;
m_procedureCallbacks.put(handle, new ProcedureCallback() {
@Override
public void clientCallback(ClientResponse clientResponse)
throws Exception {
if (clientResponse.getStatus() != ClientResponse.SUCCESS){
loggingLog.warn(
"Attempt to initiate a truncation snapshot was not successful: " +
clientResponse.getStatusString());
loggingLog.warn("Retrying log truncation snapshot in 5 minutes");
/*
* Try again in a few minute
*/
m_es.schedule(new Runnable() {
@Override
public void run() {
try {
processTruncationRequestEvent(event);
} catch (Exception e) {
VoltDB.crashLocalVoltDB("Error processing snapshot truncation request event", true, e);
}
}
}, 5, TimeUnit.MINUTES);
return;
}
final VoltTable results[] = clientResponse.getResults();
final VoltTable result = results[0];
boolean success = true;
if (result.getColumnCount() == 1) {
boolean advanced = result.advanceRow();
assert(advanced);
assert(result.getColumnCount() == 1);
assert(result.getColumnType(0) == VoltType.STRING);
loggingLog.error("Snapshot failed with failure response: " + result.getString(0));
success = false;
}
//assert(result.getColumnName(1).equals("TABLE"));
if (success) {
while (result.advanceRow()) {
if (!result.getString("RESULT").equals("SUCCESS")) {
success = false;
loggingLog.warn("Snapshot save feasibility test failed for host "
+ result.getLong("HOST_ID") + " table " + result.getString("TABLE") +
" with error message " + result.getString("ERR_MSG"));
}
}
}
if (success) {
loggingLog.info("Snapshot initiation for log truncation was successful");
/*
* Race to create the completion node before deleting
* the request node so that we can guarantee that the
* completion node will have the correct information
*/
JSONObject obj = new JSONObject(clientResponse.getAppStatusString());
final long snapshotTxnId = Long.valueOf(obj.getLong("txnId"));
try {
m_zk.delete(VoltZK.request_truncation_snapshot, -1);
} catch (Exception e) {
VoltDB.crashLocalVoltDB(
"Unexpected error deleting truncation snapshot request", true, e);
}
SiteTracker st = VoltDB.instance().getSiteTrackerForSnapshot();
int hostId = SiteTracker.getHostForSite(st.getLocalSites()[0]);
if (!SnapshotSaveAPI.createSnapshotCompletionNode(nonce, snapshotTxnId,
hostId, true, truncReqId)) {
SnapshotSaveAPI.increaseParticipateHost(snapshotTxnId, hostId);
}
try {
TruncationSnapshotAttempt snapshotAttempt =
m_truncationSnapshotAttempts.get(snapshotTxnId);
if (snapshotAttempt == null) {
snapshotAttempt = new TruncationSnapshotAttempt();
m_truncationSnapshotAttempts.put(snapshotTxnId, snapshotAttempt);
}
snapshotAttempt.nonce = nonce;
snapshotAttempt.path = snapshotPath;
} finally {
try {
truncationRequestExistenceCheck();
} catch (Exception e) {
VoltDB.crashLocalVoltDB(
"Unexpected error checking for existence of truncation snapshot request"
, true, e);
}
}
} else {
loggingLog.info("Retrying log truncation snapshot in 60 seconds");
/*
* Try again in a few minutes
*/
m_es.schedule(new Runnable() {
@Override
public void run() {
try {
processTruncationRequestEvent(event);
} catch (Exception e) {
VoltDB.crashLocalVoltDB("Exception processing truncation request event", true, e);
}
}
}, 1, TimeUnit.MINUTES);
}
}
});
try {
loggingLog.info("Initiating @SnapshotSave for log truncation");
m_initiator.initiateSnapshotDaemonWork("@SnapshotSave", handle, new Object[] { jsObj.toString(4) });
} catch (JSONException e) {
/*
* Should never happen, so fail fast
*/
VoltDB.crashLocalVoltDB("", true, e);
}
return;
}
/*
* Watcher that handles changes to the ZK node for
* internal truncation snapshot requests
*/
private final Watcher m_truncationRequestExistenceWatcher = new Watcher() {
@Override
public void process(final WatchedEvent event) {
if (event.getState() == KeeperState.Disconnected) return;
m_es.execute(new Runnable() {
@Override
public void run() {
try {
processTruncationRequestEvent(event);
} catch (Exception e) {
VoltDB.crashLocalVoltDB("Error procesing truncation request event", true, e);
}
}
});
}
};
/*
* Watcher that handles events to the user snapshot request node
* in ZK
*/
private final Watcher m_userSnapshotRequestExistenceWatcher = new Watcher() {
@Override
public void process(final WatchedEvent event) {
if (event.getState() == KeeperState.Disconnected) return;
m_es.execute(new Runnable() {
@Override
public void run() {
try {
processUserSnapshotRequestEvent(event);
} catch (Exception e) {
VoltDB.crashLocalVoltDB("Error processing user snapshot request event", true, e);
}
}
});
}
};
/*
* Process the event generated when the node for a user snapshot request
* is created.
*/
private void processUserSnapshotRequestEvent(final WatchedEvent event) throws Exception {
if (event.getType() == EventType.NodeCreated) {
byte data[] = m_zk.getData(event.getPath(), false, null);
String jsonString = new String(data, "UTF-8");
final JSONObject jsObj = new JSONObject(jsonString);
final String requestId = jsObj.getString("requestId");
/*
* Going to reuse the request object, remove the requestId
* field now that it is consumed
*/
jsObj.remove("requestId");
jsObj.put("perPartitionTxnIds", retrievePerPartitionTransactionIds());
final long handle = m_nextCallbackHandle++;
m_procedureCallbacks.put(handle, new ProcedureCallback() {
@Override
public void clientCallback(ClientResponse clientResponse) {
try {
/*
* If there is an error then we are done.
*/
if (clientResponse.getStatus() != ClientResponse.SUCCESS) {
ClientResponseImpl rimpl = (ClientResponseImpl)clientResponse;
ByteBuffer buf = ByteBuffer.allocate(rimpl.getSerializedSize());
m_zk.create(
VoltZK.user_snapshot_response + requestId,
rimpl.flattenToBuffer(buf).array(),
Ids.OPEN_ACL_UNSAFE,
CreateMode.PERSISTENT);
//Reset the watch
userSnapshotRequestExistenceCheck(true);
return;
}
/*
* Now analyze the response. If a snapshot was in progress
* we have to reattempt it later, and send a response to the client
* saying it was queued. Otherwise, forward the response
* failure/success to the client.
*/
if (isSnapshotInProgressResponse(clientResponse)) {
scheduleSnapshotForLater( jsObj.toString(4), requestId, true);
} else {
ClientResponseImpl rimpl = (ClientResponseImpl)clientResponse;
ByteBuffer buf = ByteBuffer.allocate(rimpl.getSerializedSize());
m_zk.create(
VoltZK.user_snapshot_response + requestId,
rimpl.flattenToBuffer(buf).array(),
Ids.OPEN_ACL_UNSAFE,
CreateMode.PERSISTENT);
//Reset the watch
userSnapshotRequestExistenceCheck(true);
return;
}
} catch (Exception e) {
SNAP_LOG.error("Error processing user snapshot request", e);
try {
userSnapshotRequestExistenceCheck(true);
} catch (Exception e2) {
VoltDB.crashLocalVoltDB("Error resetting watch for user snapshots", true, e2);
}
}
}
});
m_initiator.initiateSnapshotDaemonWork(
"@SnapshotSave",
handle,
new Object[] { jsObj.toString(4) });
return;
}
}
/*
* Schedule a user snapshot request for later since the database was busy.
* Continue doing this as long as the error response returned by the DB is snapshot in progress.
* Since the snapshot is being scheduled for later we will send an immediate response to the client
* via ZK relay.
*/
private void scheduleSnapshotForLater(
final String requestObj,
final String requestId,
final boolean isFirstAttempt
) throws Exception {
/*
* Only need to send the queue response the first time we attempt to schedule the snapshot
* for later. It may be necessary to reschedule via this function multiple times.
*/
if (isFirstAttempt) {
SNAP_LOG.info("A user snapshot request could not be immediately fulfilled and will be reattempted later");
/*
* Construct a result to send to the client right now via ZK
* saying we queued it to run later
*/
VoltTable result = SnapshotSave.constructNodeResultsTable();
result.addRow(-1,
CoreUtils.getHostnameOrAddress(),
"",
"SUCCESS",
"SNAPSHOT REQUEST QUEUED");
final ClientResponseImpl queuedResponse =
new ClientResponseImpl(ClientResponseImpl.SUCCESS,
new VoltTable[] { result },
"Snapshot request could not be fulfilled because a snapshot " +
"is in progress. It was queued for execution",
0);
ByteBuffer buf = ByteBuffer.allocate(queuedResponse.getSerializedSize());
m_zk.create(VoltZK.user_snapshot_response + requestId,
queuedResponse.flattenToBuffer(buf).array(),
Ids.OPEN_ACL_UNSAFE,
CreateMode.PERSISTENT);
}
/*
* Now queue the request for later
*/
final Runnable r = new Runnable() {
@Override
public void run() {
try {
/*
* Construct a callback to handle the response to the
* @SnapshotSave invocation that will reattempt the user snapshot
*/
final long handle = m_nextCallbackHandle++;
m_procedureCallbacks.put(handle, new ProcedureCallback() {
@Override
public void clientCallback(ClientResponse clientResponse) {
try {
/*
* If there is an error then we are done
* attempting this user snapshot. The params must be bad
* or things are broken.
*/
if (clientResponse.getStatus() != ClientResponse.SUCCESS) {
SNAP_LOG.error(clientResponse.getStatusString());
//Reset the watch, in case this is recoverable
userSnapshotRequestExistenceCheck(true);
return;
}
VoltTable results[] = clientResponse.getResults();
//Do this check to avoid an NPE
if (results == null || results.length == 0 || results[0].getRowCount() < 1) {
SNAP_LOG.error("Queued user snapshot request reattempt received an unexpected response" +
" and will not be reattempted");
/*
* Don't think this should happen, reset the watch to allow later requests
*/
userSnapshotRequestExistenceCheck(true);
return;
}
VoltTable result = results[0];
boolean snapshotInProgress = false;
boolean haveFailure = false;
while (result.advanceRow()) {
if (result.getString("RESULT").equals("FAILURE")) {
if (result.getString("ERR_MSG").equals("SNAPSHOT IN PROGRESS")) {
snapshotInProgress = true;
} else {
haveFailure = true;
}
}
}
/*
* If a snapshot was in progress, reattempt later, otherwise,
* if there was a failure, abort the attempt and log.
*/
if (snapshotInProgress) {
SNAP_LOG.info("Queued user snapshot was reattempted, but a snapshot was " +
" still in progress. It will be reattempted.");
//Turtles all the way down
scheduleSnapshotForLater(
requestObj,
null,//null because it shouldn't be used, request already responded to
false);
} else if (haveFailure) {
SNAP_LOG.info("Queued user snapshot was attempted, but there was a failure.");
if (requestId != null) {
ClientResponseImpl rimpl = (ClientResponseImpl)clientResponse;
ByteBuffer buf = ByteBuffer.allocate(rimpl.getSerializedSize());
m_zk.create(
VoltZK.user_snapshot_response + requestId,
rimpl.flattenToBuffer(buf).array(),
Ids.OPEN_ACL_UNSAFE,
CreateMode.PERSISTENT);
}
//Reset the watch, in case this is recoverable
userSnapshotRequestExistenceCheck(true);
//Log the details of the failure, after resetting the watch in case of some odd NPE
result.resetRowPosition();
SNAP_LOG.info(result);
} else {
if (requestId != null) {
SNAP_LOG.debug("Queued user snapshot was successfully requested, saving to path " +
VoltZK.user_snapshot_response + requestId);
/*
* Snapshot was started no problem, reset the watch for new requests
*/
ClientResponseImpl rimpl = (ClientResponseImpl)clientResponse;
ByteBuffer buf = ByteBuffer.allocate(rimpl.getSerializedSize());
m_zk.create(
VoltZK.user_snapshot_response + requestId,
rimpl.flattenToBuffer(buf).array(),
Ids.OPEN_ACL_UNSAFE,
CreateMode.PERSISTENT);
}
userSnapshotRequestExistenceCheck(true);
return;
}
} catch (Exception e) {
SNAP_LOG.error("Error processing procedure callback for user snapshot", e);
try {
userSnapshotRequestExistenceCheck(true);
} catch (Exception e1) {
VoltDB.crashLocalVoltDB(
"Error resetting watch for user snapshot requests", true, e1);
}
}
}
});
m_initiator.initiateSnapshotDaemonWork("@SnapshotSave", handle,
new Object[] { requestObj });
} catch (Exception e) {
try {
userSnapshotRequestExistenceCheck(true);
} catch (Exception e1) {
VoltDB.crashLocalVoltDB("Error checking for existence of user snapshots", true, e1);
}
}
}
};
m_es.schedule(r, m_userSnapshotRetryInterval, TimeUnit.SECONDS);
}
/*
* Check a client response to and determine if it is a snapshot in progress response
* to a snapshot request
*/
private boolean isSnapshotInProgressResponse(
ClientResponse response) {
if (response.getStatus() != ClientResponse.SUCCESS) {
return false;
}
if (response.getResults() == null) {
return false;
}
if (response.getResults().length < 1) {
return false;
}
VoltTable results = response.getResults()[0];
if (results.getRowCount() < 1) {
return false;
}
boolean snapshotInProgress = false;
while (results.advanceRow()) {
if (results.getString("RESULT").equals("FAILURE")) {
if (results.getString("ERR_MSG").equals("SNAPSHOT IN PROGRESS")) {
snapshotInProgress = true;
}
}
}
return snapshotInProgress;
}
/*
* Set the watch in ZK on the node that represents an internal request
* for a truncation snapshot
*/
void truncationRequestExistenceCheck() throws KeeperException, InterruptedException {
loggingLog.info("Checking for existence of snapshot truncation request");
if (m_zk.exists(VoltZK.request_truncation_snapshot, m_truncationRequestExistenceWatcher) != null) {
loggingLog.info("A truncation request node already existed, processing truncation request event");
processTruncationRequestEvent(new WatchedEvent(
EventType.NodeCreated,
KeeperState.SyncConnected,
VoltZK.request_truncation_snapshot));
}
}
/*
* Set the watch in ZK on the node that represents a user
* request for a snapshot
*/
void userSnapshotRequestExistenceCheck(boolean deleteExistingRequest) throws Exception {
if (deleteExistingRequest) {
m_zk.delete(VoltZK.user_snapshot_request, -1, null, null);
}
if (m_zk.exists(VoltZK.user_snapshot_request, m_userSnapshotRequestExistenceWatcher) != null) {
processUserSnapshotRequestEvent(new WatchedEvent(
EventType.NodeCreated,
KeeperState.SyncConnected,
VoltZK.user_snapshot_request));
}
}
/**
* Make this SnapshotDaemon responsible for generating snapshots
*/
public ListenableFuture<Void> makeActive(final SnapshotSchedule schedule)
{
return m_es.submit(new Callable<Void>() {
@Override
public Void call() throws Exception {
makeActivePrivate(schedule);
return null;
}
});
}
private void makeActivePrivate(final SnapshotSchedule schedule) {
m_isActive = true;
m_frequency = schedule.getFrequencyvalue();
m_retain = schedule.getRetain();
m_path = schedule.getPath();
m_prefix = schedule.getPrefix();
m_prefixAndSeparator = m_prefix + "_";
final String frequencyUnitString = schedule.getFrequencyunit().toLowerCase();
assert(frequencyUnitString.length() == 1);
final char frequencyUnit = frequencyUnitString.charAt(0);
switch (frequencyUnit) {
case 's':
m_frequencyUnit = TimeUnit.SECONDS;
break;
case 'm':
m_frequencyUnit = TimeUnit.MINUTES;
break;
case 'h':
m_frequencyUnit = TimeUnit.HOURS;
break;
default:
throw new RuntimeException("Frequency unit " + frequencyUnitString + "" +
" in snapshot schedule is not one of d,m,h");
}
m_frequencyInMillis = TimeUnit.MILLISECONDS.convert( m_frequency, m_frequencyUnit);
m_nextSnapshotTime = System.currentTimeMillis() + m_frequencyInMillis;
m_es.scheduleAtFixedRate(new Runnable() {
@Override
public void run() {
try {
doPeriodicWork(System.currentTimeMillis());
} catch (Exception e) {
SNAP_LOG.warn("Error doing periodic snapshot management work", e);
}
}
}, 0, m_periodicWorkInterval, TimeUnit.MILLISECONDS);
}
public void makeInactive() {
m_es.execute(new Runnable() {
@Override
public void run() {
m_isActive = false;
m_snapshots.clear();
}
});
}
private class Snapshot implements Comparable<Snapshot> {
private final String path;
private final String nonce;
private final Long txnId;
private Snapshot (String path, String nonce, Long txnId) {
this.path = path;
this.nonce = nonce;
this.txnId = txnId;
}
@Override
public int compareTo(Snapshot o) {
return txnId.compareTo(o.txnId);
}
@Override
public String toString() {
return path + "/" + nonce;
}
}
/**
* Invoked by the client interface occasionally. Returns null
* if nothing needs to be done or the name of a sysproc along with procedure parameters
* if there is work to be done. Responses come back later via invocations
* of processClientResponse
* @param now Current time
* @return null if there is no work to do or a sysproc with parameters if there is work
*/
private void doPeriodicWork(final long now) {
if (!m_isActive)
{
setState(State.STARTUP);
return;
}
if (m_frequencyUnit == null) {
return;
}
if (m_state == State.STARTUP) {
initiateSnapshotScan();
} else if (m_state == State.SCANNING) {
return;
} else if (m_state == State.FAILURE) {
return;
} else if (m_state == State.WAITING){
processWaitingPeriodicWork(now);
} else if (m_state == State.SNAPSHOTTING) {
return;
} else if (m_state == State.DELETING){
return;
}
}
/**
* Do periodic work when the daemon is in the waiting state. The
* daemon paces out sysproc invocations over time
* to avoid disrupting regular work. If the time for the next
* snapshot has passed it attempts to initiate a new snapshot.
* If there are too many snapshots being retains it attempts to delete
* the extras. Then it attempts to initiate a new snapshot if
* one is due
*/
private void processWaitingPeriodicWork(long now) {
if (now - m_lastSysprocInvocation < m_minTimeBetweenSysprocs) {
return;
}
if (m_snapshots.size() > m_retain) {
//Quick hack to make sure we don't delete while the snapshot is running.
//Deletes work really badly during a snapshot because the FS is occupied
if (!SnapshotSiteProcessor.ExecutionSitesCurrentlySnapshotting.isEmpty()) {
m_lastSysprocInvocation = System.currentTimeMillis() + 3000;
return;
}
deleteExtraSnapshots();
return;
}
if (m_nextSnapshotTime < now) {
initiateNextSnapshot(now);
return;
}
}
private void initiateNextSnapshot(long now) {
setState(State.SNAPSHOTTING);
m_lastSysprocInvocation = now;
final Date nowDate = new Date(now);
final String dateString = m_dateFormat.format(nowDate);
final String nonce = m_prefix + dateString;
JSONObject jsObj = new JSONObject();
try {
jsObj.put("path", m_path);
jsObj.put("nonce", nonce);
jsObj.put("perPartitionTxnIds", retrievePerPartitionTransactionIds());
m_snapshots.offer(new Snapshot(m_path, nonce, now));
long handle = m_nextCallbackHandle++;
m_procedureCallbacks.put(handle, new ProcedureCallback() {
@Override
public void clientCallback(final ClientResponse clientResponse)
throws Exception {
processClientResponsePrivate(clientResponse);
}
});
m_initiator.initiateSnapshotDaemonWork("@SnapshotSave", handle, new Object[] { jsObj.toString(4) });
} catch (JSONException e) {
/*
* Should never happen, so fail fast
*/
VoltDB.crashLocalVoltDB("", false, e);
}
}
/**
* Invoke the @SnapshotScan system procedure to discover
* snapshots on disk that are managed by this daemon
* @return
*/
private void initiateSnapshotScan() {
m_lastSysprocInvocation = System.currentTimeMillis();
Object params[] = new Object[1];
params[0] = m_path;
setState(State.SCANNING);
long handle = m_nextCallbackHandle++;
m_procedureCallbacks.put(handle, new ProcedureCallback() {
@Override
public void clientCallback(final ClientResponse clientResponse)
throws Exception {
processClientResponsePrivate(clientResponse);
}
});
m_initiator.initiateSnapshotDaemonWork("@SnapshotScan", handle, params);
}
/**
* Process responses to sysproc invocations generated by this daemon
* via processPeriodicWork
* @param response
* @return
*/
public Future<Void> processClientResponse(final Callable<ClientResponseImpl> response) {
return m_es.submit(new Callable<Void>() {
@Override
public Void call() throws Exception {
try {
ClientResponseImpl resp = response.call();
long handle = resp.getClientHandle();
m_procedureCallbacks.remove(handle).clientCallback(resp);
} catch (Exception e) {
SNAP_LOG.warn("Error when SnapshotDaemon invoked callback for a procedure invocation", e);
/*
* Don't think it is productive to propagate any exceptions here, Ideally
* they should be handled by the procedure callbacks
*/
}
return null;
}
});
}
private void processClientResponsePrivate(ClientResponse response) {
if (m_frequencyUnit == null) {
throw new RuntimeException("SnapshotDaemon received a response when it has not been configured to run");
}
if (m_state == State.STARTUP) {
throw new RuntimeException("SnapshotDaemon received a response in the startup state");
} else if (m_state == State.SCANNING) {
processScanResponse(response);
} else if (m_state == State.FAILURE) {
return;
} else if (m_state == State.DELETING){
processDeleteResponse(response);
return;
} else if (m_state == State.SNAPSHOTTING){
processSnapshotResponse(response);
return;
}
}
/**
* Confirm and log that the snapshot was a success
* @param response
*/
private void processSnapshotResponse(ClientResponse response) {
setState(State.WAITING);
final long now = System.currentTimeMillis();
m_nextSnapshotTime += m_frequencyInMillis;
if (m_nextSnapshotTime < now) {
m_nextSnapshotTime = now - 1;
}
if (response.getStatus() != ClientResponse.SUCCESS){
setState(State.FAILURE);
logFailureResponse("Snapshot failed", response);
return;
}
final VoltTable results[] = response.getResults();
final VoltTable result = results[0];
if (result.getColumnCount() == 1) {
boolean advanced = result.advanceRow();
assert(advanced);
assert(result.getColumnCount() == 1);
assert(result.getColumnType(0) == VoltType.STRING);
SNAP_LOG.error("Snapshot failed with failure response: " + result.getString(0));
m_snapshots.removeLast();
return;
}
//assert(result.getColumnName(1).equals("TABLE"));
boolean success = true;
while (result.advanceRow()) {
if (!result.getString("RESULT").equals("SUCCESS")) {
success = false;
SNAP_LOG.warn("Snapshot save feasibility test failed for host "
+ result.getLong("HOST_ID") + " table " + result.getString("TABLE") +
" with error message " + result.getString("ERR_MSG"));
}
}
if (!success) {
m_snapshots.removeLast();
}
}
/**
* Process a response to a request to delete snapshots.
* Always transitions to the waiting state even if the delete
* fails. This ensures the system will continue to snapshot
* until the disk is full in the event that there is an administration
* error or a bug.
* @param response
*/
private void processDeleteResponse(ClientResponse response) {
//Continue snapshotting even if a delete fails.
setState(State.WAITING);
if (response.getStatus() != ClientResponse.SUCCESS){
/*
* The delete may fail but the procedure should at least return success...
*/
setState(State.FAILURE);
logFailureResponse("Delete of snapshots failed", response);
return;
}
final VoltTable results[] = response.getResults();
assert(results.length > 0);
if (results[0].getColumnCount() == 1) {
final VoltTable result = results[0];
boolean advanced = result.advanceRow();
assert(advanced);
assert(result.getColumnCount() == 1);
assert(result.getColumnType(0) == VoltType.STRING);
SNAP_LOG.error("Snapshot delete failed with failure response: " + result.getString("ERR_MSG"));
return;
}
}
/**
* Process the response to a snapshot scan. Find the snapshots
* that are managed by this daemon by path and nonce
* and add it the list. Initiate a delete of any that should
* not be retained
* @param response
* @return
*/
private void processScanResponse(ClientResponse response) {
if (response.getStatus() != ClientResponse.SUCCESS){
setState(State.FAILURE);
logFailureResponse("Initial snapshot scan failed", response);
return;
}
final VoltTable results[] = response.getResults();
if (results.length == 1) {
setState(State.FAILURE);
final VoltTable result = results[0];
boolean advanced = result.advanceRow();
assert(advanced);
assert(result.getColumnCount() == 1);
assert(result.getColumnType(0) == VoltType.STRING);
SNAP_LOG.error("Initial snapshot scan failed with failure response: " + result.getString("ERR_MSG"));
return;
}
assert(results.length == 3);
final VoltTable snapshots = results[0];
assert(snapshots.getColumnCount() == 9);
final File myPath = new File(m_path);
while (snapshots.advanceRow()) {
final String path = snapshots.getString("PATH");
final File pathFile = new File(path);
if (pathFile.equals(myPath)) {
final String nonce = snapshots.getString("NONCE");
if (nonce.startsWith(m_prefixAndSeparator)) {
final Long txnId = snapshots.getLong("TXNID");
m_snapshots.add(new Snapshot(path, nonce, txnId));
}
}
}
java.util.Collections.sort(m_snapshots);
deleteExtraSnapshots();
}
/**
* Check if there are extra snapshots and initiate deletion
* @return
*/
private void deleteExtraSnapshots() {
if (m_snapshots.size() <= m_retain) {
setState(State.WAITING);
} else {
m_lastSysprocInvocation = System.currentTimeMillis();
setState(State.DELETING);
final int numberToDelete = m_snapshots.size() - m_retain;
String pathsToDelete[] = new String[numberToDelete];
String noncesToDelete[] = new String[numberToDelete];
for (int ii = 0; ii < numberToDelete; ii++) {
final Snapshot s = m_snapshots.poll();
pathsToDelete[ii] = s.path;
noncesToDelete[ii] = s.nonce;
SNAP_LOG.info("Snapshot daemon deleting " + s.nonce);
}
Object params[] =
new Object[] {
pathsToDelete,
noncesToDelete,
};
long handle = m_nextCallbackHandle++;
m_procedureCallbacks.put(handle, new ProcedureCallback() {
@Override
public void clientCallback(final ClientResponse clientResponse)
throws Exception {
processClientResponsePrivate(clientResponse);
}
});
m_initiator.initiateSnapshotDaemonWork("@SnapshotDelete", handle, params);
}
}
private void logFailureResponse(String message, ClientResponse response) {
SNAP_LOG.error(message, response.getException());
if (response.getStatusString() != null) {
SNAP_LOG.error(response.getStatusString());
}
}
State getState() {
return m_state;
}
void setState(State state) {
m_state = state;
}
public void shutdown() throws InterruptedException {
if (m_snapshotTask != null) {
m_snapshotTask.cancel(false);
}
if (m_truncationSnapshotScanTask != null) {
m_truncationSnapshotScanTask.cancel(false);
}
m_es.shutdown();
m_es.awaitTermination(Long.MAX_VALUE, TimeUnit.DAYS);
}
/*
* If we are the leader, go ahead an create the procedure invocation to do the work.
* We aren't going to journal this in ZK. if the leader dies there will be no
* one to try and complete the work. C'est la vie.
*/
public void requestUserSnapshot(final StoredProcedureInvocation invocation, final Connection c) {
m_es.submit(new Runnable() {
@Override
public void run() {
try {
submitUserSnapshotRequest(invocation, c);
} catch (Exception e) {
VoltDB.crashLocalVoltDB("Exception submitting user snapshot request", true, e);
}
}
});
}
public static final class ForwardClientException extends Exception {
private static final long serialVersionUID = 1L;
private final VoltTable m_table;
public ForwardClientException(String msg, VoltTable table) {
super(msg);
m_table = table;
}
}
private void submitUserSnapshotRequest(final StoredProcedureInvocation invocation, final Connection c) {
Object params[] = invocation.getParams().toArray();
String path = null;
String nonce = null;
boolean blocking = false;
SnapshotFormat format = SnapshotFormat.NATIVE;
try {
/*
* Dang it, have to parse the params here to validate
*/
if (params.length != 3 && params.length != 1) {
throw new Exception("@SnapshotSave requires 3 parameters or alternatively a single JSON blob. " +
"Path, nonce, and blocking");
}
if (params[0] == null) {
throw new Exception("@SnapshotSave path is null");
}
if (params.length == 3) {
if (params[1] == null) {
throw new Exception("@SnapshotSave nonce is null");
}
if (params[2] == null) {
throw new Exception("@SnapshotSave blocking is null");
}
}
if (!(params[0] instanceof String)) {
throw new Exception("@SnapshotSave path param is a " +
params[0].getClass().getSimpleName() +
" and should be a java.lang.String");
}
if (params.length == 3) {
if (!(params[1] instanceof String)) {
throw new Exception("@SnapshotSave nonce param is a " +
params[0].getClass().getSimpleName() +
" and should be a java.lang.String");
}
if (!(params[2] instanceof Byte ||
params[2] instanceof Short ||
params[2] instanceof Integer ||
params[2] instanceof Long)) {
throw new Exception("@SnapshotSave blocking param is a " +
params[0].getClass().getSimpleName() +
" and should be a java.lang.[Byte|Short|Integer|Long]");
}
}
if (params.length == 1) {
final JSONObject jsObj = new JSONObject((String)params[0]);
path = jsObj.getString("uripath");
if (path.isEmpty()) {
throw new Exception("uripath cannot be empty");
}
URI pathURI = new URI(path);
String pathURIScheme = pathURI.getScheme();
if (pathURIScheme == null) {
throw new Exception("URI scheme cannot be null");
}
if (!pathURIScheme.equals("file")) {
throw new Exception("Unsupported URI scheme " + pathURIScheme +
" if this is a file path then you must prepend file:
}
path = pathURI.getPath();
nonce = jsObj.getString("nonce");
if (nonce.isEmpty()) {
throw new Exception("nonce cannot be empty");
}
Object blockingObj = false;
if (jsObj.has("block")) {
blockingObj = jsObj.get("block");
}
if (blockingObj instanceof Number) {
blocking = ((Number)blockingObj).byteValue() == 0 ? false : true;
} else if (blockingObj instanceof Boolean) {
blocking = (Boolean)blockingObj;
} else if (blockingObj instanceof String) {
blocking = Boolean.valueOf((String)blockingObj);
} else {
throw new Exception(blockingObj.getClass().getName() + " is not supported as " +
" type for the block parameter");
}
String formatString = jsObj.optString("format",SnapshotFormat.NATIVE.toString());
/*
* Try and be very flexible about what we will accept
* as the type of the block parameter.
*/
try {
format = SnapshotFormat.getEnumIgnoreCase(formatString);
} catch (IllegalArgumentException argException) {
throw new Exception("@SnapshotSave format param is a " + format +
" and should be one of [\"native\" | \"csv\"]");
}
} else {
path = (String)params[0];
nonce = (String)params[1];
blocking = ((Number)params[2]).byteValue() == 0 ? false : true;
}
if (nonce.contains("-") || nonce.contains(",")) {
throw new Exception("Provided nonce " + nonce + " contains a prohibited character (- or ,)");
}
createAndWatchRequestNode(invocation.clientHandle, c, path, nonce, blocking, format, null, false);
} catch (Exception e) {
VoltTable tables[] = new VoltTable[0];
byte status = ClientResponseImpl.GRACEFUL_FAILURE;
if (e instanceof ForwardClientException && ((ForwardClientException)e).m_table != null) {
tables = new VoltTable[] { ((ForwardClientException)e).m_table };
status = ClientResponseImpl.SUCCESS;
}
final ClientResponseImpl errorResponse =
new ClientResponseImpl(status,
tables,
Throwables.getStackTraceAsString(e),
invocation.clientHandle);
ByteBuffer buf = ByteBuffer.allocate(errorResponse.getSerializedSize() + 4);
buf.putInt(buf.capacity() - 4);
errorResponse.flattenToBuffer(buf).flip();
c.writeStream().enqueue(buf);
return;
}
}
/**
* Try to create the ZK request node and watch it if created successfully.
*
* @param clientHandle
* @param c
* @param path
* @param nonce
* @param blocking
* @param format
* @param data
* @throws ForwardClientException
*/
public void createAndWatchRequestNode(final long clientHandle,
final Connection c,
String path,
String nonce,
boolean blocking,
SnapshotFormat format,
String data,
boolean notifyChanges) throws ForwardClientException {
boolean requestExists = false;
final String requestId = createRequestNode(path, nonce, blocking, format, data);
if (requestId == null) {
requestExists = true;
} else {
try {
registerUserSnapshotResponseWatch(requestId, clientHandle, c, notifyChanges);
} catch (Exception e) {
VoltDB.crashLocalVoltDB("Failed to register ZK watch on snapshot response", true, e);
}
}
if (requestExists) {
VoltTable result = org.voltdb.sysprocs.SnapshotSave.constructNodeResultsTable();
result.addRow(-1,
CoreUtils.getHostnameOrAddress(),
"",
"FAILURE",
"SNAPSHOT IN PROGRESS");
throw new ForwardClientException("A request to perform a user snapshot already exists", result);
}
}
/**
* Try to create the ZK node to request the snapshot.
*
* @param path can be null if the target is not a file target
* @param nonce
* @param blocking
* @param format
* @param data Any data to pass to the snapshot target
* @return The request ID if succeeded, otherwise null.
*/
private String createRequestNode(String path, String nonce,
boolean blocking, SnapshotFormat format,
String data) {
String requestId = null;
try {
final JSONObject jsObj = new JSONObject();
jsObj.put("path", path);
jsObj.put("nonce", nonce);
jsObj.put("block", blocking);
jsObj.put("format", format.toString());
requestId = java.util.UUID.randomUUID().toString();
jsObj.put("requestId", requestId);
jsObj.putOpt("data", data);
String zkString = jsObj.toString(4);
byte zkBytes[] = zkString.getBytes("UTF-8");
m_zk.create(VoltZK.user_snapshot_request, zkBytes, Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
} catch (KeeperException.NodeExistsException e) {
return null;
} catch (Exception e) {
VoltDB.crashLocalVoltDB("Exception while attempting to create user snapshot request in ZK", true, e);
}
return requestId;
}
private void registerUserSnapshotResponseWatch(
final String requestId,
final long clientHandle,
final Connection c,
final boolean notifyChanges) throws Exception {
final String responseNode = VoltZK.user_snapshot_response + requestId;
Stat exists = m_zk.exists(responseNode, new Watcher() {
@Override
public void process(final WatchedEvent event) {
if (event.getState() == KeeperState.Disconnected) return;
switch (event.getType()) {
case NodeCreated:
m_es.submit(new Runnable() {
@Override
public void run() {
try {
processUserSnapshotRequestResponse(
event,
clientHandle,
c,
notifyChanges);
} catch (Exception e) {
VoltDB.crashLocalVoltDB(
"Error retrieving user snapshot request response from ZK",
true,
e);
}
}
});
break;
default:
}
}
});
if (exists != null) {
processUserSnapshotRequestResponse(
new WatchedEvent(
EventType.NodeCreated,
KeeperState.SyncConnected,
responseNode),
clientHandle,
c,
notifyChanges);
}
}
void processUserSnapshotRequestResponse(
final WatchedEvent event,
final long clientHandle,
final Connection c,
final boolean notifyChanges) throws Exception {
byte responseBytes[] = m_zk.getData(event.getPath(), false, null);
try {
m_zk.delete(event.getPath(), -1, null, null);
} catch (Exception e) {
SNAP_LOG.error("Error cleaning up user snapshot request response in ZK", e);
}
ByteBuffer buf = ByteBuffer.wrap(responseBytes);
ClientResponseImpl response = new ClientResponseImpl();
response.initFromBuffer(buf);
response.setClientHandle(clientHandle);
// Not sure if we need to preserve the original byte buffer here, playing it safe
ByteBuffer buf2 = ByteBuffer.allocate(response.getSerializedSize() + 4);
buf2.putInt(buf2.capacity() - 4);
response.flattenToBuffer(buf2).flip();
c.writeStream().enqueue(buf2);
/*
* If the caller wants to be notified of final results for the snapshot
* request, set up a watcher only if the snapshot is queued.
*/
if (notifyChanges && (response.getStatus() == ClientResponse.SUCCESS) &&
SnapshotUtil.isSnapshotQueued(response.getResults())) {
Watcher watcher = new Watcher() {
@Override
public void process(final WatchedEvent event) {
if (event.getState() == KeeperState.Disconnected) return;
switch (event.getType()) {
case NodeCreated:
m_es.submit(new Runnable() {
@Override
public void run() {
try {
processUserSnapshotRequestResponse(
event,
clientHandle,
c,
false);
} catch (Exception e) {
VoltDB.crashLocalVoltDB(
"Error retrieving user snapshot request response from ZK",
true,
e);
}
}
});
break;
default:
}
}
};
// Set the watcher
if (m_zk.exists(event.getPath(), watcher) != null) {
processUserSnapshotRequestResponse(event, clientHandle, c, false);
}
}
}
@Override
public CountDownLatch snapshotCompleted(final SnapshotCompletionEvent event) {
if (!event.truncationSnapshot) {
return new CountDownLatch(0);
}
final CountDownLatch latch = new CountDownLatch(1);
m_es.execute(new Runnable() {
@Override
public void run() {
try {
TruncationSnapshotAttempt snapshotAttempt = m_truncationSnapshotAttempts.get(event.multipartTxnId);
if (snapshotAttempt == null) {
snapshotAttempt = new TruncationSnapshotAttempt();
m_truncationSnapshotAttempts.put(event.multipartTxnId, snapshotAttempt);
}
snapshotAttempt.finished = true;
groomTruncationSnapshots();
} finally {
latch.countDown();
}
}
});
return latch;
}
}
|
package org.voltdb;
import java.io.File;
import java.net.URI;
import java.nio.ByteBuffer;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Map;
import java.util.TreeMap;
import java.util.concurrent.Callable;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import org.apache.zookeeper_voltpatches.CreateMode;
import org.apache.zookeeper_voltpatches.KeeperException;
import org.apache.zookeeper_voltpatches.KeeperException.NodeExistsException;
import org.apache.zookeeper_voltpatches.WatchedEvent;
import org.apache.zookeeper_voltpatches.Watcher;
import org.apache.zookeeper_voltpatches.Watcher.Event.EventType;
import org.apache.zookeeper_voltpatches.Watcher.Event.KeeperState;
import org.apache.zookeeper_voltpatches.ZooDefs.Ids;
import org.apache.zookeeper_voltpatches.ZooKeeper;
import org.apache.zookeeper_voltpatches.data.Stat;
import org.json_voltpatches.JSONArray;
import org.json_voltpatches.JSONException;
import org.json_voltpatches.JSONObject;
import org.voltcore.logging.VoltLogger;
import org.voltcore.network.Connection;
import org.voltcore.utils.CoreUtils;
import org.voltdb.catalog.SnapshotSchedule;
import org.voltdb.client.ClientResponse;
import org.voltdb.client.ProcedureCallback;
import org.voltdb.dtxn.SiteTracker;
import org.voltdb.sysprocs.SnapshotSave;
import org.voltdb.sysprocs.saverestore.SnapshotUtil;
import com.google.common.base.Throwables;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.ListeningScheduledExecutorService;
import com.google.common.util.concurrent.MoreExecutors;
/**
* A scheduler of automated snapshots and manager of archived and retained snapshots.
* The new functionality for handling truncation snapshots operates separately from
* the old automated snapshots. They just share the same event processing threads. Future work
* should merge them.
*
*/
public class SnapshotDaemon implements SnapshotCompletionInterest {
private class TruncationSnapshotAttempt {
private String path;
private String nonce;
private boolean finished;
}
static int m_periodicWorkInterval = 2000;
public static volatile int m_userSnapshotRetryInterval = 30;
/*
* Something that initiates procedures for the snapshot daemon.
*/
public interface DaemonInitiator {
public void initiateSnapshotDaemonWork(final String procedureName, long clientData, Object params[]);
};
private static final VoltLogger SNAP_LOG = new VoltLogger("SNAPSHOT");
private static final VoltLogger loggingLog = new VoltLogger("LOGGING");
private final ScheduledThreadPoolExecutor m_esBase =
new ScheduledThreadPoolExecutor(1,
CoreUtils.getThreadFactory(null, "SnapshotDaemon", CoreUtils.SMALL_STACK_SIZE, false, null),
new java.util.concurrent.ThreadPoolExecutor.DiscardPolicy());
private final ListeningScheduledExecutorService m_es = MoreExecutors.listeningDecorator(m_esBase);
private ZooKeeper m_zk;
private DaemonInitiator m_initiator;
private long m_nextCallbackHandle;
private String m_truncationSnapshotPath;
/*
* Before doing truncation snapshot operations, wait a few seconds
* to give a few nodes a chance to get into the same state WRT to truncation
* so that a truncation snapshot will can service multiple truncation requests
* that arrive at the same time.
*/
int m_truncationGatheringPeriod = 10;
private final TreeMap<Long, TruncationSnapshotAttempt> m_truncationSnapshotAttempts =
new TreeMap<Long, TruncationSnapshotAttempt>();
private Future<?> m_truncationSnapshotScanTask;
private TimeUnit m_frequencyUnit;
private long m_frequencyInMillis;
private int m_frequency;
private int m_retain;
private String m_path;
private String m_prefix;
private String m_prefixAndSeparator;
private Future<?> m_snapshotTask;
private final HashMap<Long, ProcedureCallback> m_procedureCallbacks = new HashMap<Long, ProcedureCallback>();
private final SimpleDateFormat m_dateFormat = new SimpleDateFormat("'_'yyyy.MM.dd.HH.mm.ss");
// true if this SnapshotDaemon is the one responsible for generating
// snapshots
private boolean m_isActive = false;
private long m_nextSnapshotTime;
/**
* Don't invoke sysprocs too close together.
* Keep track of the last call and only do it after
* enough time has passed.
*/
private long m_lastSysprocInvocation = System.currentTimeMillis();
static long m_minTimeBetweenSysprocs = 3000;
/**
* List of snapshots on disk sorted by creation time
*/
final LinkedList<Snapshot> m_snapshots = new LinkedList<Snapshot>();
/**
* States the daemon can be in
*
*/
enum State {
/*
* Initial state
*/
STARTUP,
/*
* Invoked @SnapshotScan, waiting for results.
* Done once on startup to find number of snapshots on disk
* at path with prefix
*/
SCANNING,
/*
* Waiting in between snapshots
*/
WAITING,
/*
* Deleting snapshots that are no longer going to be retained.
*/
DELETING,
/*
* Initiated a snapshot. Will call snapshot scan occasionally to find out
* when it completes.
*/
SNAPSHOTTING,
/*
* Failure state. This state is entered when a sysproc
* fails and the snapshot Daemon can't recover. An error is logged
* and the Daemon stops working
*/
FAILURE;
}
private State m_state = State.STARTUP;
SnapshotDaemon() {
m_esBase.setContinueExistingPeriodicTasksAfterShutdownPolicy(false);
m_esBase.setExecuteExistingDelayedTasksAfterShutdownPolicy(false);
m_frequencyUnit = null;
m_retain = 0;
m_frequency = 0;
m_frequencyInMillis = 0;
m_prefix = null;
m_path = null;
m_prefixAndSeparator = null;
// Register the snapshot status to the StatsAgent
SnapshotStatus snapshotStatus = new SnapshotStatus();
VoltDB.instance().getStatsAgent().registerStatsSource(SysProcSelector.SNAPSHOTSTATUS,
0,
snapshotStatus);
VoltDB.instance().getSnapshotCompletionMonitor().addInterest(this);
}
public void init(DaemonInitiator initiator, ZooKeeper zk, Runnable threadLocalInit, GlobalServiceElector gse) {
m_initiator = initiator;
m_zk = zk;
try {
zk.create(VoltZK.nodes_currently_snapshotting, null, Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
} catch (Exception e) {}
try {
zk.create(VoltZK.completed_snapshots, null, Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
} catch (Exception e) {}
if (threadLocalInit != null) {
m_es.execute(threadLocalInit);
}
/*
* Really shouldn't leak this from a constructor, and twice to boot
* If IV2 is enabled leader election for the snapshot daemon is always tied to
* leader election for the MP coordinator so that they can't be partitioned
* from each other.
*/
if (gse == null) {
m_es.execute(new Runnable() {
@Override
public void run() {
leaderElection();
}
});
} else {
gse.registerService(new Promotable() {
@Override
public void acceptPromotion() throws InterruptedException,
ExecutionException, KeeperException {
m_es.submit(new Runnable() {
@Override
public void run() {
try {
electedTruncationLeader();
} catch (Exception e) {
VoltDB.crashLocalVoltDB("Exception in snapshot daemon electing master via ZK", true, e);
}
}
});
}
});
}
}
/*
* Search for truncation snapshots, after a failure there may be
* ones we don't know about, there may be ones from a previous instance etc.
* Do this every five minutes as an easy hack to make sure we don't leak them.
* Next time groom is called it will delete the old ones after a success.
*/
private void scanTruncationSnapshots() {
if (m_truncationSnapshotPath == null) {
try {
m_truncationSnapshotPath = new String(m_zk.getData(VoltZK.test_scan_path, false, null), "UTF-8");
} catch (Exception e) {
return;
}
}
Object params[] = new Object[1];
params[0] = m_truncationSnapshotPath;
long handle = m_nextCallbackHandle++;
m_procedureCallbacks.put(handle, new ProcedureCallback() {
@Override
public void clientCallback(final ClientResponse clientResponse)
throws Exception {
if (clientResponse.getStatus() != ClientResponse.SUCCESS){
SNAP_LOG.error(clientResponse.getStatusString());
return;
}
final VoltTable results[] = clientResponse.getResults();
if (results.length == 1) {
setState(State.FAILURE);
final VoltTable result = results[0];
boolean advanced = result.advanceRow();
assert(advanced);
assert(result.getColumnCount() == 1);
assert(result.getColumnType(0) == VoltType.STRING);
loggingLog.error("Snapshot scan failed with failure response: " + result.getString("ERR_MSG"));
return;
}
assert(results.length == 3);
final VoltTable snapshots = results[0];
assert(snapshots.getColumnCount() == 9);
TreeMap<Long, TruncationSnapshotAttempt> foundSnapshots =
new TreeMap<Long, TruncationSnapshotAttempt>();
while (snapshots.advanceRow()) {
final String path = snapshots.getString("PATH");
final String nonce = snapshots.getString("NONCE");
final Long txnId = snapshots.getLong("TXNID");
TruncationSnapshotAttempt snapshotAttempt = new TruncationSnapshotAttempt();
snapshotAttempt.path = path;
snapshotAttempt.nonce = nonce;
foundSnapshots.put(txnId, snapshotAttempt);
}
for (Map.Entry<Long, TruncationSnapshotAttempt> entry : foundSnapshots.entrySet()) {
if (!m_truncationSnapshotAttempts.containsKey(entry.getKey())) {
loggingLog.info("Truncation snapshot scan discovered new snapshot txnid " + entry.getKey() +
" path " + entry.getValue().path + " nonce " + entry.getValue().nonce);
m_truncationSnapshotAttempts.put(entry.getKey(), entry.getValue());
}
}
}
});
m_initiator.initiateSnapshotDaemonWork("@SnapshotScan", handle, params);
}
/*
* Delete all snapshots older then the last successful snapshot.
* This only effects snapshots used for log truncation
*/
private void groomTruncationSnapshots() {
ArrayList<TruncationSnapshotAttempt> toDelete = new ArrayList<TruncationSnapshotAttempt>();
boolean foundMostRecentSuccess = false;
Iterator<Map.Entry<Long, TruncationSnapshotAttempt>> iter =
m_truncationSnapshotAttempts.descendingMap().entrySet().iterator();
loggingLog.info("Snapshot daemon grooming truncation snapshots");
while (iter.hasNext()) {
Map.Entry<Long, TruncationSnapshotAttempt> entry = iter.next();
TruncationSnapshotAttempt snapshotAttempt = entry.getValue();
if (!foundMostRecentSuccess) {
if (snapshotAttempt.finished) {
loggingLog.info("Found most recent successful snapshot txnid " + entry.getKey()
+ " path " + entry.getValue().path + " nonce " + entry.getValue().nonce);
foundMostRecentSuccess = true;
} else {
loggingLog.info("Retaining possible partial snapshot txnid " + entry.getKey()
+ " path " + entry.getValue().path + " nonce " + entry.getValue().nonce);
}
} else {
loggingLog.info("Deleting old unecessary snapshot txnid " + entry.getKey()
+ " path " + entry.getValue().path + " nonce " + entry.getValue().nonce);
toDelete.add(entry.getValue());
iter.remove();
}
}
String paths[] = new String[toDelete.size()];
String nonces[] = new String[toDelete.size()];
int ii = 0;
for (TruncationSnapshotAttempt attempt : toDelete) {
paths[ii] = attempt.path;
nonces[ii++] = attempt.nonce;
}
Object params[] =
new Object[] {
paths,
nonces,
};
long handle = m_nextCallbackHandle++;
m_procedureCallbacks.put(handle, new ProcedureCallback() {
@Override
public void clientCallback(ClientResponse clientResponse)
throws Exception {
if (clientResponse.getStatus() != ClientResponse.SUCCESS) {
SNAP_LOG.error(clientResponse.getStatusString());
}
}
});
m_initiator.initiateSnapshotDaemonWork("@SnapshotDelete", handle, params);
}
/*
* If this cluster has per partition transactions ids carried over from
* previous instances, retrieve them from ZK and pass them to snapshot save so that it can
* include them in the snapshot
*/
private JSONArray retrievePerPartitionTransactionIds() {
JSONArray retval = new JSONArray();
try {
ByteBuffer values = ByteBuffer.wrap(m_zk.getData(VoltZK.perPartitionTxnIds, false, null));
int numKeys = values.getInt();
for (int ii = 0; ii < numKeys; ii++) {
retval.put(values.getLong());
}
} catch (KeeperException.NoNodeException e) {/*doesn't have to exist*/}
catch (Exception e) {
VoltDB.crashLocalVoltDB("Failed to retrieve per partition transaction ids for snapshot", false, e);
}
return retval;
}
/**
* Leader election for snapshots.
* Leader will watch for truncation and user snapshot requests
*/
private void leaderElection() {
loggingLog.info("Starting leader election for snapshot truncation daemon");
try {
while (true) {
Stat stat = m_zk.exists(VoltZK.snapshot_truncation_master, new Watcher() {
@Override
public void process(WatchedEvent event) {
switch(event.getType()) {
case NodeDeleted:
loggingLog.info("Detected the snapshot truncation leader's ephemeral node deletion");
m_es.execute(new Runnable() {
@Override
public void run() {
leaderElection();
}
});
break;
default:
break;
}
}
});
if (stat == null) {
try {
m_zk.create(VoltZK.snapshot_truncation_master, null, Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);
electedTruncationLeader();
return;
} catch (NodeExistsException e) {
}
} else {
loggingLog.info("Leader election concluded, a leader already exists");
break;
}
}
} catch (Exception e) {
VoltDB.crashLocalVoltDB("Exception in snapshot daemon electing master via ZK", true, e);
}
}
/*
* Invoked when this snapshot daemon has been elected as leader
*/
private void electedTruncationLeader() throws Exception {
loggingLog.info("This node was selected as the leader for snapshot truncation");
m_truncationSnapshotScanTask = m_es.scheduleWithFixedDelay(new Runnable() {
@Override
public void run() {
try {
scanTruncationSnapshots();
} catch (Exception e) {
loggingLog.error("Error during scan and group of truncation snapshots");
}
}
}, 0, 1, TimeUnit.HOURS);
try {
truncationRequestExistenceCheck();
userSnapshotRequestExistenceCheck(false);
} catch (Exception e) {
VoltDB.crashLocalVoltDB("Error while accepting snapshot daemon leadership", true, e);
}
}
/*
* Process the event generated when the node for a truncation request
* is created, reschedules it for a few seconds later
*/
private void processTruncationRequestEvent(final WatchedEvent event) {
if (event.getType() == EventType.NodeCreated) {
/*
* Do it 10 seconds later because these requests tend to come in bunches
* and we want one truncation snapshot to do truncation for all nodes
* so we don't get them back to back
*/
m_es.schedule(new Runnable() {
@Override
public void run() {
try {
processSnapshotTruncationRequestCreated(event);
} catch (Exception e) {
VoltDB.crashLocalVoltDB("Error processing snapshot truncation request creation", true, e);
}
}
}, m_truncationGatheringPeriod, TimeUnit.SECONDS);
return;
}
}
/*
* A ZK event occured requestion a truncation snapshot be taken
*/
private void processSnapshotTruncationRequestCreated(
final WatchedEvent event) {
loggingLog.info("Snapshot truncation leader received snapshot truncation request");
String snapshotPathTemp;
// Get the snapshot path.
try {
snapshotPathTemp = new String(m_zk.getData(VoltZK.truncation_snapshot_path, false, null), "UTF-8");
} catch (Exception e) {
loggingLog.error("Unable to retrieve truncation snapshot path from ZK, log can't be truncated");
return;
}
// Get the truncation request ID if provided.
final String truncReqId;
try {
byte[] data = m_zk.getData(event.getPath(), true, null);
if (data != null) {
truncReqId = new String(data, "UTF-8");
}
else {
truncReqId = "";
}
} catch (Exception e) {
loggingLog.error("Unable to retrieve truncation snapshot request ID from ZK, log can't be truncated");
return;
}
m_truncationSnapshotPath = snapshotPathTemp;
final String snapshotPath = snapshotPathTemp;
final long now = System.currentTimeMillis();
final String nonce = Long.toString(now);
//Allow nodes to check and see if the nonce incoming for a snapshot is
//for a truncation snapshot. In that case they will mark the completion node
//to be for a truncation snapshot. SnapshotCompletionMonitor notices the mark.
try {
ByteBuffer payload = ByteBuffer.allocate(8);
payload.putLong(0, now);
m_zk.setData(VoltZK.request_truncation_snapshot, payload.array(), -1);
} catch (Exception e) {
//Cause a cascading failure?
VoltDB.crashLocalVoltDB("Setting data on the truncation snapshot request in ZK should never fail", true, e);
}
JSONObject jsObj = new JSONObject();
try {
String sData = "";
if (truncReqId != null) {
JSONObject jsData = new JSONObject();
jsData.put("truncReqId", truncReqId);
sData = jsData.toString();
}
jsObj.put("path", snapshotPath );
jsObj.put("nonce", nonce);
jsObj.put("perPartitionTxnIds", retrievePerPartitionTransactionIds());
jsObj.put("data", sData);
} catch (JSONException e) {
/*
* Should never happen, so fail fast
*/
VoltDB.crashLocalVoltDB("", true, e);
}
long handle = m_nextCallbackHandle++;
m_procedureCallbacks.put(handle, new ProcedureCallback() {
@Override
public void clientCallback(ClientResponse clientResponse)
throws Exception {
if (clientResponse.getStatus() != ClientResponse.SUCCESS){
loggingLog.warn(
"Attempt to initiate a truncation snapshot was not successful: " +
clientResponse.getStatusString());
loggingLog.warn("Retrying log truncation snapshot in 5 minutes");
/*
* Try again in a few minute
*/
m_es.schedule(new Runnable() {
@Override
public void run() {
processTruncationRequestEvent(event);
}
}, 5, TimeUnit.MINUTES);
return;
}
final VoltTable results[] = clientResponse.getResults();
final VoltTable result = results[0];
boolean success = true;
if (result.getColumnCount() == 1) {
boolean advanced = result.advanceRow();
assert(advanced);
assert(result.getColumnCount() == 1);
assert(result.getColumnType(0) == VoltType.STRING);
loggingLog.error("Snapshot failed with failure response: " + result.getString(0));
success = false;
}
//assert(result.getColumnName(1).equals("TABLE"));
if (success) {
while (result.advanceRow()) {
if (!result.getString("RESULT").equals("SUCCESS")) {
success = false;
loggingLog.warn("Snapshot save feasibility test failed for host "
+ result.getLong("HOST_ID") + " table " + result.getString("TABLE") +
" with error message " + result.getString("ERR_MSG"));
}
}
}
if (success) {
/*
* Race to create the completion node before deleting
* the request node so that we can guarantee that the
* completion node will have the correct information
*/
JSONObject obj = new JSONObject(clientResponse.getAppStatusString());
final long snapshotTxnId = Long.valueOf(obj.getLong("txnId"));
try {
m_zk.delete(VoltZK.request_truncation_snapshot, -1);
} catch (Exception e) {
VoltDB.crashLocalVoltDB(
"Unexpected error deleting truncation snapshot request", true, e);
}
SiteTracker st = VoltDB.instance().getSiteTrackerForSnapshot();
int hostId = SiteTracker.getHostForSite(st.getLocalSites()[0]);
if (!SnapshotSaveAPI.createSnapshotCompletionNode(nonce, snapshotTxnId,
hostId, true, truncReqId)) {
SnapshotSaveAPI.increaseParticipateHost(snapshotTxnId, hostId);
}
try {
TruncationSnapshotAttempt snapshotAttempt =
m_truncationSnapshotAttempts.get(snapshotTxnId);
if (snapshotAttempt == null) {
snapshotAttempt = new TruncationSnapshotAttempt();
m_truncationSnapshotAttempts.put(snapshotTxnId, snapshotAttempt);
}
snapshotAttempt.nonce = nonce;
snapshotAttempt.path = snapshotPath;
} finally {
try {
truncationRequestExistenceCheck();
} catch (Exception e) {
VoltDB.crashLocalVoltDB(
"Unexpected error checking for existence of truncation snapshot request"
, true, e);
}
}
} else {
loggingLog.info("Retrying log truncation snapshot in 60 seconds");
/*
* Try again in a few minutes
*/
m_es.schedule(new Runnable() {
@Override
public void run() {
processTruncationRequestEvent(event);
}
}, 1, TimeUnit.MINUTES);
}
}
});
try {
m_initiator.initiateSnapshotDaemonWork("@SnapshotSave", handle, new Object[] { jsObj.toString(4) });
} catch (JSONException e) {
/*
* Should never happen, so fail fast
*/
VoltDB.crashLocalVoltDB("", true, e);
}
return;
}
/*
* Watcher that handles changes to the ZK node for
* internal truncation snapshot requests
*/
private final Watcher m_truncationRequestExistenceWatcher = new Watcher() {
@Override
public void process(final WatchedEvent event) {
if (event.getState() == KeeperState.Disconnected) return;
m_es.execute(new Runnable() {
@Override
public void run() {
processTruncationRequestEvent(event);
}
});
}
};
/*
* Watcher that handles events to the user snapshot request node
* in ZK
*/
private final Watcher m_userSnapshotRequestExistenceWatcher = new Watcher() {
@Override
public void process(final WatchedEvent event) {
if (event.getState() == KeeperState.Disconnected) return;
m_es.execute(new Runnable() {
@Override
public void run() {
try {
processUserSnapshotRequestEvent(event);
} catch (Exception e) {
VoltDB.crashLocalVoltDB("Error processing user snapshot request event", false, e);
}
}
});
}
};
/*
* Process the event generated when the node for a user snapshot request
* is created.
*/
private void processUserSnapshotRequestEvent(final WatchedEvent event) throws Exception {
if (event.getType() == EventType.NodeCreated) {
byte data[] = m_zk.getData(event.getPath(), false, null);
String jsonString = new String(data, "UTF-8");
final JSONObject jsObj = new JSONObject(jsonString);
final String requestId = jsObj.getString("requestId");
/*
* Going to reuse the request object, remove the requestId
* field now that it is consumed
*/
jsObj.remove("requestId");
jsObj.put("perPartitionTxnIds", retrievePerPartitionTransactionIds());
final long handle = m_nextCallbackHandle++;
m_procedureCallbacks.put(handle, new ProcedureCallback() {
@Override
public void clientCallback(ClientResponse clientResponse)
throws Exception {
/*
* If there is an error then we are done.
*/
if (clientResponse.getStatus() != ClientResponse.SUCCESS) {
ClientResponseImpl rimpl = (ClientResponseImpl)clientResponse;
ByteBuffer buf = ByteBuffer.allocate(rimpl.getSerializedSize());
m_zk.create(
VoltZK.user_snapshot_response + requestId,
rimpl.flattenToBuffer(buf).array(),
Ids.OPEN_ACL_UNSAFE,
CreateMode.PERSISTENT);
//Reset the watch
userSnapshotRequestExistenceCheck(true);
return;
}
/*
* Now analyze the response. If a snapshot was in progress
* we have to reattempt it later, and send a response to the client
* saying it was queued. Otherwise, forward the response
* failure/success to the client.
*/
if (isSnapshotInProgressResponse(clientResponse)) {
scheduleSnapshotForLater( jsObj.toString(4), requestId, true);
} else {
ClientResponseImpl rimpl = (ClientResponseImpl)clientResponse;
ByteBuffer buf = ByteBuffer.allocate(rimpl.getSerializedSize());
m_zk.create(
VoltZK.user_snapshot_response + requestId,
rimpl.flattenToBuffer(buf).array(),
Ids.OPEN_ACL_UNSAFE,
CreateMode.PERSISTENT);
//Reset the watch
userSnapshotRequestExistenceCheck(true);
return;
}
}
});
m_initiator.initiateSnapshotDaemonWork(
"@SnapshotSave",
handle,
new Object[] { jsObj.toString(4) });
return;
}
}
/*
* Schedule a user snapshot request for later since the database was busy.
* Continue doing this as long as the error response returned by the DB is snapshot in progress.
* Since the snapshot is being scheduled for later we will send an immediate response to the client
* via ZK relay.
*/
private void scheduleSnapshotForLater(
final String requestObj,
final String requestId,
final boolean isFirstAttempt
) throws Exception {
/*
* Only need to send the queue response the first time we attempt to schedule the snapshot
* for later. It may be necessary to reschedule via this function multiple times.
*/
if (isFirstAttempt) {
SNAP_LOG.info("A user snapshot request could not be immediately fulfilled and will be reattempted later");
/*
* Construct a result to send to the client right now via ZK
* saying we queued it to run later
*/
VoltTable result = SnapshotSave.constructNodeResultsTable();
result.addRow(-1,
CoreUtils.getHostnameOrAddress(),
"",
"SUCCESS",
"SNAPSHOT REQUEST QUEUED");
final ClientResponseImpl queuedResponse =
new ClientResponseImpl(ClientResponseImpl.SUCCESS,
new VoltTable[] { result },
"Snapshot request could not be fulfilled because a snapshot " +
"is in progress. It was queued for execution",
0);
ByteBuffer buf = ByteBuffer.allocate(queuedResponse.getSerializedSize());
m_zk.create(VoltZK.user_snapshot_response + requestId,
queuedResponse.flattenToBuffer(buf).array(),
Ids.OPEN_ACL_UNSAFE,
CreateMode.PERSISTENT);
}
/*
* Now queue the request for later
*/
final Runnable r = new Runnable() {
@Override
public void run() {
try {
/*
* Construct a callback to handle the response to the
* @SnapshotSave invocation that will reattempt the user snapshot
*/
final long handle = m_nextCallbackHandle++;
m_procedureCallbacks.put(handle, new ProcedureCallback() {
@Override
public void clientCallback(ClientResponse clientResponse)
throws Exception {
/*
* If there is an error then we are done
* attempting this user snapshot. The params must be bad
* or things are broken.
*/
if (clientResponse.getStatus() != ClientResponse.SUCCESS) {
SNAP_LOG.error(clientResponse.getStatusString());
//Reset the watch, in case this is recoverable
userSnapshotRequestExistenceCheck(true);
return;
}
VoltTable results[] = clientResponse.getResults();
//Do this check to avoid an NPE
if (results == null || results.length == 0 || results[0].getRowCount() < 1) {
SNAP_LOG.error("Queued user snapshot request reattempt received an unexpected response" +
" and will not be reattempted");
/*
* Don't think this should happen, reset the watch to allow later requests
*/
userSnapshotRequestExistenceCheck(true);
return;
}
VoltTable result = results[0];
boolean snapshotInProgress = false;
boolean haveFailure = false;
while (result.advanceRow()) {
if (result.getString("RESULT").equals("FAILURE")) {
if (result.getString("ERR_MSG").equals("SNAPSHOT IN PROGRESS")) {
snapshotInProgress = true;
} else {
haveFailure = true;
}
}
}
/*
* If a snapshot was in progress, reattempt later, otherwise,
* if there was a failure, abort the attempt and log.
*/
if (snapshotInProgress) {
SNAP_LOG.info("Queued user snapshot was reattempted, but a snapshot was " +
" still in progress. It will be reattempted.");
//Turtles all the way down
scheduleSnapshotForLater(
requestObj,
null,//null because it shouldn't be used, request already responded to
false);
} else if (haveFailure) {
SNAP_LOG.info("Queued user snapshot was attempted, but there was a failure.");
if (requestId != null) {
ClientResponseImpl rimpl = (ClientResponseImpl)clientResponse;
ByteBuffer buf = ByteBuffer.allocate(rimpl.getSerializedSize());
m_zk.create(
VoltZK.user_snapshot_response + requestId,
rimpl.flattenToBuffer(buf).array(),
Ids.OPEN_ACL_UNSAFE,
CreateMode.PERSISTENT);
}
//Reset the watch, in case this is recoverable
userSnapshotRequestExistenceCheck(true);
//Log the details of the failure, after resetting the watch in case of some odd NPE
result.resetRowPosition();
SNAP_LOG.info(result);
} else {
if (requestId != null) {
SNAP_LOG.debug("Queued user snapshot was successfully requested, saving to path " +
VoltZK.user_snapshot_response + requestId);
/*
* Snapshot was started no problem, reset the watch for new requests
*/
ClientResponseImpl rimpl = (ClientResponseImpl)clientResponse;
ByteBuffer buf = ByteBuffer.allocate(rimpl.getSerializedSize());
m_zk.create(
VoltZK.user_snapshot_response + requestId,
rimpl.flattenToBuffer(buf).array(),
Ids.OPEN_ACL_UNSAFE,
CreateMode.PERSISTENT);
}
userSnapshotRequestExistenceCheck(true);
return;
}
}
});
m_initiator.initiateSnapshotDaemonWork("@SnapshotSave", handle,
new Object[] { requestObj });
} catch (Exception e) {
}
}
};
m_es.schedule(r, m_userSnapshotRetryInterval, TimeUnit.SECONDS);
}
/*
* Check a client response to and determine if it is a snapshot in progress response
* to a snapshot request
*/
private boolean isSnapshotInProgressResponse(
ClientResponse response) {
if (response.getStatus() != ClientResponse.SUCCESS) {
return false;
}
if (response.getResults() == null) {
return false;
}
if (response.getResults().length < 1) {
return false;
}
VoltTable results = response.getResults()[0];
if (results.getRowCount() < 1) {
return false;
}
boolean snapshotInProgress = false;
while (results.advanceRow()) {
if (results.getString("RESULT").equals("FAILURE")) {
if (results.getString("ERR_MSG").equals("SNAPSHOT IN PROGRESS")) {
snapshotInProgress = true;
}
}
}
return snapshotInProgress;
}
/*
* Set the watch in ZK on the node that represents an internal request
* for a truncation snapshot
*/
void truncationRequestExistenceCheck() throws KeeperException, InterruptedException {
if (m_zk.exists(VoltZK.request_truncation_snapshot, m_truncationRequestExistenceWatcher) != null) {
processTruncationRequestEvent(new WatchedEvent(
EventType.NodeCreated,
KeeperState.SyncConnected,
VoltZK.request_truncation_snapshot));
}
}
/*
* Set the watch in ZK on the node that represents a user
* request for a snapshot
*/
void userSnapshotRequestExistenceCheck(boolean deleteExistingRequest) throws Exception {
if (deleteExistingRequest) {
m_zk.delete(VoltZK.user_snapshot_request, -1, null, null);
}
if (m_zk.exists(VoltZK.user_snapshot_request, m_userSnapshotRequestExistenceWatcher) != null) {
processUserSnapshotRequestEvent(new WatchedEvent(
EventType.NodeCreated,
KeeperState.SyncConnected,
VoltZK.user_snapshot_request));
}
}
/**
* Make this SnapshotDaemon responsible for generating snapshots
*/
public ListenableFuture<Void> makeActive(final SnapshotSchedule schedule)
{
return m_es.submit(new Callable<Void>() {
@Override
public Void call() throws Exception {
makeActivePrivate(schedule);
return null;
}
});
}
private void makeActivePrivate(final SnapshotSchedule schedule) {
m_isActive = true;
m_frequency = schedule.getFrequencyvalue();
m_retain = schedule.getRetain();
m_path = schedule.getPath();
m_prefix = schedule.getPrefix();
m_prefixAndSeparator = m_prefix + "_";
final String frequencyUnitString = schedule.getFrequencyunit().toLowerCase();
assert(frequencyUnitString.length() == 1);
final char frequencyUnit = frequencyUnitString.charAt(0);
switch (frequencyUnit) {
case 's':
m_frequencyUnit = TimeUnit.SECONDS;
break;
case 'm':
m_frequencyUnit = TimeUnit.MINUTES;
break;
case 'h':
m_frequencyUnit = TimeUnit.HOURS;
break;
default:
throw new RuntimeException("Frequency unit " + frequencyUnitString + "" +
" in snapshot schedule is not one of d,m,h");
}
m_frequencyInMillis = TimeUnit.MILLISECONDS.convert( m_frequency, m_frequencyUnit);
m_nextSnapshotTime = System.currentTimeMillis() + m_frequencyInMillis;
m_es.scheduleAtFixedRate(new Runnable() {
@Override
public void run() {
try {
doPeriodicWork(System.currentTimeMillis());
} catch (Exception e) {
}
}
}, 0, m_periodicWorkInterval, TimeUnit.MILLISECONDS);
}
public void makeInactive() {
m_es.execute(new Runnable() {
@Override
public void run() {
m_isActive = false;
m_snapshots.clear();
}
});
}
private class Snapshot implements Comparable<Snapshot> {
private final String path;
private final String nonce;
private final Long txnId;
private Snapshot (String path, String nonce, Long txnId) {
this.path = path;
this.nonce = nonce;
this.txnId = txnId;
}
@Override
public int compareTo(Snapshot o) {
return txnId.compareTo(o.txnId);
}
@Override
public String toString() {
return path + "/" + nonce;
}
}
/**
* Invoked by the client interface occasionally. Returns null
* if nothing needs to be done or the name of a sysproc along with procedure parameters
* if there is work to be done. Responses come back later via invocations
* of processClientResponse
* @param now Current time
* @return null if there is no work to do or a sysproc with parameters if there is work
*/
private void doPeriodicWork(final long now) {
if (!m_isActive)
{
setState(State.STARTUP);
return;
}
if (m_frequencyUnit == null) {
return;
}
if (m_state == State.STARTUP) {
initiateSnapshotScan();
} else if (m_state == State.SCANNING) {
return;
} else if (m_state == State.FAILURE) {
return;
} else if (m_state == State.WAITING){
processWaitingPeriodicWork(now);
} else if (m_state == State.SNAPSHOTTING) {
return;
} else if (m_state == State.DELETING){
return;
}
}
/**
* Do periodic work when the daemon is in the waiting state. The
* daemon paces out sysproc invocations over time
* to avoid disrupting regular work. If the time for the next
* snapshot has passed it attempts to initiate a new snapshot.
* If there are too many snapshots being retains it attempts to delete
* the extras. Then it attempts to initiate a new snapshot if
* one is due
*/
private void processWaitingPeriodicWork(long now) {
if (now - m_lastSysprocInvocation < m_minTimeBetweenSysprocs) {
return;
}
if (m_snapshots.size() > m_retain) {
//Quick hack to make sure we don't delete while the snapshot is running.
//Deletes work really badly during a snapshot because the FS is occupied
if (!SnapshotSiteProcessor.ExecutionSitesCurrentlySnapshotting.isEmpty()) {
m_lastSysprocInvocation = System.currentTimeMillis() + 3000;
return;
}
deleteExtraSnapshots();
return;
}
if (m_nextSnapshotTime < now) {
initiateNextSnapshot(now);
return;
}
}
private void initiateNextSnapshot(long now) {
setState(State.SNAPSHOTTING);
m_lastSysprocInvocation = now;
final Date nowDate = new Date(now);
final String dateString = m_dateFormat.format(nowDate);
final String nonce = m_prefix + dateString;
JSONObject jsObj = new JSONObject();
try {
jsObj.put("path", m_path);
jsObj.put("nonce", nonce);
jsObj.put("perPartitionTxnIds", retrievePerPartitionTransactionIds());
m_snapshots.offer(new Snapshot(m_path, nonce, now));
long handle = m_nextCallbackHandle++;
m_procedureCallbacks.put(handle, new ProcedureCallback() {
@Override
public void clientCallback(final ClientResponse clientResponse)
throws Exception {
processClientResponsePrivate(clientResponse);
}
});
m_initiator.initiateSnapshotDaemonWork("@SnapshotSave", handle, new Object[] { jsObj.toString(4) });
} catch (JSONException e) {
/*
* Should never happen, so fail fast
*/
VoltDB.crashLocalVoltDB("", false, e);
}
}
/**
* Invoke the @SnapshotScan system procedure to discover
* snapshots on disk that are managed by this daemon
* @return
*/
private void initiateSnapshotScan() {
m_lastSysprocInvocation = System.currentTimeMillis();
Object params[] = new Object[1];
params[0] = m_path;
setState(State.SCANNING);
long handle = m_nextCallbackHandle++;
m_procedureCallbacks.put(handle, new ProcedureCallback() {
@Override
public void clientCallback(final ClientResponse clientResponse)
throws Exception {
processClientResponsePrivate(clientResponse);
}
});
m_initiator.initiateSnapshotDaemonWork("@SnapshotScan", handle, params);
}
/**
* Process responses to sysproc invocations generated by this daemon
* via processPeriodicWork
* @param response
* @return
*/
public Future<Void> processClientResponse(final Callable<ClientResponseImpl> response) {
return m_es.submit(new Callable<Void>() {
@Override
public Void call() throws Exception {
try {
ClientResponseImpl resp = response.call();
long handle = resp.getClientHandle();
m_procedureCallbacks.remove(handle).clientCallback(resp);
} catch (Exception e) {
SNAP_LOG.warn("Error when SnapshotDaemon invoked callback for a procedure invocation", e);
throw e;
}
return null;
}
});
}
private void processClientResponsePrivate(ClientResponse response) {
if (m_frequencyUnit == null) {
throw new RuntimeException("SnapshotDaemon received a response when it has not been configured to run");
}
if (m_state == State.STARTUP) {
throw new RuntimeException("SnapshotDaemon received a response in the startup state");
} else if (m_state == State.SCANNING) {
processScanResponse(response);
} else if (m_state == State.FAILURE) {
return;
} else if (m_state == State.DELETING){
processDeleteResponse(response);
return;
} else if (m_state == State.SNAPSHOTTING){
processSnapshotResponse(response);
return;
}
}
/**
* Confirm and log that the snapshot was a success
* @param response
*/
private void processSnapshotResponse(ClientResponse response) {
setState(State.WAITING);
final long now = System.currentTimeMillis();
m_nextSnapshotTime += m_frequencyInMillis;
if (m_nextSnapshotTime < now) {
m_nextSnapshotTime = now - 1;
}
if (response.getStatus() != ClientResponse.SUCCESS){
setState(State.FAILURE);
logFailureResponse("Snapshot failed", response);
return;
}
final VoltTable results[] = response.getResults();
final VoltTable result = results[0];
if (result.getColumnCount() == 1) {
boolean advanced = result.advanceRow();
assert(advanced);
assert(result.getColumnCount() == 1);
assert(result.getColumnType(0) == VoltType.STRING);
SNAP_LOG.error("Snapshot failed with failure response: " + result.getString(0));
m_snapshots.removeLast();
return;
}
//assert(result.getColumnName(1).equals("TABLE"));
boolean success = true;
while (result.advanceRow()) {
if (!result.getString("RESULT").equals("SUCCESS")) {
success = false;
SNAP_LOG.warn("Snapshot save feasibility test failed for host "
+ result.getLong("HOST_ID") + " table " + result.getString("TABLE") +
" with error message " + result.getString("ERR_MSG"));
}
}
if (!success) {
m_snapshots.removeLast();
}
}
/**
* Process a response to a request to delete snapshots.
* Always transitions to the waiting state even if the delete
* fails. This ensures the system will continue to snapshot
* until the disk is full in the event that there is an administration
* error or a bug.
* @param response
*/
private void processDeleteResponse(ClientResponse response) {
//Continue snapshotting even if a delete fails.
setState(State.WAITING);
if (response.getStatus() != ClientResponse.SUCCESS){
/*
* The delete may fail but the procedure should at least return success...
*/
setState(State.FAILURE);
logFailureResponse("Delete of snapshots failed", response);
return;
}
final VoltTable results[] = response.getResults();
assert(results.length > 0);
if (results[0].getColumnCount() == 1) {
final VoltTable result = results[0];
boolean advanced = result.advanceRow();
assert(advanced);
assert(result.getColumnCount() == 1);
assert(result.getColumnType(0) == VoltType.STRING);
SNAP_LOG.error("Snapshot delete failed with failure response: " + result.getString("ERR_MSG"));
return;
}
}
/**
* Process the response to a snapshot scan. Find the snapshots
* that are managed by this daemon by path and nonce
* and add it the list. Initiate a delete of any that should
* not be retained
* @param response
* @return
*/
private void processScanResponse(ClientResponse response) {
if (response.getStatus() != ClientResponse.SUCCESS){
setState(State.FAILURE);
logFailureResponse("Initial snapshot scan failed", response);
return;
}
final VoltTable results[] = response.getResults();
if (results.length == 1) {
setState(State.FAILURE);
final VoltTable result = results[0];
boolean advanced = result.advanceRow();
assert(advanced);
assert(result.getColumnCount() == 1);
assert(result.getColumnType(0) == VoltType.STRING);
SNAP_LOG.error("Initial snapshot scan failed with failure response: " + result.getString("ERR_MSG"));
return;
}
assert(results.length == 3);
final VoltTable snapshots = results[0];
assert(snapshots.getColumnCount() == 9);
final File myPath = new File(m_path);
while (snapshots.advanceRow()) {
final String path = snapshots.getString("PATH");
final File pathFile = new File(path);
if (pathFile.equals(myPath)) {
final String nonce = snapshots.getString("NONCE");
if (nonce.startsWith(m_prefixAndSeparator)) {
final Long txnId = snapshots.getLong("TXNID");
m_snapshots.add(new Snapshot(path, nonce, txnId));
}
}
}
java.util.Collections.sort(m_snapshots);
deleteExtraSnapshots();
}
/**
* Check if there are extra snapshots and initiate deletion
* @return
*/
private void deleteExtraSnapshots() {
if (m_snapshots.size() <= m_retain) {
setState(State.WAITING);
} else {
m_lastSysprocInvocation = System.currentTimeMillis();
setState(State.DELETING);
final int numberToDelete = m_snapshots.size() - m_retain;
String pathsToDelete[] = new String[numberToDelete];
String noncesToDelete[] = new String[numberToDelete];
for (int ii = 0; ii < numberToDelete; ii++) {
final Snapshot s = m_snapshots.poll();
pathsToDelete[ii] = s.path;
noncesToDelete[ii] = s.nonce;
SNAP_LOG.info("Snapshot daemon deleting " + s.nonce);
}
Object params[] =
new Object[] {
pathsToDelete,
noncesToDelete,
};
long handle = m_nextCallbackHandle++;
m_procedureCallbacks.put(handle, new ProcedureCallback() {
@Override
public void clientCallback(final ClientResponse clientResponse)
throws Exception {
processClientResponsePrivate(clientResponse);
}
});
m_initiator.initiateSnapshotDaemonWork("@SnapshotDelete", handle, params);
}
}
private void logFailureResponse(String message, ClientResponse response) {
SNAP_LOG.error(message, response.getException());
if (response.getStatusString() != null) {
SNAP_LOG.error(response.getStatusString());
}
}
State getState() {
return m_state;
}
void setState(State state) {
m_state = state;
}
public void shutdown() throws InterruptedException {
if (m_snapshotTask != null) {
m_snapshotTask.cancel(false);
}
if (m_truncationSnapshotScanTask != null) {
m_truncationSnapshotScanTask.cancel(false);
}
m_es.shutdown();
m_es.awaitTermination(Long.MAX_VALUE, TimeUnit.DAYS);
}
/*
* If we are the leader, go ahead an create the procedure invocation to do the work.
* We aren't going to journal this in ZK. if the leader dies there will be no
* one to try and complete the work. C'est la vie.
*/
public void requestUserSnapshot(final StoredProcedureInvocation invocation, final Connection c) {
m_es.submit(new Runnable() {
@Override
public void run() {
submitUserSnapshotRequest(invocation, c);
}
});
}
public static final class ForwardClientException extends Exception {
private static final long serialVersionUID = 1L;
private final VoltTable m_table;
public ForwardClientException(String msg, VoltTable table) {
super(msg);
m_table = table;
}
}
private void submitUserSnapshotRequest(final StoredProcedureInvocation invocation, final Connection c) {
Object params[] = invocation.getParams().toArray();
String path = null;
String nonce = null;
boolean blocking = false;
SnapshotFormat format = SnapshotFormat.NATIVE;
try {
/*
* Dang it, have to parse the params here to validate
*/
if (params.length != 3 && params.length != 1) {
throw new Exception("@SnapshotSave requires 3 parameters or alternatively a single JSON blob. " +
"Path, nonce, and blocking");
}
if (params[0] == null) {
throw new Exception("@SnapshotSave path is null");
}
if (params.length == 3) {
if (params[1] == null) {
throw new Exception("@SnapshotSave nonce is null");
}
if (params[2] == null) {
throw new Exception("@SnapshotSave blocking is null");
}
}
if (!(params[0] instanceof String)) {
throw new Exception("@SnapshotSave path param is a " +
params[0].getClass().getSimpleName() +
" and should be a java.lang.String");
}
if (params.length == 3) {
if (!(params[1] instanceof String)) {
throw new Exception("@SnapshotSave nonce param is a " +
params[0].getClass().getSimpleName() +
" and should be a java.lang.String");
}
if (!(params[2] instanceof Byte ||
params[2] instanceof Short ||
params[2] instanceof Integer ||
params[2] instanceof Long)) {
throw new Exception("@SnapshotSave blocking param is a " +
params[0].getClass().getSimpleName() +
" and should be a java.lang.[Byte|Short|Integer|Long]");
}
}
if (params.length == 1) {
final JSONObject jsObj = new JSONObject((String)params[0]);
path = jsObj.getString("uripath");
if (path.isEmpty()) {
throw new Exception("uripath cannot be empty");
}
URI pathURI = new URI(path);
String pathURIScheme = pathURI.getScheme();
if (pathURIScheme == null) {
throw new Exception("URI scheme cannot be null");
}
if (!pathURIScheme.equals("file")) {
throw new Exception("Unsupported URI scheme " + pathURIScheme +
" if this is a file path then you must prepend file:
}
path = pathURI.getPath();
nonce = jsObj.getString("nonce");
if (nonce.isEmpty()) {
throw new Exception("nonce cannot be empty");
}
Object blockingObj = false;
if (jsObj.has("block")) {
blockingObj = jsObj.get("block");
}
if (blockingObj instanceof Number) {
blocking = ((Number)blockingObj).byteValue() == 0 ? false : true;
} else if (blockingObj instanceof Boolean) {
blocking = (Boolean)blockingObj;
} else if (blockingObj instanceof String) {
blocking = Boolean.valueOf((String)blockingObj);
} else {
throw new Exception(blockingObj.getClass().getName() + " is not supported as " +
" type for the block parameter");
}
String formatString = jsObj.optString("format",SnapshotFormat.NATIVE.toString());
/*
* Try and be very flexible about what we will accept
* as the type of the block parameter.
*/
try {
format = SnapshotFormat.getEnumIgnoreCase(formatString);
} catch (IllegalArgumentException argException) {
throw new Exception("@SnapshotSave format param is a " + format +
" and should be one of [\"native\" | \"csv\"]");
}
} else {
path = (String)params[0];
nonce = (String)params[1];
blocking = ((Number)params[2]).byteValue() == 0 ? false : true;
}
if (nonce.contains("-") || nonce.contains(",")) {
throw new Exception("Provided nonce " + nonce + " contains a prohibited character (- or ,)");
}
createAndWatchRequestNode(invocation.clientHandle, c, path, nonce, blocking, format, null, false);
} catch (Exception e) {
VoltTable tables[] = new VoltTable[0];
byte status = ClientResponseImpl.GRACEFUL_FAILURE;
if (e instanceof ForwardClientException && ((ForwardClientException)e).m_table != null) {
tables = new VoltTable[] { ((ForwardClientException)e).m_table };
status = ClientResponseImpl.SUCCESS;
}
final ClientResponseImpl errorResponse =
new ClientResponseImpl(status,
tables,
Throwables.getStackTraceAsString(e),
invocation.clientHandle);
ByteBuffer buf = ByteBuffer.allocate(errorResponse.getSerializedSize() + 4);
buf.putInt(buf.capacity() - 4);
errorResponse.flattenToBuffer(buf).flip();
c.writeStream().enqueue(buf);
return;
}
}
/**
* Try to create the ZK request node and watch it if created successfully.
*
* @param clientHandle
* @param c
* @param path
* @param nonce
* @param blocking
* @param format
* @param data
* @throws ForwardClientException
*/
public void createAndWatchRequestNode(final long clientHandle,
final Connection c,
String path,
String nonce,
boolean blocking,
SnapshotFormat format,
String data,
boolean notifyChanges) throws ForwardClientException {
boolean requestExists = false;
final String requestId = createRequestNode(path, nonce, blocking, format, data);
if (requestId == null) {
requestExists = true;
} else {
try {
registerUserSnapshotResponseWatch(requestId, clientHandle, c, notifyChanges);
} catch (Exception e) {
VoltDB.crashLocalVoltDB("Failed to register ZK watch on snapshot response", true, e);
}
}
if (requestExists) {
VoltTable result = org.voltdb.sysprocs.SnapshotSave.constructNodeResultsTable();
result.addRow(-1,
CoreUtils.getHostnameOrAddress(),
"",
"FAILURE",
"SNAPSHOT IN PROGRESS");
throw new ForwardClientException("A request to perform a user snapshot already exists", result);
}
}
/**
* Try to create the ZK node to request the snapshot.
*
* @param path can be null if the target is not a file target
* @param nonce
* @param blocking
* @param format
* @param data Any data to pass to the snapshot target
* @return The request ID if succeeded, otherwise null.
*/
private String createRequestNode(String path, String nonce,
boolean blocking, SnapshotFormat format,
String data) {
String requestId = null;
try {
final JSONObject jsObj = new JSONObject();
jsObj.put("path", path);
jsObj.put("nonce", nonce);
jsObj.put("block", blocking);
jsObj.put("format", format.toString());
requestId = java.util.UUID.randomUUID().toString();
jsObj.put("requestId", requestId);
jsObj.putOpt("data", data);
String zkString = jsObj.toString(4);
byte zkBytes[] = zkString.getBytes("UTF-8");
m_zk.create(VoltZK.user_snapshot_request, zkBytes, Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
} catch (KeeperException.NodeExistsException e) {
return null;
} catch (Exception e) {
VoltDB.crashLocalVoltDB("Exception while attempting to create user snapshot request in ZK", true, e);
}
return requestId;
}
private void registerUserSnapshotResponseWatch(
final String requestId,
final long clientHandle,
final Connection c,
final boolean notifyChanges) throws Exception {
final String responseNode = VoltZK.user_snapshot_response + requestId;
Stat exists = m_zk.exists(responseNode, new Watcher() {
@Override
public void process(final WatchedEvent event) {
if (event.getState() == KeeperState.Disconnected) return;
switch (event.getType()) {
case NodeCreated:
m_es.submit(new Runnable() {
@Override
public void run() {
try {
processUserSnapshotRequestResponse(
event,
clientHandle,
c,
notifyChanges);
} catch (Exception e) {
VoltDB.crashLocalVoltDB(
"Error retrieving user snapshot request response from ZK",
true,
e);
}
}
});
break;
default:
}
}
});
if (exists != null) {
processUserSnapshotRequestResponse(
new WatchedEvent(
EventType.NodeCreated,
KeeperState.SyncConnected,
responseNode),
clientHandle,
c,
notifyChanges);
}
}
void processUserSnapshotRequestResponse(
final WatchedEvent event,
final long clientHandle,
final Connection c,
final boolean notifyChanges) throws Exception {
byte responseBytes[] = m_zk.getData(event.getPath(), false, null);
try {
m_zk.delete(event.getPath(), -1, null, null);
} catch (Exception e) {
SNAP_LOG.error("Error cleaning up user snapshot request response in ZK", e);
}
ByteBuffer buf = ByteBuffer.wrap(responseBytes);
ClientResponseImpl response = new ClientResponseImpl();
response.initFromBuffer(buf);
response.setClientHandle(clientHandle);
// Not sure if we need to preserve the original byte buffer here, playing it safe
ByteBuffer buf2 = ByteBuffer.allocate(response.getSerializedSize() + 4);
buf2.putInt(buf2.capacity() - 4);
response.flattenToBuffer(buf2).flip();
c.writeStream().enqueue(buf2);
/*
* If the caller wants to be notified of final results for the snapshot
* request, set up a watcher only if the snapshot is queued.
*/
if (notifyChanges && (response.getStatus() == ClientResponse.SUCCESS) &&
SnapshotUtil.isSnapshotQueued(response.getResults())) {
Watcher watcher = new Watcher() {
@Override
public void process(final WatchedEvent event) {
if (event.getState() == KeeperState.Disconnected) return;
switch (event.getType()) {
case NodeCreated:
m_es.submit(new Runnable() {
@Override
public void run() {
try {
processUserSnapshotRequestResponse(
event,
clientHandle,
c,
false);
} catch (Exception e) {
VoltDB.crashLocalVoltDB(
"Error retrieving user snapshot request response from ZK",
true,
e);
}
}
});
break;
default:
}
}
};
// Set the watcher
if (m_zk.exists(event.getPath(), watcher) != null) {
processUserSnapshotRequestResponse(event, clientHandle, c, false);
}
}
}
@Override
public CountDownLatch snapshotCompleted(final SnapshotCompletionEvent event) {
if (!event.truncationSnapshot) {
return new CountDownLatch(0);
}
final CountDownLatch latch = new CountDownLatch(1);
m_es.execute(new Runnable() {
@Override
public void run() {
try {
TruncationSnapshotAttempt snapshotAttempt = m_truncationSnapshotAttempts.get(event.multipartTxnId);
if (snapshotAttempt == null) {
snapshotAttempt = new TruncationSnapshotAttempt();
m_truncationSnapshotAttempts.put(event.multipartTxnId, snapshotAttempt);
}
snapshotAttempt.finished = true;
groomTruncationSnapshots();
} finally {
latch.countDown();
}
}
});
return latch;
}
}
|
package org.voltdb;
import java.io.File;
import java.nio.ByteBuffer;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.concurrent.Callable;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import com.google_voltpatches.common.util.concurrent.Callables;
import org.apache.zookeeper_voltpatches.CreateMode;
import org.apache.zookeeper_voltpatches.KeeperException;
import org.apache.zookeeper_voltpatches.KeeperException.NodeExistsException;
import org.apache.zookeeper_voltpatches.WatchedEvent;
import org.apache.zookeeper_voltpatches.Watcher;
import org.apache.zookeeper_voltpatches.Watcher.Event.EventType;
import org.apache.zookeeper_voltpatches.Watcher.Event.KeeperState;
import org.apache.zookeeper_voltpatches.ZooDefs.Ids;
import org.apache.zookeeper_voltpatches.ZooKeeper;
import org.apache.zookeeper_voltpatches.data.Stat;
import org.json_voltpatches.JSONArray;
import org.json_voltpatches.JSONException;
import org.json_voltpatches.JSONObject;
import org.voltcore.logging.VoltLogger;
import org.voltcore.messaging.HostMessenger;
import org.voltcore.messaging.Mailbox;
import org.voltcore.messaging.SiteMailbox;
import org.voltcore.messaging.VoltMessage;
import org.voltcore.network.Connection;
import org.voltcore.utils.CoreUtils;
import org.voltcore.zk.ZKUtil;
import org.voltdb.catalog.SnapshotSchedule;
import org.voltdb.client.ClientResponse;
import org.voltdb.client.ProcedureCallback;
import org.voltdb.messaging.SnapshotCheckRequestMessage;
import org.voltdb.messaging.SnapshotCheckResponseMessage;
import org.voltdb.sysprocs.saverestore.SnapshotUtil;
import org.voltdb.utils.VoltTableUtil;
import com.google_voltpatches.common.base.Throwables;
import com.google_voltpatches.common.collect.Maps;
import com.google_voltpatches.common.util.concurrent.ListenableFuture;
import com.google_voltpatches.common.util.concurrent.ListeningScheduledExecutorService;
import com.google_voltpatches.common.util.concurrent.MoreExecutors;
public class SnapshotDaemon implements SnapshotCompletionInterest {
private class TruncationSnapshotAttempt {
private String path;
private String nonce;
private boolean finished;
}
static int m_periodicWorkInterval = 2000;
public static volatile int m_userSnapshotRetryInterval = 30;
/*
* Something that initiates procedures for the snapshot daemon.
*/
public interface DaemonInitiator {
public void initiateSnapshotDaemonWork(final String procedureName, long clientData, Object params[]);
}
private static final VoltLogger SNAP_LOG = new VoltLogger("SNAPSHOT");
private static final VoltLogger loggingLog = new VoltLogger("LOGGING");
private final ScheduledThreadPoolExecutor m_esBase =
new ScheduledThreadPoolExecutor(1,
CoreUtils.getThreadFactory(null, "SnapshotDaemon", CoreUtils.SMALL_STACK_SIZE, false, null),
new java.util.concurrent.ThreadPoolExecutor.DiscardPolicy());
private final ListeningScheduledExecutorService m_es = MoreExecutors.listeningDecorator(m_esBase);
private ZooKeeper m_zk;
private DaemonInitiator m_initiator;
private long m_nextCallbackHandle;
private String m_truncationSnapshotPath;
/*
* Before doing truncation snapshot operations, wait a few seconds
* to give a few nodes a chance to get into the same state WRT to truncation
* so that a truncation snapshot will can service multiple truncation requests
* that arrive at the same time.
*/
int m_truncationGatheringPeriod = 10;
private final TreeMap<Long, TruncationSnapshotAttempt> m_truncationSnapshotAttempts =
new TreeMap<Long, TruncationSnapshotAttempt>();
private Future<?> m_truncationSnapshotScanTask;
private TimeUnit m_frequencyUnit;
private long m_frequencyInMillis;
private int m_frequency;
private int m_retain;
private String m_path;
private String m_prefix;
private String m_prefixAndSeparator;
private SnapshotSchedule m_lastKnownSchedule = null;
private final HashMap<Long, ProcedureCallback> m_procedureCallbacks = new HashMap<Long, ProcedureCallback>();
private final SimpleDateFormat m_dateFormat = new SimpleDateFormat("'_'yyyy.MM.dd.HH.mm.ss");
// true if this SnapshotDaemon is the one responsible for generating
// snapshots
private boolean m_isAutoSnapshotLeader = false;
private Future<?> m_autoSnapshotTask = null;
private long m_nextSnapshotTime;
/**
* Don't invoke sysprocs too close together.
* Keep track of the last call and only do it after
* enough time has passed.
*/
private long m_lastSysprocInvocation = System.currentTimeMillis();
static long m_minTimeBetweenSysprocs = 3000;
/**
* List of snapshots on disk sorted by creation time
*/
final LinkedList<Snapshot> m_snapshots = new LinkedList<Snapshot>();
/**
* States the daemon can be in
*
*/
enum State {
/*
* Initial state
*/
STARTUP,
/*
* Invoked @SnapshotScan, waiting for results.
* Done once on startup to find number of snapshots on disk
* at path with prefix
*/
SCANNING,
/*
* Waiting in between snapshots
*/
WAITING,
/*
* Deleting snapshots that are no longer going to be retained.
*/
DELETING,
/*
* Initiated a snapshot. Will call snapshot scan occasionally to find out
* when it completes.
*/
SNAPSHOTTING,
}
private State m_state = State.STARTUP;
SnapshotDaemon() {
m_esBase.setContinueExistingPeriodicTasksAfterShutdownPolicy(false);
m_esBase.setExecuteExistingDelayedTasksAfterShutdownPolicy(false);
m_frequencyUnit = null;
m_retain = 0;
m_frequency = 0;
m_frequencyInMillis = 0;
m_prefix = null;
m_path = null;
m_prefixAndSeparator = null;
// Register the snapshot status to the StatsAgent
SnapshotStatus snapshotStatus = new SnapshotStatus();
VoltDB.instance().getStatsAgent().registerStatsSource(StatsSelector.SNAPSHOTSTATUS,
0,
snapshotStatus);
VoltDB.instance().getSnapshotCompletionMonitor().addInterest(this);
}
public void init(DaemonInitiator initiator, HostMessenger messenger, Runnable threadLocalInit, GlobalServiceElector gse) {
m_initiator = initiator;
m_zk = messenger.getZK();
m_mb = new SiteMailbox(messenger, messenger.getHSIdForLocalSite(HostMessenger.SNAPSHOT_DAEMON_ID));
messenger.createMailbox(m_mb.getHSId(), m_mb);
try {
m_zk.create(VoltZK.nodes_currently_snapshotting, null, Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
} catch (Exception e) {}
try {
m_zk.create(VoltZK.completed_snapshots, null, Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
} catch (Exception e) {}
if (threadLocalInit != null) {
m_es.execute(threadLocalInit);
}
/*
* Really shouldn't leak this from a constructor, and twice to boot
* If IV2 is enabled leader election for the snapshot daemon is always tied to
* leader election for the MP coordinator so that they can't be partitioned
* from each other.
*/
if (gse == null) {
m_es.execute(new Runnable() {
@Override
public void run() {
leaderElection();
}
});
} else {
gse.registerService(new Promotable() {
@Override
public void acceptPromotion() throws InterruptedException,
ExecutionException, KeeperException {
m_es.submit(new Runnable() {
@Override
public void run() {
try {
m_isAutoSnapshotLeader = true;
if (m_lastKnownSchedule != null) {
makeActivePrivate(m_lastKnownSchedule);
}
electedTruncationLeader();
} catch (Exception e) {
VoltDB.crashLocalVoltDB("Exception in snapshot daemon electing master via ZK", true, e);
}
}
});
}
});
}
}
private ListenableFuture<Object> m_currentFeasibilityCheck = null;
private Mailbox m_mb;
private void initiateSnapshotSave(final String requestId,
final long handle,
final Object params[])
{
if (m_currentFeasibilityCheck != null) {
if (m_currentFeasibilityCheck.isDone()) {
m_currentFeasibilityCheck = null;
} else {
// Feasibility check in progress, prevent two checks running at the same time.
final VoltTable result = SnapshotUtil.constructNodeResultsTable();
result.addRow(CoreUtils.getHostIdFromHSId(m_mb.getHSId()), CoreUtils.getHostnameOrAddress(),
"", "FAILURE", "SNAPSHOT IN PROGRESS");
final ClientResponseImpl response =
new ClientResponseImpl(ClientResponseImpl.SUCCESS, new VoltTable[]{result}, null);
response.setClientHandle(handle);
processClientResponse(Callables.returning(response));
return;
}
}
// TRAIL [TruncSnap:11] initiate is in a retriable code block
Callable<Object> work = new Callable<Object>() {
@Override
public Object call() throws Exception
{
final String jsString = String.class.cast(params[0]);
final JSONObject jsObj = new JSONObject(jsString);
boolean initiateSnapshot;
VoltTable checkResult;
// Do scan work on all known live hosts
VoltMessage msg = new SnapshotCheckRequestMessage(jsString);
List<Integer> liveHosts = VoltDB.instance().getHostMessenger().getLiveHostIds();
for (int hostId : liveHosts) {
m_mb.send(CoreUtils.getHSIdFromHostAndSite(hostId, HostMessenger.SNAPSHOT_IO_AGENT_ID), msg);
}
// Wait for responses from all hosts for a certain amount of time
Map<Integer, VoltTable> responses = Maps.newHashMap();
final long timeoutMs = 10 * 1000; // 10s timeout
final long endTime = System.currentTimeMillis() + timeoutMs;
SnapshotCheckResponseMessage response;
while ((response = (SnapshotCheckResponseMessage) m_mb.recvBlocking(timeoutMs)) != null) {
// ignore responses to previous requests
if (jsObj.getString("path").equals(response.getPath()) &&
jsObj.getString("nonce").equals(response.getNonce())) {
responses.put(CoreUtils.getHostIdFromHSId(response.m_sourceHSId), response.getResponse());
}
if (responses.size() == liveHosts.size() || System.currentTimeMillis() > endTime) {
break;
}
}
// Retry if timed out
if (responses.size() != liveHosts.size()) {
throw new CoreUtils.RetryException();
}
// TRAIL [TruncSnap:12] all participating nodes have initiated successfully
// Call @SnapshotSave if check passed, return the failure otherwise
checkResult = VoltTableUtil.unionTables(responses.values());
initiateSnapshot = SnapshotUtil.didSnapshotRequestSucceed(new VoltTable[] {checkResult});
if (initiateSnapshot) {
m_initiator.initiateSnapshotDaemonWork("@SnapshotSave", handle, params);
} else if (requestId != null) {
final ClientResponseImpl failureResponse =
new ClientResponseImpl(ClientResponseImpl.SUCCESS, new VoltTable[]{checkResult}, null);
failureResponse.setClientHandle(handle);
processClientResponse(Callables.returning(failureResponse));
}
return null;
}
};
m_currentFeasibilityCheck = CoreUtils.retryHelper(m_es, m_es, work, 3, 10, TimeUnit.SECONDS, 1, TimeUnit.HOURS);
}
private void saveResponseToZKAndReset(String requestId, ClientResponseImpl response) throws Exception
{
ByteBuffer buf = ByteBuffer.allocate(response.getSerializedSize());
m_zk.create(VoltZK.user_snapshot_response + requestId,
response.flattenToBuffer(buf).array(),
Ids.OPEN_ACL_UNSAFE,
CreateMode.PERSISTENT);
userSnapshotRequestExistenceCheck(true);
}
/*
* Search for truncation snapshots, after a failure there may be
* ones we don't know about, there may be ones from a previous instance etc.
* Do this every five minutes as an easy hack to make sure we don't leak them.
* Next time groom is called it will delete the old ones after a success.
*/
private void scanTruncationSnapshots() {
if (m_truncationSnapshotPath == null) {
try {
m_truncationSnapshotPath = new String(m_zk.getData(VoltZK.test_scan_path, false, null), "UTF-8");
} catch (Exception e) {
return;
}
}
Object params[] = new Object[1];
params[0] = m_truncationSnapshotPath;
long handle = m_nextCallbackHandle++;
m_procedureCallbacks.put(handle, new ProcedureCallback() {
@Override
public void clientCallback(final ClientResponse clientResponse)
throws Exception {
if (clientResponse.getStatus() != ClientResponse.SUCCESS){
SNAP_LOG.error(clientResponse.getStatusString());
return;
}
final VoltTable results[] = clientResponse.getResults();
if (results.length == 1) {
final VoltTable result = results[0];
boolean advanced = result.advanceRow();
assert(advanced);
assert(result.getColumnCount() == 1);
assert(result.getColumnType(0) == VoltType.STRING);
loggingLog.error("Snapshot scan failed with failure response: " + result.getString("ERR_MSG"));
return;
}
assert(results.length == 3);
final VoltTable snapshots = results[0];
assert(snapshots.getColumnCount() == 9);
TreeMap<Long, TruncationSnapshotAttempt> foundSnapshots =
new TreeMap<Long, TruncationSnapshotAttempt>();
while (snapshots.advanceRow()) {
final String path = snapshots.getString("PATH");
final String nonce = snapshots.getString("NONCE");
final Long txnId = snapshots.getLong("TXNID");
TruncationSnapshotAttempt snapshotAttempt = new TruncationSnapshotAttempt();
snapshotAttempt.path = path;
snapshotAttempt.nonce = nonce;
foundSnapshots.put(txnId, snapshotAttempt);
}
for (Map.Entry<Long, TruncationSnapshotAttempt> entry : foundSnapshots.entrySet()) {
if (!m_truncationSnapshotAttempts.containsKey(entry.getKey())) {
loggingLog.info("Truncation snapshot scan discovered new snapshot txnid " + entry.getKey() +
" path " + entry.getValue().path + " nonce " + entry.getValue().nonce);
m_truncationSnapshotAttempts.put(entry.getKey(), entry.getValue());
}
}
}
});
m_initiator.initiateSnapshotDaemonWork("@SnapshotScan", handle, params);
}
/*
* Delete all snapshots older then the last successful snapshot.
* This only effects snapshots used for log truncation
*/
private void groomTruncationSnapshots() {
ArrayList<TruncationSnapshotAttempt> toDelete = new ArrayList<TruncationSnapshotAttempt>();
boolean foundMostRecentSuccess = false;
Iterator<Map.Entry<Long, TruncationSnapshotAttempt>> iter =
m_truncationSnapshotAttempts.descendingMap().entrySet().iterator();
loggingLog.info("Snapshot daemon grooming truncation snapshots");
while (iter.hasNext()) {
Map.Entry<Long, TruncationSnapshotAttempt> entry = iter.next();
TruncationSnapshotAttempt snapshotAttempt = entry.getValue();
if (!foundMostRecentSuccess) {
if (snapshotAttempt.finished) {
loggingLog.info("Found most recent successful snapshot txnid " + entry.getKey()
+ " path " + entry.getValue().path + " nonce " + entry.getValue().nonce);
foundMostRecentSuccess = true;
} else {
loggingLog.info("Retaining possible partial snapshot txnid " + entry.getKey()
+ " path " + entry.getValue().path + " nonce " + entry.getValue().nonce);
}
} else {
loggingLog.info("Deleting old unecessary snapshot txnid " + entry.getKey()
+ " path " + entry.getValue().path + " nonce " + entry.getValue().nonce);
toDelete.add(entry.getValue());
iter.remove();
}
}
String paths[] = new String[toDelete.size()];
String nonces[] = new String[toDelete.size()];
int ii = 0;
for (TruncationSnapshotAttempt attempt : toDelete) {
paths[ii] = attempt.path;
nonces[ii++] = attempt.nonce;
}
Object params[] =
new Object[] {
paths,
nonces,
};
long handle = m_nextCallbackHandle++;
m_procedureCallbacks.put(handle, new ProcedureCallback() {
@Override
public void clientCallback(ClientResponse clientResponse)
throws Exception {
if (clientResponse.getStatus() != ClientResponse.SUCCESS) {
SNAP_LOG.error(clientResponse.getStatusString());
}
}
});
m_initiator.initiateSnapshotDaemonWork("@SnapshotDelete", handle, params);
}
/*
* If this cluster has per partition transactions ids carried over from
* previous instances, retrieve them from ZK and pass them to snapshot save so that it can
* include them in the snapshot
*/
private JSONArray retrievePerPartitionTransactionIds() {
JSONArray retval = new JSONArray();
try {
ByteBuffer values = ByteBuffer.wrap(m_zk.getData(VoltZK.perPartitionTxnIds, false, null));
int numKeys = values.getInt();
for (int ii = 0; ii < numKeys; ii++) {
retval.put(values.getLong());
}
} catch (KeeperException.NoNodeException e) {/*doesn't have to exist*/}
catch (Exception e) {
VoltDB.crashLocalVoltDB("Failed to retrieve per partition transaction ids for snapshot", false, e);
}
return retval;
}
/**
* Leader election for snapshots.
* Leader will watch for truncation and user snapshot requests
*/
private void leaderElection() {
loggingLog.info("Starting leader election for snapshot truncation daemon");
try {
while (true) {
Stat stat = m_zk.exists(VoltZK.snapshot_truncation_master, new Watcher() {
@Override
public void process(WatchedEvent event) {
switch(event.getType()) {
case NodeDeleted:
loggingLog.info("Detected the snapshot truncation leader's ephemeral node deletion");
m_es.execute(new Runnable() {
@Override
public void run() {
leaderElection();
}
});
break;
default:
break;
}
}
});
if (stat == null) {
try {
m_zk.create(VoltZK.snapshot_truncation_master, null, Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);
m_isAutoSnapshotLeader = true;
if (m_lastKnownSchedule != null) {
makeActivePrivate(m_lastKnownSchedule);
}
electedTruncationLeader();
return;
} catch (NodeExistsException e) {
}
} else {
loggingLog.info("Leader election concluded, a leader already exists");
break;
}
}
} catch (Exception e) {
VoltDB.crashLocalVoltDB("Exception in snapshot daemon electing master via ZK", true, e);
}
}
/*
* Invoked when this snapshot daemon has been elected as leader
*/
private void electedTruncationLeader() throws Exception {
loggingLog.info("This node was selected as the leader for snapshot truncation");
m_truncationSnapshotScanTask = m_es.scheduleWithFixedDelay(new Runnable() {
@Override
public void run() {
try {
scanTruncationSnapshots();
} catch (Exception e) {
loggingLog.error("Error during scan and group of truncation snapshots");
}
}
}, 0, 1, TimeUnit.HOURS);
try {
// TRAIL [TruncSnap:1] elected as leader
truncationRequestExistenceCheck();
userSnapshotRequestExistenceCheck(false);
} catch (Exception e) {
VoltDB.crashLocalVoltDB("Error while accepting snapshot daemon leadership", true, e);
}
}
/*
* Process the event generated when the node for a truncation request
* is created, reschedules it for a few seconds later
*/
private void processTruncationRequestEvent(final WatchedEvent event) {
if (event.getType() == EventType.NodeCreated) {
loggingLog.info("Scheduling truncation request processing 10 seconds from now");
/*
* Do it 10 seconds later because these requests tend to come in bunches
* and we want one truncation snapshot to do truncation for all nodes
* so we don't get them back to back
*
* TRAIL [TruncSnap:5] wait 10 secs to process request
*/
m_es.schedule(new Runnable() {
@Override
public void run() {
try {
processSnapshotTruncationRequestCreated(event);
} catch (Exception e) {
VoltDB.crashLocalVoltDB("Error processing snapshot truncation request creation", true, e);
}
}
}, m_truncationGatheringPeriod, TimeUnit.SECONDS);
return;
} else {
/*
* We are very careful to cancel the watch if we find that a truncation requests exists. We are
* the only thread and daemon that should delete the node or change the data and the watch
* isn't set when that happens because it is part of processing the request and the watch should
* either be canceled or have already fired.
*/
VoltDB.crashLocalVoltDB(
"Trunction request watcher fired with event type other then created: " + event.getType(),
true,
null);
}
}
/*
* A ZK event occured requestion a truncation snapshot be taken
*/
private void processSnapshotTruncationRequestCreated(
final WatchedEvent event) {
loggingLog.info("Snapshot truncation leader received snapshot truncation request");
String snapshotPathTemp;
// TRAIL [TruncSnap:6] Get the snapshot path.
try {
snapshotPathTemp = new String(m_zk.getData(VoltZK.truncation_snapshot_path, false, null), "UTF-8");
} catch (Exception e) {
loggingLog.error("Unable to retrieve truncation snapshot path from ZK, log can't be truncated");
return;
}
// Get the truncation request ID if provided.
final String truncReqId;
try {
byte[] data = m_zk.getData(event.getPath(), true, null);
if (data != null) {
truncReqId = new String(data, "UTF-8");
}
else {
truncReqId = "";
}
} catch (Exception e) {
loggingLog.error("Unable to retrieve truncation snapshot request ID from ZK, log can't be truncated");
return;
}
m_truncationSnapshotPath = snapshotPathTemp;
final String snapshotPath = snapshotPathTemp;
final long now = System.currentTimeMillis();
final String nonce = Long.toString(now);
//Allow nodes to check and see if the nonce incoming for a snapshot is
//for a truncation snapshot. In that case they will mark the completion node
//to be for a truncation snapshot. SnapshotCompletionMonitor notices the mark.
// TRAIL [TruncSnap:7] write current ts to request zk node data
try {
ByteBuffer payload = ByteBuffer.allocate(8);
payload.putLong(0, now);
m_zk.setData(VoltZK.request_truncation_snapshot, payload.array(), -1);
} catch (Exception e) {
//Cause a cascading failure?
VoltDB.crashLocalVoltDB("Setting data on the truncation snapshot request in ZK should never fail", true, e);
}
// for the snapshot save invocations
JSONObject jsObj = new JSONObject();
try {
String sData = "";
if (truncReqId != null) {
JSONObject jsData = new JSONObject();
jsData.put("truncReqId", truncReqId);
sData = jsData.toString();
}
jsObj.put("path", snapshotPath );
jsObj.put("nonce", nonce);
jsObj.put("perPartitionTxnIds", retrievePerPartitionTransactionIds());
jsObj.put("data", sData);
} catch (JSONException e) {
/*
* Should never happen, so fail fast
*/
VoltDB.crashLocalVoltDB("", true, e);
}
// for the snapshot save invocations
long handle = m_nextCallbackHandle++;
// for the snapshot save invocation
m_procedureCallbacks.put(handle, new ProcedureCallback() {
@Override
public void clientCallback(ClientResponse clientResponse)
throws Exception {
if (clientResponse.getStatus() != ClientResponse.SUCCESS){
loggingLog.warn(
"Attempt to initiate a truncation snapshot was not successful: " +
clientResponse.getStatusString());
loggingLog.warn("Retrying log truncation snapshot in 5 minutes");
/*
* TRAIL [TruncSnap:8] (callback) on failed response try again in a few minute
*/
m_es.schedule(new Runnable() {
@Override
public void run() {
try {
processTruncationRequestEvent(event);
} catch (Exception e) {
VoltDB.crashLocalVoltDB("Error processing snapshot truncation request event", true, e);
}
}
}, 5, TimeUnit.MINUTES);
return;
}
final VoltTable results[] = clientResponse.getResults();
final VoltTable result = results[0];
boolean success = true;
final String err = SnapshotUtil.didSnapshotRequestFailWithErr(results);
if (err != null) {
loggingLog.warn("Snapshot failed with failure response: " + err);
success = false;
}
//assert(result.getColumnName(1).equals("TABLE"));
if (success) {
while (result.advanceRow()) {
if (!result.getString("RESULT").equals("SUCCESS")) {
success = false;
loggingLog.warn("Snapshot save feasibility test failed for host "
+ result.getLong("HOST_ID") + " table " + result.getString("TABLE") +
" with error message " + result.getString("ERR_MSG"));
}
}
}
if (success) {
loggingLog.info("Snapshot initiation for log truncation was successful");
JSONObject obj = new JSONObject(clientResponse.getAppStatusString());
final long snapshotTxnId = Long.valueOf(obj.getLong("txnId"));
try {
m_zk.delete(VoltZK.request_truncation_snapshot, -1);
} catch (Exception e) {
VoltDB.crashLocalVoltDB(
"Unexpected error deleting truncation snapshot request", true, e);
}
try {
TruncationSnapshotAttempt snapshotAttempt =
m_truncationSnapshotAttempts.get(snapshotTxnId);
if (snapshotAttempt == null) {
snapshotAttempt = new TruncationSnapshotAttempt();
m_truncationSnapshotAttempts.put(snapshotTxnId, snapshotAttempt);
}
snapshotAttempt.nonce = nonce;
snapshotAttempt.path = snapshotPath;
} finally {
// TRAIL [TruncSnap:9] (callback) restart the whole request check cycle
try {
truncationRequestExistenceCheck();
} catch (Exception e) {
VoltDB.crashLocalVoltDB(
"Unexpected error checking for existence of truncation snapshot request"
, true, e);
}
}
} else {
loggingLog.info("Retrying log truncation snapshot in 60 seconds");
/*
* TRAIL [TruncSnap:10] (callback) on table reported failure try again in a few minutes
*/
m_es.schedule(new Runnable() {
@Override
public void run() {
try {
processTruncationRequestEvent(event);
} catch (Exception e) {
VoltDB.crashLocalVoltDB("Exception processing truncation request event", true, e);
}
}
}, 1, TimeUnit.MINUTES);
}
}
});
try {
loggingLog.info("Initiating @SnapshotSave for log truncation");
initiateSnapshotSave(truncReqId, handle, new Object[]{jsObj.toString(4)});
} catch (JSONException e) {
/*
* Should never happen, so fail fast
*/
VoltDB.crashLocalVoltDB("", true, e);
}
return;
}
private TruncationRequestExistenceWatcher m_currentTruncationWatcher = new TruncationRequestExistenceWatcher();
/*
* Watcher that handles changes to the ZK node for
* internal truncation snapshot requests
*/
private class TruncationRequestExistenceWatcher extends ZKUtil.CancellableWatcher {
public TruncationRequestExistenceWatcher() {
super(m_es);
}
@Override
public void pProcess(final WatchedEvent event) {
if (event.getState() == KeeperState.Disconnected) return;
try {
// TRAIL [TruncSnap:4] watch event on zk node fires
processTruncationRequestEvent(event);
} catch (Exception e) {
VoltDB.crashLocalVoltDB("Error procesing truncation request event", true, e);
}
}
};
/*
* Watcher that handles events to the user snapshot request node
* in ZK
*/
private final Watcher m_userSnapshotRequestExistenceWatcher = new Watcher() {
@Override
public void process(final WatchedEvent event) {
if (event.getState() == KeeperState.Disconnected) return;
m_es.execute(new Runnable() {
@Override
public void run() {
try {
processUserSnapshotRequestEvent(event);
} catch (Exception e) {
VoltDB.crashLocalVoltDB("Error processing user snapshot request event", true, e);
}
}
});
}
};
/*
* Process the event generated when the node for a user snapshot request
* is created.
*/
private void processUserSnapshotRequestEvent(final WatchedEvent event) throws Exception {
if (event.getType() == EventType.NodeCreated) {
byte data[] = m_zk.getData(event.getPath(), false, null);
String jsonString = new String(data, "UTF-8");
final JSONObject jsObj = new JSONObject(jsonString);
final String requestId = jsObj.getString("requestId");
/*
* Going to reuse the request object, remove the requestId
* field now that it is consumed
*/
jsObj.remove("requestId");
jsObj.put("perPartitionTxnIds", retrievePerPartitionTransactionIds());
final long handle = m_nextCallbackHandle++;
m_procedureCallbacks.put(handle, new ProcedureCallback() {
@Override
public void clientCallback(ClientResponse clientResponse) {
try {
/*
* If there is an error then we are done.
*/
if (clientResponse.getStatus() != ClientResponse.SUCCESS) {
ClientResponseImpl rimpl = (ClientResponseImpl)clientResponse;
saveResponseToZKAndReset(requestId, rimpl);
return;
}
/*
* Now analyze the response. If a snapshot was in progress
* we have to reattempt it later, and send a response to the client
* saying it was queued. Otherwise, forward the response
* failure/success to the client.
*/
if (isSnapshotInProgressResponse(clientResponse)) {
scheduleSnapshotForLater(jsObj.toString(4), requestId, true);
} else {
ClientResponseImpl rimpl = (ClientResponseImpl)clientResponse;
saveResponseToZKAndReset(requestId, rimpl);
return;
}
} catch (Exception e) {
SNAP_LOG.error("Error processing user snapshot request", e);
try {
userSnapshotRequestExistenceCheck(true);
} catch (Exception e2) {
VoltDB.crashLocalVoltDB("Error resetting watch for user snapshots", true, e2);
}
}
}
});
initiateSnapshotSave(requestId, handle, new Object[]{jsObj.toString(4)});
return;
}
}
/*
* Schedule a user snapshot request for later since the database was busy.
* Continue doing this as long as the error response returned by the DB is snapshot in progress.
* Since the snapshot is being scheduled for later we will send an immediate response to the client
* via ZK relay.
*/
private void scheduleSnapshotForLater(
final String requestObj,
final String requestId,
final boolean isFirstAttempt
) throws Exception {
/*
* Only need to send the queue response the first time we attempt to schedule the snapshot
* for later. It may be necessary to reschedule via this function multiple times.
*/
if (isFirstAttempt) {
SNAP_LOG.info("A user snapshot request could not be immediately fulfilled and will be reattempted later");
/*
* Construct a result to send to the client right now via ZK
* saying we queued it to run later
*/
VoltTable result = SnapshotUtil.constructNodeResultsTable();
result.addRow(-1,
CoreUtils.getHostnameOrAddress(),
"",
"SUCCESS",
"SNAPSHOT REQUEST QUEUED");
final ClientResponseImpl queuedResponse =
new ClientResponseImpl(ClientResponseImpl.SUCCESS,
new VoltTable[] { result },
"Snapshot request could not be fulfilled because a snapshot " +
"is in progress. It was queued for execution",
0);
ByteBuffer buf = ByteBuffer.allocate(queuedResponse.getSerializedSize());
m_zk.create(VoltZK.user_snapshot_response + requestId,
queuedResponse.flattenToBuffer(buf).array(),
Ids.OPEN_ACL_UNSAFE,
CreateMode.PERSISTENT);
}
/*
* Now queue the request for later
*/
final Runnable r = new Runnable() {
@Override
public void run() {
try {
/*
* Construct a callback to handle the response to the
* @SnapshotSave invocation that will reattempt the user snapshot
*/
final long handle = m_nextCallbackHandle++;
m_procedureCallbacks.put(handle, new ProcedureCallback() {
@Override
public void clientCallback(ClientResponse clientResponse) {
try {
/*
* If there is an error then we are done
* attempting this user snapshot. The params must be bad
* or things are broken.
*/
if (clientResponse.getStatus() != ClientResponse.SUCCESS) {
SNAP_LOG.error(clientResponse.getStatusString());
//Reset the watch, in case this is recoverable
userSnapshotRequestExistenceCheck(true);
return;
}
VoltTable results[] = clientResponse.getResults();
//Do this check to avoid an NPE
if (results == null || results.length == 0 || results[0].getRowCount() < 1) {
SNAP_LOG.error("Queued user snapshot request reattempt received an unexpected response" +
" and will not be reattempted. The client response is (status: " +
clientResponse.getStatus() + " " + clientResponse.getStatusString() +
" result: " + (results != null && results.length > 0 ? results[0] : "null") +
")");
/*
* Don't think this should happen, reset the watch to allow later requests
*/
userSnapshotRequestExistenceCheck(true);
return;
}
VoltTable result = results[0];
boolean snapshotInProgress = false;
boolean haveFailure = false;
while (result.advanceRow()) {
if (result.getString("RESULT").equals("FAILURE")) {
if (result.getString("ERR_MSG").equals("SNAPSHOT IN PROGRESS")) {
snapshotInProgress = true;
} else {
haveFailure = true;
}
}
}
/*
* If a snapshot was in progress, reattempt later, otherwise,
* if there was a failure, abort the attempt and log.
*/
if (snapshotInProgress) {
SNAP_LOG.info("Queued user snapshot was reattempted, but a snapshot was " +
" still in progress. It will be reattempted.");
//Turtles all the way down
scheduleSnapshotForLater(
requestObj,
requestId,
false);
} else if (haveFailure) {
SNAP_LOG.info("Queued user snapshot was attempted, but there was a failure.");
try {
ClientResponseImpl rimpl = (ClientResponseImpl)clientResponse;
saveResponseToZKAndReset(requestId, rimpl);
}
catch (NodeExistsException e) {
// used to pass null as request ID to avoid this check if the request ID
// already existed, this gives us the same behavior with a pre-existing
// request ID
}
//Log the details of the failure, after resetting the watch in case of some odd NPE
result.resetRowPosition();
SNAP_LOG.info(result);
} else {
try {
SNAP_LOG.debug("Queued user snapshot was successfully requested, saving to path " +
VoltZK.user_snapshot_response + requestId);
/*
* Snapshot was started no problem, reset the watch for new requests
*/
ClientResponseImpl rimpl = (ClientResponseImpl)clientResponse;
saveResponseToZKAndReset(requestId, rimpl);
}
catch (NodeExistsException e) {
// used to pass null as request ID to avoid this check if the request ID
// already existed, this gives us the same behavior with a pre-existing
// request ID
}
return;
}
} catch (Exception e) {
SNAP_LOG.error("Error processing procedure callback for user snapshot", e);
try {
userSnapshotRequestExistenceCheck(true);
} catch (Exception e1) {
VoltDB.crashLocalVoltDB(
"Error resetting watch for user snapshot requests", true, e1);
}
}
}
});
JSONObject jsonObj = new JSONObject(requestObj);
initiateSnapshotSave(requestId, handle, new Object[]{requestObj});
} catch (Exception e) {
try {
userSnapshotRequestExistenceCheck(true);
} catch (Exception e1) {
VoltDB.crashLocalVoltDB("Error checking for existence of user snapshots", true, e1);
}
}
}
};
m_es.schedule(r, m_userSnapshotRetryInterval, TimeUnit.SECONDS);
}
/*
* Check a client response to and determine if it is a snapshot in progress response
* to a snapshot request
*/
private boolean isSnapshotInProgressResponse(
ClientResponse response) {
if (response.getStatus() != ClientResponse.SUCCESS) {
return false;
}
if (response.getResults() == null) {
return false;
}
if (response.getResults().length < 1) {
return false;
}
VoltTable results = response.getResults()[0];
if (results.getRowCount() < 1) {
return false;
}
boolean snapshotInProgress = false;
while (results.advanceRow()) {
if (results.getString("RESULT").equals("FAILURE")) {
if (results.getString("ERR_MSG").equals("SNAPSHOT IN PROGRESS")) {
snapshotInProgress = true;
}
}
}
return snapshotInProgress;
}
/*
* Set the watch in ZK on the node that represents an internal request
* for a truncation snapshot
*/
void truncationRequestExistenceCheck() throws KeeperException, InterruptedException {
loggingLog.info("Checking for existence of snapshot truncation request");
m_currentTruncationWatcher.cancel();
m_currentTruncationWatcher = new TruncationRequestExistenceWatcher();
// TRAIL [TruncSnap:2] checking for zk node existence
if (m_zk.exists(VoltZK.request_truncation_snapshot, m_currentTruncationWatcher) != null) {
loggingLog.info("A truncation request node already existed, processing truncation request event");
m_currentTruncationWatcher.cancel();
// TRAIL [TruncSnap:3] fake a node created event (req ZK node already there)
processTruncationRequestEvent(new WatchedEvent(
EventType.NodeCreated,
KeeperState.SyncConnected,
VoltZK.request_truncation_snapshot));
}
}
/*
* Set the watch in ZK on the node that represents a user
* request for a snapshot
*/
void userSnapshotRequestExistenceCheck(boolean deleteExistingRequest) throws Exception {
if (deleteExistingRequest) {
m_zk.delete(VoltZK.user_snapshot_request, -1, null, null);
}
if (m_zk.exists(VoltZK.user_snapshot_request, m_userSnapshotRequestExistenceWatcher) != null) {
processUserSnapshotRequestEvent(new WatchedEvent(
EventType.NodeCreated,
KeeperState.SyncConnected,
VoltZK.user_snapshot_request));
}
}
/**
* Make this SnapshotDaemon responsible for generating snapshots
*/
public ListenableFuture<Void> mayGoActiveOrInactive(final SnapshotSchedule schedule)
{
return m_es.submit(new Callable<Void>() {
@Override
public Void call() throws Exception {
makeActivePrivate(schedule);
return null;
}
});
}
private void makeActivePrivate(final SnapshotSchedule schedule) {
m_lastKnownSchedule = schedule;
if (schedule.getEnabled()) {
m_frequency = schedule.getFrequencyvalue();
m_retain = schedule.getRetain();
m_path = schedule.getPath();
m_prefix = schedule.getPrefix();
m_prefixAndSeparator = m_prefix + "_";
final String frequencyUnitString = schedule.getFrequencyunit().toLowerCase();
assert(frequencyUnitString.length() == 1);
final char frequencyUnit = frequencyUnitString.charAt(0);
switch (frequencyUnit) {
case 's':
m_frequencyUnit = TimeUnit.SECONDS;
break;
case 'm':
m_frequencyUnit = TimeUnit.MINUTES;
break;
case 'h':
m_frequencyUnit = TimeUnit.HOURS;
break;
default:
throw new RuntimeException("Frequency unit " + frequencyUnitString + "" +
" in snapshot schedule is not one of d,m,h");
}
m_frequencyInMillis = TimeUnit.MILLISECONDS.convert( m_frequency, m_frequencyUnit);
m_nextSnapshotTime = System.currentTimeMillis() + m_frequencyInMillis;
}
if (m_isAutoSnapshotLeader) {
if (schedule.getEnabled()) {
if (m_autoSnapshotTask == null) {
m_autoSnapshotTask = m_es.scheduleAtFixedRate(new Runnable() {
@Override
public void run() {
try {
doPeriodicWork(System.currentTimeMillis());
} catch (Exception e) {
SNAP_LOG.warn("Error doing periodic snapshot management work", e);
}
}
}, 0, m_periodicWorkInterval, TimeUnit.MILLISECONDS);
}
} else {
if (m_autoSnapshotTask != null) {
m_autoSnapshotTask.cancel(false);
m_autoSnapshotTask = null;
}
}
}
}
public void makeInactive() {
m_es.execute(new Runnable() {
@Override
public void run() {
m_snapshots.clear();
}
});
}
private class Snapshot implements Comparable<Snapshot> {
private final String path;
private final String nonce;
private final Long txnId;
private Snapshot (String path, String nonce, Long txnId) {
this.path = path;
this.nonce = nonce;
this.txnId = txnId;
}
@Override
public int compareTo(Snapshot o) {
return txnId.compareTo(o.txnId);
}
@Override
public String toString() {
return path + "/" + nonce;
}
}
/**
* Invoked by the client interface occasionally. Returns null
* if nothing needs to be done or the name of a sysproc along with procedure parameters
* if there is work to be done. Responses come back later via invocations
* of processClientResponse
* @param now Current time
* @return null if there is no work to do or a sysproc with parameters if there is work
*/
private void doPeriodicWork(final long now) {
if (m_lastKnownSchedule == null)
{
setState(State.STARTUP);
return;
}
if (m_frequencyUnit == null) {
return;
}
if (m_state == State.STARTUP) {
initiateSnapshotScan();
} else if (m_state == State.SCANNING) {
return;
} else if (m_state == State.WAITING){
processWaitingPeriodicWork(now);
} else if (m_state == State.SNAPSHOTTING) {
return;
} else if (m_state == State.DELETING){
return;
}
}
/**
* Do periodic work when the daemon is in the waiting state. The
* daemon paces out sysproc invocations over time
* to avoid disrupting regular work. If the time for the next
* snapshot has passed it attempts to initiate a new snapshot.
* If there are too many snapshots being retains it attempts to delete
* the extras. Then it attempts to initiate a new snapshot if
* one is due
*/
private void processWaitingPeriodicWork(long now) {
if (now - m_lastSysprocInvocation < m_minTimeBetweenSysprocs) {
return;
}
if (m_snapshots.size() > m_retain) {
//Quick hack to make sure we don't delete while the snapshot is running.
//Deletes work really badly during a snapshot because the FS is occupied
if (!SnapshotSiteProcessor.ExecutionSitesCurrentlySnapshotting.isEmpty()) {
m_lastSysprocInvocation = System.currentTimeMillis() + 3000;
return;
}
deleteExtraSnapshots();
return;
}
if (m_nextSnapshotTime < now) {
initiateNextSnapshot(now);
return;
}
}
private void initiateNextSnapshot(long now) {
setState(State.SNAPSHOTTING);
m_lastSysprocInvocation = now;
final Date nowDate = new Date(now);
final String dateString = m_dateFormat.format(nowDate);
final String nonce = m_prefix + dateString;
JSONObject jsObj = new JSONObject();
try {
jsObj.put("path", m_path);
jsObj.put("nonce", nonce);
jsObj.put("perPartitionTxnIds", retrievePerPartitionTransactionIds());
m_snapshots.offer(new Snapshot(m_path, nonce, now));
long handle = m_nextCallbackHandle++;
m_procedureCallbacks.put(handle, new ProcedureCallback() {
@Override
public void clientCallback(final ClientResponse clientResponse)
throws Exception
{
processClientResponsePrivate(clientResponse);
}
});
initiateSnapshotSave(null, handle, new Object[]{jsObj.toString(4)});
} catch (JSONException e) {
/*
* Should never happen, so fail fast
*/
VoltDB.crashLocalVoltDB("", false, e);
}
}
/**
* Invoke the @SnapshotScan system procedure to discover
* snapshots on disk that are managed by this daemon
* @return
*/
private void initiateSnapshotScan() {
m_lastSysprocInvocation = System.currentTimeMillis();
Object params[] = new Object[1];
params[0] = m_path;
setState(State.SCANNING);
long handle = m_nextCallbackHandle++;
m_procedureCallbacks.put(handle, new ProcedureCallback() {
@Override
public void clientCallback(final ClientResponse clientResponse)
throws Exception {
processClientResponsePrivate(clientResponse);
}
});
m_initiator.initiateSnapshotDaemonWork("@SnapshotScan", handle, params);
}
/**
* Process responses to sysproc invocations generated by this daemon
* via processPeriodicWork
* @param response
* @return
*/
public Future<Void> processClientResponse(final Callable<ClientResponseImpl> response) {
return m_es.submit(new Callable<Void>() {
@Override
public Void call() throws Exception {
try {
ClientResponseImpl resp = response.call();
long handle = resp.getClientHandle();
m_procedureCallbacks.remove(handle).clientCallback(resp);
} catch (Exception e) {
SNAP_LOG.warn("Error when SnapshotDaemon invoked callback for a procedure invocation", e);
/*
* Don't think it is productive to propagate any exceptions here, Ideally
* they should be handled by the procedure callbacks
*/
}
return null;
}
});
}
private void processClientResponsePrivate(ClientResponse response) {
if (m_frequencyUnit == null) {
throw new RuntimeException("SnapshotDaemon received a response when it has not been configured to run");
}
if (m_state == State.STARTUP) {
throw new RuntimeException("SnapshotDaemon received a response in the startup state");
} else if (m_state == State.SCANNING) {
processScanResponse(response);
} else if (m_state == State.DELETING){
processDeleteResponse(response);
return;
} else if (m_state == State.SNAPSHOTTING){
processSnapshotResponse(response);
return;
}
}
/**
* Confirm and log that the snapshot was a success
* @param response
*/
private void processSnapshotResponse(ClientResponse response) {
setState(State.WAITING);
final long now = System.currentTimeMillis();
m_nextSnapshotTime += m_frequencyInMillis;
if (m_nextSnapshotTime < now) {
m_nextSnapshotTime = now - 1;
}
if (response.getStatus() != ClientResponse.SUCCESS){
logFailureResponse("Snapshot failed", response);
return;
}
final VoltTable results[] = response.getResults();
final VoltTable result = results[0];
final String err = SnapshotUtil.didSnapshotRequestFailWithErr(results);
if (err != null) {
SNAP_LOG.warn("Snapshot failed with failure response: " + err);
m_snapshots.removeLast();
return;
}
//assert(result.getColumnName(1).equals("TABLE"));
boolean success = true;
while (result.advanceRow()) {
if (!result.getString("RESULT").equals("SUCCESS")) {
success = false;
SNAP_LOG.warn("Snapshot save feasibility test failed for host "
+ result.getLong("HOST_ID") + " table " + result.getString("TABLE") +
" with error message " + result.getString("ERR_MSG"));
}
}
if (!success) {
m_snapshots.removeLast();
}
}
/**
* Process a response to a request to delete snapshots.
* Always transitions to the waiting state even if the delete
* fails. This ensures the system will continue to snapshot
* until the disk is full in the event that there is an administration
* error or a bug.
* @param response
*/
private void processDeleteResponse(ClientResponse response) {
//Continue snapshotting even if a delete fails.
setState(State.WAITING);
if (response.getStatus() != ClientResponse.SUCCESS){
logFailureResponse("Delete of snapshots failed", response);
return;
}
final VoltTable results[] = response.getResults();
final String err = SnapshotUtil.didSnapshotRequestFailWithErr(results);
if (err != null) {
SNAP_LOG.warn("Snapshot delete failed with failure response: " + err);
return;
}
}
/**
* Process the response to a snapshot scan. Find the snapshots
* that are managed by this daemon by path and nonce
* and add it the list. Initiate a delete of any that should
* not be retained
* @param response
* @return
*/
private void processScanResponse(ClientResponse response) {
setState(State.WAITING);
if (response.getStatus() != ClientResponse.SUCCESS) {
logFailureResponse("Initial snapshot scan failed", response);
return;
}
final VoltTable results[] = response.getResults();
if (results.length == 1) {
final VoltTable result = results[0];
boolean advanced = result.advanceRow();
assert(advanced);
assert(result.getColumnCount() == 1);
assert(result.getColumnType(0) == VoltType.STRING);
SNAP_LOG.warn("Initial snapshot scan failed with failure response: " + result.getString("ERR_MSG"));
return;
}
assert(results.length == 3);
final VoltTable snapshots = results[0];
assert(snapshots.getColumnCount() == 9);
final File myPath = new File(m_path);
while (snapshots.advanceRow()) {
final String path = snapshots.getString("PATH");
final File pathFile = new File(path);
if (pathFile.equals(myPath)) {
final String nonce = snapshots.getString("NONCE");
if (nonce.startsWith(m_prefixAndSeparator)) {
final Long txnId = snapshots.getLong("TXNID");
m_snapshots.add(new Snapshot(path, nonce, txnId));
}
}
}
java.util.Collections.sort(m_snapshots);
deleteExtraSnapshots();
}
/**
* Check if there are extra snapshots and initiate deletion
* @return
*/
private void deleteExtraSnapshots() {
if (m_snapshots.size() <= m_retain) {
setState(State.WAITING);
} else {
m_lastSysprocInvocation = System.currentTimeMillis();
setState(State.DELETING);
final int numberToDelete = m_snapshots.size() - m_retain;
String pathsToDelete[] = new String[numberToDelete];
String noncesToDelete[] = new String[numberToDelete];
for (int ii = 0; ii < numberToDelete; ii++) {
final Snapshot s = m_snapshots.poll();
pathsToDelete[ii] = s.path;
noncesToDelete[ii] = s.nonce;
SNAP_LOG.info("Snapshot daemon deleting " + s.nonce);
}
Object params[] =
new Object[] {
pathsToDelete,
noncesToDelete,
};
long handle = m_nextCallbackHandle++;
m_procedureCallbacks.put(handle, new ProcedureCallback() {
@Override
public void clientCallback(final ClientResponse clientResponse)
throws Exception {
processClientResponsePrivate(clientResponse);
}
});
m_initiator.initiateSnapshotDaemonWork("@SnapshotDelete", handle, params);
}
}
private void logFailureResponse(String message, ClientResponse response) {
SNAP_LOG.warn(message + "\n" + response.getStatusString());
if (response.getStatusString() != null) {
SNAP_LOG.warn(response.getStatusString());
}
}
State getState() {
return m_state;
}
void setState(State state) {
m_state = state;
}
public void shutdown() throws InterruptedException {
if (m_truncationSnapshotScanTask != null) {
m_truncationSnapshotScanTask.cancel(false);
}
m_es.shutdown();
m_es.awaitTermination(Long.MAX_VALUE, TimeUnit.DAYS);
}
/*
* If we are the leader, go ahead an create the procedure invocation to do the work.
* We aren't going to journal this in ZK. if the leader dies there will be no
* one to try and complete the work. C'est la vie.
*/
public void requestUserSnapshot(final StoredProcedureInvocation invocation, final Connection c) {
m_es.submit(new Runnable() {
@Override
public void run() {
try {
submitUserSnapshotRequest(invocation, c);
} catch (Exception e) {
VoltDB.crashLocalVoltDB("Exception submitting user snapshot request", true, e);
}
}
});
}
public static final class ForwardClientException extends Exception {
private static final long serialVersionUID = 1L;
private final VoltTable m_table;
public ForwardClientException(String msg, VoltTable table) {
super(msg);
m_table = table;
}
}
private void submitUserSnapshotRequest(final StoredProcedureInvocation invocation, final Connection c) {
Object params[] = invocation.getParams().toArray();
try {
/*
* Dang it, have to parse the params here to validate
*/
SnapshotInitiationInfo snapInfo = new SnapshotInitiationInfo(params);
createAndWatchRequestNode(invocation.clientHandle, c, snapInfo,
false);
} catch (Exception e) {
VoltTable tables[] = new VoltTable[0];
byte status = ClientResponseImpl.GRACEFUL_FAILURE;
if (e instanceof ForwardClientException && ((ForwardClientException)e).m_table != null) {
tables = new VoltTable[] { ((ForwardClientException)e).m_table };
status = ClientResponseImpl.SUCCESS;
}
final ClientResponseImpl errorResponse =
new ClientResponseImpl(status,
tables,
Throwables.getStackTraceAsString(e),
invocation.clientHandle);
ByteBuffer buf = ByteBuffer.allocate(errorResponse.getSerializedSize() + 4);
buf.putInt(buf.capacity() - 4);
errorResponse.flattenToBuffer(buf).flip();
c.writeStream().enqueue(buf);
return;
}
}
/**
* Try to create the ZK request node and watch it if created successfully.
*/
public void createAndWatchRequestNode(final long clientHandle,
final Connection c,
SnapshotInitiationInfo snapInfo,
boolean notifyChanges) throws ForwardClientException {
boolean requestExists = false;
final String requestId = createRequestNode(snapInfo);
if (requestId == null) {
requestExists = true;
} else {
if (!snapInfo.isTruncationRequest()) {
try {
registerUserSnapshotResponseWatch(requestId, clientHandle, c, notifyChanges);
} catch (Exception e) {
VoltDB.crashLocalVoltDB("Failed to register ZK watch on snapshot response", true, e);
}
}
else {
// need to construct a success response of some sort here to indicate the truncation attempt
// was successfully attempted
VoltTable result = SnapshotUtil.constructNodeResultsTable();
result.addRow(-1,
CoreUtils.getHostnameOrAddress(),
"",
"SUCCESS",
"SNAPSHOT REQUEST QUEUED");
final ClientResponseImpl resp =
new ClientResponseImpl(ClientResponseImpl.SUCCESS,
new VoltTable[] {result},
"User-requested truncation snapshot successfully queued for execution.",
clientHandle);
ByteBuffer buf = ByteBuffer.allocate(resp.getSerializedSize() + 4);
buf.putInt(buf.capacity() - 4);
resp.flattenToBuffer(buf).flip();
c.writeStream().enqueue(buf);
}
}
if (requestExists) {
VoltTable result = SnapshotUtil.constructNodeResultsTable();
result.addRow(-1,
CoreUtils.getHostnameOrAddress(),
"",
"FAILURE",
"SNAPSHOT IN PROGRESS");
throw new ForwardClientException("A request to perform a user snapshot already exists", result);
}
}
/**
* Try to create the ZK node to request the snapshot.
*
* @param snapInfo SnapshotInitiationInfo object with the requested snapshot initiation settings
* @return The request ID if succeeded, otherwise null.
*/
private String createRequestNode(SnapshotInitiationInfo snapInfo)
{
String requestId = null;
try {
requestId = java.util.UUID.randomUUID().toString();
if (!snapInfo.isTruncationRequest()) {
final JSONObject jsObj = snapInfo.getJSONObjectForZK();
jsObj.put("requestId", requestId);
String zkString = jsObj.toString(4);
byte zkBytes[] = zkString.getBytes("UTF-8");
m_zk.create(VoltZK.user_snapshot_request, zkBytes, Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
}
else {
m_zk.create(VoltZK.request_truncation_snapshot, null, Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
}
} catch (KeeperException.NodeExistsException e) {
return null;
} catch (Exception e) {
VoltDB.crashLocalVoltDB("Exception while attempting to create user snapshot request in ZK", true, e);
}
return requestId;
}
private void registerUserSnapshotResponseWatch(
final String requestId,
final long clientHandle,
final Connection c,
final boolean notifyChanges) throws Exception {
final String responseNode = VoltZK.user_snapshot_response + requestId;
Stat exists = m_zk.exists(responseNode, new Watcher() {
@Override
public void process(final WatchedEvent event) {
if (event.getState() == KeeperState.Disconnected) return;
switch (event.getType()) {
case NodeCreated:
m_es.submit(new Runnable() {
@Override
public void run() {
try {
processUserSnapshotRequestResponse(
event,
clientHandle,
c,
notifyChanges);
} catch (Exception e) {
VoltDB.crashLocalVoltDB(
"Error retrieving user snapshot request response from ZK",
true,
e);
}
}
});
break;
default:
}
}
});
if (exists != null) {
processUserSnapshotRequestResponse(
new WatchedEvent(
EventType.NodeCreated,
KeeperState.SyncConnected,
responseNode),
clientHandle,
c,
notifyChanges);
}
}
void processUserSnapshotRequestResponse(
final WatchedEvent event,
final long clientHandle,
final Connection c,
final boolean notifyChanges) throws Exception {
byte responseBytes[] = m_zk.getData(event.getPath(), false, null);
try {
m_zk.delete(event.getPath(), -1, null, null);
} catch (Exception e) {
SNAP_LOG.error("Error cleaning up user snapshot request response in ZK", e);
}
ByteBuffer buf = ByteBuffer.wrap(responseBytes);
ClientResponseImpl response = new ClientResponseImpl();
response.initFromBuffer(buf);
response.setClientHandle(clientHandle);
// Not sure if we need to preserve the original byte buffer here, playing it safe
ByteBuffer buf2 = ByteBuffer.allocate(response.getSerializedSize() + 4);
buf2.putInt(buf2.capacity() - 4);
response.flattenToBuffer(buf2).flip();
c.writeStream().enqueue(buf2);
/*
* If the caller wants to be notified of final results for the snapshot
* request, set up a watcher only if the snapshot is queued.
*/
if (notifyChanges && (response.getStatus() == ClientResponse.SUCCESS) &&
SnapshotUtil.isSnapshotQueued(response.getResults())) {
Watcher watcher = new Watcher() {
@Override
public void process(final WatchedEvent event) {
if (event.getState() == KeeperState.Disconnected) return;
switch (event.getType()) {
case NodeCreated:
m_es.submit(new Runnable() {
@Override
public void run() {
try {
processUserSnapshotRequestResponse(
event,
clientHandle,
c,
false);
} catch (Exception e) {
VoltDB.crashLocalVoltDB(
"Error retrieving user snapshot request response from ZK",
true,
e);
}
}
});
break;
default:
}
}
};
// Set the watcher
if (m_zk.exists(event.getPath(), watcher) != null) {
processUserSnapshotRequestResponse(event, clientHandle, c, false);
}
}
}
@Override
public CountDownLatch snapshotCompleted(final SnapshotCompletionEvent event) {
if (!event.truncationSnapshot) {
return new CountDownLatch(0);
}
final CountDownLatch latch = new CountDownLatch(1);
m_es.execute(new Runnable() {
@Override
public void run() {
try {
TruncationSnapshotAttempt snapshotAttempt = m_truncationSnapshotAttempts.get(event.multipartTxnId);
if (snapshotAttempt == null) {
snapshotAttempt = new TruncationSnapshotAttempt();
snapshotAttempt.path = event.path;
snapshotAttempt.nonce = event.nonce;
m_truncationSnapshotAttempts.put(event.multipartTxnId, snapshotAttempt);
}
snapshotAttempt.finished = true;
groomTruncationSnapshots();
} finally {
latch.countDown();
}
}
});
return latch;
}
}
|
package gui.projectwindow;
import common.ClassLoaderUtil;
import jade.wrapper.AgentContainer;
import jade.wrapper.AgentController;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.Observable;
import java.util.Observer;
import java.util.Properties;
import java.util.Vector;
import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.filechooser.FileNameExtensionFilter;
import application.Application;
import application.Project;
public class ProjectResources extends JPanel implements ActionListener, Observer {
private static final long serialVersionUID = 1L;
private Project currProjet = null;
private JList jListResources = null;
private JButton jButtonAdd = null;
private JButton jButtonRemove = null;
DefaultListModel myModel=null;
private JButton jButton = null;
/**
* This is the default constructor
*/
public ProjectResources(Project cp) {
super();
currProjet = cp;
initialize();
myModel=new DefaultListModel();
jListResources.setModel(myModel);
;
}
private String adjustString(String path)
{
final String projectFolder=currProjet.getProjectFolder();
if(path.contains(projectFolder))
{
int find=path.indexOf(projectFolder);
return path.substring(find-1);
}
return path;
}
private boolean alreay_there(String path)
{
return currProjet.projectResources.contains(path);
}
private Vector<String> adjustPaths(File[] files)
{
Vector<String> result=new Vector<String>();
if(files!=null)
{
for(File file : files)
{
String path=file.getAbsolutePath();
if(!path.contains(".jar"))
{
Vector<String> directoryFiles=handleDirectories(file);
for(String foreignJar : directoryFiles)
{
if(!alreay_there(foreignJar))
{
result.add(this.adjustString(foreignJar)); // Use relative paths within projects
}
}
}
else
{
if(!alreay_there(path))
{
result.add(this.adjustString(path)); // Use absolut within projects
}
}
}
}
return result;
}
/**
* This method initializes this
*
* @return void
*/
private void initialize() {
GridBagConstraints gridBagConstraints11 = new GridBagConstraints();
gridBagConstraints11.gridx = 3;
gridBagConstraints11.gridy = 0;
GridBagConstraints gridBagConstraints2 = new GridBagConstraints();
gridBagConstraints2.gridx = 2;
gridBagConstraints2.gridy = 0;
GridBagConstraints gridBagConstraints1 = new GridBagConstraints();
gridBagConstraints1.gridx = 1;
gridBagConstraints1.gridy = 0;
GridBagConstraints gridBagConstraints = new GridBagConstraints();
gridBagConstraints.fill = GridBagConstraints.BOTH;
gridBagConstraints.gridy = 0;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
gridBagConstraints.insets = new Insets(20, 20, 20, 20);
gridBagConstraints.gridx = 0;
this.setSize(581, 273);
this.setLayout(new GridBagLayout());
this.add(getJListResources(), gridBagConstraints);
this.add(getJButtonAdd(), gridBagConstraints1);
this.add(getJButtonRemove(), gridBagConstraints2);
this.add(getJButton(), gridBagConstraints11);
}
private Vector<String> handleDirectories(File dir)
{
Vector<String> result=new Vector<String>();
try
{
result.add(dir.getAbsolutePath());
File[] possibleJars = dir.listFiles(); // Find all Files
for(File possibleJar : possibleJars)
{
if(possibleJar.getAbsolutePath().contains(".jar"))
{
//result.add(possibleJar.getAbsolutePath());
//ClassLoaderUtil.addFile(possibleJar);
}
}
}
catch(Exception e)
{
e.printStackTrace();
}
return result;
}
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
}
@Override
public void update(Observable o, Object arg) {
// TODO Auto-generated method stub
}
/**
* This method initializes jListResources
*
* @return javax.swing.JList
*/
private JList getJListResources() {
if (jListResources == null) {
jListResources = new JList();
}
return jListResources;
}
/**
* This method initializes jButtonAdd
*
* @return javax.swing.JButton
*/
private JButton getJButtonAdd() {
if (jButtonAdd == null) {
jButtonAdd = new JButton();
jButtonAdd.setText("Add");
jButtonAdd.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent e) {
JFileChooser chooser=new JFileChooser();
chooser.setCurrentDirectory(new File(currProjet.getProjectFolderFullPath()));
FileNameExtensionFilter filter = new FileNameExtensionFilter("jar","JAR");
chooser.setFileFilter(filter);
chooser.setMultiSelectionEnabled(true);
chooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
chooser.setAcceptAllFileFilterUsed(false);
chooser.showDialog(jButtonAdd, "Load Files");
Vector<String > names=adjustPaths(chooser.getSelectedFiles());
currProjet.projectResources.addAll(names);
for(String name: names)
{
myModel.addElement(name);
}
// myModel.addElement(names);
jListResources.updateUI();
currProjet.setChangedAndNotify("projectResources");
}
});
}
return jButtonAdd;
}
/**
* This method initializes jButtonRemove
*
* @return javax.swing.JButton
*/
private JButton getJButtonRemove() {
if (jButtonRemove == null) {
jButtonRemove = new JButton();
jButtonRemove.setText("Remove");
jButtonRemove.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent e) {
System.out.println( jListResources.getSelectedValue());
Object [] values= jListResources.getSelectedValues();
//Remove from the classpath
if(values!=null)
{
for(Object file: values)
{
myModel.removeElement(file);
currProjet.projectResources.remove(file);
String jarFile=(String) file;
jarFile=ClassLoaderUtil.adjustPathForLoadin(jarFile, currProjet.getProjectFolder(), currProjet.getProjectFolderFullPath());
try {
ClassLoaderUtil.removeFile(jarFile);
} catch (RuntimeException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (NoSuchFieldException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IllegalAccessException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
currProjet.setChangedAndNotify("projectResources");
}
}
});
}
return jButtonRemove;
}
/**
* This method initializes jButton
*
* @return javax.swing.JButton
*/
private JButton getJButton() {
if (jButton == null) {
jButton = new JButton();
jButton.setText("Load");
jButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent e) {
String [] res=new String[jListResources.getSelectedValues().length];
for(Object obj:jListResources.getSelectedValues())
{
int index=0;
String test=obj.toString();
res[index]=test;
index++;
}
try {
//D:\\JadeAgent\\AgentGUI\\projects\\bla\\
Vector<String> allClasses=new Vector<String>();
ClassLoaderUtil.addFile(Application.RunInfo.PathJade(true));
for(String selectedJar: res)
{
File file = null;
selectedJar=ClassLoaderUtil.adjustPathForLoadin(selectedJar, currProjet.getProjectFolder(), currProjet.getProjectFolderFullPath());
file=new File(selectedJar);
URL url=file.toURI().toURL();
if(url.getPath().contains(".jar"))
{
ClassLoaderUtil.addFile(file.getAbsoluteFile());
Vector<String> classNames=ClassLoaderUtil.getClassNamesFromJar(url);
allClasses.addAll(classNames);
}
}
Application.JadePlatform.jadeStart();
AgentContainer container=Application.JadePlatform.MASmc;
//Application.JadePlatform.jadeAgentStart(className, className);
//Application.JadePlatform.jadeAgentStart(className, c, null, container.getContainerName());
Vector<AgentController> controller=ClassLoaderUtil.loadAgentsIntoContainer(allClasses, container);
// System.out.println("ClassPath:"+Application.RunInfo.getClassPathEntries());
//Application.RunInfo.getJadeDefaultPlatformConfig().
for(AgentController control: controller)
{
if(control.getName().contains("StartAgent"))
{
// control.start();
}
}
} catch (Exception e1) {
// TODO Auto-generated catch block
System.out.println("Fehler:"+e1.getMessage());
e1.printStackTrace();
} catch (Throwable e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
}
});
}
return jButton;
}
} // @jve:decl-index=0:visual-constraint="-105,-76"
|
package io.miti.shortstop.util;
public final class HeaderField
{
/** Request header fields. */
public static final String REQ_ACCEPT = "Accept";
public static final String REQ_ACCEPT_CHARSET = "Accept-Charset";
public static final String REQ_ACCEPT_ENCODING = "Accept-Encoding";
public static final String REQ_ACCEPT_LANGUAGE = "Accept-Language";
public static final String REQ_ACCEPT_DATETIME = "Accept-Datetime";
public static final String REQ_AUTHORIZATION = "Authorization";
public static final String REQ_CACHE_CONTROL = "Cache-Control";
public static final String REQ_CONNECTION = "Connection";
public static final String REQ_COOKIE = "Cookie";
public static final String REQ_CONTENT_LENGTH = "Content-Length";
public static final String REQ_CONTENT_MD5 = "Content-MD5";
public static final String REQ_CONTENT_TYPE = "Content-Type";
public static final String REQ_DATE = "Date";
public static final String REQ_EXPECT = "Expect";
public static final String REQ_FROM = "From";
public static final String REQ_HOST = "Host";
public static final String REQ_IF_MATCH = "If-Match";
public static final String REQ_IF_MODIFIED_SINCE = "If-Modified-Since";
public static final String REQ_IF_NONE_MATCH = "If-None-Match";
public static final String REQ_IF_RANGE = "If-Range";
public static final String REQ_IF_UNMODIFIED_SINCE = "If-Unmodified-Since";
public static final String REQ_MAX_FORWARDS = "Max-Forwards";
public static final String REQ_ORIGIN = "Origin";
public static final String REQ_PRAGMA = "Pragma";
public static final String REQ_PROXY_AUTHORIZATION = "Proxy-Authorization";
public static final String REQ_RANGE = "Range";
public static final String REQ_REFERER = "Referer";
public static final String REQ_TE = "TE";
public static final String REQ_USER_AGENT = "User-Agent";
public static final String REQ_UPGRADE = "Upgrade";
public static final String REQ_VIA = "Via";
public static final String REQ_WARNING = "Warning";
/** Response header fields. */
public static final String RES_ACCESS_CONTROL_ALLOW_ORIGIN = "Access-Control-Allow-Origin";
public static final String RES_ACCEPT_PATCH = "Accept-Patch";
public static final String RES_ACCEPT_RANGES = "Accept-Ranges";
public static final String RES_AGE = "Age";
public static final String RES_ALLOW = "Allow";
public static final String RES_CACHE_CONTROL = "Cache-Control";
public static final String RES_CONNECTION = "Connection";
public static final String RES_CONTENT_DISPOSITION = "Content-Disposition";
public static final String RES_CONTENT_ENCODING = "Content-Encoding";
public static final String RES_CONTENT_LANGUAGE = "Content-Language";
public static final String RES_CONTENT_LENGTH = "Content-Length";
public static final String RES_CONTENT_LOCATION = "Content-Location";
public static final String RES_CONTENT_MD5 = "Content-MD5";
public static final String RES_CONTENT_RANGE = "Content-Range";
public static final String RES_CONTENT_TYPE = "Content-Type";
public static final String RES_DATE = "Date";
public static final String RES_ETAG = "ETag";
public static final String RES_EXPIRES = "Expires";
public static final String RES_LAST_MODIFIED = "Last-Modified";
public static final String RES_LINK = "Link";
public static final String RES_LOCATION = "Location";
public static final String RES_P3P = "P3P";
public static final String RES_PRAGMA = "Pragma";
public static final String RES_PROXY_AUTHENTICATE = "Proxy-Authenticate";
public static final String RES_PUBLIC_KEY_PINS = "Public-Key-Pins";
public static final String RES_REFRESH = "Refresh";
public static final String RES_RETRY_AFTER = "Retry-After";
public static final String RES_SERVER = "Server";
public static final String RES_SET_COOKIE = "Set-Cookie";
public static final String RES_STATUS = "Status";
public static final String RES_STRICT_TRANSPORT_SECURITY = "Strict-Transport-Security";
public static final String RES_TRAILER = "Trailer";
public static final String RES_TRANSFER_ENCODING = "Transfer-Encoding";
public static final String RES_UPGRADE = "Upgrade";
public static final String RES_VARY = "Vary";
public static final String RES_VIA = "Via";
public static final String RES_WARNING = "Warning";
public static final String RES_WWW_AUTHENTICATE = "WWW-Authenticate";
public static final String RES_X_FRAME_OPTIONS = "X-Frame-Options";
/** Make the default constructor private. */
private HeaderField() {
super();
}
}
|
package org.httpkit.client;
import org.httpkit.*;
import org.httpkit.ProtocolException;
import org.httpkit.logger.ContextLogger;
import org.httpkit.logger.EventNames;
import org.httpkit.logger.EventLogger;
import javax.net.ssl.SNIHostName;
import javax.net.ssl.SNIServerName;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLEngine;
import javax.net.ssl.SSLException;
import javax.net.ssl.SSLParameters;
import java.io.IOException;
import java.net.*;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Queue;
import java.util.Set;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.atomic.AtomicInteger;
import static java.lang.System.currentTimeMillis;
import static java.nio.channels.SelectionKey.*;
import static org.httpkit.HttpUtils.SP;
import static org.httpkit.HttpUtils.getServerAddr;
import static org.httpkit.client.State.ALL_READ;
import static org.httpkit.client.State.READ_INITIAL;
public class HttpClient implements Runnable {
private static final AtomicInteger ID = new AtomicInteger(0);
public static final SSLContext DEFAULT_CONTEXT;
static {
try {
DEFAULT_CONTEXT = SSLContext.getDefault();
} catch (NoSuchAlgorithmException e) {
throw new Error("Failed to initialize SSLContext", e);
}
}
// queue request, for only issue connection in the IO thread
private final Queue<Request> pending = new ConcurrentLinkedQueue<Request>();
// ongoing requests, saved for timeout check
private final PriorityQueue<Request> requests = new PriorityQueue<Request>();
// reuse TCP connection
private final PriorityQueue<PersistentConn> keepalives = new PriorityQueue<PersistentConn>();
private final long maxConnections;
private volatile long numConnections = 0;
private volatile boolean running = true;
// shared, single thread
private final ByteBuffer buffer = ByteBuffer.allocateDirect(1024 * 64);
private final Selector selector;
private final ContextLogger<String, Throwable> errorLogger;
private final EventLogger<String> eventLogger;
private final EventNames eventNames;
public static interface AddressFinder {
InetSocketAddress findAddress(URI uri) throws UnknownHostException;
}
private final AddressFinder addressFinder;
public static final AddressFinder DEFAULT_ADDRESS_FINDER = new AddressFinder() {
public InetSocketAddress findAddress(URI uri) throws UnknownHostException {
return getServerAddr(uri);
}
};
public HttpClient() throws IOException {
this(-1);
}
public HttpClient(long maxConnections, AddressFinder addressFinder,
ContextLogger<String, Throwable> errorLogger,
EventLogger<String> eventLogger, EventNames eventNames) throws IOException {
this.addressFinder = addressFinder;
this.errorLogger = errorLogger;
this.eventLogger = eventLogger;
this.eventNames = eventNames;
int id = ID.incrementAndGet();
String name = "client-loop";
if (id > 1) {
name = name + "
}
this.maxConnections = maxConnections;
selector = Selector.open();
Thread t = new Thread(this, name);
t.setDaemon(true);
t.start();
}
public HttpClient(long maxConnections) throws IOException {
this(maxConnections, DEFAULT_ADDRESS_FINDER, ContextLogger.ERROR_PRINTER, EventLogger.NOP, EventNames.DEFAULT);
}
private void clearTimeout(long now) {
Request r;
while ((r = requests.peek()) != null) {
if (r.isTimeout(now)) {
boolean connected = r.isConnected();
String msg = connected ? "idle timeout: " : "connect timeout: ";
long timeout = connected ? r.cfg.idleTimeout : r.cfg.connTimeout;
// will remove it from queue
r.finish(new TimeoutException(msg + timeout + "ms"));
if (r.key != null) {
closeQuietly(r.key);
}
} else {
break;
}
}
PersistentConn pc;
while ((pc = keepalives.peek()) != null) {
if (pc.isTimeout(now)) {
closeQuietly(pc.key);
keepalives.poll();
} else {
break;
}
}
}
/**
* http-kit think all connections are keep-alived (since some say it is, but
* actually is not). but, some are not, http-kit pick them out after the fact
* <ol>
* <li>The connection is reused</li>
* <li>No data received</li>
* </ol>
*/
private boolean cleanAndRetryIfBroken(SelectionKey key, Request req) {
closeQuietly(key);
keepalives.remove(key);
// keep-alived connection, remote server close it without sending byte
if (req.isReuseConn && req.decoder.state == READ_INITIAL) {
for (ByteBuffer b : req.request) {
b.position(0); // reset for retry
}
req.isReuseConn = false;
requests.remove(req); // remove from timeout queue
pending.offer(req); // queue for retry
selector.wakeup();
return true; // retry: re-open a connection to server, sent the request again
}
return false;
}
private void doRead(SelectionKey key, long now) {
Request req = (Request) key.attachment();
SocketChannel ch = (SocketChannel) key.channel();
int read = 0;
try {
buffer.clear();
if (req instanceof HttpsRequest) {
HttpsRequest httpsReq = (HttpsRequest) req;
if (httpsReq.handshaken) {
// SSLEngine closed => fine, will return -1 in the next run
read = httpsReq.unwrapRead(buffer);
} else {
read = httpsReq.doHandshake(buffer);
}
} else {
read = ch.read(buffer);
}
} catch (IOException e) { // The remote forcibly closed the connection
if (!cleanAndRetryIfBroken(key, req)) {
req.finish(e); // os X get Connection reset by peer error,
}
// java.security.InvalidAlgorithmParameterException: Prime size must be multiple of 64, and can only range from 512 to 1024 (inclusive)
// java.lang.RuntimeException: Could not generate DH keypair
} catch (Exception e) {
req.finish(e);
}
if (read == -1) { // read all, remote closed it cleanly
if (!cleanAndRetryIfBroken(key, req)) {
req.finish();
}
} else if (read > 0) {
req.onProgress(now);
buffer.flip();
try {
if (req.decoder.decode(buffer) == ALL_READ) {
req.finish();
if (req.cfg.keepAlive > 0) {
keepalives.offer(new PersistentConn(now + req.cfg.keepAlive, req.addr, key));
} else {
closeQuietly(key);
}
}
} catch (HTTPException e) {
closeQuietly(key);
req.finish(e);
} catch (Exception e) {
closeQuietly(key);
req.finish(e);
errorLogger.log("should not happen", e); // decoding
eventLogger.log(eventNames.clientImpossible);
}
}
}
private void closeQuietly(SelectionKey key) {
try {
// TODO engine.closeInbound
key.channel().close();
} catch (Exception ignore) {
}
numConnections
}
private void doWrite(SelectionKey key, long now) {
// TODO [#327]: call `onProgress(now)` on write progress?
Request req = (Request) key.attachment();
SocketChannel ch = (SocketChannel) key.channel();
try {
if (req instanceof HttpsRequest) {
HttpsRequest httpsReq = (HttpsRequest) req;
if (httpsReq.handshaken) {
// will flip to OP_READ
httpsReq.writeWrappedRequest();
} else {
buffer.clear();
if (httpsReq.doHandshake(buffer) < 0) {
req.finish(); // will be a No status exception
}
}
} else {
ByteBuffer[] buffers = req.request;
ch.write(buffers);
if (!buffers[buffers.length - 1].hasRemaining()) {
key.interestOps(OP_READ);
}
}
} catch (IOException e) {
if (!cleanAndRetryIfBroken(key, req)) {
req.finish(e);
}
} catch (Exception e) { // rarely happen
req.finish(e);
}
}
public void exec(String url, RequestConfig cfg, SSLEngine engine, IRespListener cb) {
URI uri,proxyUri = null;
try {
uri = new URI(url);
if (cfg.proxy_url != null) {
proxyUri = new URI(cfg.proxy_url);
}
} catch (URISyntaxException e) {
cb.onThrowable(e);
return;
}
if (uri.getHost() == null) {
cb.onThrowable(new IllegalArgumentException("host is null: " + url));
return;
}
String scheme = uri.getScheme();
if (!"http".equals(scheme) && !"https".equals(scheme)) {
String message = (scheme == null) ? "No protocol specified" : scheme + " is not supported";
cb.onThrowable(new ProtocolException(message));
return;
}
InetSocketAddress addr;
try {
if (proxyUri == null) {
addr = addressFinder.findAddress(uri);
} else {
addr = addressFinder.findAddress(proxyUri);
}
} catch (UnknownHostException e) {
cb.onThrowable(e);
return;
}
// copy to modify, normalize header
HeaderMap headers = HeaderMap.camelCase(cfg.headers);
if (!headers.containsKey("Host")) // if caller set it explicitly, let he do it
headers.put("Host", HttpUtils.getHost(uri));
/**
* commented on 2014/3/18: Accept is not required
*/
// if (!headers.containsKey("Accept")) // allow override
// headers.put("Accept", "*/*");
if (!headers.containsKey("User-Agent")) // allow override
headers.put("User-Agent", RequestConfig.DEFAULT_USER_AGENT); // default
if (!headers.containsKey("Accept-Encoding"))
headers.put("Accept-Encoding", "gzip, deflate"); // compression is good
ByteBuffer request[];
try {
if (proxyUri == null) {
request = encode(cfg.method, headers, cfg.body, HttpUtils.getPath(uri));
} else {
String proxyScheme = proxyUri.getScheme();
headers.put("Proxy-Connection","Keep-Alive");
if (("http".equals(proxyScheme) && ! "https".equals(scheme)) || cfg.tunnel == false) {
request = encode(cfg.method, headers, cfg.body, uri.toString());
} else if ( "https".equals(proxyScheme) || "https".equals(scheme) ){
headers.put("Host", HttpUtils.getProxyHost(uri));
headers.put("Protocol","https");
HttpMethod https_method = cfg.tunnel == true ? HttpMethod.valueOf("CONNECT") : cfg.method;
request = encode(https_method, headers, cfg.body, HttpUtils.getProxyHost(uri));
} else {
String message = (proxyScheme == null) ? "No proxy protocol specified" : proxyScheme + " for proxy is not supported";
cb.onThrowable(new ProtocolException(message));
return;
}
}
} catch (IOException e) {
cb.onThrowable(e);
return;
}
if ((proxyUri == null && "https".equals(scheme))
|| (proxyUri != null && "https".equals(proxyUri.getScheme()))) {
if (engine == null) {
engine = DEFAULT_CONTEXT.createSSLEngine();
}
if(!engine.getUseClientMode())
engine.setUseClientMode(true);
SSLParameters sslParameters = engine.getSSLParameters();
SNIServerName hostName = new SNIHostName(uri.getHost());
List<SNIServerName> list = new ArrayList<SNIServerName>();
list.add(hostName);
sslParameters.setServerNames(list);
engine.setSSLParameters(sslParameters);
pending.offer(new HttpsRequest(addr, request, cb, requests, cfg, engine));
} else {
pending.offer(new Request(addr, request, cb, requests, cfg));
}
// pending.offer(new Request(addr, request, cb, requests, cfg));
selector.wakeup();
}
private ByteBuffer[] encode(HttpMethod method, HeaderMap headers, Object body,
String path) throws IOException {
ByteBuffer bodyBuffer = HttpUtils.bodyBuffer(body);
if (body != null) {
headers.putOrReplace("Content-Length", Integer.toString(bodyBuffer.remaining()));
} else {
headers.putOrReplace("Content-Length", "0");
}
DynamicBytes bytes = new DynamicBytes(196);
bytes.append(method.toString()).append(SP).append(path);
bytes.append(" HTTP/1.1\r\n");
headers.encodeHeaders(bytes);
ByteBuffer headBuffer = ByteBuffer.wrap(bytes.get(), 0, bytes.length());
if (bodyBuffer == null) {
return new ByteBuffer[]{headBuffer};
} else {
return new ByteBuffer[]{headBuffer, bodyBuffer};
}
}
private void finishConnect(SelectionKey key, long now) {
SocketChannel ch = (SocketChannel) key.channel();
Request req = (Request) key.attachment();
try {
if (ch.finishConnect()) {
req.setConnected(true);
req.onProgress(now);
key.interestOps(OP_WRITE);
if (req instanceof HttpsRequest) {
((HttpsRequest) req).engine.beginHandshake();
}
}
} catch (IOException e) {
closeQuietly(key); // not added to kee-alive yet;
req.finish(e);
}
}
private void processPending() {
Request job = pending.peek();
if (job != null) {
if (job.cfg.keepAlive > 0) {
PersistentConn con = keepalives.remove(job.addr);
if (con != null) { // keep alive
SelectionKey key = con.key;
if (key.isValid()) {
job.isReuseConn = true;
// reuse key, engine
try {
job.recycle((Request) key.attachment());
key.attach(job);
key.interestOps(OP_WRITE);
requests.offer(job);
pending.poll();
return;
} catch (SSLException e) {
closeQuietly(key); // https wrap SSLException, start from fresh
}
} else {
// this should not happen often
closeQuietly(key);
}
}
}
if (maxConnections == -1 || numConnections < maxConnections) {
try {
pending.poll();
SocketChannel ch = SocketChannel.open();
ch.setOption(StandardSocketOptions.SO_KEEPALIVE, Boolean.TRUE);
ch.setOption(StandardSocketOptions.TCP_NODELAY, Boolean.TRUE);
ch.configureBlocking(false);
boolean connected = ch.connect(job.addr);
job.setConnected(connected);
numConnections++;
// if connection is established immediatelly, should wait for write. Fix
job.key = ch.register(selector, connected ? OP_WRITE : OP_CONNECT, job);
// save key for timeout check
requests.offer(job);
} catch (IOException e) {
job.finish(e);
// HttpUtils.printError("Try to connect " + job.addr, e);
}
}
}
}
public void run() {
while (running) {
try {
Request first = requests.peek();
long timeout = 2000;
if (first != null) {
timeout = Math.max(first.toTimeout(currentTimeMillis()), 200L);
}
int select = selector.select(timeout);
long now = currentTimeMillis();
if (select > 0) {
Set<SelectionKey> selectedKeys = selector.selectedKeys();
Iterator<SelectionKey> ite = selectedKeys.iterator();
while (ite.hasNext()) {
SelectionKey key = ite.next();
if (!key.isValid()) {
continue;
}
if (key.isConnectable()) {
finishConnect(key, now);
} else if (key.isReadable()) {
doRead(key, now);
} else if (key.isWritable()) {
doWrite(key, now);
}
ite.remove();
}
}
clearTimeout(now);
processPending();
} catch (Throwable e) { // catch any exception (including OOM), print it: do not exits the loop
errorLogger.log("select exception, should not happen", e);
eventLogger.log(eventNames.clientImpossible);
}
}
}
public void stop() throws IOException {
running = false;
if (selector != null) {
selector.close();
}
}
@Override
public String toString() {
return this.getClass().getCanonicalName();
}
}
|
package bdv.viewer;
import bdv.TransformEventHandler3D;
import java.awt.event.KeyListener;
import org.scijava.ui.behaviour.KeyPressedManager;
import org.scijava.ui.behaviour.io.InputTriggerConfig;
import bdv.viewer.animate.MessageOverlayAnimator;
import bdv.viewer.render.AccumulateProjector;
import bdv.viewer.render.AccumulateProjectorARGB;
import bdv.viewer.render.AccumulateProjectorFactory;
import bdv.viewer.render.MultiResolutionRenderer;
import net.imglib2.realtransform.AffineTransform3D;
import net.imglib2.type.numeric.ARGBType;
import bdv.TransformEventHandlerFactory;
/**
* Optional parameters for {@link ViewerPanel}.
*
* @author Tobias Pietzsch
*/
public class ViewerOptions
{
public final Values values = new Values();
/**
* Create default {@link ViewerOptions}.
* @return default {@link ViewerOptions}.
*/
public static ViewerOptions options()
{
return new ViewerOptions();
}
/**
* Set width of {@link ViewerPanel} canvas.
*/
public ViewerOptions width( final int w )
{
values.width = w;
return this;
}
/**
* Set height of {@link ViewerPanel} canvas.
*/
public ViewerOptions height( final int h )
{
values.height = h;
return this;
}
/**
* Set the number and scale factors for scaled screen images.
*
* @param s
* Scale factors from the viewer canvas to screen images of
* different resolutions. A scale factor of 1 means 1 pixel in
* the screen image is displayed as 1 pixel on the canvas, a
* scale factor of 0.5 means 1 pixel in the screen image is
* displayed as 2 pixel on the canvas, etc.
* @see MultiResolutionRenderer
*/
public ViewerOptions screenScales( final double[] s )
{
values.screenScales = s;
return this;
}
/**
* Set target rendering time in nanoseconds.
*
* @param t
* Target rendering time in nanoseconds. The rendering time for
* the coarsest rendered scale should be below this threshold.
* @see MultiResolutionRenderer
*/
public ViewerOptions targetRenderNanos( final long t )
{
values.targetRenderNanos = t;
return this;
}
/**
* Set how many threads to use for rendering.
*
* @param n
* How many threads to use for rendering.
* @see MultiResolutionRenderer
*/
public ViewerOptions numRenderingThreads( final int n )
{
values.numRenderingThreads = n;
return this;
}
/**
* Set how many source groups there are initially.
*
* @param n
* How many source groups to create initially.
*/
public ViewerOptions numSourceGroups( final int n )
{
values.numSourceGroups = n;
return this;
}
/**
* Set whether volatile versions of sources should be used if available.
*
* @param v
* whether volatile versions of sources should be used if
* available.
* @see MultiResolutionRenderer
*/
public ViewerOptions useVolatileIfAvailable( final boolean v )
{
values.useVolatileIfAvailable = v;
return this;
}
public ViewerOptions msgOverlay( final MessageOverlayAnimator o )
{
values.msgOverlay = o;
return this;
}
public ViewerOptions transformEventHandlerFactory( final TransformEventHandlerFactory f )
{
values.transformEventHandlerFactory = f;
return this;
}
/**
* Set the factory for creating {@link AccumulateProjector}. This can be
* used to customize how sources are combined.
*
* @param f
* factory for creating {@link AccumulateProjector}.
* @see MultiResolutionRenderer
*/
public ViewerOptions accumulateProjectorFactory( final AccumulateProjectorFactory< ARGBType > f )
{
values.accumulateProjectorFactory = f;
return this;
}
/**
* Set the {@link InputTriggerConfig} from which keyboard and mouse action mapping is loaded.
*
* @param c the {@link InputTriggerConfig} from which keyboard and mouse action mapping is loaded
*/
public ViewerOptions inputTriggerConfig( final InputTriggerConfig c )
{
values.inputTriggerConfig = c;
return this;
}
/**
* Set the {@link KeyPressedManager} to share
* {@link KeyListener#keyPressed(java.awt.event.KeyEvent)} events with other
* ui-behaviour windows.
* <p>
* The goal is to make keyboard click/drag behaviours work like mouse
* click/drag: When a behaviour is initiated with a key press, the window
* under the mouse receives focus and the behaviour is handled there.
* </p>
*
* @param manager
* @return
*/
public ViewerOptions shareKeyPressedEvents( final KeyPressedManager manager )
{
values.keyPressedManager = manager;
return this;
}
/**
* Read-only {@link ViewerOptions} values.
*/
public static class Values
{
private int width = 800;
private int height = 600;
private double[] screenScales = new double[] { 1, 0.75, 0.5, 0.25, 0.125 };
private long targetRenderNanos = 30 * 1000000l;
private int numRenderingThreads = 3;
private int numSourceGroups = 10;
private boolean useVolatileIfAvailable = true;
private MessageOverlayAnimator msgOverlay = new MessageOverlayAnimator( 800 );
private TransformEventHandlerFactory transformEventHandlerFactory = TransformEventHandler3D::new;
private AccumulateProjectorFactory< ARGBType > accumulateProjectorFactory = AccumulateProjectorARGB.factory;
private InputTriggerConfig inputTriggerConfig = null;
private KeyPressedManager keyPressedManager = null;
public ViewerOptions optionsFromValues()
{
return new ViewerOptions().
width( width ).
height( height ).
screenScales( screenScales ).
targetRenderNanos( targetRenderNanos ).
numRenderingThreads( numRenderingThreads ).
numSourceGroups( numSourceGroups ).
useVolatileIfAvailable( useVolatileIfAvailable ).
msgOverlay( msgOverlay ).
transformEventHandlerFactory( transformEventHandlerFactory ).
accumulateProjectorFactory( accumulateProjectorFactory ).
inputTriggerConfig( inputTriggerConfig ).
shareKeyPressedEvents( keyPressedManager );
}
public int getWidth()
{
return width;
}
public int getHeight()
{
return height;
}
public double[] getScreenScales()
{
return screenScales;
}
public long getTargetRenderNanos()
{
return targetRenderNanos;
}
public int getNumRenderingThreads()
{
return numRenderingThreads;
}
public int getNumSourceGroups()
{
return numSourceGroups;
}
public boolean isUseVolatileIfAvailable()
{
return useVolatileIfAvailable;
}
public MessageOverlayAnimator getMsgOverlay()
{
return msgOverlay;
}
public TransformEventHandlerFactory getTransformEventHandlerFactory()
{
return transformEventHandlerFactory;
}
public AccumulateProjectorFactory< ARGBType > getAccumulateProjectorFactory()
{
return accumulateProjectorFactory;
}
public InputTriggerConfig getInputTriggerConfig()
{
return inputTriggerConfig;
}
public KeyPressedManager getKeyPressedManager()
{
return keyPressedManager;
}
}
}
|
package com.bats.batbelt;
import com.bats.batbelt.handler.ConfigHandler;
import com.bats.batbelt.handler.FuelHandler;
import com.bats.batbelt.reference.ModRef;
import com.bats.batbelt.register.BlockRegister;
import com.bats.batbelt.register.ItemRegister;
import com.bats.batbelt.register.RecipeRegister;
import cpw.mods.fml.common.FMLCommonHandler;
import cpw.mods.fml.common.Mod;
import cpw.mods.fml.common.Mod.EventHandler;
import cpw.mods.fml.common.Mod.Instance;
import cpw.mods.fml.common.event.FMLInitializationEvent;
import cpw.mods.fml.common.event.FMLPostInitializationEvent;
import cpw.mods.fml.common.event.FMLPreInitializationEvent;
import cpw.mods.fml.common.registry.GameRegistry;
import net.minecraftforge.common.MinecraftForge;
@Mod(modid = ModRef.MOD_ID, name = ModRef.MOD_NAME, version = ModRef.MOD_VERSION, dependencies = "required-after:Forge@[10.13.3.1395]")
public class BatBelt
{
@Instance(ModRef.MOD_ID)
public static BatBelt instance;
@EventHandler
public void preInit(FMLPreInitializationEvent event)
{
ConfigHandler.init(event.getSuggestedConfigurationFile());
FMLCommonHandler.instance().bus().register(new ConfigHandler());
ItemRegister.init();
BlockRegister.init();
}
@EventHandler
public void init(FMLInitializationEvent event)
{
RecipeRegister.init();
GameRegistry.registerFuelHandler(new FuelHandler());
}
@EventHandler
public void postInit(FMLPostInitializationEvent event)
{
}
}
|
/**
* Created Oct 16, 2007
*/
package com.crawljax.util;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import org.apache.commons.io.FileUtils;
import org.apache.log4j.Logger;
import org.custommonkey.xmlunit.DetailedDiff;
import org.custommonkey.xmlunit.Diff;
import org.custommonkey.xmlunit.Difference;
import org.cyberneko.html.parsers.DOMParser;
import org.w3c.dom.Attr;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
/**
* @author mesbah
* @version $Id$
*/
public final class Helper {
private static final int BASE_LENGTH = 3;
private static final int START_LENGTH = 7;
private static final int TEXT_CUTOFF = 50;
public static final Logger LOGGER = Logger.getLogger(Helper.class.getName());
private Helper() {
}
/**
* @param location
* TODO: DOCUMENT ME!
* @param link
* TODO: DOCUMENT ME!
* @return TODO: DOCUMENT ME!
*/
public static boolean isLinkExternal(String location, String link) {
boolean check = false;
if (location.startsWith("file") && link.startsWith("http")) {
return true;
}
if (link.startsWith("http") && location.startsWith("http")) {
String subLink = link.substring(START_LENGTH);
int index = subLink.indexOf("/");
if (index > -1) {
subLink = subLink.substring(0, index);
}
String subLoc = location.substring(START_LENGTH);
index = subLoc.indexOf("/");
if (index > -1) {
subLoc = subLoc.substring(0, subLoc.indexOf("/"));
}
if (!subLoc.equals(subLink)) {
check = true;
}
LOGGER.debug(subLink);
}
return check;
}
/**
* @param url
* the URL string.
* @return the base part of the URL.
*/
public static String getBaseUrl(String url) {
String temp = new String(url);
String head = temp.substring(0, temp.indexOf(":"));
String subLoc = url.substring(head.length() + BASE_LENGTH);
return head + "://" + subLoc.substring(0, subLoc.indexOf("/"));
}
/**
* transforms a string into a Document object.
*
* @param html
* the HTML string.
* @return The DOM Document version of the HTML string.
* @throws IOException
* if an IO failure occurs.
* @throws SAXException
* if an exception occurs while parsing the HTML string.
*/
public static Document getDocument(String html) throws SAXException, IOException {
DOMParser domParser = new DOMParser();
domParser.setProperty("http://cyberneko.org/html/properties/names/elems", "match");
domParser.parse(new InputSource(new StringReader(html)));
return domParser.getDocument();
}
/**
* @param html
* the HTML string.
* @return a Document object made from the HTML string.
* @throws SAXException
* if an exception occurs while parsing the HTML string.
* @throws IOException
* if an IO failure occurs.
*/
public static Document getDocumentNoBalance(String html) throws SAXException, IOException {
DOMParser domParser = new DOMParser();
domParser.setProperty("http://cyberneko.org/html/properties/names/elems", "match");
domParser.setFeature("http://cyberneko.org/html/features/balance-tags", false);
domParser.parse(new InputSource(new StringReader(html)));
return domParser.getDocument();
}
/**
* @param element
* The DOM Element.
* @return A string representation of all the element's attributes.
*/
public static String getAllElementAttributes(Element element) {
return getElementAttributes(element, new ArrayList<String>());
}
/**
* @param element
* The DOM Element.
* @param exclude
* the list of exclude strings.
* @return A string representation of the element's attributes excluding exclude.
*/
public static String getElementAttributes(Element element, List<String> exclude) {
StringBuffer buffer = new StringBuffer();
if (element != null) {
NamedNodeMap attributes = element.getAttributes();
for (int i = 0; i < attributes.getLength(); i++) {
Attr attr = (Attr) attributes.item(i);
if (!exclude.contains(attr.getNodeName())) {
buffer.append(attr.getNodeName() + "=");
buffer.append(attr.getNodeValue() + " ");
}
}
}
return buffer.toString().trim();
}
/**
* @param element
* the element.
* @return a string representation of the element including its attributes.
*/
public static String getElementString(Element element) {
if (element == null) {
return "";
}
String text = Helper.removeNewLines(Helper.getTextValue(element)).trim();
String info = "";
if (!text.equals("")) {
info += "\"" + text + "\" ";
// Helper.removeNewLines(this.text.trim()) + " - ";
}
if (element != null) {
if (element.hasAttribute("id")) {
info += "ID: " + element.getAttribute("id") + " ";
}
info += Helper.getAllElementAttributes(element) + " ";
}
return info;
}
/**
* @param document
* The Document object.
* @param filePathname
* the filename to write the document to.
*/
public static void writeDocumentToFile(Document document, String filePathname) {
try {
TransformerFactory tFactory = TransformerFactory.newInstance();
Transformer transformer = tFactory.newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
transformer.setOutputProperty(OutputKeys.METHOD, "text");
DOMSource source = new DOMSource(document);
Result result = new StreamResult(new FileOutputStream(filePathname));
transformer.transform(source, result);
} catch (TransformerConfigurationException e) {
LOGGER.error(e.getMessage(), e);
} catch (TransformerException e) {
LOGGER.error(e.getMessage(), e);
} catch (FileNotFoundException e) {
LOGGER.error(e.getMessage(), e);
}
}
/**
* @param dom
* the DOM document.
* @param xpath
* the xpath.
* @return The element found on DOM having the xpath position.
* @throws XPathExpressionException
* if the xpath fails.
*/
public static Element getElementByXpath(Document dom, String xpath)
throws XPathExpressionException {
XPath xp = XPathFactory.newInstance().newXPath();
xp.setNamespaceContext(new HtmlNamespace());
return (Element) xp.evaluate(xpath, dom, XPathConstants.NODE);
}
/**
* @param dom
* the DOM document.
* @param xpath
* the xpath.
* @return The element found on DOM having the xpath position.
* @throws XPathExpressionException
* if the xpath fails.
*/
public static NodeList getElementsByXpath(Document dom, String xpath)
throws XPathExpressionException {
XPath xp = XPathFactory.newInstance().newXPath();
return (NodeList) xp.evaluate(xpath, dom, XPathConstants.NODESET);
}
/**
* Removes all the <SCRIPT/> tags from the document.
*
* @param dom
* the document object.
* @return the changed dom.
*/
public static Document removeScriptTags(Document dom) {
if (dom != null) {
// NodeList list = dom.getElementsByTagName("SCRIPT");
NodeList list;
try {
list = Helper.getElementsByXpath(dom, "//SCRIPT");
while (list.getLength() > 0) {
Node sc = list.item(0);
if (sc != null) {
sc.getParentNode().removeChild(sc);
}
list = Helper.getElementsByXpath(dom, "//SCRIPT");
// list = dom.getElementsByTagName("SCRIPT");
}
} catch (XPathExpressionException e) {
LOGGER.error(e.getMessage(), e);
}
return dom;
}
return null;
}
/**
* Checks the existence of the directory. If it does not exist, the method creates it.
*
* @param dir
* the directory to check.
* @throws IOException
* if fails.
*/
public static void directoryCheck(String dir) throws IOException {
final File file = new File(dir);
if (!file.exists()) {
FileUtils.forceMkdir(file);
}
}
/**
* Checks whether the folder exists for fname, and creates it if neccessary TODO: anyone, check,
* probably does not work correctly.
*
* @param fname
* folder name.
* @throws IOException
* an IO exception.
*/
public static void checkFolderForFile(String fname) throws IOException {
if (fname.lastIndexOf("/") > 0) {
String folder = fname.substring(0, fname.lastIndexOf("/"));
Helper.directoryCheck(folder);
}
}
/**
* Retrieve the var value for varName from a HTTP query string (format is
* "var1=val1&var2=val2").
*
* @param varName
* the name.
* @param haystack
* the haystack.
* @return variable value for varName
*/
public static String getVarFromQueryString(String varName, String haystack) {
if (haystack == null || haystack.length() == 0) {
return null;
}
if (haystack.charAt(0) == '?') {
haystack = haystack.substring(1);
}
String[] vars = haystack.split("&");
for (String var : vars) {
String[] tuple = var.split("=");
if (tuple.length == 2 && tuple[0].equals(varName)) {
return tuple[1];
}
}
return null;
}
/**
* @param dom
* the DOM document.
* @return a string representation of the DOM.
*/
public static String getDocumentToString(Document dom) {
try {
Source source = new DOMSource(dom);
StringWriter stringWriter = new StringWriter();
Result result = new StreamResult(stringWriter);
TransformerFactory factory = TransformerFactory.newInstance();
Transformer transformer = factory.newTransformer();
transformer.transform(source, result);
return stringWriter.getBuffer().toString();
} catch (TransformerConfigurationException e) {
LOGGER.error(e.getMessage(), e);
} catch (TransformerException e) {
LOGGER.error(e.getMessage(), e);
}
return null;
}
/**
* Serialize the Document object.
*
* @param dom
* the document to serialize
* @return the serialized dom String
*/
public static byte[] getDocumentToByteArray(Document dom) {
try {
TransformerFactory tFactory = TransformerFactory.newInstance();
Transformer transformer = tFactory.newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
transformer.setOutputProperty(OutputKeys.METHOD, "html");
// TODO should be fixed to read doctype declaration
// transformer.setOutputProperty(OutputKeys.DOCTYPE_PUBLIC,
// "-//W3C//DTD XHTML 1.0 Transitional//EN\"
transformer.setOutputProperty(OutputKeys.DOCTYPE_PUBLIC,
"-//W3C//DTD XHTML 1.0 Strict//EN\" "
+ "\"http:
// transformer.setOutputProperty(OutputKeys.DOCTYPE_PUBLIC,
DOMSource source = new DOMSource(dom);
ByteArrayOutputStream out = new ByteArrayOutputStream();
Result result = new StreamResult(out);
transformer.transform(source, result);
// System.out.println("Injected Javascript!");
return out.toByteArray();
} catch (TransformerConfigurationException e) {
LOGGER.error(e.getMessage(), e);
} catch (TransformerException e) {
LOGGER.error(e.getMessage(), e);
}
return null;
}
/**
* Save a string to a file.
*
* @param filename
* The filename to save to.
* @param text
* The text to save.
* @param append
* Whether to append to existing file.
* @throws IOException
* On error.
*/
public static void writeToFile(String filename, String text, boolean append)
throws IOException {
FileWriter fw = new FileWriter(filename, append);
fw.write(text + "\n");
fw.close();
}
/**
* @param code
* hashcode.
* @return String version of hashcode.
*/
public static String hashCodeToString(long code) {
if (code < 0) {
return "0" + (code * -1);
} else {
return "" + code;
}
}
/**
* Returns the text value of an element (title, alt or contents). Note that the result is 50
* characters or less in length.
*
* @param element
* The element.
* @return The text value of the element.
*/
public static String getTextValue(Element element) {
String ret = "";
if (element == null) {
return "";
}
if (element.getTextContent() != null) {
ret = element.getTextContent();
} else if (element.hasAttribute("title")) {
ret = element.getAttribute("title");
} else if (element.hasAttribute("alt")) {
ret = element.getAttribute("alt");
}
if (ret.length() > TEXT_CUTOFF) {
return ret.substring(0, TEXT_CUTOFF);
} else {
return ret;
}
}
/**
* Get differences between doms.
*
* @param controlDom
* The control dom.
* @param testDom
* The test dom.
* @return The differences.
*/
@SuppressWarnings("unchecked")
public static List<Difference> getDifferences(String controlDom, String testDom) {
try {
Diff d = new Diff(Helper.getDocument(controlDom), Helper.getDocument(testDom));
DetailedDiff dd = new DetailedDiff(d);
return dd.getAllDifferences();
} catch (Exception e) {
LOGGER.error("Error with getDifferences: " + e.getMessage(), e);
}
return null;
}
/**
* Removes newlines from a string.
*
* @param html
* The string.
* @return The new string without the newlines or tabs.
*/
public static String removeNewLines(String html) {
return html.replaceAll("[\\t\\n\\x0B\\f\\r]", "");
}
/**
* Get the contents of a file.
*
* @param file
* The name of the file.
* @return The contents as a String.
*/
public static String getContent(File file) {
StringBuilder contents = new StringBuilder();
try {
BufferedReader input = new BufferedReader(new FileReader(file));
try {
String line = null; // not declared within while loop
while ((line = input.readLine()) != null) {
contents.append(line);
}
} finally {
input.close();
}
} catch (IOException e) {
LOGGER.error(e.getMessage(), e);
}
return contents.toString();
}
/**
* Filters attributes from the HTML string.
*
* @param html
* The HTML to filter.
* @return The filtered HTML string.
*/
public static String filterAttributes(String html) {
if (PropertyHelper.getCrawlFilterAttributesValues() != null) {
for (String attribute : PropertyHelper.getCrawlFilterAttributesValues()) {
String regex = "\\s" + attribute + "=\"[^\"]*\"";
Pattern p = Pattern.compile(regex, Pattern.CASE_INSENSITIVE);
Matcher m = p.matcher(html);
html = m.replaceAll("");
}
}
return html;
}
/**
* @param string
* The original string.
* @param regex
* The regular expression.
* @param replace
* What to replace it with.
* @return replaces regex in str by replace where the dot sign also supports newlines
*/
public static String replaceString(String string, String regex, String replace) {
Pattern p = Pattern.compile(regex, Pattern.DOTALL);
Matcher m = p.matcher(string);
return m.replaceAll(replace);
}
/**
* Adds a slash to a path if it doesn't end with a slash.
*
* @param folderName
* The path to append a possible slash.
* @return The new, correct path.
*/
public static String addFolderSlashIfNeeded(String folderName) {
if (!folderName.equals("") && !folderName.endsWith("/")) {
return folderName + "/";
} else {
return folderName;
}
}
/**
* Returns the filename in a path. For example with path = "foo/bar/crawljax.txt" returns
* "crawljax.txt"
*
* @param path
* @return the filename from the path
*/
private static String getFileNameInPath(String path) {
String fname;
if (path.indexOf("/") != -1) {
fname = path.substring(path.lastIndexOf("/") + 1);
} else {
fname = path;
}
return fname;
}
/**
* Retrieves the content of the filename. Also reads from JAR Searches for the resource in the
* root folder in the jar
*
* @param fname
* Filename.
* @return The contents of the file.
* @throws IOException
* On error.
*/
public static String getTemplateAsString(String fname) throws IOException {
// in .jar file
String fnameJar = getFileNameInPath(fname);
InputStream inStream = Helper.class.getResourceAsStream("/" + fnameJar);
if (inStream == null) {
// try to find file normally
File f = new File(fname);
if (f.exists()) {
inStream = new FileInputStream(f);
} else {
throw new IOException("Cannot find " + fname + " or " + fnameJar);
}
}
InputStreamReader streamReader = new InputStreamReader(inStream);
BufferedReader bufferedReader = new BufferedReader(streamReader);
String line;
StringBuilder stringBuilder = new StringBuilder();
while ((line = bufferedReader.readLine()) != null) {
stringBuilder.append(line + "\n");
}
return stringBuilder.toString();
}
/**
* @param xpath
* The xpath of the element.
* @return The JavaScript to get an element.
*/
public static String getJSGetElement(String xpath) {
String js =
""
+ "function ATUSA_getElementInNodes(nodes, tagName, number){"
+ "try{"
+ "var pos = 1;"
+ "for(i=0; i<nodes.length; i++){"
+ "if(nodes[i]!=null && nodes[i].tagName!=null && "
+ "nodes[i].tagName.toLowerCase() == tagName){"
+ "if(number==pos){"
+ "return nodes[i];"
+ "}else{"
+ "pos++;"
+ "}"
+ "}"
+ "}"
+ "}catch(e){}"
+ "return null;"
+ "}"
+ "function ATUSA_getElementByXpath(xpath){"
+ "try{"
+ "var elements = xpath.toLowerCase().split('/');"
+ "var curNode = document.body;"
+ "var tagName, number;"
+ "for(j=0; j<elements.length; j++){"
+ "if(elements[j]!=''){"
+ "if(elements[j].indexOf('[')==-1){"
+ "tagName = elements[j];"
+ "number = 1;"
+ "}else{"
+ "tagName = elements[j].substring(0, elements[j].indexOf('['));"
+ "number = elements[j].substring(elements[j].indexOf('[')+1, "
+ "elements[j].lastIndexOf(']'));"
+ "}"
+ "if(tagName!='body' && tagName!='html'){"
+ "curNode = ATUSA_getElementInNodes(curNode.childNodes, tagName, number);"
+ "if(curNode==null){" + "return null;" + "}" + "}" + "}" + "}"
+ "}catch(e){return null;}" + "return curNode;" + "}"
+ "try{var ATUSA_element = ATUSA_getElementByXpath('" + xpath
+ "');}catch(e){return null;}";
return js;
}
/**
* @param frame
* the frame element.
* @return the name or id of this element if they are present, otherwise null.
*/
public static String getFrameIdentification(Element frame) {
Attr attr = (Attr) frame.getAttributeNode("name");
if (attr != null && attr.getNodeValue() != null && !attr.getNodeValue().equals("")) {
return attr.getNodeValue();
}
attr = (Attr) frame.getAttributeNode("id");
if (attr != null && attr.getNodeValue() != null && !attr.getNodeValue().equals("")) {
return attr.getNodeValue();
}
return null;
}
/**
* @param document
* the document object.
* @param filePathname
* the path name of the file to be written to.
*/
public static void writeDocumentToHTMLFile(Document document, String filePathname) {
try {
Transformer transformer = TransformerFactory.newInstance().newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
transformer.setOutputProperty(OutputKeys.METHOD, "html");
Result result = new StreamResult(new FileOutputStream(filePathname));
transformer.transform(new DOMSource(document), result);
} catch (TransformerConfigurationException e) {
LOGGER.error(e.getMessage(), e);
} catch (TransformerException e) {
LOGGER.error(e.getMessage(), e);
} catch (FileNotFoundException e) {
LOGGER.error(e.getMessage(), e);
}
}
}
|
package com.dnw.depmap;
import org.eclipse.jdt.core.dom.MethodDeclaration;
import org.eclipse.jdt.core.dom.MethodInvocation;
import org.eclipse.jdt.core.dom.TypeDeclaration;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.jface.util.IPropertyChangeListener;
import org.eclipse.jface.util.PropertyChangeEvent;
import org.eclipse.ui.plugin.AbstractUIPlugin;
import org.osgi.framework.BundleContext;
import com.dnw.depmap.ast.MethodDeclarationVisitor;
import com.dnw.depmap.ast.MethodInvocationVisitor;
import com.dnw.depmap.ast.TypeDeclarationVisitor;
import com.dnw.depmap.neo.NeoDao;
import com.dnw.depmap.neo.NeoWriter;
import com.dnw.depmap.preferences.PrefKeys;
import com.dnw.depmap.resource.JavaFileVisitor;
import com.dnw.matcher.CompositeList;
import com.dnw.matcher.RegexMatcher;
import com.dnw.matcher.StringMatcher;
import com.dnw.neo.EmbeddedNeoAccessor;
import com.dnw.neo.NeoAccessor;
import com.dnw.neo.RestfulNeoAccessor;
import com.dnw.plugin.ast.GeneralVisitorRegistry;
import com.dnw.plugin.ast.IVisitorDelegator;
import com.dnw.plugin.ast.IVisitorRegistry;
import com.dnw.plugin.ast.NodeTypeBitMapSet;
import com.dnw.plugin.ast.RegistryBasedVisitorDelegator;
import com.dnw.plugin.resource.FileExtResourceVisitorFactory;
import com.dnw.plugin.util.ConsoleUtil;
/**
* The activator class controls the plug-in life cycle.
*
* @author manbaum
* @since Sep 29, 2014
*/
public class Activator extends AbstractUIPlugin {
// The plug-in ID
public static final String PLUGIN_ID = "com.dnw.depmap";
// The directory locates the Neo4j database store.
private static String DBPATH = "/Users/manbaum/workspace/neo4j-community-2.1.5/data/graph.db";
private static String DBURL = "http://localhost:7474/db/data";
private static boolean useEmbedded = false;
// The shared instance.
private static Activator plugin;
// The plug-in's console.
public static final ConsoleUtil console = ConsoleUtil.getConsole(PLUGIN_ID);
// This factory defines what kinds of files will be inspected in a project.
// For now, we only support .java files.
public static final FileExtResourceVisitorFactory factory = new FileExtResourceVisitorFactory();
// The white list to limit what packages or classes should be focused.
public static final CompositeList<String> filter = new CompositeList<String>();
// The AST node type set defines a stop set. (not used now)
// All nodes with its type in this set will be ignored, do not traverse it to improve the performance.
public static final NodeTypeBitMapSet stopSet = new NodeTypeBitMapSet();
// Register the corresponding AST visitor to visit the AST.
public static final IVisitorRegistry registry = new GeneralVisitorRegistry();
// Apply the stop set on the visitors.
public static final IVisitorDelegator delegator = new RegistryBasedVisitorDelegator(registry,
stopSet);
// TODO: the following setting should be put in a Eclipse preference page.
static {
factory.registerVisitor("java", JavaFileVisitor.class);
// factory.registerVisitor("xml", XmlFileVisitor.class);
// filter.addAllowMatcher(new StringMatcher("java.lang.Object"));
// filter.addAllowMatcher(new RegexMatcher("org\\.eclipse\\.jdt\\.core\\.dom\\..*"));
// filter.addAllowMatcher(new RegexMatcher("com\\.dnw\\..*"));
registry.add(TypeDeclaration.class, new TypeDeclarationVisitor());
registry.add(MethodDeclaration.class, new MethodDeclarationVisitor());
registry.add(MethodInvocation.class, new MethodInvocationVisitor());
}
// Neo4j database Cypher language executor.
public NeoAccessor accessor;
// Call Neo4j accessor to generate all AST nodes and its relations.
public NeoDao neo;
// If it's true, the database will be cleaned before AST traverse.
public static boolean preExec = false;
public static String[] statements = new String[0];
public IPropertyChangeListener listener;
/**
* Constructor of Activator.
*
* @author manbaum
* @since Sep 29, 2014
*/
public Activator() {
listener = new IPropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent event) {
loadPerference();
}
};
}
private void loadPerference() {
IPreferenceStore store = super.getPreferenceStore();
if (store.getBoolean(PrefKeys.P_USESTANDALONE)) {
useEmbedded = false;
DBURL = store.getString(PrefKeys.P_DBURL);
} else if (store.getBoolean(PrefKeys.P_USEEMBEDDED)) {
useEmbedded = true;
DBPATH = store.getString(PrefKeys.P_DBDIR);
} else {
useEmbedded = false;
DBURL = "http://localhost:7474/db/data";
store.setValue(PrefKeys.P_USESTANDALONE, true);
store.setValue(PrefKeys.P_DBURL, DBURL);
}
filter.clearAllows();
if (store.getBoolean(PrefKeys.P_USEWHITE)) {
String white = store.getString(PrefKeys.P_WHITELIST);
if (white != null) {
String[] list = white.split("\\s*;\\s*");
for (String s : list) {
console.println("allow: \"" + s + "\"");
if (s.startsWith("@"))
filter.addAllowMatcher(new StringMatcher(s.substring(1)));
else
filter.addAllowMatcher(new RegexMatcher(s));
}
}
}
filter.clearBlocks();
if (store.getBoolean(PrefKeys.P_USEBLACK)) {
String black = store.getString(PrefKeys.P_BLACKLIST);
if (black != null) {
String[] list = black.split("\\s*;\\s*");
for (String s : list) {
console.println("block: \"" + s + "\"");
if (s.startsWith("@"))
filter.addBlockMatcher(new StringMatcher(s.substring(1)));
else
filter.addBlockMatcher(new RegexMatcher(s));
}
}
}
preExec = store.getBoolean(PrefKeys.P_USEPREEXEC);
if (preExec) {
String ss = store.getString(PrefKeys.P_PREEXEC);
if (ss != null) {
statements = ss.split("\\s*;\\s*");
for (String s : statements) {
console.println("statement: \"" + s + "\"");
}
} else {
preExec = false;
}
}
accessor = useEmbedded ? new EmbeddedNeoAccessor(DBPATH) : new RestfulNeoAccessor(DBURL);
neo = new NeoDao(new NeoWriter(accessor), filter);
}
/**
* Starts up this plug-in.
*
* @author manbaum
* @since Sep 29, 2014
* @param context the bundle context for this plug-in.
* @throws Exception if this plug-in did not start up properly.
* @see org.eclipse.ui.plugin.AbstractUIPlugin#start(org.osgi.framework.BundleContext)
*/
@Override
public void start(BundleContext context) throws Exception {
super.start(context);
plugin = this;
loadPerference();
super.getPreferenceStore().addPropertyChangeListener(listener);
}
/**
* Stops this plug-in.
*
* @author manbaum
* @since Sep 29, 2014
* @param context the bundle context for this plug-in.
* @throws Exception if this plug-in did not stopped properly.
* @see org.eclipse.ui.plugin.AbstractUIPlugin#stop(org.osgi.framework.BundleContext)
*/
@Override
public void stop(BundleContext context) throws Exception {
super.getPreferenceStore().removePropertyChangeListener(listener);
accessor.shutdown();
plugin = null;
super.stop(context);
}
/**
* Returns the shared instance.
*
* @author manbaum
* @since Sep 29, 2014
* @return the shared instance.
*/
public static Activator getDefault() {
return plugin;
}
/**
* Exposes the database operations.
*
* @author manbaum
* @since Oct 13, 2014
* @return the DAO of Neo4j database.
*/
public static NeoDao neo() {
return plugin.neo;
}
/**
* Returns an image descriptor for the image file at the given plug-in relative path. The path
* must not have a leading "." or path separator. Clients should use a path like
* "icons/mysample.gif" rather than "./icons/mysample.gif" or "/icons/mysample.gif".
*
* @author manbaum
* @since Sep 29, 2014
* @param path the path.
* @return the image descriptor.
*/
public static ImageDescriptor getImageDescriptor(String path) {
return imageDescriptorFromPlugin(PLUGIN_ID, path);
}
}
|
package com.global;
import org.hibernate.service.spi.ServiceException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.DataAccessException;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.HttpMediaTypeNotSupportedException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import javax.servlet.http.HttpServletRequest;
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import javax.validation.ValidationException;
import java.sql.SQLException;
import java.util.Set;
@RestControllerAdvice
public class GlobalHandler {
private static final Logger LOGGER = LoggerFactory.getLogger(GlobalHandler.class);
@ResponseStatus(HttpStatus.UNAUTHORIZED)
@ExceptionHandler(AuthenticationException.class)
public ResponseEntity<String> handleAuthenticationException(AuthenticationException e) {
LOGGER.error("AuthenticationException:{}", e.getMessage(), e);
return ResponseEntity.badRequest().body(e.getMessage());
}
@ExceptionHandler(Exception.class)
public ResponseEntity<?> exceptionHandler(Throwable e) {
LOGGER.error(e.getMessage(), e);
if (e instanceof SQLException | e instanceof DataAccessException) {
return ResponseEntity.badRequest().body("The server is off.Please contact the developer");
}
return ResponseEntity.badRequest().body(e.getMessage());
}
@ExceptionHandler(BindException.class)
public ResponseEntity handleBindException(HttpServletRequest request, BindException e) {
StringBuilder result = new StringBuilder();
for (FieldError fieldError : e.getFieldErrors()) {
result.append(fieldError.getField()).append(":").
append(fieldError.getDefaultMessage()).
append(System.lineSeparator());
}
LOGGER.error("{}?{},{}", request.getRequestURI(), request.getQueryString(), result, e.getMessage());
return ResponseEntity.badRequest().body(result.toString());
}
/**
* 400 - Bad Request
*/
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ExceptionHandler(MissingServletRequestParameterException.class)
public ResponseEntity handleMissingServletRequestParameterException(MissingServletRequestParameterException e) {
LOGGER.error("", e);
return ResponseEntity.badRequest().body("required_parameter_is_not_present");
}
/**
* 400 - Bad Request
*/
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ExceptionHandler(HttpMessageNotReadableException.class)
public ResponseEntity handleHttpMessageNotReadableException(HttpMessageNotReadableException e) {
LOGGER.error("", e);
return ResponseEntity.badRequest().body("could_not_read_json");
}
/**
* 400 - Bad Request
*/
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ExceptionHandler(MethodArgumentNotValidException.class)
public ResponseEntity handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
LOGGER.error("", e);
BindingResult result = e.getBindingResult();
FieldError error = result.getFieldError();
String field = error.getField();
String code = error.getDefaultMessage();
String message = String.format("%s:%s", field, code);
return ResponseEntity.badRequest().body(message);
}
/**
* 400 - Bad Request
*/
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ExceptionHandler(BindException.class)
public ResponseEntity handleBindException(BindException e) {
LOGGER.error("", e);
BindingResult result = e.getBindingResult();
FieldError error = result.getFieldError();
String field = error.getField();
String code = error.getDefaultMessage();
String message = String.format("%s:%s", field, code);
return ResponseEntity.badRequest().body(message);
}
/**
* 400 - Bad Request
*/
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ExceptionHandler(ConstraintViolationException.class)
public ResponseEntity handleServiceException(ConstraintViolationException e) {
LOGGER.error("", e);
Set<ConstraintViolation<?>> violations = e.getConstraintViolations();
ConstraintViolation<?> violation = violations.iterator().next();
String message = violation.getMessage();
return ResponseEntity.badRequest().body("parameter:" + message);
}
/**
* 400 - Bad Request
*/
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ExceptionHandler(ValidationException.class)
public ResponseEntity handleValidationException(ValidationException e) {
LOGGER.error("", e);
return ResponseEntity.badRequest().body("validation_exception");
}
/**
* 405 - Method Not Allowed
*/
@ResponseStatus(HttpStatus.METHOD_NOT_ALLOWED)
@ExceptionHandler(HttpRequestMethodNotSupportedException.class)
public ResponseEntity handleHttpRequestMethodNotSupportedException(HttpRequestMethodNotSupportedException e) {
LOGGER.error("", e);
return ResponseEntity.badRequest().body("request_method_not_supported");
}
/**
* 415 - Unsupported Media Type
*/
@ResponseStatus(HttpStatus.UNSUPPORTED_MEDIA_TYPE)
@ExceptionHandler(HttpMediaTypeNotSupportedException.class)
public ResponseEntity handleHttpMediaTypeNotSupportedException(Exception e) {
LOGGER.error("", e);
return ResponseEntity.badRequest().body("content_type_not_supported");
}
/**
* 500 - Internal Server Error
*/
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
@ExceptionHandler(ServiceException.class)
public ResponseEntity handleServiceException(ServiceException e) {
LOGGER.error("", e);
return ResponseEntity.badRequest().body("" + e.getMessage());
}
/**
* 500 - Internal Server Error
*/
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
@ExceptionHandler(Exception.class)
public ResponseEntity handleException(Exception e) {
LOGGER.error("", e);
return ResponseEntity.badRequest().body("" + e.getMessage());
}
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
@ExceptionHandler(DataIntegrityViolationException.class)
public ResponseEntity handleException(DataIntegrityViolationException e) {
LOGGER.error(":", e);
return ResponseEntity.badRequest().body("");
}
}
|
package com.kodcu.other;
import com.kodcu.service.ThreadService;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.joox.JOOX;
import org.joox.Match;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import javax.imageio.ImageIO;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.URLDecoder;
import java.nio.charset.Charset;
import java.nio.file.*;
import java.nio.file.attribute.BasicFileAttributes;
import java.nio.file.attribute.FileAttribute;
import java.nio.file.attribute.FileTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.function.BiPredicate;
import java.util.stream.Stream;
public class IOHelper {
private static final Logger logger = LoggerFactory.getLogger(IOHelper.class);
public static void writeToFile(File file, String content, StandardOpenOption... openOption) {
writeToFile(file.toPath(), content, openOption);
}
public static Optional<Exception> writeToFile(Path path, String content, StandardOpenOption... openOption) {
try {
Files.write(path, content.getBytes(Charset.forName("UTF-8")), openOption);
} catch (Exception e) {
logger.error("Problem occured while writing to {}", path, e);
return Optional.of(e);
}
return Optional.empty();
}
public static void writeToFile(Path path, byte[] content, StandardOpenOption... openOption) {
try {
Files.write(path, content, openOption);
} catch (Exception e) {
logger.error("Problem occured while writing {}", path, e);
}
}
public static String readFile(InputStream inputStream) {
String content = "";
try {
content = IOUtils.toString(inputStream, "UTF-8");
IOUtils.closeQuietly(inputStream);
} catch (Exception e) {
logger.error("Problem occured while reading inputstream", e);
}
return content;
}
public static String readFile(Path path) {
String content = "";
try (InputStream is = Files.newInputStream(path, StandardOpenOption.READ, StandardOpenOption.SYNC)) {
content = IOUtils.toString(is, "UTF-8");
} catch (Exception e) {
logger.error("Problem occured while reading file {}", path, e);
}
return content;
}
public static void createDirectories(Path path) {
try {
Files.createDirectories(path);
} catch (Exception e) {
logger.error("Problem occured while creating directories {}", path, e);
}
}
public static Path createTempFile(String suffix) {
try {
return Files.createTempFile("asciidoc-temp", suffix);
} catch (Exception e) {
logger.error("Problem occured while creating temp file", e);
}
return null;
}
public static Path createTempFile(Path path, String prefix, String suffix) {
if (Objects.isNull(path)) {
return createTempFile(suffix);
}
try {
return Files.createTempFile(path, prefix, suffix);
} catch (Exception e) {
logger.error("Problem occured while creating temp file {}", path, e);
}
return null;
}
public static Path createTempFile(Path path, String suffix) {
if (Objects.isNull(path)) {
return createTempFile(suffix);
}
return createTempFile(path, "asciidoc-temp", suffix);
}
public static void copy(Path source, Path target, CopyOption... copyOptions) {
try {
Files.copy(source, target, copyOptions);
} catch (Exception e) {
logger.error("Problem occured while copying {} to {}", source, target, e);
}
}
public static String pathToUrl(Path path) {
try {
return path.toUri().toURL().toString();
} catch (Exception e) {
logger.error("Problem occured while getting URL of {}", path, e);
}
return null;
}
public static Stream<Path> list(Path path) {
try {
return Files.list(path);
} catch (Exception e) {
logger.error("Problem occured while listing {}", path, e);
}
return Stream.empty();
}
public static void imageWrite(BufferedImage bufferedImage, String format, File output) {
try {
ImageIO.write(bufferedImage, format, output);
} catch (Exception e) {
logger.error("Problem occured while writing buff image to {}", output, e);
}
}
public static byte[] readAllBytes(Path path) {
try {
return Files.readAllBytes(path);
} catch (Exception e) {
logger.error("Problem occured while reading {}", path, e);
}
return new byte[]{};
}
public static void move(Path source, Path target, StandardCopyOption... option) {
try {
Files.move(source, target, option);
} catch (Exception e) {
logger.error("Problem occured while moving {} to {}", source, target, e);
}
}
public static Match $(InputSource inputSource) {
try {
return JOOX.$(inputSource);
} catch (SAXException | IOException e) {
logger.error("Problem occured while selecting Match", e);
}
return null;
}
public static Match $(File file) {
try {
return JOOX.$(file);
} catch (SAXException | IOException e) {
logger.error("Problem occured while selecting Match for {}", file, e);
}
return JOOX.$();
}
public static void transform(Transformer transformer, StreamSource xmlSource, StreamResult streamResult) {
try {
transformer.transform(xmlSource, streamResult);
} catch (TransformerException e) {
logger.error("Problem occured while transforming XML Source to Stream result", e);
}
}
public static void matchWrite(Match root, File file) {
try {
root.write(file);
} catch (Exception e) {
logger.error("Problem occured while writing XML Match to {}", file, e);
}
}
public static void copyDirectoryToDirectory(File source, File target) {
try {
FileUtils.copyDirectoryToDirectory(source, target);
} catch (Exception e) {
logger.error("Problem occured while copying {} to {}", source, target, e);
}
}
public static Optional<Exception> deleteIfExists(Path path) {
try {
Files.deleteIfExists(path);
} catch (Exception e) {
logger.error("Problem occured while deleting {}", path, e);
return Optional.ofNullable(e);
}
return Optional.empty();
}
public static void copyDirectory(Path sourceDir, Path targetDir) {
try {
FileUtils.copyDirectory(sourceDir.toFile(), targetDir.toFile());
} catch (Exception e) {
logger.error("Problem occured while copying {} to {}", sourceDir, targetDir, e);
}
}
public static Stream<Path> find(Path start, int maxDepth, BiPredicate<Path, BasicFileAttributes> matcher, FileVisitOption... options) {
try {
return Files.find(start, Integer.MAX_VALUE, matcher, options);
} catch (Exception e) {
logger.error("Problem occured while finding in path {}", start, e);
}
return Stream.empty();
}
public static boolean isHidden(Path path) {
try {
return Files.exists(path) && (Files.isHidden(path) || path.getFileName().toString().startsWith("."));
} catch (Exception e) {
// logger.error("Problem occured while detecting hidden path {}", path, e);
}
return false;
}
public static void copyFileToDirectory(File file, File directory) {
try {
FileUtils.copyFileToDirectory(file, directory);
} catch (Exception e) {
logger.error("Problem occured while copying {} to {}", file, directory, e);
}
}
public static void copyFile(File file, File dest) {
try {
FileUtils.copyFile(file, dest);
} catch (Exception e) {
logger.error("Problem occured while copying {} to {}", file, dest, e);
}
}
public static void createDirectory(Path path) {
try {
Files.createDirectory(path);
} catch (Exception e) {
logger.error("Problem occured while creating {} path", path, e);
}
}
public static void deleteDirectory(Path path) {
try {
// Firstly try forced delete
Optional<Exception> forceDelete = IOHelper.forceDelete(path);
if (!forceDelete.isPresent()) {
return;
}
// if forced delete failed, try recursively delete dir
Files.walkFileTree(path, new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
Optional<Exception> exception = IOHelper
.forceDelete(file)
.flatMap(e -> {
ThreadService.sleep(100);
return IOHelper.forceDelete(file);
});
if (exception.isPresent()) {
throw new IOException(exception.get());
}
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException {
Optional<Exception> exception = IOHelper
.forceDelete(file)
.flatMap(e -> {
ThreadService.sleep(100);
return IOHelper.forceDelete(file);
});
if (exception.isPresent()) {
throw new IOException(exception.get());
}
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
if (exc == null) {
Optional<Exception> exception = IOHelper
.forceDelete(dir)
.flatMap(e -> {
ThreadService.sleep(100);
return IOHelper.forceDelete(dir);
});
if (exception.isPresent()) {
throw new IOException(exception.get());
}
return FileVisitResult.CONTINUE;
} else {
throw exc;
}
}
});
} catch (Exception e) {
logger.error("Problem occured while deleting {} path", path, e);
}
}
private static Optional<Exception> forceDelete(Path path) {
try {
Objects.requireNonNull(path);
if (Files.notExists(path)) {
return Optional.empty();
}
FileUtils.forceDelete(path.toFile());
} catch (FileNotFoundException fnx) {
return Optional.empty();
} catch (Exception e) {
logger.error("Problem occured while deleting {}", path, e);
return Optional.ofNullable(e);
}
return Optional.empty();
}
public static List<String> readAllLines(Path path) {
try {
return Files.readAllLines(path);
} catch (Exception e) {
logger.error("Problem occured while reading {} path", path, e);
}
return new ArrayList<>();
}
public static Reader fileReader(Path path) {
try {
FileInputStream fileInputStream = new FileInputStream(path.toFile());
return new InputStreamReader(fileInputStream, "UTF-8");
} catch (Exception e) {
logger.error("Problem occured while creating FileReader for {} path", path, e);
}
return null;
}
public static void close(Closeable... closeables) {
for (Closeable closeable : closeables) {
try {
closeable.close();
} catch (Exception e) {
// logger.error("Problem occured while closing resource");
}
}
}
public static FileTime getLastModifiedTime(Path path) {
try {
return Files.getLastModifiedTime(path);
} catch (Exception e) {
// e.printStackTrace();
}
return null;
}
public static String decode(String uri, String encoding) {
try {
return URLDecoder.decode(uri, encoding);
} catch (UnsupportedEncodingException e) {
// e.printStackTrace();
}
return uri;
}
public static Path createTempDirectory(Path path, String prefix, FileAttribute<?>... attrs) {
try {
return Files.createTempDirectory(path, prefix, attrs);
} catch (Exception e) {
logger.error("Problem occured while creating temp directory");
}
return null;
}
public static String getPathCleanName(Path object) {
return object.getFileName().toString().replaceAll("\\..*", "");
}
public static <T> T readFile(Path path, Class<T> clazz) {
if (clazz.isAssignableFrom(byte[].class)) {
return clazz.cast(readAllBytes(path));
} else {
return clazz.cast(readFile(path));
}
}
public static boolean isEmptyDir(Path path) {
try (DirectoryStream<Path> dirStream = Files.newDirectoryStream(path)) {
return !dirStream.iterator().hasNext();
} catch (Exception e) {
// logger.warn("Problem occured while checking is directory empty {}", path);
}
return false;
}
public static WatchService newWatchService() {
try {
return FileSystems.getDefault().newWatchService();
} catch (Exception e) {
logger.warn("Problem occured while creating new watch service");
}
return null;
}
public static Optional<Long> size(Path path) {
try {
long size = Files.size(path);
return Optional.of(size);
} catch (Exception e) {
logger.warn("Problem occured while getting size info of {}", path);
}
return Optional.empty();
}
public static boolean contains(Path root, Path inside) {
if (inside == null)
return false;
if (inside.equals(root))
return true;
return contains(root, inside.getParent());
}
public static Stream<Path> walk(Path path, int deepth) {
try {
return Files.walk(path,deepth);
} catch (Exception e) {
logger.warn("Problem occured while walking path {}", path);
}
return Stream.empty();
}
}
|
package com.leo.ostbm;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Desktop;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GraphicsEnvironment;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.lang.reflect.Type;
import java.util.LinkedList;
import java.util.List;
import javax.imageio.ImageIO;
import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.DefaultComboBoxModel;
import javax.swing.DefaultListModel;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.ListCellRenderer;
import javax.swing.ListSelectionModel;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.filechooser.FileNameExtensionFilter;
import javax.swing.text.BadLocationException;
import javax.swing.text.DefaultHighlighter;
import javax.swing.text.Highlighter;
import javax.swing.text.Highlighter.HighlightPainter;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import com.leo.ostbm.Resources.Facepic;
import com.leo.ostbm.Resources.Icon;
public class MakerPanel extends JPanel implements ActionListener, ListSelectionListener {
private static final long serialVersionUID = 1L;
public static final FileNameExtensionFilter TBPROJ_FILTER = new FileNameExtensionFilter("Project files", "tbproj");
public static final Color COLOR_TEXTBOX = Color.decode("0x180C1E");
public static final Color COLOR_TEXTBOX_B = COLOR_TEXTBOX.brighter().brighter();
public static final String A_FACE_FOLDER = "faceFolder";
public static final String A_CUSTOM_FACE = "customFace";
public static final String A_REMOVE_BOX = "removeBox";
public static final String A_ADD_BOX = "addBox";
public static final String A_MAKE_BOXES = "makeBoxes";
class Textbox {
public String face;
public String text;
public Textbox(String face, String text) {
this.face = face;
this.text = text;
}
public Textbox(String text) {
this(Resources.FACE_BLANK, text);
}
public Textbox() {
this(Resources.FACE_BLANK, "");
}
@Override
public String toString() {
String t = text;
t = t.trim().replace('\n', ' ');
final int maxLen = 26;
if (t.length() > maxLen)
t = t.substring(0, maxLen) + "...";
if (t.isEmpty())
t = "(empty)";
return t;
}
}
private File projectFile;
private int currentBox;
private List<Textbox> boxes;
private JList<Textbox> boxSelect;
private DefaultListModel<Textbox> boxSelectModel;
private JButton addBoxButton, removeBoxButton;
private JComboBox<String> faceSelect;
private JButton openFaceFolderButton, customFaceButton;
private JTextArea textArea;
private JButton makeTextboxButton;
public MakerPanel() {
currentBox = 0;
boxes = new LinkedList<>();
boxes.add(new Textbox());
setBorder(BorderFactory.createEmptyBorder(4, 4, 4, 4));
setLayout(new BorderLayout());
JPanel boxSelectPanel = new JPanel();
boxSelectPanel.setLayout(new BorderLayout());
JPanel boxControlPanel = new JPanel();
boxControlPanel.setLayout(new BoxLayout(boxControlPanel, BoxLayout.LINE_AXIS));
addBoxButton = new JButton(Resources.getIcon(Icon.ADD_TEXTBOX));
addBoxButton.addActionListener(this);
addBoxButton.setActionCommand(A_ADD_BOX);
addBoxButton.setToolTipText("Add a new textbox");
addBoxButton.setMaximumSize(new Dimension(24, 24));
boxControlPanel.add(addBoxButton);
removeBoxButton = new JButton(Resources.getIcon(Icon.REMOVE_TEXTBOX));
removeBoxButton.addActionListener(this);
removeBoxButton.setActionCommand(A_REMOVE_BOX);
removeBoxButton.setToolTipText("Remove the current textbox");
removeBoxButton.setMaximumSize(new Dimension(24, 24));
boxControlPanel.add(removeBoxButton);
boxSelectPanel.add(boxControlPanel, BorderLayout.PAGE_START);
boxSelect = new JList<>();
boxSelect.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
boxSelect.addListSelectionListener(this);
boxSelect.setCellRenderer(new TextboxListRenderer());
boxSelectModel = new DefaultListModel<>();
updateBoxList();
JScrollPane scroll = new JScrollPane(boxSelect);
boxSelectPanel.add(scroll, BorderLayout.CENTER);
add(boxSelectPanel, BorderLayout.LINE_START);
JPanel boxEditPanel = new JPanel();
boxEditPanel.setLayout(new BorderLayout());
boxEditPanel.setBorder(BorderFactory.createEmptyBorder(0, 4, 0, 0));
JPanel faceSelectPanel = new JPanel();
faceSelectPanel.setLayout(new BoxLayout(faceSelectPanel, BoxLayout.LINE_AXIS));
faceSelectPanel.setBorder(BorderFactory.createEmptyBorder(0, 0, 4, 0));
faceSelect = new JComboBox<String>();
faceSelect.setModel(new DefaultComboBoxModel<>(Resources.getFaces()));
faceSelect.setSelectedItem(boxes.get(currentBox).face);
faceSelect.setBackground(COLOR_TEXTBOX);
faceSelect.setForeground(Color.WHITE);
faceSelect.setRenderer(new FacesComboBoxRenderer());
faceSelect.setToolTipText("Select a facepic to add to the textbox");
faceSelectPanel.add(faceSelect);
JPanel faceControlPanel = new JPanel();
faceControlPanel.setLayout(new BoxLayout(faceControlPanel, BoxLayout.PAGE_AXIS));
openFaceFolderButton = new JButton(Resources.getIcon(Icon.FACE_FOLDER));
openFaceFolderButton.addActionListener(this);
openFaceFolderButton.setActionCommand(A_FACE_FOLDER);
openFaceFolderButton.setToolTipText("Open the facepic folder");
openFaceFolderButton.setPreferredSize(new Dimension(24, 24));
faceControlPanel.add(openFaceFolderButton);
customFaceButton = new JButton(Resources.getIcon(Icon.ADD_FACE));
customFaceButton.addActionListener(this);
customFaceButton.setActionCommand(A_CUSTOM_FACE);
customFaceButton.setToolTipText("Add a custom facepic");
customFaceButton.setPreferredSize(new Dimension(24, 24));
faceControlPanel.add(customFaceButton);
faceSelectPanel.add(faceControlPanel);
boxEditPanel.add(faceSelectPanel, BorderLayout.PAGE_START);
textArea = new TextboxTextArea(boxes.get(currentBox).text);
textArea.setFont(Resources.getFontBox());
textArea.setBackground(COLOR_TEXTBOX);
textArea.setForeground(Color.WHITE);
textArea.setCaretColor(Color.WHITE);
boxEditPanel.add(new JScrollPane(textArea), BorderLayout.CENTER);
JPanel bottomPanel = new JPanel();
bottomPanel.setLayout(new BorderLayout());
makeTextboxButton = new JButton("Make a Textbox!");
makeTextboxButton.addActionListener(this);
makeTextboxButton.setActionCommand(A_MAKE_BOXES);
bottomPanel.add(makeTextboxButton, BorderLayout.PAGE_END);
boxEditPanel.add(bottomPanel, BorderLayout.PAGE_END);
add(boxEditPanel, BorderLayout.CENTER);
}
private void updateCurrentBox() {
Textbox box = boxes.get(currentBox);
box.face = faceSelect.getItemAt(faceSelect.getSelectedIndex());
box.text = textArea.getText();
boxSelect.repaint();
}
private void updateBoxComponents() {
Textbox box = boxes.get(currentBox);
faceSelect.setSelectedItem(box.face);
textArea.setText(box.text);
}
private void updateBoxList() {
boxSelectModel = new DefaultListModel<>();
for (Textbox b : boxes)
boxSelectModel.addElement(b);
boxSelect.setModel(boxSelectModel);
boxSelect.setSelectedIndex(currentBox);
}
public boolean isProjectEmpty() {
updateCurrentBox();
boolean emptyProject = true;
for (Textbox box : boxes) {
if (!box.text.isEmpty() || !Resources.FACE_BLANK.equals(box.face)) {
emptyProject = false;
break;
}
}
return emptyProject;
}
public File getProjectFile() {
return projectFile;
}
public void newProjectFile() throws IOException {
updateCurrentBox();
boolean emptyProject = isProjectEmpty();
if (!emptyProject) {
int result = JOptionPane.showConfirmDialog(this,
"Do you want to save the current project before creating a new project?",
"Save before creating new project?", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.WARNING_MESSAGE);
if (result == JOptionPane.CANCEL_OPTION)
return;
else if (result == JOptionPane.YES_OPTION)
saveProjectFile(null);
}
projectFile = null;
boxes.clear();
boxes.add(new Textbox());
currentBox = 0;
updateBoxComponents();
updateBoxList();
}
public void saveProjectFile(File dest) throws IOException {
updateCurrentBox();
int hasCustomFace = -1;
for (int i = 0; i < boxes.size(); i++) {
if (Resources.getFace(boxes.get(i).face).isCustom()) {
hasCustomFace = i;
break;
}
}
if (hasCustomFace != -1) {
int result = JOptionPane.showConfirmDialog(this, "Textbox " + (hasCustomFace + 1)
+ " has a custom face!\nThis will prevent a user without the custom from opening the project file.\nSave anyway?",
"Textbox has custom face", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE);
if (result == JOptionPane.NO_OPTION)
return;
}
if (dest == null) {
if (projectFile == null) {
File sel = Main.openFileDialog(true, this, "Save project file", TBPROJ_FILTER);
if (sel == null)
return;
projectFile = sel;
}
dest = projectFile;
}
if (dest.exists() && !dest.equals(projectFile)) {
int result = JOptionPane.showConfirmDialog(this, "File \"" + dest + "\" already exists.\nOverwrite it?",
"Destination file exists", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE);
if (result == JOptionPane.NO_OPTION)
return;
dest.delete();
dest.createNewFile();
}
Gson gson = new GsonBuilder().setPrettyPrinting().create();
try (FileWriter fw = new FileWriter(dest); BufferedWriter writer = new BufferedWriter(fw)) {
gson.toJson(boxes, writer);
} catch (IOException e) {
throw e;
}
projectFile = dest;
}
public void loadProjectFile(File src) throws IOException {
boolean emptyProject = isProjectEmpty();
if (!emptyProject) {
int result = JOptionPane.showConfirmDialog(this,
"Do you want to save the current project before loading another project?",
"Save before loading other project?", JOptionPane.YES_NO_CANCEL_OPTION,
JOptionPane.WARNING_MESSAGE);
if (result == JOptionPane.CANCEL_OPTION)
return;
else if (result == JOptionPane.YES_OPTION)
saveProjectFile(null);
}
if (src == null) {
src = Main.openFileDialog(false, this, "Load project file", TBPROJ_FILTER);
if (src == null)
return;
}
Gson gson = new GsonBuilder().create();
try (FileReader fr = new FileReader(src); BufferedReader reader = new BufferedReader(fr)) {
Type type = new TypeToken<List<Textbox>>() {
}.getType();
List<Textbox> temp = gson.fromJson(reader, type);
for (int i = 0; i < temp.size(); i++) {
Textbox box = temp.get(i);
if (Resources.getFace(box.face) == null) {
JOptionPane.showMessageDialog(this,
"Textbox " + (i + 1) + " specifies a facepic that isn't currently loaded: \"" + box.face
+ "\"\nPlease make sure there is a loaded facepic with that name, then try again.",
"Missing facepic", JOptionPane.ERROR_MESSAGE);
return;
}
}
boxes.clear();
boxes.addAll(temp);
boxSelect.setSelectedIndex(-1);
updateBoxList();
} catch (IOException e) {
throw e;
}
projectFile = src;
updateBoxComponents();
updateBoxList();
}
@Override
public void actionPerformed(ActionEvent e) {
String a = e.getActionCommand();
JFileChooser fc;
int ret;
Textbox box;
switch (a) {
case A_FACE_FOLDER:
if (!Desktop.isDesktopSupported())
return;
try {
Desktop.getDesktop().browse(new File("res/faces").toURI());
} catch (IOException e2) {
e2.printStackTrace();
}
break;
case A_CUSTOM_FACE:
fc = new JFileChooser();
fc.setMultiSelectionEnabled(true);
fc.setAcceptAllFileFilterUsed(false);
fc.setDialogTitle("Open face image(s)");
fc.setFileFilter(new FileNameExtensionFilter("PNG files", "png"));
fc.setCurrentDirectory(new File(System.getProperty("user.dir")));
ret = fc.showOpenDialog(this);
if (ret == JFileChooser.APPROVE_OPTION) {
File[] sels = fc.getSelectedFiles();
for (File sel : sels) {
String faceName = sel.getName();
faceName = faceName.substring(0, faceName.lastIndexOf('.'));
try {
BufferedImage image = ImageIO.read(sel);
if (image.getWidth() != 96 || image.getHeight() != 96) {
JOptionPane.showMessageDialog(this, "Face must be 96 by 96!", "Bad face dimensions!",
JOptionPane.ERROR_MESSAGE);
return;
}
Resources.addFace(faceName, sel, image);
} catch (IOException e1) {
e1.printStackTrace();
JOptionPane.showMessageDialog(this, "An exception occured while loading the face:\n" + e1,
"Couldn't load face!", JOptionPane.ERROR_MESSAGE);
}
}
}
String[] faces = Resources.getFaces();
faceSelect.setModel(new DefaultComboBoxModel<>(faces));
faceSelect.setSelectedIndex(faces.length - 1);
break;
case A_REMOVE_BOX:
updateCurrentBox();
if (!boxes.get(currentBox).text.trim().isEmpty()) {
int result = JOptionPane.showConfirmDialog(this,
"Are you sure you want to delete textbox " + (currentBox + 1) + "?", "Confirm deleting textbox",
JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE);
if (result != JOptionPane.YES_OPTION)
break;
}
if (boxes.size() == 1) {
box = boxes.get(currentBox);
box.face = Resources.FACE_BLANK;
box.text = "";
} else
boxes.remove(currentBox);
if (currentBox == boxes.size())
currentBox
if (currentBox < 0)
currentBox = 0;
updateBoxComponents();
updateBoxList();
break;
case A_ADD_BOX:
updateCurrentBox();
Textbox lastBox = boxes.get(boxes.size() - 1);
box = new Textbox();
box.face = lastBox.face;
boxes.add(box);
currentBox = boxes.size() - 1;
updateBoxComponents();
updateBoxList();
break;
case A_MAKE_BOXES:
updateCurrentBox();
BufferedImage boxesImage = new BufferedImage(608, 128 * boxes.size() + 2 * (boxes.size() - 1),
BufferedImage.TYPE_4BYTE_ABGR);
Graphics big = boxesImage.getGraphics();
for (int i = 0; i < boxes.size(); i++) {
Textbox b = boxes.get(i);
String text = b.text.trim();
if (text.isEmpty()) {
JOptionPane.showMessageDialog(this,
"Textbox " + (i + 1) + " is blank!\nPlease write something there.", "Text cannot be blank!",
JOptionPane.ERROR_MESSAGE);
return;
}
String[] lines = text.split("\n");
int linesNum = lines.length;
if (linesNum > 4) {
JOptionPane.showMessageDialog(this,
"Textbox " + (i + 1) + " has too many lines!\nIt has " + linesNum
+ " lines, but a single textbox can only fit 4 lines.",
"Too many lines!", JOptionPane.ERROR_MESSAGE);
return;
}
int maxLen = 47;
String errorBit = "with a face";
if (Resources.FACE_BLANK.equals(b.face)) {
maxLen += 10;
errorBit = "without a face";
}
for (int l = 0; l < lines.length; l++) {
int lineLen = lines[l].length();
if (lineLen > maxLen) {
JOptionPane.showMessageDialog(this,
"Line " + (l + 1) + " in textbox " + (i + 1) + " is too long!\nIt has " + lineLen
+ " characters, but textboxes " + errorBit + " can only fit " + maxLen
+ " characters per line.",
"Line too long!", JOptionPane.ERROR_MESSAGE);
return;
}
}
drawTextbox(big, b.face, text, 0, 130 * i, i < boxes.size() - 1);
}
JFrame previewFrame = new JFrame();
previewFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
final int extraHeight = 72;
final Dimension size = new Dimension(652, boxesImage.getHeight() + extraHeight);
final int maxHeight = 128 * 5 + 2 * 4 + extraHeight;
if (size.height > maxHeight)
size.height = maxHeight + 16;
previewFrame.setMinimumSize(size);
previewFrame.setPreferredSize(size);
previewFrame.setMaximumSize(size);
previewFrame.setResizable(false);
previewFrame.add(new PreviewPanel(boxesImage));
previewFrame.pack();
previewFrame.setLocationRelativeTo(null);
previewFrame.setTitle("Textbox(es) preview");
previewFrame.setVisible(true);
break;
default:
System.out.println("Undefined action: " + a);
break;
}
}
@Override
public void valueChanged(ListSelectionEvent e) {
if (e.getSource().equals(boxSelect)) {
if (faceSelect != null && textArea != null)
updateCurrentBox();
int sel = boxSelect.getSelectedIndex();
if (sel < 0)
return;
currentBox = sel;
if (faceSelect != null && textArea != null)
updateBoxComponents();
}
}
public static BufferedImage drawTextbox(String face, String text) {
BufferedImage ret = new BufferedImage(608, 128, BufferedImage.TYPE_INT_ARGB);
Graphics g = ret.getGraphics();
drawTextbox(g, face, text, 0, 0, false);
return ret;
}
public static void drawTextbox(Graphics g, String face, String text, int x, int y, boolean drawArrow) {
g.drawImage(Resources.getBox(), x, y, null);
BufferedImage faceImage = Resources.getFace(face).getImage();
if (faceImage != null)
g.drawImage(faceImage, x + 496, y + 16, null);
if (drawArrow)
g.drawImage(Resources.getArrow(), x + 299, y + 118, null);
drawTextboxString(g, text, x + 20, y + 10);
}
private static void drawTextboxString(Graphics g, String str, int x, int y) {
g.setFont(Resources.getFontBox());
g.setColor(Color.WHITE);
final int lineSpace = g.getFontMetrics().getHeight() + 1;
for (String line : str.split("\n")) {
y += lineSpace;
g.drawString(line, x, y);
}
}
static class TextboxListRenderer extends JLabel implements ListCellRenderer<Textbox> {
private static final long serialVersionUID = 1L;
private static final BufferedImage IMAGE = new BufferedImage(1, 1, BufferedImage.TYPE_4BYTE_ABGR);
public TextboxListRenderer() {
setOpaque(true);
setHorizontalAlignment(LEFT);
setVerticalAlignment(CENTER);
}
@Override
public Component getListCellRendererComponent(JList<? extends Textbox> list, Textbox value, int index,
boolean isSelected, boolean cellHasFocus) {
if (isSelected) {
setBackground(list.getSelectionBackground());
setForeground(list.getSelectionForeground());
} else {
setBackground(list.getBackground());
setForeground(list.getForeground());
}
String text = "<html><b>Textbox " + (index + 1) + "</b><br>" + value.toString() + "</html>";
setText(text);
// getGraphics() returns null here so we need to make our own Graphics object
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
Graphics2D g = ge.createGraphics(IMAGE);
g.setFont(getFont());
Rectangle2D bounds = g.getFontMetrics().getStringBounds(text, g);
setPreferredSize(new Dimension(200, (int) bounds.getHeight() + g.getFontMetrics().getHeight()));
return this;
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
}
}
class FacesComboBoxRenderer extends JLabel implements ListCellRenderer<String> {
private static final long serialVersionUID = 1L;
public FacesComboBoxRenderer() {
setOpaque(true);
setHorizontalAlignment(LEFT);
setVerticalAlignment(CENTER);
}
@Override
public Component getListCellRendererComponent(JList<? extends String> list, String value, int index,
boolean isSelected, boolean cellHasFocus) {
if (isSelected)
setBackground(COLOR_TEXTBOX_B);
else
setBackground(COLOR_TEXTBOX);
Facepic face = Resources.getFace(value);
ImageIcon faceIcon = face.getIcon();
if (faceIcon == null)
setIcon(Resources.getFace(Resources.FACE_BLANK).getIcon());
else
setIcon(faceIcon);
String text = "<html><font color=white>" + face.getName();
if (face.isCustom())
text += "<b>*</b>";
File faceFile = face.getFile();
if (faceFile != null)
text += "</font><br><font color=gray><i>" + faceFile.getPath() + "</i>";
text += "</font></html>";
setText(text);
return this;
}
}
class TextboxTextArea extends JTextArea {
private static final long serialVersionUID = 1L;
public TextboxTextArea(String text) {
super(text);
addKeyListener(new KeyAdapter() {
@Override
public void keyPressed(KeyEvent e) {
String text = getText();
Highlighter hl = getHighlighter();
hl.removeAllHighlights();
HighlightPainter p = new DefaultHighlighter.DefaultHighlightPainter(Color.RED);
int line = 0, lineLen = 0, hlStart = -1;
int maxLen = 57;
if (faceSelect.getSelectedItem() != Resources.FACE_BLANK)
maxLen -= 10;
for (int i = 0; i < text.length(); i++) {
if (line > 3) {
try {
hl.addHighlight(getLineStartOffset(line), text.length(), p);
} catch (BadLocationException e1) {
e1.printStackTrace();
}
break;
}
char c = text.charAt(lineLen);
if (c == '\n') {
line++;
lineLen = 0;
hlStart = -1;
continue;
}
System.out.println("line " + line + ", char " + lineLen + ", total chars " + i);
lineLen++;
if (lineLen > maxLen && hlStart < 0) {
hlStart = i;
}
if (hlStart > -1) {
try {
hl.addHighlight(hlStart, i + 1, p);
} catch (BadLocationException e1) {
e1.printStackTrace();
}
}
}
}
});
}
}
}
|
package com.sybit.airtable;
import com.google.gson.annotations.SerializedName;
import com.mashape.unirest.http.HttpResponse;
import com.mashape.unirest.http.Unirest;
import com.mashape.unirest.http.exceptions.UnirestException;
import com.mashape.unirest.request.GetRequest;
import com.sybit.airtable.exception.AirtableException;
import com.sybit.airtable.exception.HttpResponseExceptionHandler;
import com.sybit.airtable.vo.Attachment;
import com.sybit.airtable.vo.Delete;
import com.sybit.airtable.vo.PostRecord;
import com.sybit.airtable.vo.RecordItem;
import com.sybit.airtable.vo.Records;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.PropertyUtils;
import org.apache.http.client.HttpResponseException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.apache.commons.beanutils.BeanUtilsBean;
/**
* Representation Class of Airtable Tables.
*
* @since 0.1
*/
public class Table<T> {
private static final Logger LOG = LoggerFactory.getLogger( Table.class );
private final String name;
private final Class<T> type;
private Base parent;
/**
*
* @param name
* @param type
*/
public Table(String name, Class<T> type) {
this.type = type;
this.name = name;
}
/**
*
* @param name
* @param type
* @param base
*/
@SuppressWarnings("WeakerAccess")
public Table(String name, Class<T> type, Base base){
this(name, type);
setParent(base);
}
/**
*
* @param parent
*/
public void setParent(Base parent) {
this.parent = parent;
}
/**
*
* If no Parameter ser all querys to null.
*
* @return
* @throws AirtableException
*/
public List<T> select() throws AirtableException, HttpResponseException {
return select(new Query() {
@Override
public Integer getMaxRecords() {
return null;
}
@Override
public String getView() {
return null;
}
@Override
public List<Sort> getSort() {
return null;
}
@Override
public String filterByFormula() {
return null;
}
@Override
public String[] getFields() {
return null;
}
@Override
public Integer getPageSize() {
return null;
}
});
}
/**
* Select List of data of table with defined Query Parameters.
*
* @param query
* @return
* @throws AirtableException
*/
@SuppressWarnings("WeakerAccess")
public List<T> select(Query query) throws AirtableException {
HttpResponse<Records> response;
try {
GetRequest request = Unirest.get(getTableEndpointUrl())
.header("accept", "application/json")
.header("Authorization", getBearerToken());
if(query.getFields() != null && query.getFields().length > 0){
String[] fields = query.getFields();
for (int i = 0; i < fields.length; i++) {
request.queryString("fields[]",fields[i]);
}
}
if(query.getMaxRecords() != null) {
request.queryString("maxRecords", query.getMaxRecords());
}
if(query.getView() != null) {
request.queryString("view", query.getView());
}
if(query.filterByFormula() != null) {
request.queryString("filterByFormula", query.filterByFormula());
}
if(query.getPageSize() != null){
if (query.getPageSize() > 100) {
request.queryString("pageSize",100);
} else {
request.queryString("pageSize",query.getPageSize());
}
}
if(query.getSort() != null) {
int i = 0;
for (Sort sort : query.getSort()) {
request.queryString("sort[" + i + "][field]", sort.getField());
request.queryString("sort[" + i + "][direction]", sort.getDirection());
}
}
LOG.debug("URL=" + request.getUrl());
response = request.asObject(Records.class);
}
catch (UnirestException e) {
throw new AirtableException(e);
}
int code = response.getStatus();
List<T> list = null;
if(200 == code) {
list = getList(response);
} else {
HttpResponseExceptionHandler.onResponse(response);
}
return list;
}
/**
* select with Parameter maxRecords
*
* @param maxRecords
* @return
* @throws AirtableException
* @throws HttpResponseException
*/
public List<T> select(Integer maxRecords) throws AirtableException, HttpResponseException {
return select(new Query() {
@Override
public Integer getMaxRecords() {
return maxRecords;
}
@Override
public String getView() {
return null;
}
@Override
public List<Sort> getSort() {
return null;
}
@Override
public String filterByFormula() {
return null;
}
@Override
public String[] getFields() {
return null;
}
@Override
public Integer getPageSize() {
return null;
}
});
}
/**
* Select data of table by definied view.
* @param view
* @return
* @throws AirtableException
* @throws HttpResponseException
*/
public List<T> select(String view) throws AirtableException, HttpResponseException {
return select(new Query() {
@Override
public Integer getMaxRecords() {
return null;
}
@Override
public String getView() {
return view;
}
@Override
public List<Sort> getSort() {
return null;
}
@Override
public String filterByFormula() {
return null;
}
@Override
public String[] getFields() {
return null;
}
@Override
public Integer getPageSize() {
return null;
}
});
}
/**
*select Table data with defined sortation
*
* @param sortation
* @return
* @throws AirtableException
* @throws HttpResponseException
*/
public List<T> select(Sort sortation) throws AirtableException, HttpResponseException {
final List<Sort> sortList = new ArrayList<>();
sortList.add(sortation);
return select(new Query() {
@Override
public Integer getMaxRecords() {
return null;
}
@Override
public String getView() {
return null;
}
@Override
public List<Sort> getSort() {
return sortList;
}
@Override
public String filterByFormula() {
return null;
}
@Override
public String[] getFields() {
return null;
}
@Override
public Integer getPageSize() {
return null;
}
});
}
/**
* select only Table data with defined Fields
*
* @param fields
* @return
* @throws AirtableException
* @throws HttpResponseException
*/
public List<T> select(String[] fields) throws AirtableException, HttpResponseException {
return select(new Query() {
@Override
public Integer getMaxRecords() {
return null;
}
@Override
public String getView() {
return null;
}
@Override
public List<Sort> getSort() {
return null;
}
@Override
public String filterByFormula() {
return null;
}
@Override
public String[] getFields() {
return fields;
}
@Override
public Integer getPageSize() {
return null;
}
});
}
/**
* Get List of records of response.
*
* @param response
* @return
*/
private List<T> getList(HttpResponse<Records> response) {
final Records records = response.getBody();
final List<T> list = new ArrayList<>();
for(Map<String, Object> record : records.getRecords()) {
T item = null;
try {
item = transform(record, this.type.newInstance());
} catch (InstantiationException | IllegalAccessException | InvocationTargetException e) {
LOG.error(e.getMessage(), e);
}
list.add(item);
}
return list;
}
/**
* Find record by given id.
*
* @param id id of record.
* @return searched record.
* @throws AirtableException
*/
public T find(String id) throws AirtableException {
RecordItem body = null;
HttpResponse<RecordItem> response;
try {
response = Unirest.get( getTableEndpointUrl() + "/" + id)
.header("accept", "application/json")
.header("Authorization", getBearerToken())
.asObject(RecordItem.class);
} catch (UnirestException e) {
throw new AirtableException(e);
}
int code = response.getStatus();
if(200 == code) {
body = response.getBody();
} else {
HttpResponseExceptionHandler.onResponse(response);
}
try {
return transform(body, this.type.newInstance() );
} catch (InvocationTargetException | IllegalAccessException | InstantiationException e) {
LOG.error(e.getMessage(), e);
}
return null;
}
public T create(T item) throws AirtableException, IllegalAccessException, InvocationTargetException, NoSuchMethodException {
RecordItem responseBody = null;
checkProperties(item);
PostRecord body = new PostRecord<T>();
body.setFields(item);
HttpResponse<RecordItem> response;
try {
response = Unirest.post( getTableEndpointUrl())
.header("accept", "application/json")
.header("Authorization", getBearerToken())
.header("Content-type","application/json")
.body(body)
.asObject(RecordItem.class);
} catch (UnirestException e) {
throw new AirtableException(e);
}
int code = response.getStatus();
if(200 == code) {
responseBody = response.getBody();
} else {
HttpResponseExceptionHandler.onResponse(response);
}
try {
return transform(responseBody, this.type.newInstance() );
} catch (InvocationTargetException | IllegalAccessException | InstantiationException e) {
LOG.error(e.getMessage(), e);
}
return null;
}
public T update(T item) throws AirtableException, IllegalAccessException, InvocationTargetException, NoSuchMethodException {
RecordItem responseBody = null;
String id = getIdOfItem(item);
PostRecord body = new PostRecord<T>();
body.setFields(filterFields(item));
HttpResponse<RecordItem> response;
try {
response = Unirest.patch( getTableEndpointUrl()+"/"+id)
.header("accept", "application/json")
.header("Authorization", getBearerToken())
.header("Content-type","application/json")
.body(body)
.asObject(RecordItem.class);
} catch (UnirestException e) {
throw new AirtableException(e);
}
int code = response.getStatus();
if(200 == code) {
responseBody = response.getBody();
} else {
HttpResponseExceptionHandler.onResponse(response);
}
try {
return transform(responseBody, this.type.newInstance() );
} catch (InvocationTargetException | IllegalAccessException | InstantiationException e) {
LOG.error(e.getMessage(), e);
}
return null;
}
public T replace(T item) {
throw new UnsupportedOperationException("not yet implemented");
}
/**
* Delete Record by given id
*
* @param id
* @throws AirtableException
*/
public void destroy(String id) throws AirtableException {
Delete body = null;
HttpResponse<Delete> response;
try {
response = Unirest.delete(getTableEndpointUrl() + "/" + id)
.header("accept", "application/json")
.header("Authorization", getBearerToken())
.asObject(Delete.class);
} catch (UnirestException e) {
throw new AirtableException(e);
}
int code = response.getStatus();
if(200 == code) {
body = response.getBody();
} else {
HttpResponseExceptionHandler.onResponse(response);
}
if(!body.isDeleted()){
throw new AirtableException("Record id: "+body.getId()+" could not be deleted.");
}
}
/**
*
* @return
*/
private Base base() {
return parent;
}
/**
* Get the endpoint for the specified table.
*
* @return URL of tables endpoint.
*/
private String getTableEndpointUrl() {
return base().airtable().endpointUrl() + "/" + base().name() + "/" + this.name;
}
/**
* Get Bearer Token for Authentication Header.
*
* @return
*/
private String getBearerToken() {
return "Bearer " + base().airtable().apiKey();
}
private T transform(Map<String, Object> record, T retval) throws InvocationTargetException, IllegalAccessException {
for(String key: record.keySet()) {
if("fields".equals(key)) {
//noinspection unchecked
retval = transform((Map<String, Object>)record.get("fields"), retval);
} else {
setProperty(retval, key, record.get(key));
}
}
return retval;
}
private T transform(RecordItem record, T retval) throws InvocationTargetException, IllegalAccessException {
setProperty(retval, "id", record.getId());
setProperty(retval, "createdTime", record.getCreatedTime());
retval = transform(record.getFields(), retval);
return retval;
}
private void setProperty(T retval, String key, Object value) throws IllegalAccessException, InvocationTargetException {
String property = key2property(key);
for (Field f: this.type.getDeclaredFields()) {
final SerializedName annotation = f.getAnnotation(SerializedName.class);
if(annotation != null && property.equalsIgnoreCase(annotation.value())){
property = f.getName();
break;
}
}
if (propertyExists(retval, property)) {
BeanUtils.setProperty(retval, property, value);
}else {
LOG.warn(retval.getClass() + " does not support public setter for existing property [" + property + "]");
}
}
/**
* Convert AirTable ColumnName to Java PropertyName.
*
* @param key
* @return
*/
private String key2property(String key) {
if(key.contains(" ") || key.contains("-") ) {
LOG.warn( "Annotate columns having special characters by using @SerializedName for property: [" + key + "]");
}
String property = key.trim();
property = property.substring(0,1).toLowerCase() + property.substring(1, property.length());
return property;
}
/**
* Check if writable property exists.
*
* @param bean bean to inspect
* @param property name of property
* @return true if writable property exists.
*/
private static boolean propertyExists (Object bean, String property) {
return PropertyUtils.isReadable(bean, property) &&
PropertyUtils.isWriteable(bean, property);
}
private void checkProperties(T item) throws AirtableException, IllegalAccessException, InvocationTargetException, NoSuchMethodException {
if(propertyExists(item,"id") || propertyExists(item,"createdTime")){
Field[] attributes = item.getClass().getDeclaredFields();
for (Field attribute : attributes) {
String name = attribute.getName();
if (name.equals("id") || name.equals("createdTime")) {
if(BeanUtils.getProperty(item,attribute.getName()) != null){
throw new AirtableException("Property "+name+" should be null!");
}
} else if (name.equals("photos")){
List<Attachment> obj = (List<Attachment>) BeanUtilsBean.getInstance().getPropertyUtils().getProperty(item, "photos");
checkPropertiesOfAttachement(obj);
}
}
}
}
private void checkPropertiesOfAttachement(List<Attachment> attachements) throws AirtableException, IllegalAccessException, InvocationTargetException, NoSuchMethodException{
if(attachements != null){
for (int i = 0; i < attachements.size(); i++) {
if(propertyExists(attachements.get(i),"id") || propertyExists(attachements.get(i),"size") || propertyExists(attachements.get(i), "type") || propertyExists(attachements.get(i), "filename")){
Field[] attributesPhotos = attachements.getClass().getDeclaredFields();
for (Field attributePhoto : attributesPhotos) {
String namePhotoAttribute = attributePhoto.getName();
if (namePhotoAttribute.equals("id") || namePhotoAttribute.equals("size") || namePhotoAttribute.equals("Tpye") || namePhotoAttribute.equals("filename")) {
if(BeanUtils.getProperty(attachements.get(i),namePhotoAttribute) != null){
throw new AirtableException("Property "+namePhotoAttribute+" should be null!");
}
}
}
}
}
}
}
private String getIdOfItem(T item) throws AirtableException, IllegalAccessException, InvocationTargetException, NoSuchMethodException {
if(propertyExists(item,"id")){
String id = BeanUtils.getProperty(item, "id");
if(id != null){
return id;
}
}
throw new AirtableException("Id of "+item+" not Found!");
}
private T filterFields(T item) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {
System.out.println(item);
Field[] attributes = item.getClass().getDeclaredFields();
for (Field attribute : attributes) {
String name = attribute.getName();
if ((name.equals("id") || name.equals("createdTime")) && (BeanUtils.getProperty(item,name) != null)) {
BeanUtilsBean.getInstance().getPropertyUtils().setProperty(item, name, null);
}
}
return item;
}
}
|
package configFiles;
public class mhcConfigNew {
public static final String driver = "jdbc:sqlserver://SERVERADDRESS:PORT";
public static final String databaseName = ";databaseName=DATABASENAME";
public static final String username = ";user=USERNAME";
public static final String password = ";password=PASSWORD";
public static String getDriver() {
return driver;
}
public static String getDatabaseName() {
return databaseName;
}
public static String getUsername() {
return username;
}
public static String getPassword() {
return password;
}
}
|
package de.teiesti.postie;
import org.pmw.tinylog.Logger;
import java.io.BufferedWriter;
import java.io.IOException;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingDeque;
/**
* An {@code Outbox} is the part of a {@link Mailbox} which sends messages ("letters"). Any message that is given to
* this {@code Outbox} using the {@link #send(String)}-method will be stored until it can be transferred. This class
* should only be accessed from the associated {@link Mailbox}.<br />
* <br />
* Warning: Do not start a {@link Thread} for a {@code Outbox}. These things are completely handled from inside the
* class.<br />
* Note: An {@link Outbox} must be closed after the last message was handed over to it. When closing the instance,
* no message will be discarded.
*/
class Outbox implements Runnable, AutoCloseable {
/** the sink where the messages go to */
private BufferedWriter out;
/** a queue storing messages that have not been transferred yet */
private BlockingQueue<String> outbox = new LinkedBlockingDeque<>();
/** a flag that indicated weather this {@code Inbox} should be closed*/
private boolean close = false;
private Thread worker;
public Outbox(BufferedWriter out) {
if (out == null)
throw new IllegalArgumentException("out == null");
this.out = out;
this.worker = new Thread(this);
worker.start();
}
public void send(String letter) {
if (letter == null)
throw new IllegalArgumentException("letter == null");
if (close)
throw new IllegalStateException("cannot send a letter because this is already closed");
try {
outbox.put(letter);
} catch (InterruptedException e) {
Logger.error(e);
System.exit(1);
}
}
@Override
public void run() {
String letter;
try {
while (!close) {
letter = outbox.take();
out.write(letter);
out.newLine();
if (outbox.isEmpty()) out.flush();
}
} catch (InterruptedException | IOException e) {
Logger.error(e);
System.exit(1);
}
}
@Override
public void close() {
if (!close) {
try {
// close the worker thread
close = true;
worker.join();
// clean things up
String letter = outbox.poll();
while (letter != null) {
out.write(letter);
out.newLine();
}
// don't close out here, because it belongs to a socket which is handled from elsewhere
out.flush();
} catch (IOException | InterruptedException e) {
Logger.error(e);
System.exit(1);
}
}
}
}
|
package dk.itu.donkey;
// General utilities
import java.util.ArrayList;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
// Reflection utilities
import java.lang.reflect.Field;
// SQL utilities
import java.sql.SQLException;
/**
* The Model Query class is used for querying database rows related to models
* and, in contrast to a raw {@link Query}, returns {@link Model}s rather than
* {@link Row}s.
*
* @param <T> The type of model to query.
*
* @since 1.0.0 Initial release.
*/
public final class ModelQuery<T extends Model> {
/**
* The model to query.
*/
private Class<T> type;
/**
* The table to query.
*/
private String table;
/**
* The query to build and perform.
*/
private Query query;
/**
* Keep track of tables that have been joined into the query.
*/
private Set<String> tables = new HashSet<>();
/**
* Initialize a model query.
*
* @param type The model subclass to query.
*/
public ModelQuery(final Class<T> type) {
Model model = Model.instantiate(type);
this.type = type;
this.query = model.query();
this.table = model.table();
}
/**
* Prefix a column with the table name of the model being queried if needed.
*
* <p>
* If the column has already been prefixed with another table name, the
* column will simply pass through without being touched.
*
* @param column The column to prefix.
* @return The prefixed column.
*/
private String prefixColumn(final String column) {
if (!column.matches(".*\\..*")) {
return String.format("%s.%s", this.table, column);
}
else {
return column;
}
}
/**
* Add a where clause to the query.
*
* @param column The column to compare.
* @param operator The logical operator to use for the comparison.
* @param value The value to compare against.
* @return The current {@link ModelQuery} object, for chaining.
*/
public ModelQuery where(
final String column,
final String operator,
final Object value
) {
this.query.where(this.prefixColumn(column), operator, value);
return this;
}
/**
* Add a where clause to the query.
*
* @param column The column to compare.
* @param value The value to compare against.
* @return The current {@link ModelQuery} object, for chaining.
*/
public ModelQuery where(final String column, final Object value) {
this.query.where(this.prefixColumn(column), value);
return this;
}
/**
* Add a or where clause to the query.
*
* @param column The column to compare.
* @param operator The logical operator to use for the comparison.
* @param value The value to compare against.
* @return The current {@link ModelQuery} object, for chaining.
*/
public ModelQuery orWhere(
final String column,
final String operator,
final Object value
) {
this.query.orWhere(this.prefixColumn(column), operator, value);
return this;
}
/**
* Add a or where clause to the query.
*
* @param column The column to compare.
* @param value The value to compare against.
* @return The current {@link ModelQuery} object, for chaining.
*/
public ModelQuery orWhere(final String column, final Object value) {
this.query.orWhere(this.prefixColumn(column), value);
return this;
}
/**
* Add an order by clause to the query.
*
* @param column The column to order by.
* @param direction The ordering direction. Either "asc" or "desc".
* @return The current {@link ModelQuery} object, for chaining.
*/
public ModelQuery orderBy(final String column, final String direction) {
this.query.orderBy(this.prefixColumn(column), direction);
return this;
}
/**
* Add an order by clause to the query.
*
* @param column The column to order by.
* @return The current {@link ModelQuery} object, for chaining.
*/
public ModelQuery orderBy(final String column) {
this.query.orderBy(this.prefixColumn(column));
return this;
}
/**
* Add a limit clause to the query.
*
* @param limit The limit to add.
* @return The current {@link ModelQuery} object, for chaining.
*/
public ModelQuery limit(final int limit) {
this.query.limit(limit);
return this;
}
/**
* Add an offset clause to the query.
*
* @param offset The offset to add.
* @return The current {@link ModelQuery} object, for chaining.
*/
public ModelQuery offset(final int offset) {
this.query.offset(offset);
return this;
}
/**
* Count the number of models.
*
* @return The number of models.
*
* @throws SQLException In case of a SQL error.
*/
public Number count() throws SQLException {
return this.query.count();
}
/**
* Get the largest value of a model field.
*
* @param field The field to find the largest value of.
* @return The largest value of the specified field.
*
* @throws SQLException In case of a SQL error.
*/
public Object max(final String field) throws SQLException {
return this.query.max(this.prefixColumn(field));
}
/**
* Get the smallest value of a model field.
*
* @param field The field to find the smallet value of.
* @return The smallest value of the specified field.
*
* @throws SQLException In case of a SQL error.
*/
public Object min(final String field) throws SQLException {
return this.query.min(this.prefixColumn(field));
}
/**
* Get the average value of a model field.
*
* @param field The field to find the average value of.
* @return The average value of the specified field.
*
* @throws SQLException In case of a SQL error.
*/
public Number avg(final String field) throws SQLException {
return this.query.avg(this.prefixColumn(field));
}
/**
* Get the sum of a model field.
*
* @param field The field to find the sum of.
* @return The sum of the specified field.
*
* @throws SQLException In case of a SQL error.
*/
public Number sum(final String field) throws SQLException {
return this.query.sum(this.prefixColumn(field));
}
/**
* Recursively traverse a model and join in its relations on the current
* query object.
*
* @param type The model type to traverse.
*/
private void getRelations(final Class type) {
Model outer = Model.instantiate(type);
// Remember that this model has already been added as a relation.
this.tables.add(outer.table());
// Select the ID column of the model in the format "table_id".
this.query.select(String.format("%s.id as %1$s_id", outer.table()));
for (Field field: outer.getFields()) {
String fieldName = field.getName();
Class fieldType = field.getType();
boolean isList = false;
// If the field being looked at is a list, get the generic type of the
// list.
if (List.class.isAssignableFrom(fieldType)) {
fieldType = Model.getGenericType(field);
// Remember that the field type was a list.
isList = true;
}
if (Model.class.isAssignableFrom(fieldType)) {
Model inner = Model.instantiate(fieldType);
// If the model hasn't already been added as a relation, join it into
// the query if it represents a single field, e.g. a comment belonging
// to a post, and look for further relations...
if (!this.tables.contains(inner.table())) {
if (!isList) {
this.query.join(
inner.table(),
String.format("%s.%s", outer.table(), fieldName),
String.format("%s.%s", inner.table(), "id")
);
// Remember that this table has already been added as a relation.
this.tables.add(inner.table());
}
// Look for further relations.
this.getRelations(fieldType);
}
// ...otherwise, assume that the model is a relation of an already
// joined model. This will be the case in a two-way relation (either
// One-to-One or One-to-Many) and so a reverse join is performed if the
// field isn't a list, e.g. joining a single post with a list of
// comments.
else if (!isList) {
this.query.join(
outer.table(),
String.format("%s.%s", inner.table(), "id"),
String.format("%s.%s", outer.table(), fieldName)
);
}
}
else {
// Prefix all the columns of the model with its table name to ensure
// that non-unique columns can be differentiated if other data is
// joined in. I.e. people.name becomes people_name.
this.query.select(String.format(
"%s.%s as %1$s_%2$s", outer.table(), fieldName.toLowerCase()
));
}
}
}
/**
* Recursively traverse a model and initialize its relations based on a
* database response.
*
* @param type The type of model to traverse.
* @param rows The database rows to use for initializing the models.
* @return A list of models initialized with their relations.
*/
private List<Model> setRelations(
final Class context,
final Class type,
final List<Row> rows
) {
// Create a map for tracking model instances by their ID. When joining data,
// the same instance of a model might appear several times in the query
// response (e.g. the same post for several comments). The map will ensure
// that only the first occurence of each unique model is instantiated.
Map<Integer, Model> models = new LinkedHashMap<>();
Map<Integer, List<Row>> modelRows = new LinkedHashMap<>();
// Partition the rows.
for (Row row: rows) {
Model model = Model.instantiate(type);
List<Row> subRows;
// Grab the ID of the current model table from the row.
Integer id = (Integer) row.get(
String.format("%s_%s", model.table(), "id")
);
if (id == null) {
continue;
}
if (!models.containsKey(id)) {
subRows = new ArrayList<>();
subRows.add(row);
modelRows.put(id, subRows);
models.put(id, model);
// Set the current row on the model. Since each column in the response
// is prefixed with the table name of the model, only columns specific
// to the model will be set on it.
model.setRow(row);
}
else {
subRows = modelRows.get(id);
subRows.add(row);
modelRows.put(id, subRows);
model = models.get(id);
}
}
for (Model model: models.values()) {
// Run through each of the fields of the model and look for further
// relations.
for (Field field: model.getFields()) {
String fieldName = field.getName();
Class fieldType = field.getType();
boolean isList = false;
// If the field being looked at is a list, get the generic type of the
// list.
if (List.class.isAssignableFrom(fieldType)) {
fieldType = Model.getGenericType(field);
// Remember that the field type was a list.
isList = true;
}
if (Model.class.isAssignableFrom(fieldType)) {
// If the field is of the same type as the context, bail out. This is
// to avoid an infinite loop where two models both have fields of
// oneanother's type, e.g. a post with a list of comments and a
// comment that belongs to a post.
if (fieldType == context) {
continue;
}
List<Model> value = this.setRelations(
type, fieldType, modelRows.get(model.id())
);
if (isList) {
model.setField(fieldName, value);
}
else {
model.setField(fieldName, value.get(0));
}
}
}
}
return new ArrayList<Model>(models.values());
}
/**
* Perform the query and return a list of matching models.
*
* @return A list of models.
*
* @throws SQLException In case of a SQL error.
*/
public List<Model> get() throws SQLException {
this.getRelations(this.type);
return this.setRelations(null, this.type, this.query.get());
}
}
|
package edu.hm.hafner;
import java.util.Date;
/**
* Useless class - only for test-cases.
*
* @author Christian Möstl
*/
public class RightCurly {
private Date date;
private int number;
private final String text;
/**
* Creates a new instance of {@link RightCurly}.
*
* @param date
* Date
* @param number
* number
* @param text
* Text
*/
public RightCurly(final Date date, final int number, final String text) {
this.date = date;
this.number = number;
this.text = text;
}
/**
* Do sth...
*
* @param a
* number
*/
public void doSth(int a) {
int b = 0;
if (a < 0) {
System.out.println("a<0"); }
if (a > 0) {
System.out.println(">0");
if (a == 1) {
++b;
System.out.println("a=1");
}
}
System.out.println(b);
}
/**
* Returns the date.
*
* @return the date
*/
public Date getDate() {
return date;
}
/**
* Returns the number.
*
* @return the number
*/
public int getNumber() {
return number;
}
/**
* Returns the text.
*
* @return the text
*/
public String getText() {
return text;
}
}
|
package edu.mines.jtk.util;
import java.util.Hashtable;
import java.util.StringTokenizer;
/**
* A class for dimensional analysis of and conversions among units of measure.
* For example, you can determine that ft/s and km/s have the same physical
* dimensions (length/time), and you can convert ft/s to km/s and vice-versa.
* However, you cannot convert s/ft to ft/s.
* <p>
* A typical pattern for dealing with units is to (1) check the dimensions,
* (2) convert parameters to SI units, and (3) use the parameters, now with
* consistent (SI) units.
* <p>
* Here is a simple example:
* <code><pre>
* // Ensure frequency units have dimensions of inverse time.
* if (!freqUnits.haveDimensionsOf(Units.inv(timeUnits))) {
* // handle error
* }
*
* // Convert both frequency and time to SI units.
* freq = freqUnits.toSI(freq);
* time = timeUnits.toSI(time);
*
* // Use frequency and time, without worrying about units.
* ...
* </pre></code>
* <p>
* When converting many values from some units to some other units
* (with the same dimensions) it is more efficient to compute a shift
* and scale factor and then use these instead of calling conversion
* methods. For example,
* <code><pre>
* // Determine shift and scale.
* double shift = toUnits.doubleShiftFrom(fromUnits);
* double scale = toUnits.doubleScaleFrom(fromUnits);
*
* // Use shift and scale to convert lots of values.
* for (int i=0; i<n; ++i) to[i] = shift+scale*from[i];
* </pre></code>
*
* @author Dave Hale, Colorado School of Mines
* @version 2000.02.17, 2006.07.19
*/
public final class Units implements Cloneable {
/**
* Constructs dimensionless units.
*/
public Units() {
}
/**
* Constructs units from a units definition.
* @param definition the units definition (e.g., "coulomb/volt").
* @exception UnitsFormatException if the units definition is not a valid
* combination of units already defined.
*/
public Units(String definition) throws UnitsFormatException {
Units units = unitsFromDefinition(definition);
_scale = units._scale;
_shift = units._shift;
for (int i=0; i<_power.length; ++i) {
_power[i] = units._power[i];
}
}
/**
* Clones these units.
* @return a clone of these units.
*/
public Object clone() {
try {
Units units = (Units)super.clone();
units._power = _power.clone();
return units;
} catch (CloneNotSupportedException e) {
throw new InternalError();
}
}
/**
* Determines whether specified object equals these units.
* @param object the object to compare with these units.
* @return true, if equal; false, otherwise.
*/
public boolean equals(Object object) {
if (object instanceof Units) return equals((Units)object);
return false;
}
/**
* Determines whether specified units equal these units.
* @param units the units to compare with these units.
* @return true, if equal; false, otherwise.
*/
public boolean equals(Units units) {
if (_scale!=units._scale) return false;
if (_shift!=units._shift) return false;
for (int i=0; i<_power.length; ++i) {
if (_power[i]!=units._power[i]) return false;
}
return true;
}
/**
* Converts the specified value in these units to the corresponding value
* in SI base units (seconds, meters, moles, etc.). For example, if these
* units are "km", then convert will multiply the specified value by 1000.
* @param value the value to convert.
* @return the converted value.
*/
public float toSI(float value) {
return (float)((value-_shift)*_scale);
}
/**
* Converts the specified value in these units to the corresponding value
* in SI base units (seconds, meters, moles, etc.). For example, if these
* units are "km", then convert will multiply the specified value by 1000.
* @param value the value to convert.
* @return the converted value.
*/
public double toSI(double value) {
return (value-_shift)*_scale;
}
/**
* Converts the specified value in SI base units (seconds, meters, moles,
* etc.) to the corresponding value in these units. For example, if these
* units are "km", then convert will divide the specified value by 1000.
* @param value the value to convert.
* @return the converted value.
*/
public float fromSI(float value) {
return (float)(_shift+value/_scale);
}
/**
* Converts the specified value in SI base units (seconds, meters, moles,
* etc.) to the corresponding value in these units. For example, if these
* units are "km", then convert will divide the specified value by 1000.
* @param value the value to convert.
* @return the converted value.
*/
public double fromSI(double value) {
return _shift+value/_scale;
}
/**
* Returns the shift needed to convert values from the specified
* units to these units.
* The specified units must have the dimensions of these units.
* @param units the units from which to convert.
* @return the shift.
*/
public float floatShiftFrom(Units units) {
return (float)doubleShiftFrom(units);
}
/**
* Returns the shift needed to convert values from the specified
* units to these units.
* The specified units must have the dimensions of these units.
* @param units the units from which to convert.
* @return the shift.
*/
public double doubleShiftFrom(Units units) {
Check.argument(units.haveDimensionsOf(this),"same dimensions");
return fromSI(units.toSI(0.0));
}
/**
* Returns the scale factor needed to convert values from the specified
* units to these units.
* The specified units must have the dimensions of these units.
* @param units the units from which to convert.
* @return the scale factor.
*/
public float floatScaleFrom(Units units) {
return (float)doubleScaleFrom(units);
}
/**
* Returns the scale factor needed to convert values from the specified
* units to these units.
* The specified units must have the dimensions of these units.
* @param units the units from which to convert.
* @return the scale factor.
*/
public double doubleScaleFrom(Units units) {
Check.argument(units.haveDimensionsOf(this),"same dimensions");
return fromSI(units.toSI(1.0))-doubleShiftFrom(units);
}
/**
* Determines whether these units have dimensions.
* @return true, if these units have dimensions; false, otherwise.
*/
public boolean haveDimensions() {
for (int power:_power)
if (power!=0) return true;
return false;
}
/**
* Determines whether these units have the dimensions of specified units.
* @param units units with which to compare dimensions.
* @return true, if units are the same; false, otherwise.
*/
public boolean haveDimensionsOf(Units units) {
for (int i=0; i<_power.length; ++i) {
if (_power[i]!=units._power[i]) return false;
}
return true;
}
/**
* Gets the standard definition of these units. A standard definition is
* the definition expressed entirely in base SI units.
* @return the standard definition of these units.
*/
public String standardDefinition() {
String sd = "";
boolean appending = false;
if (_scale!=1.0) {
sd += _scale;
appending = true;
}
for (int i=0; i<_nbase; ++i) {
if (_power[i]!=0) {
if (appending) sd += " ";
sd += _bases[i];
if (_power[i]!=1) sd += "^"+_power[i];
appending = true;
}
}
if (_shift!=0.0) {
double abs_shift = (_shift>0.0)?_shift:-_shift;
if (appending) sd += " ";
sd += (_shift>0.0)?"+ ":"- ";
sd += abs_shift;
}
return sd;
}
/**
* Adds a scalar to units.
* @param units first operand.
* @param s second operand.
* @return the sum units + s.
*/
public static Units add(Units units, double s) {
return ((Units)units.clone()).shift(s);
}
/**
* Subtracts a scalar from units.
* @param units first operand.
* @param s second operand.
* @return the difference units - s.
*/
public static Units sub(Units units, double s) {
return ((Units)units.clone()).shift(-s);
}
/**
* Multiplies units by scalar.
* @param units first operand.
* @param s second operand.
* @return the product units * s.
*/
public static Units mul(Units units, double s) {
return ((Units)units.clone()).scale(s);
}
/**
* Divides units by scalar.
* @param units first operand.
* @param s second operand.
* @return the quotient units1 / s.
*/
public static Units div(Units units, double s) {
return ((Units)units.clone()).scale(1.0/s);
}
/**
* Multiplies units by units.
* @param units1 first operand.
* @param units2 second operand.
* @return the product units1 * units2.
*/
public static Units mul(Units units1, Units units2) {
return ((Units)units1.clone()).mul(units2);
}
/**
* Divides units by units.
* @param units1 first operand.
* @param units2 second operand.
* @return the quotient units1 / units2.
*/
public static Units div(Units units1, Units units2) {
return ((Units)units1.clone()).div(units2);
}
/**
* Inverts units.
* @param units to invert.
* @return the inverse 1 / units.
*/
public static Units inv(Units units) {
return ((Units)units.clone()).inv();
}
/**
* Raises units to a power.
* @param units first operand.
* @param p second operand.
* @return the power units^p.
*/
public static Units pow(Units units, int p) {
return ((Units)units.clone()).pow(p);
}
/**
* Adds a definition of units to the table of units.
* <p>
* An extensive default table of units may be provided, so that explicit
* definition using this method may be unnecessary.
* <p>
* Most units are defined in terms of other units already defined. However,
* some units, such as "ampere" and "second", are base units representing
* the physical dimensions, such as electric current and time, respectively.
* We define derived units in terms of base units and other derived
* units. Only one base units should be defined for each physical dimension.
* @param name the string by which the units will be known (e.g,, "farad").
* @param plural true, if the name has a simple plural form, as in "farads".
* @param definition the units definition, as in "coulomb/volt". If the
* definition is null, then the name is assumed to define new base units,
* such as "meter".
* Multiplication is denoted by a space, '.', or '*'.
* Division is denoted by a '/'.
* Addition and subtraction are denoted by '+' and '-'.
* Note: only addition and subtraction of constants is
* supported, and the constant must appear on the right-hand-side
* of the '+' or '-', as in "degK - 273.15", not "-273.15 + degK".
* Exponentiation is denoted by '^', as in s^2.
* @return true, if the units were successfully defined; false, otherwise.
* Units will not be defined if (1) units with the specified name
* already exist or (2) the limit on the number of base units
* has been exceeded.
* @exception UnitsFormatException if the definition is not a valid
* combination of existing units.
*/
public static synchronized boolean define(String name, boolean plural,
String definition)
throws UnitsFormatException {
return addDefinition(name,plural,definition);
}
/**
* Determines if a string is a valid units definition.
* Valid definitions are those consistent with
* the format described above.
* @param definition the units definition in question (e.g., "coulomb/volt").
* @return true, if the units definition is valid; false, otherwise.
*/
public static synchronized boolean isValidDefinition(String definition) {
try {
unitsFromDefinition(definition);
} catch (UnitsFormatException e) {
return false;
}
return true;
}
/**
* Determines whether units with the specified name are defined.
* @param name the string by which the units are known (e.g., "farad")
* @return true, if the units are currently defined; false, otherwise.
*/
public static synchronized boolean isDefined(String name) {
return _table.containsKey(name);
}
// package
// Scale these units.
Units scale(double s) {
_scale *= s;
_shift /= s;
return this;
}
// Shift these units.
Units shift(double s) {
_shift += s;
return this;
}
// Multiply these units by specified units.
Units mul(Units u) {
_shift = (_shift!=0.0)?_shift/u._scale:u._shift/_scale;
_scale *= u._scale;
for (int i=0; i<_power.length; ++i) {
_power[i] += u._power[i];
}
return this;
}
// Divide these units by specified units.
Units div(Units u) {
_shift *= u._scale;
_scale /= u._scale;
for (int i=0; i<_power.length; ++i) {
_power[i] -= u._power[i];
}
return this;
}
// Invert these units.
Units inv() {
_scale = 1.0/_scale;
_shift = 0.0;
for (int i=0; i<_power.length; ++i) {
_power[i] = (byte)(-_power[i]);
}
return this;
}
// Raise these units to a power.
Units pow(int p) {
_scale = Math.pow(_scale,p);
_shift = 0.0;
for (int i=0; i<_power.length; ++i) {
_power[i] *= (byte)p;
}
return this;
}
// Construct new Units corresponding to the specified name in the table
// of Units. If the name is not found in the table, return null.
static synchronized Units unitsFromName(String name) {
// Special cases.
if (name==null || name.equals("")) return new Units();
// First, search the table.
UnitsTableEntry entry = _table.get(name);
if (entry!=null) {
return (Units)entry._units.clone();
}
// Second, if the name has a prefix (like "milli").
double factor = 1.0;
int index = findPrefix(name);
boolean prefix = (index>=0);
if (prefix) {
factor = _prefix_factor[index];
String temp = name.substring(_prefix_string[index].length());
entry = _table.get(temp);
if (entry!=null) {
Units units = (Units)entry._units.clone();
units.scale(factor);
return units;
}
}
// Third, if the name has a suffix (like "s").
boolean suffix = (name.length()>0 && name.charAt(name.length()-1)=='s');
if (suffix) {
name = name.substring(0,name.length()-1);
entry = _table.get(name);
if (entry!=null && entry._plural) {
Units units = (Units)entry._units.clone();
return units;
}
}
// Fourth, if the name has both prefix and suffix.
if (prefix && suffix) {
name = name.substring(_prefix_string[index].length());
entry = _table.get(name);
if (entry!=null && entry._plural) {
Units units = (Units)entry._units.clone();
units.scale(factor);
return units;
}
}
// Finally, give up.
return null;
}
// private
// For internal use only. An entry in the table of units.
private static class UnitsTableEntry {
UnitsTableEntry(String name, boolean plural, Units units) {
_name = name;
_plural = plural;
_units = units;
}
String _name = null;
boolean _plural = false;
Units _units = null;
}
private static final int NPOWERS = 16;
private static Hashtable<String, UnitsTableEntry> _table = null;
private static String[] _bases = null;
private static int _nbase = 0;
private static final String _prefix_string[] = {
"E","G","M","P","T","Y","Z",
"a","atto","c","centi","d","da","deca","deci","deka",
"exa","f","femto","giga","h","hecto","k","kilo",
"m","mega","micro","milli","n","nano","p","peta","pico",
"tera","u","y","yocto","yotta","z","zepto","zetta"
};
private static final double _prefix_factor[] = {
1e18,1e9,1e6,1e15,1e12,1e24,1e21,
1e-18,1e-18,1e-2,1e-2,1e-1,1e1,1e1,1e-1,1e1,
1e18,1e-15,1e-15,1e9,1e2,1e2,1e3,1e3,
1e-3,1e6,1e-6,1e-3,1e-9,1e-9,1e-12,1e15,1e-12,
1e12,1e-6,1e-24,1e-24,1e24,1e-21,1e-21,1e21
};
static {
_table = new Hashtable<String, UnitsTableEntry>();
_bases = new String[NPOWERS];
loadTable();
}
private double _scale = 1.0;
private double _shift = 0.0;
private byte _power[] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
// Construct new Units by parsing the specified definition.
private static synchronized Units unitsFromDefinition(String definition)
throws UnitsFormatException {
// If the definition corresponds to a name in the table,
// construct and return the named Units.
Units units = unitsFromName(definition);
if (units!=null) return units;
// Otherwise, parse the definition to construct new Units.
try {
return UnitsParser.parse(definition);
} catch (Exception e) {
throw new UnitsFormatException(e.getMessage());
}
}
// Search the prefix table for matching prefixes in the specified name.
// If a match is found, return the index of the longest matching prefix.
// Otherwise, return -1.
private static int findPrefix(String name) {
if (name.length()<1) return -1;
char name0 = name.charAt(0);
int length = 0;
int index = -1;
for (int i=0; i<_prefix_string.length; ++i) {
String prefix = _prefix_string[i];
char prefix0 = prefix.charAt(0);
if (name0>prefix0) continue;
if (name0<prefix0) break;
if (name.startsWith(prefix) && length<prefix.length()) {
length = prefix.length();
index = i;
}
}
return index;
}
// Add one units definition to the units table.
private static synchronized boolean addDefinition(String name,
boolean plural,
String definition)
throws UnitsFormatException {
// Because the table is shared, cannot overwrite existing entries.
if (_table.containsKey(name)) return false;
// If the definition is null, try to create new base units.
if (definition==null || definition.equals("")) {
Units units = new Units();
if (_nbase>=units._power.length-1) return false;
++units._power[_nbase];
_bases[_nbase++] = name;
_table.put(name,new UnitsTableEntry(name,plural,units));
return true;
}
// Construct new Units from the specified definition.
Units units = unitsFromDefinition(definition);
// Add the new Units to the table.
_table.put(name,new UnitsTableEntry(name,plural,units));
return true;
}
// Load the default units table.
private static synchronized void loadTable() {
String[] specs = UnitsSpecs.specs;
for (String spec:specs) {
if (spec.startsWith("#")) continue;
StringTokenizer st = new StringTokenizer(spec);
if (st.countTokens()<2) continue;
String name = st.nextToken();
String plural_str = st.nextToken();
if (!plural_str.equals("S") && !plural_str.equals("P")) continue;
boolean plural = plural_str.equals("P");
String definition = (st.hasMoreTokens())?st.nextToken(""):null;
if (definition!=null) {
int index = definition.indexOf("
if (index>=0) definition = definition.substring(0,index);
definition = definition.trim();
}
if (definition!=null && definition.equals("")) definition = null;
try {
boolean defined = addDefinition(name,plural,definition);
if (!defined) {
System.err.println("Units.loadTable: failed to define " +
name+" = "+definition);
}
} catch (UnitsFormatException e) {
System.err.println("Units.loadTable: failed to define " +
name+" = "+definition+" because "+e.getMessage());
}
}
}
}
|
package eu.digitisation.DA;
import static eu.digitisation.DA.WordType.LOWERCASE;
import static eu.digitisation.DA.WordType.MIXED;
import static eu.digitisation.DA.WordType.UPPERCASE;
import eu.digitisation.layout.SortPageXML;
import eu.digitisation.log.Messages;
import eu.digitisation.text.CharFilter;
import eu.digitisation.text.StringNormalizer;
import eu.digitisation.xml.DocumentParser;
import eu.digitisation.xml.XPathFilter;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.text.Collator;
import java.util.ArrayList;
import java.util.List;
import javax.xml.xpath.XPathExpressionException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
public class Split {
static XPathFilter selector; // Selects XML elements with relevant content
final static Collator collator; // Defines the lexicographic order
static CharFilter cfilter; // Map PUA characters
static {
String[] inclusions = {"TextRegion[@type='paragraph']"};
URL url = Split.class.getResource("/UnicodeCharEquivalences.csv");
File file = new File(url.getFile());
System.out.println(file);
try {
selector = new XPathFilter(inclusions, null);
} catch (XPathExpressionException ex) {
Messages.severe(ex.getMessage());
}
collator = OldSpanishCollator.getInstance();
cfilter = new CharFilter(true, file);
}
/**
*
* @param text a string
* @return the longest prefix of the text containing only uppercase letters
*/
protected static String header(String text) {
StringBuilder builder = new StringBuilder();
String[] tokens = text.split("\\p{Space}+");
for (String token : tokens) {
String normal = cfilter.translate(token);
String word = StringNormalizer.trim(normal);
switch (WordType.typeOf(word)) {
case UPPERCASE: // header word
if (builder.length() > 0) {
builder.append(' ');
}
builder.append(token);
break;
case LOWERCASE: // end of header
return builder.toString();
case MIXED: // striking content
if (WordType.initial(word)) {
return builder.toString();
} else {
if (builder.length() > 0) {
builder.append(' ');
}
builder.append(token);
}
}
}
return builder.toString();
}
/**
*
* @param e a document element
* @return the longest prefix of the textual content containing only
* uppercase letters
* @throws IOException
*/
protected static String header(Element e) throws IOException {
String text = e.getTextContent().trim();
return header(text);
}
/**
*
* @param doc an XML document
* @return the initial sentences in every selected textual element
* @throws IOException
*/
public static List<String> headers(Document doc) throws IOException {
List<String> list = new ArrayList<String>();
for (Element e : selector.selectElements(doc)) {
String head = header(e);
if (!head.isEmpty()) {
list.add(head);
}
}
return list;
}
/**
*
* @param text a string of text
* @return the initial word (sequence of consecutive letters) in the text
*/
private static String initial(String text) {
if (text.length() > 0 && Character.isLetter(text.charAt(0))) {
return text.split("[^\\p{L}]+")[0];
} else {
return "";
}
}
/**
* Function for debugging
*
* @param file
*/
public static void view(File file) throws IOException {
Document doc = SortPageXML.isSorted(file) ? DocumentParser.parse(file)
: SortPageXML.sorted(DocumentParser.parse(file));
for (String head : headers(doc)) {
System.out.println(head);
}
}
public static String split(File ifile, String last) throws IOException {
Document doc = SortPageXML.isSorted(ifile) ? DocumentParser.parse(ifile)
: SortPageXML.sorted(DocumentParser.parse(ifile));
System.out.println(ifile);
for (String head : headers(doc)) {
if (!head.isEmpty()) {
String start = initial(head).replaceAll("ñ", "Ñ");
//System.out.println(text);
if (WordType.typeOf(start) == WordType.UPPERCASE) {
int n = collator.compare(last, start);
if (n < 0) {
System.out.println("<entry>" + head + "</entry>");
} else if (n == 0) {
System.out.println(" <subentry>" + head + "</subentry>");
} else if (isParticiple(start, last)) {
System.out.println("<PastPart>" + head + "</PastPart>");
} else {
System.out.println("***");
System.out.println("<entry>" + head + "</entry>");
}
last = start;
} else if (WordType.typeOf(start.replaceAll("l", "I"))
== WordType.UPPERCASE && !WordType.initial(start)) {
// wrong transcription
System.out.println("<Itypo>" + head + "</Itypo>");
} else if (WordType.nearlyUpper(start)) {
// a single mismatch
System.out.println("<check>" + head + "</check>");
} else if (WordType.typeOf(start) == WordType.MIXED
&& !WordType.initial(start)) {
System.out.println("<<<<" + head);
} else {
;//System.out.println(">>>" + text);
}
}
}
return last;
}
/**
* Check if an entry can be a past participle of the preceding word
*
* @param head the entry
* @param last the preceding word
* @return true if head is a past participle entry after the last word
*/
protected static boolean isParticiple(String head, String last) {
//System.out.println("="+last.replaceFirst("[AEI]R$", ""));
return last.replaceFirst("[AEI]R(SE)?$", "")
.equals(head.replaceFirst("[AI]DO$", ""));
}
public static void main(String[] args) throws IOException {
String lastEntry = "";
for (String arg : args) {
File file = new File(arg);
//Split.view(file);
lastEntry = Split.split(file, lastEntry);
}
}
}
|
package gsg.infrastructure;
import gsg.threads.IJob;
import gsg.threads.JobRunner;
import gsg.threads.JobRunnerConfiguration;
/**
* @author zkejid@gmail.com
* Created: 23.07.15 9:37
*/
public class Utils {
public static String getMessage(String line) {
final int i = line.indexOf(" ");
if (i > -1 && i < line.length()) {
return line.substring(i+1, line.length());
}
else {
return null;
}
}
public static String getKey(String line) {
final int i = line.indexOf(" ");
if (i > -1) {
return line.substring(0, i);
}
else {
return null;
}
}
public static JobRunner runLoop(IJob job) {
final JobRunnerConfiguration configuration = new JobRunnerConfiguration();
configuration.setDoLog(false);
final JobRunner runner = new JobRunner(configuration, job);
runner.start();
return runner;
}
public static void runLoopAndJoin(IJob job) {
final JobRunner runner = runLoop(job);
try {
runner.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
|
package hex.deeplearning;
import static hex.deeplearning.DeepLearning.Loss;
import hex.FrameTask;
import org.junit.Ignore;
import org.junit.Test;
import water.MemoryManager;
import water.PrettyPrint;
import water.api.DocGen;
import water.api.Request.API;
import water.util.Utils;
import java.util.Arrays;
/**
* This class implements the concept of a Neuron layer in a Neural Network
* During training, every MRTask2 F/J thread is expected to create these neurons for every map call (Cheap to make).
* These Neurons are NOT sent over the wire.
* The weights connecting the neurons are in a separate class (DeepLearningModel.DeepLearningModelInfo), and will be shared per node.
*/
public abstract class Neurons {
static final int API_WEAVER = 1;
public static DocGen.FieldDoc[] DOC_FIELDS;
@API(help = "Number of neurons")
protected int units;
/**
* Constructor of a Neuron Layer
* @param units How many neurons are in this layer?
*/
Neurons(int units) {
this.units = units;
}
/**
* Print the status of this neuron layer
* @return populated String
*/
@Override
public String toString() {
String s = this.getClass().getSimpleName();
s += "\nNumber of Neurons: " + units;
s += "\nParameters:\n" + params.toString();
if (_dropout != null) s += "\nDropout:\n" + _dropout.toString();
return s;
}
/**
* Parameters (deep-cloned() from the user input, can be modified here, e.g. learning rate decay)
*/
protected DeepLearning params;
/**
* Layer state (one per neuron): activity, error
*/
public transient float[] _a, _e;
/**
* References for feed-forward connectivity
*/
public Neurons _previous; // previous layer of neurons
DeepLearningModel.DeepLearningModelInfo _minfo; //reference to shared model info
public float[] _w; //reference to _minfo.weights[layer] for convenience
public float[] _b; //reference to _minfo.biases[layer] for convenience
// momentum
float[] _wm; //reference to _minfo.weights_momenta[layer] for convenience
private float[] _bm; //reference to _minfo.biases_momenta[layer] for convenience
// ADADELTA
private float[] _E_dx2; //reference to _minfo.E_dx2[layer] for convenience
private float[] _E_g2; //reference to _minfo.E_g2[layer] for convenience
/**
* For Dropout training
*/
protected Dropout _dropout;
// /**
// * We need a way to encode a missing value in the neural net forward/back-propagation scheme.
// * For simplicity and performance, we simply use the largest values to encode a missing value.
// * If we run into exactly one of those values with regular neural net updates, then we're very
// * likely also running into overflow problems, which will trigger a NaN somewhere, which will be
// * caught and lead to automatic job cancellation.
// */
// public static final int missing_int_value = Integer.MAX_VALUE; //encode missing label or target
// public static final double missing_double_value = Double.MAX_VALUE; //encode missing input
/**
* Helper to check sanity of Neuron layers
* @param training whether training or testing is done
*/
void sanityCheck(boolean training) {
if (this instanceof Input) {
assert(_previous == null);
assert (!training || _dropout != null);
} else {
assert(_previous != null);
if (_minfo.has_momenta()) {
assert(_wm != null);
assert(_bm != null);
assert(_E_dx2 == null);
assert(_E_g2 == null);
}
if (_minfo.adaDelta()) {
if (params.rho == 0) throw new IllegalArgumentException("rho must be > 0 if epsilon is >0.");
if (params.epsilon == 0) throw new IllegalArgumentException("epsilon must be > 0 if rho is >0.");
assert(_minfo.adaDelta());
assert(_E_dx2 != null);
assert(_E_g2 != null);
assert(_wm == null);
assert(_bm == null);
}
if (this instanceof MaxoutDropout || this instanceof TanhDropout || this instanceof RectifierDropout) {
assert (!training || _dropout != null);
}
}
}
/**
* Initialization of the parameters and connectivity of a Neuron layer
* @param neurons Array of all neuron layers, to establish feed-forward connectivity
* @param index Which layer am I?
* @param p User-given parameters (Job parental object hierarchy is not used)
* @param minfo Model information (weights/biases and their momenta)
* @param training Whether training is done or just testing (no need for dropout)
*/
public final void init(Neurons[] neurons, int index, DeepLearning p, final DeepLearningModel.DeepLearningModelInfo minfo, boolean training) {
params = (DeepLearning)p.clone();
params.rate *= Math.pow(params.rate_decay, index-1);
_a = new float[units];
if (!(this instanceof Output) && !(this instanceof Input)) {
_e = new float[units];
}
if (training && (this instanceof MaxoutDropout || this instanceof TanhDropout
|| this instanceof RectifierDropout || this instanceof Input) ) {
_dropout = new Dropout(units);
}
if (!(this instanceof Input)) {
_previous = neurons[index-1]; //incoming neurons
_minfo = minfo;
_w = minfo.get_weights(index-1); //incoming weights
_b = minfo.get_biases(index-1); //bias for this layer (starting at hidden layer)
if (minfo.has_momenta()) {
_wm = minfo.get_weights_momenta(index-1); //incoming weights
_bm = minfo.get_biases_momenta(index-1); //bias for this layer (starting at hidden layer)
}
if (minfo.adaDelta()) {
_E_dx2 = minfo.get_E_dx2(index-1);
_E_g2 = minfo.get_E_g2(index - 1);
}
}
sanityCheck(training);
}
/**
* Forward propagation
* @param seed For seeding the RNG inside (for dropout)
* @param training Whether training is done or just testing (no need for dropout)
*/
protected abstract void fprop(long seed, boolean training);
/**
* Back propagation
*/
protected abstract void bprop();
/**
* Backpropagation: w -= rate * dE/dw, where dE/dw = dE/dy * dy/dnet * dnet/dw
* This method adds the dnet/dw = activation term per unit
* @param u unit (which neuron)
* @param g partial derivative dE/dnet = dE/dy * dy/net
* @param r rate
* @param m momentum
*/
final void bprop(int u, float g, float r, float m) {
// only correct weights if the gradient is large enough
if (params.fast_mode || (
// not doing fast mode, but also don't have anything else to update (neither momentum nor ADADELTA history), and no L1/L2
!_minfo.get_params().adaptive_rate && !_minfo.has_momenta() && params.l1 == 0.0 && params.l2 == 0.0)) {
if (Math.abs(g) <= 1e-10) return;
}
// Log.info("bprop(u=" + u + ", g=" + g + ", r=" + r + ", m=" + m);
double r2 = 0;
final float rho = (float)params.rho;
final float eps = (float)params.epsilon;
final int off = u * _previous._a.length;
for( int i = 0; i < _previous._a.length; i++ ) {
int w = off + i;
// propagate the error dE/dnet to the previous layer, via connecting weights
if( _previous._e != null ) _previous._e[i] += g * _w[w];
//this is the actual gradient dE/dw
float grad = g * _previous._a[i] - (float)(_w[w] * params.l2) - (float)(Math.signum(_w[w]) * params.l1);
// adaptive learning rate r from ADADELTA
if (_E_dx2 != null && _E_g2 != null) {
assert(_wm == null && _bm == null);
final float grad2 = grad*grad;
_E_g2[w] *= rho;
_E_g2[w] += (1f-rho)*grad2;
final float RMS_dx = approxSqrt(_E_dx2[w] + eps);
final float invRMS_g = approxInvSqrt(_E_g2[w] + eps);
r = RMS_dx*invRMS_g;
_E_dx2[w] = rho * _E_dx2[w] + (1f-rho)*r*r*grad2;
}
// TODO finish per-weight acceleration, doesn't help for now
// if( _wp != null && d != 0 ) {
// boolean sign = _wp[w] >= 0;
// double mult = Math.abs(_wp[w]);
// // If the gradient kept its sign, increase
// if( (d >= 0) == sign )
// mult += .05f;
// else {
// if( mult > 1 )
// mult *= .95f;
// else
// sign = !sign;
// d *= mult;
// _wp[w] = sign ? mult : -mult;
if (!params.nesterov_accelerated_gradient) {
final float delta = r * grad;
_w[w] += delta;
if( _wm != null ) {
_w[w] += m * _wm[w];
_wm[w] = delta;
}
} else {
if( _wm != null ) {
_wm[w] *= m;
_wm[w] += grad;
grad = _wm[w];
}
_w[w] += r * grad;
// Log.info("w[" + w + "] += " + r + " * " + d + " = " + _w[w]);
}
if (params.max_w2 != Double.POSITIVE_INFINITY)
r2 += _w[w] * _w[w];
}
if( params.max_w2 != Double.POSITIVE_INFINITY && r2 > params.max_w2 ) { // C.f. Improving neural networks by preventing co-adaptation of feature detectors
final double scale = approxSqrt((float)(params.max_w2 / r2));
for( int i = 0; i < _previous._a.length; i++ ) _w[off + i] *= scale;
}
if (!params.nesterov_accelerated_gradient) {
final float delta = r * g;
_b[u] += delta;
if( _bm != null ) {
_b[u] += m * _bm[u];
_bm[u] = delta;
}
} else {
float d = g;
if( _bm != null ) {
_bm[u] *= m;
_bm[u] += d;
d = _bm[u];
}
_b[u] += r * d;
}
if (Float.isInfinite(_b[u])) _minfo.set_unstable();
}
private static double approxSqrt(double x) {
return Double.longBitsToDouble( ( ( Double.doubleToLongBits( 289358932. )-(1l<<52) )>>1 ) + ( 1l<<61 ) );
}
private static float approxSqrt(float x) {
return Float.intBitsToFloat(532483686 + (Float.floatToRawIntBits(x) >> 1));
}
private static double approxInvSqrt(double x) {
double xhalf = 0.5d*x; x = Double.longBitsToDouble(0x5fe6ec85e7de30daL - (Double.doubleToLongBits(x)>>1)); return x*(1.5d - xhalf*x*x);
}
private static float approxInvSqrt(float x) {
float xhalf = 0.5f*x; x = Float.intBitsToFloat(0x5f3759df - (Float.floatToIntBits(x)>>1)); return x*(1.5f - xhalf*x*x);
}
/**
* The learning rate
* @param n The number of training samples seen so far (for rate_annealing > 0)
* @return Learning rate
*/
public float rate(long n) {
return (float)(params.rate / (1 + params.rate_annealing * n));
}
/**
* The momentum - real number in [0, 1)
* Can be a linear ramp from momentum_start to momentum_stable, over momentum_ramp training samples
* @param n The number of training samples seen so far
* @return momentum
*/
public float momentum(long n) {
double m = params.momentum_start;
if( params.momentum_ramp > 0 ) {
if( n >= params.momentum_ramp )
m = params.momentum_stable;
else
m += (params.momentum_stable - params.momentum_start) * n / params.momentum_ramp;
}
return (float)m;
}
/**
* Input layer of the Neural Network
* This layer is different from other layers as it has no incoming weights,
* but instead gets its activation values from the training points.
*/
public static class Input extends Neurons {
private FrameTask.DataInfo _dinfo; //training data
Input(int units, final FrameTask.DataInfo d) {
super(units);
_dinfo = d;
_a = new float[units];
}
@Override protected void bprop() { throw new UnsupportedOperationException(); }
@Override protected void fprop(long seed, boolean training) { throw new UnsupportedOperationException(); }
/**
* One of two methods to set layer input values. This one is for raw double data, e.g. for scoring
* @param seed For seeding the RNG inside (for input dropout)
* @param data Data (training columns and responses) to extract the training columns
* from to be mapped into the input neuron layer
*/
public void setInput(long seed, final double[] data) {
assert(_dinfo != null);
double [] nums = MemoryManager.malloc8d(_dinfo._nums); // a bit wasteful - reallocated each time
int [] cats = MemoryManager.malloc4(_dinfo._cats); // a bit wasteful - reallocated each time
int i = 0, ncats = 0;
for(; i < _dinfo._cats; ++i){
int c = (int)data[i];
if(c != 0)cats[ncats++] = c + _dinfo._catOffsets[i] - 1;
}
final int n = data.length; // data contains only input features - no response is included
for(;i < n;++i){
double d = data[i];
if(_dinfo._normMul != null) d = (d - _dinfo._normSub[i-_dinfo._cats])*_dinfo._normMul[i-_dinfo._cats];
nums[i-_dinfo._cats] = d;
}
setInput(seed, nums, ncats, cats);
}
/**
* The second method used to set input layer values. This one is used directly by FrameTask.processRow() and by the method above.
* @param seed For seeding the RNG inside (for input dropout)
* @param nums Array containing numerical values, can be NaN
* @param numcat Number of horizontalized categorical non-zero values (i.e., those not being the first factor of a class)
* @param cats Array of indices, the first numcat values are the input layer unit (==column) indices for the non-zero categorical values
* (This allows this array to be re-usable by the caller, without re-allocating each time)
*/
public void setInput(long seed, final double[] nums, final int numcat, final int[] cats) {
Arrays.fill(_a, 0f);
for (int i=0; i<numcat; ++i) _a[cats[i]] = 1f;
for (int i=0; i<nums.length; ++i) _a[_dinfo.numStart()+i] = Double.isNaN(nums[i]) ? 0f : (float)nums[i];
// Input Dropout
final double rate = params.input_dropout_ratio;
if (rate == 0 || _dropout == null) return;
seed += params.seed + 0x1337B4BE;
_dropout.randomlySparsifyActivation(_a, rate, seed);
}
}
/**
* Tanh neurons - most common, most stable
*/
public static class Tanh extends Neurons {
public Tanh(int units) { super(units); }
// public static double fastExp(double val) {
// final long tmp = (long) (1512775 * val + 1072632447);
// return Double.longBitsToDouble(tmp << 32);
@Override protected void fprop(long seed, boolean training) {
gemv(_a, _w, _previous._a, _b, _dropout != null ? _dropout.bits() : null);
for( int o = 0; o < _a.length; o++ )
_a[o] = 1f - 2f / (1f + (float)Math.exp(2*_a[o])); //evals faster than tanh(x), but is slightly less numerically stable - OK
}
@Override protected void bprop() {
final long processed = _minfo.get_processed_total();
float m = momentum(processed);
float r = rate(processed) * (1 - m);
for( int u = 0; u < _a.length; u++ ) {
// Computing partial derivative g = dE/dnet = dE/dy * dy/dnet, where dE/dy is the backpropagated error
// dy/dnet = (1 - a^2) for y(net) = tanh(net)
float g = _e[u] * (1f - _a[u] * _a[u]);
bprop(u, g, r, m);
}
}
}
/**
* Tanh neurons with 50% dropout
*/
public static class TanhDropout extends Tanh {
public TanhDropout(int units) { super(units); }
@Override protected void fprop(long seed, boolean training) {
if (training) {
seed += params.seed + 0xDA7A6000;
_dropout.fillBytes(seed);
super.fprop(seed, true);
}
else {
super.fprop(seed, false);
Utils.div(_a, 2.f);
}
}
}
/**
* Maxout neurons
*/
public static class Maxout extends Neurons {
public Maxout(int units) { super(units); }
@Override protected void fprop(long seed, boolean training) {
float max = 0;
for( int o = 0; o < _a.length; o++ ) {
_a[o] = 0;
if( !training || _dropout == null || _dropout.unit_active(o) ) {
final int off = o * _previous._a.length;
_a[o] = Float.NEGATIVE_INFINITY;
for( int i = 0; i < _previous._a.length; i++ )
_a[o] = Math.max(_a[o], _w[off+i] * _previous._a[i]);
_a[o] += _b[o];
max = Math.max(_a[o], max);
}
}
if( max > 1 ) Utils.div(_a, max);
}
@Override protected void bprop() {
final long processed = _minfo.get_processed_total();
float m = momentum(processed);
float r = rate(processed) * (1 - m);
for( int u = 0; u < _a.length; u++ ) {
float g = _e[u];
// if( _a[o] < 0 ) Not sure if we should be using maxout with a hard zero bottom
// g = 0;
bprop(u, g, r, m);
}
}
}
/**
* Maxout neurons with 50% dropout
*/
public static class MaxoutDropout extends Maxout {
public MaxoutDropout(int units) { super(units); }
@Override protected void fprop(long seed, boolean training) {
if (training) {
seed += params.seed + 0x51C8D00D;
_dropout.fillBytes(seed);
super.fprop(seed, true);
}
else {
super.fprop(seed, false);
Utils.div(_a, 2.f);
}
}
}
/**
* Rectifier linear unit (ReLU) neurons
*/
public static class Rectifier extends Neurons {
public Rectifier(int units) { super(units); }
@Override protected void fprop(long seed, boolean training) {
gemv(_a, _w, _previous._a, _b, _dropout != null ? _dropout.bits() : null);
for( int o = 0; o < _a.length; o++ )
_a[o] = Math.max(_a[o], 0f);
}
@Override protected void bprop() {
final long processed = _minfo.get_processed_total();
float m = momentum(processed);
float r = rate(processed) * (1 - m);
for( int u = 0; u < _a.length; u++ ) {
//(d/dx)(max(0,x)) = 1 if x > 0, otherwise 0
final float g = _a[u] > 0f ? _e[u] : 0;
bprop(u, g, r, m);
}
}
}
/**
* Rectifier linear unit (ReLU) neurons with 50% dropout
*/
public static class RectifierDropout extends Rectifier {
public RectifierDropout(int units) { super(units); }
@Override protected void fprop(long seed, boolean training) {
if (training) {
seed += params.seed + 0x3C71F1ED;
_dropout.fillBytes(seed);
super.fprop(seed, true);
}
else {
super.fprop(seed, false);
Utils.div(_a, 2.f);
}
}
}
/**
* Abstract class for Output neurons
*/
public static abstract class Output extends Neurons {
static final int API_WEAVER = 1;
public static DocGen.FieldDoc[] DOC_FIELDS;
Output(int units) { super(units); }
protected abstract void fprop(); //don't differentiate between testing/training
protected void fprop(long seed, boolean training) { throw new UnsupportedOperationException(); }
protected void bprop() { throw new UnsupportedOperationException(); }
}
/**
* Output neurons for classification - Softmax
*/
public static class Softmax extends Output {
public Softmax(int units) { super(units); }
@Override protected void fprop() {
gemv(_a, _w, _previous._a, _b, null);
final float max = Utils.maxValue(_a);
float scale = 0;
for( int o = 0; o < _a.length; o++ ) {
_a[o] = (float)Math.exp(_a[o] - max);
scale += _a[o];
}
for( int o = 0; o < _a.length; o++ ) {
if (Float.isNaN(_a[o]))
throw new RuntimeException("Numerical instability, predicted NaN.");
_a[o] /= scale;
}
}
/**
* Backpropagation for classification
* Update every weight as follows: w += -rate * dE/dw
* Compute dE/dw via chain rule: dE/dw = dE/dy * dy/dnet * dnet/dw, where net = sum(xi*wi)+b and y = activation function
* @param target actual class label
*/
protected void bprop(int target) {
// if (target == missing_int_value) return; //ignore missing response values
final long processed = _minfo.get_processed_total();
float m = momentum(processed);
float r = rate(processed) * (1 - m);
float g; //partial derivative dE/dy * dy/dnet
for( int u = 0; u < _a.length; u++ ) {
final float t = (u == target ? 1 : 0);
final float y = _a[u];
//dy/dnet = derivative of softmax = (1-y)*y
if (params.loss == Loss.CrossEntropy) {
//nothing else needed, -dCE/dy * dy/dnet = target - y
g = t - y;
} else {
assert(params.loss == Loss.MeanSquare);
//-dMSE/dy = target-y
g = (t - y) * (1 - y) * y;
}
// this call expects dE/dnet
bprop(u, g, r, m);
}
}
}
/**
* Output neurons for regression - Softmax
*/
public static class Linear extends Output {
public Linear(int units) { super(units); }
@Override protected void fprop() {
gemv(_a, _w, _previous._a, _b, null);
}
/**
* Backpropagation for regression
* @param target floating-point target value
*/
protected void bprop(float target) {
// if (target == missing_double_value) return;
if (params.loss != Loss.MeanSquare) throw new UnsupportedOperationException("Regression is only implemented for MeanSquare error.");
final int u = 0;
// Computing partial derivative: dE/dnet = dE/dy * dy/dnet = dE/dy * 1
final float g = target - _a[u]; //for MSE -dMSE/dy = target-y
final long processed = _minfo.get_processed_total();
float m = momentum(processed);
float r = rate(processed) * (1 - m);
bprop(u, g, r, m);
}
}
/**
* Mat-Vec Plus Add (with optional row dropout)
* @param res = a*x+y (pre-allocated, will be overwritten)
* @param a matrix of size rows x cols
* @param x vector of length cols
* @param y vector of length rows
* @param row_bits if not null, check bits of this byte[] to determine whether a row is used or not
*/
static void gemv_naive(final float[] res, final float[] a, final float[] x, final float[] y, byte[] row_bits) {
final int cols = x.length;
final int rows = y.length;
assert(res.length == rows);
for(int r = 0; r<rows; r++) {
res[r] = 0;
if( row_bits != null && (row_bits[r / 8] & (1 << (r % 8))) == 0) continue;
float tmp = 0;
for(int i = 0; i<cols; i++)
tmp += a[r*cols+i] * x[i];
res[r] += tmp + y[r];
}
}
/**
* Optimized Mat-Vec Plus Add (with optional row dropout)
* Optimization: Partial sums can be evaluated in parallel
* @param res = a*x+y (pre-allocated, will be overwritten)
* @param a matrix of size rows x cols
* @param x vector of length cols
* @param y vector of length rows
* @param row_bits if not null, check bits of this byte[] to determine whether a row is used or not
*/
static void gemv(float[] res, float[] a, float[] x, final float[] y, byte[] row_bits) {
final int cols = x.length;
final int rows = y.length;
assert(res.length == rows);
final int extra=cols-cols%8;
final int multiple = (cols/8)*8-1;
int idx = 0;
for (int r = 0; r<rows; r++) {
res[r] = 0;
if( row_bits == null || (row_bits[r / 8] & (1 << (r % 8))) != 0) {
float psum0 = 0, psum1 = 0, psum2 = 0, psum3 = 0, psum4 = 0, psum5 = 0, psum6 = 0, psum7 = 0;
for (int c = 0; c < multiple; c += 8) {
int off = idx + c;
psum0 += a[off ] * x[c ];
psum1 += a[off + 1] * x[c + 1];
psum2 += a[off + 2] * x[c + 2];
psum3 += a[off + 3] * x[c + 3];
psum4 += a[off + 4] * x[c + 4];
psum5 += a[off + 5] * x[c + 5];
psum6 += a[off + 6] * x[c + 6];
psum7 += a[off + 7] * x[c + 7];
}
for (int j = extra; j < cols; j++)
res[r] += a[idx + j] * x[j];
res[r] += psum0 + psum1 + psum2 + psum3;
res[r] += psum4 + psum5 + psum6 + psum7;
res[r] += y[r];
}
idx += cols;
}
}
// Test mat-vec performance
static public class MatVecTester {
@Test
@Ignore
public void run() {
int rows = 2048;
int cols = 1024;
int loops = 5000;
float [] a = new float[rows*cols];
float [] x = new float[cols];
float [] y = new float[rows];
float [] res = new float[rows];
byte [] bits = new byte[rows];
for (int i=0;i<rows;++i) {
y[i] = 0;
res[i] = 0;
bits[i] = (byte)(new String("abcdefghijklmnopqrstuvwxyz").toCharArray()[i%26]);
}
for (int i=0;i<cols;++i) {
x[i] = ((float)i)/cols;
}
for (int i=0;i<rows;++i) {
int off = i*cols;
for (int j=0;j<cols;++j) {
a[off+j] = ((float)(i+j))/cols;
}
}
/**
* naive version
*/
System.out.println("warming up.");
float sum = 0;
//warmup
for (int l=0;l<11000;++l) {
gemv_naive(res, a, x, y, bits);
sum += res[rows/2];
}
//warmup
for (int l=0;l<11000;++l) {
gemv(res, a, x, y, bits);
sum += res[rows/2];
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
/**
* naive version
*/
System.out.println("starting naive.");
sum = 0;
long start = System.currentTimeMillis();
for (int l=0;l<loops;++l) {
gemv_naive(res, a, x, y, bits);
sum += res[rows/2]; //do something useful
}
System.out.println("result: " + sum + " and " + Utils.sum(res));
System.out.println("Naive time: " + PrettyPrint.msecs(System.currentTimeMillis()-start, true));
/**
* optimized version
*/
System.out.println("starting optimized.");
sum = 0;
start = System.currentTimeMillis();
for (int l=0;l<loops;++l) {
gemv(res, a, x, y, bits);
sum += res[rows/2]; //do something useful
}
System.out.println("result: " + sum + " and " + Utils.sum(res));
System.out.println("Optimized time: " + PrettyPrint.msecs(System.currentTimeMillis()-start, true));
}
}
}
|
package javaschool.app;
import asg.cliche.Command;
import asg.cliche.Shell;
import asg.cliche.ShellDependent;
import asg.cliche.ShellFactory;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class PhoneBook implements ShellDependent {
private List<Record> list = new ArrayList<>();
private Shell theShell;
public static void main(String[] args) {
}
@Override
public void cliSetShell(Shell theShell) {
this.theShell = theShell;
}
@Command
public void add(String name) {
Record record = new Record();
record.setName(name);
list.add(record);
}
@Command
public void edit(String name) throws IOException {
Record record = lookup(name);
if (record == null) {
System.out.printf("Record with name \"%s\" not found.\n", name);
} else {
ShellFactory.createSubshell(record.getName(), theShell, "Editing " + record.getName(), record)
.commandLoop();
}
}
@Command
public List<Record> list() {
return list;
}
@Command
public void clear() {
list.clear();
}
private Record lookup(String name) {
for (Record record: list) {
if (name.equals(record.getName())) {
return record;
}
}
return null;
}
}
|
package javaschool.app;
import asg.cliche.Command;
import asg.cliche.Shell;
import asg.cliche.ShellDependent;
import asg.cliche.ShellFactory;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class PhoneBook implements ShellDependent {
private List<Record> list = new ArrayList<>();
private Shell theShell;
public static void main(String[] args) {
}
@Override
public void cliSetShell(Shell theShell) {
this.theShell = theShell;
}
@Command
public void add(String name) {
Record record = new Record();
record.setName(name);
list.add(record);
}
@Command
public void edit(String name) throws IOException {
Record record = lookup(name);
if (record == null) {
System.out.printf("Record with name \"%s\" not found.\n", name);
} else {
ShellFactory.createSubshell(record.getName(), theShell, "Editing " + record.getName(), record)
.commandLoop();
}
}
@Command
public List<Record> list() {
return list;
}
@Command
public void clear() {
list.clear();
}
@Command
public List<Record> search(String substring) {
List<Record> list = new ArrayList<>();
this.list.forEach((Record record) -> {
if (record.getName().toLowerCase().contains(substring.toLowerCase())) {
list.add(record);
}
});
return list;
}
private Record lookup(String name) {
for (Record record : list) {
if (name.equals(record.getName())) {
return record;
}
}
return null;
}
}
|
package net.praqma.monkit;
import java.io.BufferedWriter;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.StringWriter;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import javax.xml.validation.Validator;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
public class MonKit {
public static final String __ROOT_TAG = "categories";
public static final String __SCHEMA = "http://code.praqma.net/schemas/monkit/1.0.1/monkit.xsd";
private File destination = null;
private Element root = null;
private Document doc = null;
/**
* Constructor initializing an empty MonKit
*/
public MonKit() {
destination = new File( "monkit.xml" );
initialize();
}
/**
* Constructor initializing an empty MonKit with a predefined output
* destination
*
* @param destination
* A File representing the output file
*/
public MonKit( File destination ) {
initialize();
}
/**
* Constructor initializing a MonKit given a Document
*
* @param doc
* A valid MonKit Document
* @throws MonKitException
*/
public MonKit( Document doc ) throws MonKitException {
this.doc = doc;
Node node = doc.getFirstChild();
if( node == null ) {
throw new MonKitException( "Empty MonKit file" );
}
if( !node.getNodeName().equals( MonKit.__ROOT_TAG ) ) {
throw new MonKitException( "Not a valid MonKit format" );
}
root = (Element) node;
}
private void initialize() {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware( true );
try {
factory.setSchema( MonKit.getSchema() );
} catch( Exception e ) {
/* No op, just don't set the schema... */
}
DocumentBuilder builder;
try {
builder = factory.newDocumentBuilder();
doc = builder.newDocument();
} catch( ParserConfigurationException e ) {
e.printStackTrace();
}
/* Preparing the root note */
root = (Element) doc.appendChild( doc.createElement( MonKit.__ROOT_TAG ) );
root.setAttributeNS( "http:
}
/**
* Create a MonKit object from an xml file
*
* @param xml
* A File with the MonKit obersations
* @return A new MonKit object
* @throws MonKitException
*/
public static MonKit fromXML( File xml ) throws MonKitException {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware( true );
DocumentBuilder builder;
Document doc = null;
try {
builder = factory.newDocumentBuilder();
doc = builder.parse( xml );
} catch( Exception e ) {
throw new MonKitException( "Could not parse the file" );
}
return new MonKit( doc );
}
/**
* Given a String, a MonKit is initialized
*
* @param str
* A valid MonKit
* @return A MonKit
* @throws MonKitException
*/
public static MonKit fromString( String str ) throws MonKitException {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware( true );
DocumentBuilder builder;
Document doc = null;
try {
builder = factory.newDocumentBuilder();
doc = builder.parse( new ByteArrayInputStream( str.getBytes( "UTF-8" ) ) );
} catch( Exception e ) {
throw new MonKitException( "Coult not parse the file" );
}
return new MonKit( doc );
}
/**
* Add a category to the MonKit
*
* @param name
* The name of the category
* @param scale
* The scale of the category
*/
public void addCategory( String name, String scale ) {
if( getCategory( name ) != null ) {
return;
}
Element c = doc.createElement( "category" );
c.setAttribute( "name", name );
c.setAttribute( "scale", scale );
c.appendChild( doc.createElement( "observations" ) );
root.appendChild( c );
}
/**
* Add an observation given the three arguments
*
* @param name
* Name of the observation
* @param scale
* The scale of the observation
* @param value
* Value of the observation
* @throws MonKitException
*/
public void add( String name, String value, String category ) {
_add( name, value, category );
}
/**
* Add an observation given a {@link MonKitObservation}
*
* @param mke
* A MonKitElement
*/
public void add( MonKitObservation mke, String category ) {
_add( mke.getName(), mke.getValue(), category );
}
private void _add( String name, String value, String category ) {
Element c = getCategory( category );
if( c == null ) {
return;
}
Element e = getObservation( name, category );
if( e != null ) {
e.setTextContent( value );
e.setAttribute( "name", name );
} else {
Element o = doc.createElement( "observation" );
o.setAttribute( "name", name );
o.setTextContent( value );
Element obs = (Element) c.getElementsByTagName( "observations" ).item( 0 );
if( obs != null ) {
obs.appendChild( o );
}
}
}
/**
* Add a List of categories to the MonKit
*
* @param categories
* The list of MonKitCategories
*/
public void add( List<MonKitCategory> categories ) {
for( MonKitCategory mkc : categories ) {
add( mkc );
}
}
/**
* Add another MonKitCategory to the MonKit
*
* @param mkc
*/
public void add( MonKitCategory mkc ) {
addCategory( mkc.getName(), mkc.getScale() );
add( mkc, mkc.getName() );
}
/**
* Add a series of observations
*
* @param elements
* A list of {@link MonKitObservation}s
*/
public void add( List<MonKitObservation> elements, String category ) {
for( MonKitObservation mke : elements ) {
add( mke, category );
}
}
/**
* Get a List of the available categories
*
* @return
*/
public List<MonKitCategory> getCategories() {
NodeList nodes = root.getElementsByTagName( "category" );
List<MonKitCategory> elements = new ArrayList<MonKitCategory>();
for( int i = 0, len = nodes.getLength(); i < len; ++i ) {
Node node = nodes.item( i );
if( node.getNodeType() == Node.ELEMENT_NODE ) {
Element e = (Element) node;
String name = e.getAttribute( "name" );
String scale = e.getAttribute( "scale" );
elements.add( new MonKitCategory( name, scale, getObservations( name ) ) );
}
}
return elements;
}
private Element getCategory( String name ) {
NodeList nodes = root.getElementsByTagName( "category" );
for( int i = 0, len = nodes.getLength(); i < len; ++i ) {
Node node = nodes.item( i );
if( node.getNodeType() == Node.ELEMENT_NODE ) {
Element e = (Element) node;
if( e.getAttribute( "name" ).equalsIgnoreCase( name ) ) {
return e;
}
}
}
return null;
}
private Element getObservationsElement( Element category ) {
NodeList nodes = category.getElementsByTagName( "observations" );
for( int i = 0, len = nodes.getLength(); i < len; ++i ) {
Node node = nodes.item( i );
if( node.getNodeType() == Node.ELEMENT_NODE ) {
return (Element) node;
}
}
return null;
}
/**
* Retrieve the observations
*
* @return A list of {@link MonKitObservation}s
*/
public List<MonKitObservation> getObservations( String name ) {
Element category = getCategory( name );
if( category == null ) {
return null;
}
NodeList nodes = category.getElementsByTagName( "observation" );
List<MonKitObservation> elements = new ArrayList<MonKitObservation>();
for( int i = 0, len = nodes.getLength(); i < len; ++i ) {
Node node = nodes.item( i );
if( node.getNodeType() == Node.ELEMENT_NODE ) {
Element e = (Element) node;
elements.add( new MonKitObservation( e.getAttribute( "name" ), e.getTextContent() ) );
}
}
return elements;
}
private Element getObservation( String name, String category ) {
Element c = getCategory( category );
if( c == null ) {
return null;
}
Element obs = (Element) c.getElementsByTagName( "observations" ).item( 0 );
NodeList nodes = obs.getElementsByTagName( "observation" );
for( int i = 0, len = nodes.getLength(); i < len; ++i ) {
Node node = nodes.item( i );
if( node.getNodeType() == Node.ELEMENT_NODE ) {
Element e = (Element) node;
if( e.getAttribute( "name" ).equalsIgnoreCase( name ) ) {
return e;
}
}
}
return null;
}
/**
* Merge two or more {@link MonKit}s
*
* @param mks
* An array of MonKits
* @return A new instantiation of MonKit
*/
public static MonKit merge( MonKit... mks ) {
MonKit nmk = new MonKit();
for( MonKit mk : mks ) {
if( mk != null ) {
nmk.add( mk.getCategories() );
}
}
return nmk;
}
/**
* Merge two or more {@link MonKit}s
*
* @param mks
* A List of MonKits
* @return A new instantiation of MonKit
*/
public static MonKit merge( List<MonKit> mks ) {
MonKit nmk = new MonKit();
for( MonKit mk : mks ) {
if( mk != null ) {
nmk.add( mk.getCategories() );
}
}
return nmk;
}
/**
* Get the observations as String
*
* @return
*/
public String getXML() {
StringWriter out = new StringWriter();
try {
TransformerFactory factory = TransformerFactory.newInstance();
Transformer transformer = factory.newTransformer();
transformer.setOutputProperty( OutputKeys.METHOD, "xml" );
transformer.setOutputProperty( OutputKeys.INDENT, "yes" );
transformer.setOutputProperty( "{http://xml.apache.org/xslt}indent-amount", "4" );
Source src = new DOMSource( doc );
Result dest = new StreamResult( out );
transformer.transform( src, dest );
} catch( Exception e ) {
e.printStackTrace();
}
return out.toString();
}
public String toString() {
return getXML();
}
public static Schema getSchema() {
SchemaFactory schemaFactory = SchemaFactory.newInstance( "http:
try {
return schemaFactory.newSchema( new URL( "http://code.praqma.net/schemas/monkit/1.0.0/monkit.xsd" ) );
} catch( Exception e ) {
e.printStackTrace();
/* Just to be sure! */
} catch( NoSuchMethodError e ) {
return null;
}
return null;
}
/**
* Validate the MonKit xml file
*
* @return True or false whether the xml is valid or not
*/
public boolean validate() {
SchemaFactory schemaFactory = SchemaFactory.newInstance( "http:
try {
Schema schema = schemaFactory.newSchema( new URL( __SCHEMA ) );
Validator validator = schema.newValidator();
validator.validate( new DOMSource( doc ) );
return true;
} catch( MalformedURLException e ) {
System.err.println( "Whoops... Not good: " + e );
} catch( SAXException e ) {
System.err.println( "Not valid: " + e );
} catch( IOException e ) {
System.err.println( "Whoops... Not good: " + e );
}
return false;
}
public List<MonKitObservation> toList( String name ) {
return getObservations( name );
}
/**
* Save the MonKit
*
* @throws IOException
*/
public void save() throws IOException {
save( destination );
}
/**
* Save the MonKit to a given destination
*
* @param filename
* @throws IOException
*/
public void save( File filename ) throws IOException {
String xml = getXML();
try {
System.out.println( "[MonKit] Saving file to " + filename.getAbsolutePath() );
BufferedWriter bw = new BufferedWriter( new FileWriter( filename ) );
this.destination = filename;
bw.append( xml );
bw.close();
} catch( IOException e ) {
throw e;
}
}
public File getDestination() {
return destination;
}
}
|
package no.ntnu.okse;
import no.ntnu.okse.core.CoreService;
import no.ntnu.okse.web.Server;
public class Application {
public static void main(String[] args) {
Server server = new Server();
CoreService cs = new CoreService();
server.run();
cs.run();
}
}
|
package org.apdplat.word;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.apdplat.word.segmentation.Segmentation;
import org.apdplat.word.segmentation.StopWord;
import org.apdplat.word.segmentation.Word;
import org.apdplat.word.segmentation.WordSegmentation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
*
* @author
*/
public class WordSeg {
private static final Logger LOGGER = LoggerFactory.getLogger(WordSeg.class);
private static final Segmentation segmentation = new WordSegmentation();
/**
*
* @param text
* @return
*/
public static List<Word> seg(String text){
List<Word> words = segmentation.seg(text);
Iterator<Word> iter = words.iterator();
while(iter.hasNext()){
Word word = iter.next();
if(StopWord.is(word.getText())){
LOGGER.debug(""+word.getText());
iter.remove();
}
}
return words;
}
/**
*
* @param input
* @param output
* @throws Exception
*/
public static void seg(File input, File output) throws Exception{
LOGGER.info(""+input.toString());
float max=(float)Runtime.getRuntime().maxMemory()/1000000;
float total=(float)Runtime.getRuntime().totalMemory()/1000000;
float free=(float)Runtime.getRuntime().freeMemory()/1000000;
String pre=":"+max+"-"+total+"+"+free+"="+(max-total+free);
try(BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(input),"utf-8"));
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(output),"utf-8"))){
long size = Files.size(input.toPath());
LOGGER.info("size:"+size);
LOGGER.info(""+(float)size/1024/1024+" MB");
int textLength=0;
int progress=0;
long start = System.currentTimeMillis();
String line = null;
while((line = reader.readLine()) != null){
textLength += line.length();
List<Word> words = seg(line);
for(Word word : words){
writer.write(word.getText()+" ");
}
writer.write("\n");
progress += line.length();
if( progress > 500000){
progress = 0;
LOGGER.info(""+(int)((float)textLength*2/size*100)+"%");
}
}
long cost = System.currentTimeMillis() - start;
float rate = textLength/cost;
LOGGER.info(""+textLength);
LOGGER.info(""+cost+" ");
LOGGER.info(""+rate+" /");
}
max=(float)Runtime.getRuntime().maxMemory()/1000000;
total=(float)Runtime.getRuntime().totalMemory()/1000000;
free=(float)Runtime.getRuntime().freeMemory()/1000000;
String post=":"+max+"-"+total+"+"+free+"="+(max-total+free);
LOGGER.info(pre);
LOGGER.info(post);
LOGGER.info(" "+input.toString()+" "+output);
}
private static void demo(){
long start = System.currentTimeMillis();
List<String> sentences = new ArrayList<>();
sentences.add("APDPlat");
sentences.add("");
sentences.add("");
sentences.add("");
sentences.add("");
sentences.add("");
sentences.add("");
sentences.add("");
sentences.add("");
sentences.add("");
sentences.add("");
sentences.add("");
sentences.add("");
sentences.add(",");
sentences.add("");
sentences.add("");
sentences.add("");
sentences.add("");
sentences.add("");
sentences.add("");
sentences.add("");
sentences.add("");
sentences.add("");
sentences.add("");
sentences.add("");
sentences.add("");
sentences.add("");
sentences.add("");
sentences.add("");
sentences.add("");
sentences.add("");
sentences.add("");
sentences.add("");
sentences.add("");
sentences.add("");
sentences.add("");
sentences.add("");
sentences.add("");
sentences.add("");
sentences.add("");
sentences.add("");
sentences.add("wordysc");
int i=1;
for(String sentence : sentences){
List<Word> words = seg(sentence);
LOGGER.info((i++)+": "+sentence);
LOGGER.info(" "+words);
}
long cost = System.currentTimeMillis() - start;
LOGGER.info(": "+cost+" ");
}
public static void processCommand(String... args) throws Exception{
if(args == null || args.length < 1){
LOGGER.info("");
return;
}
switch(args[0]){
case "demo":
demo();
break;
case "text":
if(args.length != 2){
showUsage();
}else{
List<Word> words = seg(args[1]);
LOGGER.info(""+args[1]);
LOGGER.info(""+words.toString());
}
break;
case "file":
if(args.length != 3){
showUsage();
}else{
seg(new File(args[1]), new File(args[2]));
}
break;
default:
LOGGER.info(""+args[0]);
}
}
private static void run(String encoding) throws UnsupportedEncodingException, IOException, Exception {
try(BufferedReader reader = new BufferedReader(new InputStreamReader(System.in, encoding))){
String line = null;
while((line = reader.readLine()) != null){
if("exit".equals(line)){
System.exit(0);
LOGGER.info("");
return;
}
if(line.trim().equals("")){
continue;
}
processCommand(line.split(" "));
showUsage();
}
}
}
private static void showUsage(){
LOGGER.info("");
LOGGER.info("********************************************");
LOGGER.info(": command [text] [input] [output]");
LOGGER.info("commanddemotextfile");
LOGGER.info("demo");
LOGGER.info("text APDPlat");
LOGGER.info("file d:/text.txt d:/word.txt");
LOGGER.info("exit");
LOGGER.info("********************************************");
LOGGER.info("");
}
public static void main(String[] args) throws Exception{
String encoding = "utf-8";
if(args.length == 1){
encoding = args[0];
}
showUsage();
run(encoding);
}
}
|
package org.asu.apmg;
import hudson.EnvVars;
import hudson.Extension;
import hudson.Launcher;
import hudson.model.AbstractBuild;
import hudson.model.AbstractProject;
import hudson.model.BuildListener;
import hudson.tasks.BuildStepDescriptor;
import hudson.tasks.Builder;
import org.apache.commons.io.FileUtils;
import org.kohsuke.stapler.DataBoundConstructor;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Properties;
/**
* @author aesanch2
*/
public class APMGBuilder extends Builder {
private APMGGit git;
private boolean rollbackEnabled, updatePackageEnabled;
// Fields in config.jelly must match the parameter names in the "DataBoundConstructor"
@DataBoundConstructor
public APMGBuilder(Boolean rollbackEnabled,
Boolean updatePackageEnabled) {
this.rollbackEnabled = rollbackEnabled;
this.updatePackageEnabled = updatePackageEnabled;
}
@Override
public boolean perform(AbstractBuild build, Launcher launcher, BuildListener listener) {
String newCommit;
String prevCommit;
String workspaceDirectory;
String jobName;
String buildNumber;
String jenkinsHome;
ArrayList<String> listOfDestructions, listOfUpdates;
ArrayList<APMGMetadataObject> members;
try{
//Load our environment variables for the job
EnvVars envVars = build.getEnvironment(listener);
newCommit = envVars.get("GIT_COMMIT");
workspaceDirectory = envVars.get("WORKSPACE");
jobName = envVars.get("JOB_NAME");
buildNumber = envVars.get("BUILD_NUMBER");
jenkinsHome = envVars.get("JENKINS_HOME");
//Create a deployment space for this job within the workspace
File deployStage = new File(workspaceDirectory + "/apmg");
if(deployStage.exists()){
FileUtils.deleteDirectory(deployStage);
}deployStage.mkdirs();
//Set up our repository connection
String pathToRepo = workspaceDirectory + "/.git";
//Read this job's property file and setup the appropriate APMGGit wrapper
String jobRoot = jenkinsHome + "/jobs/";
File lastSuccess = new File(jobRoot + jobName + "/lastSuccessful/apmgBuilder.properties");
File newSuccess = new File(jobRoot + jobName + "/builds/" + buildNumber + "/apmgBuilder.properties");
OutputStream output = new FileOutputStream(newSuccess);
Properties jobProperties = new Properties();
if (lastSuccess.exists() && !lastSuccess.isDirectory()){
jobProperties.load(new FileInputStream(lastSuccess));
prevCommit = jobProperties.getProperty("LAST_SUCCESSFUL_COMMIT");
git = new APMGGit(pathToRepo, prevCommit, newCommit);
}
//This was the initial commit to the repo or the first build
else{
prevCommit = null;
git = new APMGGit(pathToRepo, newCommit);
}
//Get our lists
listOfDestructions = git.getDeletions();
listOfUpdates = git.getNewChangeSet();
//Generate the manifests
members = APMGUtility.generateManifests(listOfDestructions, listOfUpdates, deployStage.getPath());
listener.getLogger().println("[APMG] - Created deployment package.");
//Copy the files to the deployStage
APMGUtility.replicateMembers(members, workspaceDirectory, deployStage.getPath());
//Check for rollback
if (getRollbackEnabled() && prevCommit != null){
String rollbackDirectory = newSuccess.getParent() + "/rollback";
File rollbackStage = new File(rollbackDirectory);
if(rollbackStage.exists()){
FileUtils.deleteDirectory(rollbackStage);
}rollbackStage.mkdirs();
//Get our lists
ArrayList<String> listOfOldItems = git.getOldChangeSet();
ArrayList<String> listOfAdditions = git.getAdditions();
//Generate the manifests for the rollback package
ArrayList<APMGMetadataObject> rollbackMembers =
APMGUtility.generateManifests(listOfAdditions, listOfOldItems, rollbackDirectory);
//Copy the files to the rollbackStage and zip up the rollback stage
git.getPrevCommitFiles(rollbackMembers, rollbackDirectory);
APMGUtility.zipRollbackPackage(rollbackDirectory, jobName, buildNumber);
listener.getLogger().println("[APMG] - Created rollback package.");
}
//Check to see if we need to update the repository's package.xml file
if(updatePackageEnabled){
boolean updateRequired = git.updatePackageXML(workspaceDirectory + "/src/package.xml");
if (updateRequired)
listener.getLogger().println("[APMG] - Updated repository package.xml file.");
}
//Store the commit
jobProperties.setProperty("LAST_SUCCESSFUL_COMMIT", newCommit);
jobProperties.store(output, null);
}catch(Exception e){
e.printStackTrace(listener.getLogger());
return false;
}
return true;
}
// Overridden for better type safety.
// If your plugin doesn't really define any property on Descriptor,
// you don't have to do this.
@Override
public DescriptorImpl getDescriptor() {
return (DescriptorImpl)super.getDescriptor();
}
/**
* Descriptor for {@link APMGBuilder}. Used as a singleton.
* The class is marked as public so that it can be accessed from views.
*/
@Extension // This indicates to Jenkins that this is an implementation of an extension point.
public static final class DescriptorImpl extends BuildStepDescriptor<Builder> {
/**
* In order to load the persisted global configuration, you have to
* call load() in the constructor.
*/
public DescriptorImpl() {
load();
}
public boolean isApplicable(Class<? extends AbstractProject> aClass) {
// Indicates that this builder can be used with all kinds of project types
return true;
}
/**
* This human readable name is used in the configuration screen.
*/
public String getDisplayName() {
return "APMG";
}
}
public boolean getRollbackEnabled() { return rollbackEnabled;}
public boolean getUpdatePackageEnabled() {return updatePackageEnabled; }
}
|
package org.basex.query.expr;
import java.io.IOException;
import org.basex.io.serial.Serializer;
import org.basex.query.QueryContext;
import org.basex.query.QueryException;
import org.basex.query.item.Value;
import org.basex.query.iter.Iter;
import org.basex.query.util.Var;
import org.basex.util.InputInfo;
public final class Try extends Single {
/** Query exception. */
QueryException qe;
/** Catches. */
private final Catch[] ctch;
/**
* Constructor.
* @param ii input info
* @param t try expression
* @param c catch expressions
*/
public Try(final InputInfo ii, final Expr t, final Catch[] c) {
super(ii, t);
ctch = c;
}
@Override
public Expr comp(final QueryContext ctx) throws QueryException {
// check if none or all try/catch expressions are updating
final Expr[] tmp = new Expr[ctch.length + 1];
tmp[0] = expr;
for(int c = 0; c < ctch.length; ++c) tmp[c + 1] = ctch[c].expr;
checkUp(ctx, tmp);
// compile expression
try {
super.comp(ctx);
// return value, which will never throw an error
if(expr.value()) return expr;
} catch(final QueryException ex) {
// catch exception for evaluation if expression fails at compile time
qe = ex;
}
// compile catch expressions
for(final Catch c : ctch) c.comp(ctx);
// evaluate result type
type = expr.type();
for(final Catch c : ctch) type = type.intersect(c.type());
return this;
}
@Override
public Iter iter(final QueryContext ctx) throws QueryException {
return value(ctx).iter();
}
@Override
public Value value(final QueryContext ctx) throws QueryException {
final int s = ctx.vars.size();
try {
// don't catch errors from error handlers
if(qe != null) return err(ctx, qe);
try {
return expr.value(ctx);
} catch(final QueryException ex) {
return err(ctx, ex);
}
} finally {
// always reset the scope
ctx.vars.reset(s);
}
}
/**
* Handles an exception.
* @param ctx query context
* @param ex query exception
* @return result
* @throws QueryException query exception
*/
private Value err(final QueryContext ctx, final QueryException ex)
throws QueryException {
for(final Catch c : ctch) {
final Value val = c.value(ctx, ex);
if(val != null) return val;
}
throw ex;
}
@Override
public int count(final Var v) {
int c = super.count(v);
for(final Catch ct : ctch) c += ct.count(v);
return c;
}
@Override
public boolean uses(final Use u) {
for(final Catch c : ctch) if(c.uses(u)) return true;
return super.uses(u);
}
@Override
public boolean removable(final Var v) {
for(final Catch c : ctch) if(!c.removable(v)) return false;
return super.removable(v);
}
@Override
public Expr remove(final Var v) {
for(final Catch c : ctch) c.remove(v);
return super.remove(v);
}
@Override
public void plan(final Serializer ser) throws IOException {
ser.openElement(this);
expr.plan(ser);
for(final Catch c : ctch) c.plan(ser);
ser.closeElement();
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder("try { " + expr + " }");
for(final Catch c : ctch) sb.append(" " + c);
return sb.toString();
}
}
|
package org.cruk.seq;
import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Arrays;
import java.util.Random;
import nu.xom.Document;
import nu.xom.Element;
import nu.xom.Serializer;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.GnuParser;
import org.apache.commons.cli.ParseException;
import org.cruk.util.CommandLineUtility;
/**
* Program for sampling a specified number of records from a FASTQ file.
*
* @author eldrid01
*/
public class SampleFastq extends CommandLineUtility
{
public static int DEFAULT_SAMPLE_SIZE = 100000;
public static int DEFAULT_MAX_SAMPLE_FROM = 5000000;
private String datasetId;
private String[] fastqFilenames;
private String summaryFilename;
private String prefix;
private int sampleSize;
private int maxSampleFrom;
/**
* Runs the SampleFastq utility with the given command-line arguments.
*
* @param args
*/
public static void main(String[] args)
{
SampleFastq sampleFastq = new SampleFastq(args);
sampleFastq.execute();
}
/**
* Initializes a new SampleFastq utility instance with the given command-line arguments.
*
* @param args
*/
private SampleFastq(String[] args)
{
super("fastq_file(s)", args);
}
/**
* Parse command line arguments.
*
* @param args
*/
protected void parseCommandLineArguments(String[] args)
{
CommandLineParser parser = new GnuParser();
options.addOption("i", "dataset-id", true, "Identifier for the sequence dataset.");
options.addOption("s", "sample-size", true, "Number of sequences to sample for alignment (default: " + DEFAULT_SAMPLE_SIZE + ")");
options.addOption("m", "max-sample-from", true, "Maximum number of sequences to sample from (default: " + DEFAULT_MAX_SAMPLE_FROM + ")");
options.addOption("o", "output-file", true, "Output file for sampled FASTQ sequences");
options.addOption("x", "summary-file", true, "Output file containing sampling summary statistics");
options.addOption("p", "seq-id-prefix", true, "The prefix to use if renaming sequence identifiers");
try
{
CommandLine commandLine = parser.parse(options, args);
if (commandLine.hasOption("dataset-id"))
{
datasetId = commandLine.getOptionValue("dataset-id");
}
if (commandLine.hasOption("sample-size"))
{
try
{
sampleSize = Integer.parseInt(commandLine.getOptionValue("sample-size"));
}
catch (NumberFormatException e)
{
error("Error parsing command line option: sample size must be an integer number.");
}
}
else
{
sampleSize = DEFAULT_SAMPLE_SIZE;
}
if (sampleSize < 1)
{
error("Error: invalid sample size.");
}
if (commandLine.hasOption("max-sample-from"))
{
try
{
maxSampleFrom = Integer.parseInt(commandLine.getOptionValue("max-sample-from"));
}
catch (NumberFormatException e)
{
error("Error parsing command line option: maximum number to sample from must be an integer number.");
}
}
else
{
maxSampleFrom = DEFAULT_MAX_SAMPLE_FROM;
}
if (maxSampleFrom < sampleSize)
{
error("Error: sample size cannot be greater than the number of records from which to sample.");
}
if (commandLine.hasOption("output-file"))
{
outputFilename = commandLine.getOptionValue("output-file");
}
if (outputFilename == null)
{
error("Error: an output file must be specified.");
}
if (commandLine.hasOption("summary-file"))
{
summaryFilename = commandLine.getOptionValue("summary-file");
}
if (commandLine.hasOption("seq-id-prefix"))
{
prefix = commandLine.getOptionValue("seq-id-prefix");
}
args = commandLine.getArgs();
if (args.length == 0)
{
error("Error parsing command line: missing FASTQ filename.", true);
}
fastqFilenames = args;
}
catch (ParseException e)
{
error("Error parsing command-line options: " + e.getMessage(), true);
}
}
/**
* Runs the FASTQ sampling utility.
*
* @throws Exception
*/
protected void run() throws Exception
{
try
{
Fastq[] records = reservoirSampling(fastqFilenames, sampleSize, maxSampleFrom, prefix != null);
// Later code requires that the prefix ends with an underscore.
String safePrefix = prefix;
if (prefix != null && !prefix.endsWith("_"))
{
safePrefix = prefix + "_";
}
for (int i = 0; i < records.length; i++)
{
Fastq record = records[i];
if (prefix != null)
{
record.setDescription(safePrefix + (i + 1));
}
out.print(record);
}
writeSummary(datasetId, records.length);
}
catch (FastqFormatException e)
{
error(e.getMessage());
}
}
/**
* Samples records from a FASTQ file using reservoir sampling.
*
* @param fastqFilenames the FASTQ file(s).
* @param sampleSize the number of records to sample.
* @param maxRecordsToSample the maximum number of records to sample from.
* @param removeDescriptions to remove sequence identifiers/descriptions to save on space.
* @return the sampled FASTQ records.
* @throws IOException
* @throws FastqFormatException
*/
private Fastq[] reservoirSampling(String[] fastqFilenames, int sampleSize, int maxSampleFrom, boolean removeDescriptions)
throws IOException, FastqFormatException
{
FastqReader reader = new FastqReader(fastqFilenames, true);
Fastq[] records = new Fastq[sampleSize];
for (int i = 0; i < sampleSize; i++)
{
Fastq record = reader.readFastq();
if (record == null) return Arrays.copyOf(records, i);
if (removeDescriptions) record.setDescription(null);
records[i] = record;
}
Random rand = new Random();
for (int i = sampleSize + 1; i <= maxSampleFrom; i++)
{
Fastq record = reader.readFastq();
if (record == null) break;
int j = rand.nextInt(i);
if (j < sampleSize) records[j] = record;
}
reader.close();
return records;
}
/**
* Writes an XML file containing a summary of the sampling.
*
* @param datasetId the dataset id
* @param sampledCount the sample size
*/
private void writeSummary(String datasetId, int sampledCount)
{
if (summaryFilename == null) return;
BufferedOutputStream outputStream = null;
try
{
outputStream = new BufferedOutputStream(new FileOutputStream(summaryFilename));
}
catch (IOException e)
{
error("Error creating file " + summaryFilename);
}
try
{
Element root = new Element("SamplingSummary");
Element element = new Element("DatasetId");
if (datasetId != null) element.appendChild(datasetId);
root.appendChild(element);
element = new Element("SampledCount");
element.appendChild(Integer.toString(sampledCount));
root.appendChild(element);
Document document = new Document(root);
Serializer serializer;
serializer = new Serializer(outputStream, "ISO-8859-1");
serializer.setIndent(2);
serializer.setMaxLength(64);
serializer.setLineSeparator("\n");
serializer.write(document);
outputStream.flush();
}
catch (UnsupportedEncodingException e)
{
error(e);
}
catch (IOException e)
{
error("Error writing summary XML file");
}
finally
{
try
{
outputStream.close();
}
catch (IOException e)
{
error("Error closing file " + summaryFilename);
}
}
}
}
|
package org.lantern;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import org.codehaus.jackson.annotate.JsonIgnoreProperties;
import org.lantern.proxy.FallbackProxy;
@JsonIgnoreProperties(ignoreUnknown = true)
public class BaseS3Config {
public static final String DEFAULT_CONTROLLER_ID = "lanternctrl1-2";
public static final String DEFAULT_FLASHLIGHT_CLOUDCONFIG = "https://s3.amazonaws.com/lantern_config/cloud.yaml.1.5.8";
public static final String DEFAULT_FLASHLIGHT_CLOUDCONFIG_CA = "
public static final String DEFAULT_WADDELL_ADDR = "128.199.130.61:443";
public static final String DEFAULT_FLASHLIGHT_CONFIG_ADDR = "localhost:23000";
public static final String[] DEFAULT_MASQUERADE_HOSTS = new String[] {
"elance.com",
"ojooo.com",
"news.ycombinator.com",
};
public static final Map<String, String> DEFAULT_HOSTS_TO_CERTS =
new HashMap<String, String>();
private String controller = DEFAULT_CONTROLLER_ID;
private int minpoll = 5;
private int maxpoll = 15;
private Collection<FallbackProxy> fallbacks = Collections.emptyList();
/**
* Milliseconds to wait before retrying disconnected signaling connections.
*/
private long signalingRetryTime = 6000;
/**
* Get stats every minute.
*/
private int statsGetInterval = 60;
/**
* Wait a bit before first posting stats, to give the system a chance to
* initialize metadata.
*/
private int statsPostInterval = 5 * 60;
private String[] masqueradeHosts = DEFAULT_MASQUERADE_HOSTS;
private String dnsRegUrl = "cloudflare-peerdnsreg.herokuapp.com";
/**
* Note that DEFAULT_HOSTS_TO_CERTS is populated in the constructor of
* subclasses.
*/
private Map<String, String> masqueradeHostsToCerts = DEFAULT_HOSTS_TO_CERTS;
private String flashlightCloudConfig = DEFAULT_FLASHLIGHT_CLOUDCONFIG;
private String flashlightCloudConfigCA = DEFAULT_FLASHLIGHT_CLOUDCONFIG_CA;
private String waddellAddr = DEFAULT_WADDELL_ADDR;
private String flashlightConfigAddr = DEFAULT_FLASHLIGHT_CONFIG_ADDR;
public BaseS3Config() {
}
public String getController() {
return controller;
}
public int getMinpoll() {
return minpoll;
}
public int getMaxpoll() {
return maxpoll;
}
public Collection<FallbackProxy> getFallbacks() {
return fallbacks;
}
public void setController(String controller) {
this.controller = controller;
}
public void setMinpoll(int minpoll) {
this.minpoll = minpoll;
}
public void setMaxpoll(int maxpoll) {
this.maxpoll = maxpoll;
}
public void setFallbacks(Collection<FallbackProxy> fallbacks) {
this.fallbacks = fallbacks;
}
public int getStatsGetInterval() {
return statsGetInterval;
}
public void setStatsGetInterval(int statsGetInterval) {
this.statsGetInterval = statsGetInterval;
}
public int getStatsPostInterval() {
return statsPostInterval;
}
public void setStatsPostInterval(int statsPostInterval) {
this.statsPostInterval = statsPostInterval;
}
public long getSignalingRetryTime() {
return signalingRetryTime;
}
public void setSignalingRetryTime(long signalingRetryTime) {
this.signalingRetryTime = signalingRetryTime;
}
public Map<String, String> getMasqueradeHostsToCerts() {
return this.masqueradeHostsToCerts;
}
public void setMasqueradeHostsToCerts(Map<String, String> masqueradeHostsToCerts) {
this.masqueradeHostsToCerts = masqueradeHostsToCerts;
}
public String getDnsRegUrl() {
return dnsRegUrl;
}
public void setDnsRegUrl(String dnsRegUrl) {
this.dnsRegUrl = dnsRegUrl;
}
public String[] getMasqueradeHosts() {
return masqueradeHosts;
}
public void setMasqueradeHosts(String[] masqueradeHosts) {
this.masqueradeHosts = masqueradeHosts;
}
public String getFlashlightCloudConfig() {
return flashlightCloudConfig;
}
public void setFlashlightCloudConfig(String flashlightCloudConfig) {
this.flashlightCloudConfig = flashlightCloudConfig;
}
public String getFlashlightCloudConfigCA() {
return flashlightCloudConfigCA;
}
public void setFlashlightCloudConfigCA(String flashlightCloudConfigCA) {
this.flashlightCloudConfigCA = flashlightCloudConfigCA;
}
public String getWaddellAddr() {
return waddellAddr;
}
public void setWaddellAddr(String waddellAddr) {
this.waddellAddr = waddellAddr;
}
public String getFlashlightConfigAddr() {
return flashlightConfigAddr;
}
public void setFlashlightConfigAddr(String flashlightConfigAddr) {
this.flashlightConfigAddr = flashlightConfigAddr;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result
+ ((controller == null) ? 0 : controller.hashCode());
result = prime * result
+ ((dnsRegUrl == null) ? 0 : dnsRegUrl.hashCode());
result = prime * result
+ ((fallbacks == null) ? 0 : fallbacks.hashCode());
result = prime
* result
+ ((masqueradeHostsToCerts == null) ? 0
: masqueradeHostsToCerts.hashCode());
result = prime * result + maxpoll;
result = prime * result + minpoll;
result = prime * result
+ (int) (signalingRetryTime ^ (signalingRetryTime >>> 32));
result = prime * result + statsGetInterval;
result = prime * result + statsPostInterval;
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
BaseS3Config other = (BaseS3Config) obj;
if (controller == null) {
if (other.controller != null)
return false;
} else if (!controller.equals(other.controller))
return false;
if (dnsRegUrl == null) {
if (other.dnsRegUrl != null)
return false;
} else if (!dnsRegUrl.equals(other.dnsRegUrl))
return false;
if (fallbacks == null) {
if (other.fallbacks != null)
return false;
} else if (!fallbacks.equals(other.fallbacks))
return false;
if (masqueradeHostsToCerts == null) {
if (other.masqueradeHostsToCerts != null)
return false;
} else if (!masqueradeHostsToCerts.equals(other.masqueradeHostsToCerts))
return false;
if (maxpoll != other.maxpoll)
return false;
if (minpoll != other.minpoll)
return false;
if (signalingRetryTime != other.signalingRetryTime)
return false;
if (statsGetInterval != other.statsGetInterval)
return false;
if (statsPostInterval != other.statsPostInterval)
return false;
return true;
}
@Override
public String toString() {
return "BaseS3Config [controller=" + controller + ", minpoll="
+ minpoll + ", maxpoll=" + maxpoll + ", fallbacks=" + fallbacks
+ ", signalingRetryTime=" + signalingRetryTime
+ ", statsGetInterval=" + statsGetInterval
+ ", statsPostInterval=" + statsPostInterval + ", dnsRegUrl="
+ dnsRegUrl + ", masqueradeHostsToCerts="
+ masqueradeHostsToCerts + "]";
}
}
|
package org.mariadb.jdbc;
import org.mariadb.jdbc.internal.common.DefaultOptions;
import org.mariadb.jdbc.internal.common.Options;
import org.mariadb.jdbc.internal.common.ParameterConstant;
import org.mariadb.jdbc.internal.common.UrlHAMode;
import org.mariadb.jdbc.internal.common.query.IllegalParameterException;
import java.util.List;
import java.util.Properties;
/**
* <p>parse and verification of URL.</p>
*
*
* <p>basic syntax :<br>
* {@code jdbc:(mysql|mariadb):[replication:|loadbalance:|aurora:]//<hostDescription>[,<hostDescription>]/[database>][?<key1>=<value1>[&<key2>=<value2>]] }
*</p>
* <p>
* hostDescription:<br>
* - simple :<br>
* {@code <host>:<portnumber>}<br>
* (for example localhost:3306)<br><br>
* - complex :<br>
* {@code address=[(type=(master|slave))][(port=<portnumber>)](host=<host>)}<br>
*<br><br>
* type is by default master<br>
* port is by default 3306<br>
*</p>
* <p>
* host can be dns name, ipv4 or ipv6.<br>
* in case of ipv6 and simple host description, the ip must be written inside bracket.<br>
* exemple : {@code jdbc:mysql://[2001:0660:7401:0200:0000:0000:0edf:bdd7]:3306}<br>
*</p>
*<p>
* Some examples :<br>
* {@code jdbc:mysql://localhost:3306/database?user=greg&password=pass}<br>
* {@code jdbc:mysql://address=(type=master)(host=master1),address=(port=3307)(type=slave)(host=slave1)/database?user=greg&password=pass}<br>
*</p>
*/
public class JDBCUrl {
private String database;
private Options options;
private List<HostAddress> addresses;
private UrlHAMode haMode;
private JDBCUrl(){};
protected JDBCUrl(String database, List<HostAddress> addresses, Options options, UrlHAMode haMode) {
this.options = options;
this.database = database;
this.addresses = addresses;
this.haMode = haMode;
if (haMode == UrlHAMode.AURORA) {
for (HostAddress hostAddress : addresses) hostAddress.type = null;
} else {
for (HostAddress hostAddress : addresses) {
if (hostAddress.type == null)hostAddress.type = ParameterConstant.TYPE_MASTER;
}
}
}
static boolean acceptsURL(String url) {
return (url != null) &&
(url.startsWith("jdbc:mariadb://") || url.startsWith("jdbc:mysql://"));
}
public static JDBCUrl parse(final String url) {
return parse(url, new Properties());
}
public static JDBCUrl parse(final String url, Properties prop) {
if (url != null) {
if (prop == null) prop = new Properties();
if (url.startsWith("jdbc:mysql:")) {
JDBCUrl jdbcUrl = new JDBCUrl();
parseInternal(jdbcUrl, url, prop);
return jdbcUrl;
}
String[] arr = new String[]{"jdbc:mysql:thin:", "jdbc:mariadb:"};
for (String prefix : arr) {
if (url.startsWith(prefix)) {
JDBCUrl jdbcUrl = new JDBCUrl();
parseInternal(jdbcUrl, "jdbc:mysql:" + url.substring(prefix.length()), prop);
return jdbcUrl;
}
}
}
throw new IllegalArgumentException("Invalid connection URL url " + url);
}
public void parseUrl(String url) {
if (!url.startsWith("jdbc:mysql:")) throw new IllegalArgumentException("Url must start with \"jdbc:mysql:\"");
parseInternal(this, url, new Properties());
}
/*
Parse ConnectorJ compatible urls
jdbc:mysql://host:port/database
Example: jdbc:mysql://localhost:3306/test?user=root&password=passwd
*/
private static void parseInternal(JDBCUrl jdbcUrl, String url, Properties properties) {
String[] baseTokens = url.substring(0,url.indexOf("//")).split(":");
//parse HA mode
jdbcUrl.haMode = UrlHAMode.NONE;
if (baseTokens.length > 2) {
try {
jdbcUrl.haMode = UrlHAMode.valueOf(baseTokens[2].toUpperCase());
}catch (IllegalArgumentException i) {
throw new IllegalArgumentException("url parameter error '" + baseTokens[2] +"' is a unknown parameter in the url "+url);
}
}
url = url.substring(url.indexOf("
String[] tokens = url.split("/");
String hostAddressesString= tokens[0];
String additionalParameters = (tokens.length > 1) ? url.substring(tokens[0].length() + 1) : null;
jdbcUrl.addresses = HostAddress.parse(hostAddressesString, jdbcUrl.haMode);
if (additionalParameters == null) {
jdbcUrl.database = null;
jdbcUrl.options = DefaultOptions.parse(jdbcUrl.haMode, "",properties);
} else {
int ind = additionalParameters.indexOf('?');
if (ind > -1) {
jdbcUrl.database = additionalParameters.substring(0, ind);
jdbcUrl.options = DefaultOptions.parse(jdbcUrl.haMode, additionalParameters.substring(ind + 1),properties);
} else {
jdbcUrl.database = additionalParameters;
jdbcUrl.options = DefaultOptions.parse(jdbcUrl.haMode, "",properties);
}
}
if (jdbcUrl.haMode == UrlHAMode.AURORA) {
for (HostAddress hostAddress : jdbcUrl.addresses) hostAddress.type = null;
} else {
for (HostAddress hostAddress : jdbcUrl.addresses) {
if (hostAddress.type == null) hostAddress.type = ParameterConstant.TYPE_MASTER;
}
}
}
public String getUsername() {
return options.user;
}
public String getPassword() {
return options.password;
}
public String getDatabase() {
return database;
}
public List<HostAddress> getHostAddresses() {
return this.addresses;
}
protected void setUsername(String username) {
options.user = username;
}
protected void setPassword(String password) {
options.password = password;
}
public Options getOptions() {
return options;
}
protected void setDatabase(String database) {
this.database = database;
}
protected void setProperties(String urlParameters) {
DefaultOptions.parse(this.haMode, urlParameters, this.options);
}
public String toString() {
String s = "jdbc:mysql:
if (!haMode.equals(UrlHAMode.NONE)) s = "jdbc:mysql:"+haMode.toString().toLowerCase()+":
if (addresses != null)
s += HostAddress.toString(addresses);
if (database != null)
s += "/" + database;
return s;
}
public UrlHAMode getHaMode() {
return haMode;
}
}
|
package org.scribe.model;
import java.io.*;
import java.net.*;
import java.util.*;
import java.util.concurrent.TimeUnit;
import org.scribe.exceptions.*;
import org.scribe.utils.*;
/**
* Represents an HTTP Request object
*
* @author Pablo Fernandez
*/
class Request
{
private static final String CONTENT_LENGTH = "Content-Length";
private String url;
private Verb verb;
private Map<String, String> bodyParams;
private Map<String, String> headers;
private String payload = null;
private HttpURLConnection connection;
/**
* Creates a new Http Request
*
* @param verb Http Verb (GET, POST, etc)
* @param url url with optional querystring parameters.
*/
public Request(Verb verb, String url)
{
this.verb = verb;
this.url = url;
this.bodyParams = new HashMap<String, String>();
this.headers = new HashMap<String, String>();
try
{
connection = (HttpURLConnection) new URL(url).openConnection();
} catch (IOException ioe)
{
throw new OAuthException("Could not open connection to: " + url, ioe);
}
}
/**
* Execute the request and return a {@link Response}
*
* @return Http Response
* @throws RuntimeException
* if the connection cannot be created.
*/
public Response send()
{
try
{
return doSend();
} catch (IOException ioe)
{
throw new OAuthException("Problems while creating connection", ioe);
}
}
Response doSend() throws IOException
{
connection.setRequestMethod(this.verb.name());
addHeaders(connection);
if (verb.equals(Verb.PUT) || verb.equals(Verb.POST))
{
addBody(connection, getBodyContents());
}
return new Response(connection);
}
void addHeaders(HttpURLConnection conn)
{
for (String key : headers.keySet())
conn.setRequestProperty(key, headers.get(key));
}
void addBody(HttpURLConnection conn, String content) throws IOException
{
conn.setRequestProperty(CONTENT_LENGTH, String.valueOf(content.getBytes().length));
conn.setDoOutput(true);
conn.getOutputStream().write(content.getBytes());
}
/**
* Add an HTTP Header to the Request
*
* @param key the header name
* @param value the header value
*/
public void addHeader(String key, String value)
{
this.headers.put(key, value);
}
/**
* Add a body Parameter (for POST/ PUT Requests)
*
* @param key the parameter name
* @param value the parameter value
*/
public void addBodyParameter(String key, String value)
{
this.bodyParams.put(key, value);
}
/**
* Add body payload.
*
* This method is used when the HTTP body is not a form-url-encoded string,
* but another thing. Like for example XML.
*
* Note: The contents are not part of the OAuth signature
*
* @param payload the body of the request
*/
public void addPayload(String payload)
{
this.payload = payload;
}
/**
* Get a {@link Map} of the query string parameters.
*
* @return a map containing the query string parameters
*/
public Map<String, String> getQueryStringParams()
{
try
{
Map<String, String> params = new HashMap<String, String>();
String query = new URL(url).getQuery();
if (query != null)
{
for (String param : query.split("&"))
{
String pair[] = param.split("=");
params.put(pair[0], pair[1]);
}
}
return params;
} catch (MalformedURLException mue)
{
throw new OAuthException("Malformed URL", mue);
}
}
/**
* Obtains a {@link Map} of the body parameters.
*
* @return a map containing the body parameters.
*/
public Map<String, String> getBodyParams()
{
return bodyParams;
}
/**
* Obtains the URL of the HTTP Request.
*
* @return the original URL of the HTTP Request
*/
public String getUrl()
{
return url;
}
/**
* Returns the URL without the port and the query string part.
*
* @return the OAuth-sanitized URL
*/
public String getSanitizedUrl()
{
return url.replaceAll("\\?.*", "").replace("\\:\\d{4}", "");
}
/**
* Returns the body of the request
*
* @return form encoded string
*/
public String getBodyContents()
{
return (payload != null) ? payload : URLUtils.formURLEncodeMap(bodyParams);
}
/**
* Returns the HTTP Verb
*
* @return the verb
*/
public Verb getVerb()
{
return verb;
}
/**
* Returns the connection headers as a {@link Map}
*
* @return map of headers
*/
public Map<String, String> getHeaders()
{
return headers;
}
/**
* Sets the connect timeout for the underlying {@link HttpURLConnection}
*
* @param duration duration of the timeout
*
* @param unit unit of time (milliseconds, seconds, etc)
*/
public void setConnectTimeout(int duration, TimeUnit unit)
{
this.connection.setConnectTimeout((int) unit.toMillis(duration));
}
/**
* Sets the read timeout for the underlying {@link HttpURLConnection}
*
* @param duration duration of the timeout
*
* @param unit unit of time (milliseconds, seconds, etc)
*/
public void setReadTimeout(int duration, TimeUnit unit)
{
this.connection.setReadTimeout((int) unit.toMillis(duration));
}
/*
* We need this in order to stub the connection object for test cases
*/
void setConnection(HttpURLConnection connection)
{
this.connection = connection;
}
@Override
public String toString()
{
return String.format("@Request(%s %s)", getVerb(), getUrl());
}
}
|
package seedu.jimi.ui;
import java.util.List;
import java.util.Stack;
import java.util.logging.Logger;
import com.google.common.eventbus.Subscribe;
import javafx.fxml.FXML;
import javafx.scene.Node;
import javafx.scene.control.SplitPane;
import javafx.scene.control.TextField;
import javafx.scene.input.KeyEvent;
import javafx.scene.layout.AnchorPane;
import javafx.stage.Stage;
import seedu.jimi.commons.core.LogsCenter;
import seedu.jimi.commons.core.Messages;
import seedu.jimi.commons.events.ui.IncorrectCommandAttemptedEvent;
import seedu.jimi.commons.util.CommandUtil;
import seedu.jimi.commons.util.FxViewUtil;
import seedu.jimi.commons.util.StringUtil;
import seedu.jimi.logic.Logic;
import seedu.jimi.logic.commands.CommandResult;
public class CommandBox extends UiPart {
private final Logger logger = LogsCenter.getLogger(CommandBox.class);
private static final String FXML = "CommandBox.fxml";
private AnchorPane placeHolderPane;
private AnchorPane commandPane;
private ResultDisplay resultDisplay;
String previousCommandTest;
private Logic logic;
private Stack<String> previousInputs = new Stack<String>();
private Stack<String> aheadInputs = new Stack<String>();
public static final String MESSAGE_COMMAND_SUGGESTIONS =
"Are you looking for these commands? \n"
+ "> %1$s";
@FXML
private TextField commandTextField;
private CommandResult mostRecentResult;
public static CommandBox load(Stage primaryStage, AnchorPane commandBoxPlaceholder,
ResultDisplay resultDisplay, Logic logic) {
CommandBox commandBox = UiPartLoader.loadUiPart(primaryStage, commandBoxPlaceholder, new CommandBox());
commandBox.configure(resultDisplay, logic);
commandBox.addToPlaceholder();
return commandBox;
}
public void configure(ResultDisplay resultDisplay, Logic logic) {
this.resultDisplay = resultDisplay;
this.logic = logic;
registerAsAnEventHandler(this);
}
private void addToPlaceholder() {
SplitPane.setResizableWithParent(placeHolderPane, false);
placeHolderPane.getChildren().add(commandTextField);
FxViewUtil.applyAnchorBoundaryParameters(commandPane, 0.0, 0.0, 0.0, 0.0);
FxViewUtil.applyAnchorBoundaryParameters(commandTextField, 0.0, 0.0, 0.0, 0.0);
}
@Override
public void setNode(Node node) {
commandPane = (AnchorPane) node;
}
@Override
public String getFxmlPath() {
return FXML;
}
@Override
public void setPlaceholder(AnchorPane pane) {
this.placeHolderPane = pane;
}
@FXML
private void handleCommandInputChanged() {
// Do nothing for empty input.
if (commandTextField.getText().trim().isEmpty()) {
return;
}
//Take a copy of the command text
previousCommandTest = commandTextField.getText().trim();
resetTextInputStacks();
previousInputs.push(previousCommandTest);
/* We assume the command is correct. If it is incorrect, the command box will be changed accordingly
* in the event handling code {@link #handleIncorrectCommandAttempted}
*/
setResultDisplayAndCmdBoxToDefault();
mostRecentResult = logic.execute(previousCommandTest);
resultDisplay.postMessage(mostRecentResult.feedbackToUser);
logger.info("Result: " + mostRecentResult.feedbackToUser);
}
// @@author A0140133B
@FXML
private void handleTextFieldKeyReleased(KeyEvent event) {
switch (event.getCode()) {
case UP :
cyclePreviousInput();
return;
case DOWN :
cycleAheadInput();
return;
case ENTER :
return; // Do nothing since {@link #handleCommandInputChanged} already handles this.
default :
handleTextFieldKeyTyped();
}
}
/** Handles the event when a key is typed in {@code commandTextField}. */
private void handleTextFieldKeyTyped() {
String currentText = commandTextField.getText().trim();
logger.info("Text in text field: " + currentText);
if (currentText.isEmpty()) {
setResultDisplayAndCmdBoxToDefault();
} else {
postRealTimeSuggestions(currentText);
}
}
/** Posts suggestions for commands in real time according to the first word of {@code currentText} */
private void postRealTimeSuggestions(String currentText) {
String firstWordOfInput = StringUtil.getFirstWord(currentText);
List<String> commandWordMatches = CommandUtil.getInstance().getCommandWordMatches(firstWordOfInput);
logger.info("Suggestions: " + commandWordMatches);
/*
* Only providing suggestions for first word, so once the full input text length
* exceeds the length of the first word, stop providing suggestions.
*/
if (currentText.length() > firstWordOfInput.length() || commandWordMatches.isEmpty()) {
setResultDisplayToDefault();
} else {
resultDisplay.postMessage(String.format(MESSAGE_COMMAND_SUGGESTIONS, String.join(", ", commandWordMatches)));
}
}
/** Sets {@code resultDisplay} to its default posting */
private void setResultDisplayToDefault() {
// If most recent result does not exist, post welcome message instead.
resultDisplay.postMessage(
mostRecentResult == null ? Messages.MESSAGE_WELCOME_JIMI : mostRecentResult.feedbackToUser);
}
/** Sets {@code commandTextField} and {@code resultDisplay} to their default styles/postings */
private void setResultDisplayAndCmdBoxToDefault() {
setCommandBoxtoDefault();
setResultDisplayToDefault();
}
/** Sets {@code commandTextField} with input texts following the most recent input texts. */
private void cycleAheadInput() {
if (aheadInputs.isEmpty()) {
return;
}
commandTextField.setText(aheadInputs.peek());
setCaretToRightEnd();
// Last input text does not need to be popped so as to avoid double counting.
if (aheadInputs.size() > 1) {
previousInputs.push(aheadInputs.pop());
}
}
/** Shifts caret to the right end of text field */
private void setCaretToRightEnd() {
commandTextField.positionCaret(commandTextField.getText().length());
}
/** Sets texts field with input texts following the latest input text. */
private void cyclePreviousInput() {
if (previousInputs.isEmpty()) {
return;
}
commandTextField.setText(previousInputs.peek());
setCaretToRightEnd();
// Last input text does not need to be popped so as to avoid double counting.
if (previousInputs.size() > 1) {
aheadInputs.push(previousInputs.pop());
}
}
/** Pushes all input text in {@code aheadInputs} into {@code previousInputs}. */
private void resetTextInputStacks() {
while (!aheadInputs.isEmpty()) {
previousInputs.push(aheadInputs.pop());
}
}
// @@author
/**
* Sets the command box style to indicate a correct command.
*/
private void setCommandBoxtoDefault() {
commandTextField.getStyleClass().remove("error");
commandTextField.setText("");
}
@Subscribe
private void handleIncorrectCommandAttempted(IncorrectCommandAttemptedEvent event){
logger.info(LogsCenter.getEventHandlingLogMessage(event, "Invalid command: " + previousCommandTest));
setStyleToIndicateIncorrectCommand();
restoreCommandText();
setCaretToRightEnd();
}
/**
* Restores the command box text to the previously entered command
*/
private void restoreCommandText() {
commandTextField.setText(previousCommandTest);
}
/**
* Sets the command box style to indicate an error
*/
private void setStyleToIndicateIncorrectCommand() {
commandTextField.getStyleClass().add("error");
}
}
|
package tars.logic.parser;
import static tars.commons.core.Messages.MESSAGE_INVALID_COMMAND_FORMAT;
import static tars.commons.core.Messages.MESSAGE_UNKNOWN_COMMAND;
import java.time.DateTimeException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Optional;
import java.util.Set;
import java.util.TreeMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import tars.commons.core.Messages;
import tars.commons.exceptions.IllegalValueException;
import tars.commons.flags.Flag;
import tars.commons.util.DateTimeUtil;
import tars.commons.util.ExtractorUtil;
import tars.commons.util.StringUtil;
import tars.logic.commands.AddCommand;
import tars.logic.commands.CdCommand;
import tars.logic.commands.ClearCommand;
import tars.logic.commands.Command;
import tars.logic.commands.DeleteCommand;
import tars.logic.commands.EditCommand;
import tars.logic.commands.ExitCommand;
import tars.logic.commands.FindCommand;
import tars.logic.commands.HelpCommand;
import tars.logic.commands.IncorrectCommand;
import tars.logic.commands.ListCommand;
import tars.logic.commands.MarkCommand;
import tars.logic.commands.RedoCommand;
import tars.logic.commands.SelectCommand;
import tars.logic.commands.UndoCommand;
import tars.model.task.TaskQuery;
/**
* Parses user input.
*/
public class Parser {
/**
* Used for initial separation of command word and args.
*/
private static final Pattern BASIC_COMMAND_FORMAT = Pattern.compile("(?<commandWord>\\S+)(?<arguments>.*)");
private static final Pattern TASK_INDEX_ARGS_FORMAT = Pattern.compile("(?<targetIndex>.+)");
private static final Pattern FILEPATH_ARGS_FORMAT = Pattern.compile("(?<filepath>\\S+)");
private static final Pattern KEYWORDS_ARGS_FORMAT = Pattern.compile("(?<keywords>\\S+(?:\\s+\\S+)*)"); // one
// more
// whitespace
public Parser() {
}
/**
* Parses user input into command for execution.
*
* @param userInput
* full user input string
* @return the command based on the user input
*/
public Command parseCommand(String userInput) {
final Matcher matcher = BASIC_COMMAND_FORMAT.matcher(userInput.trim());
if (!matcher.matches()) {
return new IncorrectCommand(String.format(MESSAGE_INVALID_COMMAND_FORMAT, HelpCommand.MESSAGE_USAGE));
}
final String commandWord = matcher.group("commandWord");
final String arguments = matcher.group("arguments");
switch (commandWord) {
case AddCommand.COMMAND_WORD:
return prepareAdd(arguments);
case SelectCommand.COMMAND_WORD:
return prepareSelect(arguments);
case EditCommand.COMMAND_WORD:
return prepareEdit(arguments);
case DeleteCommand.COMMAND_WORD:
return prepareDelete(arguments);
case ClearCommand.COMMAND_WORD:
return new ClearCommand();
case FindCommand.COMMAND_WORD:
return prepareFind(arguments);
case ListCommand.COMMAND_WORD:
if (arguments != null && !arguments.isEmpty()) {
return prepareList(arguments);
} else {
return new ListCommand();
}
case UndoCommand.COMMAND_WORD:
return new UndoCommand();
case RedoCommand.COMMAND_WORD:
return new RedoCommand();
case MarkCommand.COMMAND_WORD:
return prepareMark(arguments);
case CdCommand.COMMAND_WORD:
return prepareCd(arguments);
case ExitCommand.COMMAND_WORD:
return new ExitCommand();
case HelpCommand.COMMAND_WORD:
return new HelpCommand();
default:
return new IncorrectCommand(MESSAGE_UNKNOWN_COMMAND);
}
}
/**
* Parses arguments in the context of the add task command.
*
* @@author A0139924W
* @param args
* full command args string
* @return the prepared command
*/
private Command prepareAdd(String args) {
// there is no arguments
if (args.trim().length() == 0) {
return new IncorrectCommand(String.format(MESSAGE_INVALID_COMMAND_FORMAT, AddCommand.MESSAGE_USAGE));
}
String name = "";
Flag priorityFlag = new Flag(Flag.PRIORITY, false);
Flag dateTimeFlag = new Flag(Flag.DATETIME, false);
Flag tagFlag = new Flag(Flag.TAG, true);
Flag[] flags = { priorityFlag, dateTimeFlag, tagFlag };
TreeMap<Integer, Flag> flagsPosMap = ExtractorUtil.getFlagPositon(args, flags);
HashMap<Flag, String> argumentMap = ExtractorUtil.getArguments(args, flags, flagsPosMap);
if (flagsPosMap.size() == 0) {
name = args;
} else if (flagsPosMap.firstKey() == 0) {
// there are arguments but name should be the first argument
return new IncorrectCommand(String.format(MESSAGE_INVALID_COMMAND_FORMAT, AddCommand.MESSAGE_USAGE));
} else {
name = args.substring(0, flagsPosMap.firstKey()).trim();
}
try {
return new AddCommand(name,
DateTimeUtil.getDateTimeFromArgs(argumentMap.get(dateTimeFlag).replace(Flag.DATETIME + " ", "")),
argumentMap.get(priorityFlag).replace(Flag.PRIORITY + " ", ""),
ExtractorUtil.getTagsFromArgs(argumentMap.get(tagFlag), tagFlag));
} catch (IllegalValueException ive) {
return new IncorrectCommand(ive.getMessage());
} catch (DateTimeException dte) {
return new IncorrectCommand(Messages.MESSAGE_INVALID_DATE);
}
}
/**
* Parses arguments in the context of the edit task command.
*
* @@author A0121533W
* @param args
* full command args string
* @return the prepared command
*/
private Command prepareEdit(String args) {
args = args.trim();
int targetIndex = 0;
if (args.indexOf(" ") != -1) {
targetIndex = args.indexOf(" ");
}
Optional<Integer> index = parseIndex(args.substring(0, targetIndex));
if (!index.isPresent()) {
return new IncorrectCommand(String.format(MESSAGE_INVALID_COMMAND_FORMAT, EditCommand.MESSAGE_USAGE));
}
Flag[] flags = generateFlagArrayForEditCommand();
TreeMap<Integer, Flag> flagsPosMap = ExtractorUtil.getFlagPositon(args, flags);
HashMap<Flag, String> argumentMap = ExtractorUtil.getArguments(args, flags, flagsPosMap);
if (flagsPosMap.size() == 0) {
return new IncorrectCommand(String.format(MESSAGE_INVALID_COMMAND_FORMAT, EditCommand.MESSAGE_USAGE));
}
return new EditCommand(index.get(), argumentMap);
}
private Flag[] generateFlagArrayForEditCommand() {
Flag nameFlag = new Flag(Flag.NAME, false);
Flag priorityFlag = new Flag(Flag.PRIORITY, false);
Flag dateTimeFlag = new Flag(Flag.DATETIME, false);
Flag addTagFlag = new Flag(Flag.ADDTAG, true);
Flag removeTagFlag = new Flag(Flag.REMOVETAG, true);
Flag[] flags = { nameFlag, priorityFlag, dateTimeFlag, addTagFlag, removeTagFlag };
return flags;
}
/**
* Parses arguments in the context of the delete task command.
*
* @param args
* full command args string
* @return the prepared command
*/
private Command prepareDelete(String args) {
Optional<Integer> index = parseIndex(args);
if (!index.isPresent()) {
return new IncorrectCommand(String.format(MESSAGE_INVALID_COMMAND_FORMAT, DeleteCommand.MESSAGE_USAGE));
}
return new DeleteCommand(index.get());
}
/**
* Parses arguments in the context of the mark task command.
*
* @@author A0121533W
* @param args
* full command args string
* @return the prepared command
*/
private Command prepareMark(String args) {
Flag doneFlag = new Flag(Flag.DONE, false);
Flag undoneFlag = new Flag(Flag.UNDONE, false);
Flag[] flags = { doneFlag, undoneFlag };
TreeMap<Integer, Flag> flagsPosMap = ExtractorUtil.getFlagPositon(args, flags);
HashMap<Flag, String> argumentMap = ExtractorUtil.getArguments(args, flags, flagsPosMap);
if (flagsPosMap.size() == 0) {
return new IncorrectCommand(String.format(MESSAGE_INVALID_COMMAND_FORMAT, MarkCommand.MESSAGE_USAGE));
}
String markDone = argumentMap.get(doneFlag).replace(Flag.DONE + " ", "");
String markUndone = argumentMap.get(undoneFlag).replace(Flag.UNDONE + " ", "");
return new MarkCommand(markDone, markUndone);
}
/**
* Parses arguments in the context of the select task command.
*
* @param args
* full command args string
* @return the prepared command
*/
private Command prepareSelect(String args) {
Optional<Integer> index = parseIndex(args);
if (!index.isPresent()) {
return new IncorrectCommand(String.format(MESSAGE_INVALID_COMMAND_FORMAT, SelectCommand.MESSAGE_USAGE));
}
return new SelectCommand(index.get());
}
/**
* Returns the specified index in the {@code command} IF a positive unsigned
* integer is given as the index. Returns an {@code Optional.empty()}
* otherwise.
*/
private Optional<Integer> parseIndex(String command) {
final Matcher matcher = TASK_INDEX_ARGS_FORMAT.matcher(command.trim());
if (!matcher.matches()) {
return Optional.empty();
}
String index = matcher.group("targetIndex");
if (!StringUtil.isUnsignedInteger(index)) {
return Optional.empty();
}
return Optional.of(Integer.parseInt(index));
}
/**
* Parses arguments in the context of the find task command.
*
* @param args
* full command args string
* @return the prepared command
*/
private Command prepareFind(String args) {
final Matcher matcher = KEYWORDS_ARGS_FORMAT.matcher(args.trim());
if (!matcher.matches()) {
return new IncorrectCommand(String.format(MESSAGE_INVALID_COMMAND_FORMAT, FindCommand.MESSAGE_USAGE));
}
Flag[] flags = generateFlagArrayForFindCommand();
TreeMap<Integer, Flag> flagsPosMap = ExtractorUtil.getFlagPositon(args.trim(), flags);
HashMap<Flag, String> argumentMap = ExtractorUtil.getArguments(args.trim(), flags, flagsPosMap);
if (flagsPosMap.size() == 0) {
return new FindCommand(generateKeywordSetFromArgs(args.trim()));
}
TaskQuery taskQuery;
try {
taskQuery = createTaskQuery(argumentMap, flags);
} catch (IllegalValueException ive) {
return new IncorrectCommand(ive.getMessage());
} catch (DateTimeException dte) {
return new IncorrectCommand(Messages.MESSAGE_INVALID_DATE);
}
return new FindCommand(taskQuery);
}
private TaskQuery createTaskQuery(HashMap<Flag, String> argumentMap, Flag[] flags)
throws DateTimeException, IllegalValueException {
TaskQuery taskQuery = new TaskQuery();
Boolean statusDone = true;
Boolean statusUndone = false;
taskQuery.createNameQuery(argumentMap.get(flags[0]).replace(Flag.NAME, "").trim().replaceAll("( )+", " "));
taskQuery.createDateTimeQuery(
DateTimeUtil.getDateTimeFromArgs(argumentMap.get(flags[1]).replace(Flag.DATETIME, "").trim()));
taskQuery.createPriorityQuery(argumentMap.get(flags[2]).replace(Flag.PRIORITY, "").trim());
if (!argumentMap.get(flags[3]).isEmpty() && !argumentMap.get(flags[4]).isEmpty()) {
throw new IllegalValueException(TaskQuery.MESSAGE_BOTH_STATUS_SEARCHED_ERROR);
} else {
if (!argumentMap.get(flags[3]).isEmpty()) {
taskQuery.createStatusQuery(statusDone);
}
if (!argumentMap.get(flags[4]).isEmpty()) {
taskQuery.createStatusQuery(statusUndone);
}
}
taskQuery.createTagsQuery(argumentMap.get(flags[5]).replace(Flag.TAG, "").trim().replaceAll("( )+", " "));
return taskQuery;
}
private ArrayList<String> generateKeywordSetFromArgs(String keywordsArgs) {
String[] keywordsArray = keywordsArgs.split("\\s+");
return new ArrayList<String>(Arrays.asList(keywordsArray));
}
private Flag[] generateFlagArrayForFindCommand() {
Flag nameFlag = new Flag(Flag.NAME, false);
Flag priorityFlag = new Flag(Flag.PRIORITY, false);
Flag dateTimeFlag = new Flag(Flag.DATETIME, false);
Flag doneFlag = new Flag(Flag.DONE, false);
Flag undoneFlag = new Flag(Flag.UNDONE, false);
Flag tagFlag = new Flag(Flag.TAG, false);
Flag[] flags = { nameFlag, dateTimeFlag, priorityFlag, doneFlag, undoneFlag, tagFlag };
return flags;
}
/**
* Parses arguments in the context of the list task command.
*
* @@author @A0140022H
* @param args
* full command args string
* @return the prepared command
*/
private Command prepareList(String args) {
final Matcher matcher = KEYWORDS_ARGS_FORMAT.matcher(args.trim());
if (!matcher.matches()) {
return new IncorrectCommand(String.format(MESSAGE_INVALID_COMMAND_FORMAT, ListCommand.MESSAGE_USAGE));
}
// keywords delimited by whitespace
final String[] keywords = matcher.group("keywords").split("\\s+");
final Set<String> keywordSet = new HashSet<>(Arrays.asList(keywords));
return new ListCommand(keywordSet);
}
/**
* Parses arguments in the context of the change storage file directory (cd)
* command.
*
* @@author A0124333U
* @param args
* full command args string
* @return the prepared command
*/
private Command prepareCd(String args) {
final Matcher matcher = FILEPATH_ARGS_FORMAT.matcher(args.trim());
if (!matcher.matches()) {
return new IncorrectCommand(String.format(CdCommand.MESSAGE_INVALID_FILEPATH));
}
if (!isFileTypeValid(args.trim())) {
return new IncorrectCommand(String.format(CdCommand.MESSAGE_INVALID_FILEPATH));
}
return new CdCommand(args.trim());
}
/**
* Checks if new file type is a valid file type
*
* @@author A0124333U
* @param args
* @return Boolean variable of whether the file type is valid
**/
private Boolean isFileTypeValid(String args) {
String filePath = args.trim();
String extension = filePath.substring(filePath.lastIndexOf(".") + 1, filePath.length());
if (extension.equals(CdCommand.getXmlFileExt())) {
return true;
}
return false;
}
}
|
package urchin.domain.model;
import java.time.LocalDateTime;
public class User {
private int id;
private final String username;
private LocalDateTime created;
public User(String username) {
this.username = username;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUsername() {
return username;
}
public LocalDateTime getCreated() {
return created;
}
public void setCreated(LocalDateTime created) {
this.created = created;
}
}
|
package program;
import engine.*;
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
String estimationAlgorithm = args[0];
int initialTagsNumber = Integer.parseInt(args[1]);
int incrementTagRate = Integer.parseInt(args[2]);
int maxTagsNumber = Integer.parseInt(args[3]);
int iterationsNumber = Integer.parseInt(args[4]);
int initialFrameSize = Integer.parseInt(args[5]);
Simulator simulator = new Simulator (estimationAlgorithm, initialTagsNumber, incrementTagRate,
maxTagsNumber, iterationsNumber, initialFrameSize);
simulator.execute();
}
}
|
package com.yahoo.config.model.api;
import com.yahoo.component.Version;
import com.yahoo.config.application.api.ApplicationPackage;
import com.yahoo.config.application.api.DeployLogger;
import com.yahoo.config.application.api.FileRegistry;
import com.yahoo.config.provision.ApplicationId;
import com.yahoo.config.provision.AthenzDomain;
import com.yahoo.config.provision.DockerImage;
import com.yahoo.config.provision.HostName;
import com.yahoo.config.provision.NodeResources;
import com.yahoo.config.provision.Zone;
import java.io.File;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.net.URI;
import java.util.List;
import java.util.Optional;
import java.util.Set;
/**
* Model context containing state provided to model factories.
*
* @author Ulf Lilleengen
*/
public interface ModelContext {
ApplicationPackage applicationPackage();
Optional<Model> previousModel();
Optional<ApplicationPackage> permanentApplicationPackage();
HostProvisioner getHostProvisioner();
Provisioned provisioned();
DeployLogger deployLogger();
ConfigDefinitionRepo configDefinitionRepo();
FileRegistry getFileRegistry();
default Optional<? extends Reindexing> reindexing() { return Optional.empty(); }
Properties properties();
default Optional<File> appDir() { return Optional.empty();}
/** The Docker image repo we want to use for images for this deployment (optional, will use default if empty) */
default Optional<DockerImage> wantedDockerImageRepo() { return Optional.empty(); }
/** The Vespa version this model is built for */
Version modelVespaVersion();
/** The Vespa version we want nodes to become */
Version wantedNodeVespaVersion();
/**
* How to remove a temporary feature flags:
* 1)
* - Remove flag definition from Flags
* - Remove method implementation from ModelContextImpl.FeatureFlags
* - Modify default implementation of below method to return the new default value
* - Remove all usage of below method from config-model
*
* 2)
* - (optional) Track Vespa version that introduced changes from 1) in annotation field 'removeAfter'
*
* 3)
* - Remove below method once all config-model versions in hosted production include changes from 1)
* - Remove all flag data files from hosted-feature-flag repository
*/
interface FeatureFlags {
@ModelFeatureFlag(owners = {"jonmv"}) default Optional<NodeResources> dedicatedClusterControllerFlavor() { return Optional.empty(); }
@ModelFeatureFlag(owners = {"baldersheim"}, comment = "Revisit in May or June 2021") default double defaultTermwiseLimit() { throw new UnsupportedOperationException("TODO specify default value"); }
@ModelFeatureFlag(owners = {"vekterli"}) default boolean useThreePhaseUpdates() { throw new UnsupportedOperationException("TODO specify default value"); }
@ModelFeatureFlag(owners = {"baldersheim"}, comment = "Select sequencer type use while feeding") default String feedSequencerType() { throw new UnsupportedOperationException("TODO specify default value"); }
@ModelFeatureFlag(owners = {"baldersheim"}) default String responseSequencerType() { throw new UnsupportedOperationException("TODO specify default value"); }
@ModelFeatureFlag(owners = {"baldersheim"}) default int defaultNumResponseThreads() { return 2; }
@ModelFeatureFlag(owners = {"baldersheim"}) default int maxPendingMoveOps() { throw new UnsupportedOperationException("TODO specify default value"); }
@ModelFeatureFlag(owners = {"baldersheim"}) default boolean skipCommunicationManagerThread() { throw new UnsupportedOperationException("TODO specify default value"); }
@ModelFeatureFlag(owners = {"baldersheim"}) default boolean skipMbusRequestThread() { throw new UnsupportedOperationException("TODO specify default value"); }
@ModelFeatureFlag(owners = {"baldersheim"}) default boolean skipMbusReplyThread() { throw new UnsupportedOperationException("TODO specify default value"); }
@ModelFeatureFlag(owners = {"tokle"}) default boolean useAccessControlTlsHandshakeClientAuth() { return false; }
@ModelFeatureFlag(owners = {"baldersheim"}) default boolean useAsyncMessageHandlingOnSchedule() { throw new UnsupportedOperationException("TODO specify default value"); }
@ModelFeatureFlag(owners = {"baldersheim"}) default double feedConcurrency() { throw new UnsupportedOperationException("TODO specify default value"); }
@ModelFeatureFlag(owners = {"baldersheim"}) default boolean useBucketExecutorForLidSpaceCompact() { throw new UnsupportedOperationException("TODO specify default value"); }
@ModelFeatureFlag(owners = {"baldersheim"}) default boolean useBucketExecutorForBucketMove() { throw new UnsupportedOperationException("TODO specify default value"); }
@ModelFeatureFlag(owners = {"musum", "mpolden"}, comment = "Revisit in February 2021") default boolean reconfigurableZookeeperServer() { return false; }
@ModelFeatureFlag(owners = {"geirst"}) default boolean enableFeedBlockInDistributor() { return false; }
@ModelFeatureFlag(owners = {"baldersheim", "geirst", "toregge"}) default double maxDeadBytesRatio() { return 0.2; }
@ModelFeatureFlag(owners = {"hmusum"}) default int clusterControllerMaxHeapSizeInMb() { return 512; }
@ModelFeatureFlag(owners = {"bjorncs", "tokle"}) default List<String> allowedAthenzProxyIdentities() { return List.of(); }
@ModelFeatureFlag(owners = {"tokle"}) default boolean tenantIamRole() { return false; }
@ModelFeatureFlag(owners = {"vekterli"}) default int maxActivationInhibitedOutOfSyncGroups() { return 0; }
}
/** Warning: As elsewhere in this package, do not make backwards incompatible changes that will break old config models! */
interface Properties {
FeatureFlags featureFlags();
boolean multitenant();
ApplicationId applicationId();
List<ConfigServerSpec> configServerSpecs();
HostName loadBalancerName();
URI ztsUrl();
String athenzDnsSuffix();
boolean hostedVespa();
Zone zone();
Set<ContainerEndpoint> endpoints();
boolean isBootstrap();
boolean isFirstTimeDeployment();
default Optional<EndpointCertificateSecrets> endpointCertificateSecrets() { return Optional.empty(); }
default Optional<AthenzDomain> athenzDomain() { return Optional.empty(); }
Optional<ApplicationRoles> applicationRoles();
default Quota quota() { return Quota.unlimited(); }
/// Default setting for the gc-options attribute if not specified explicit by application
String jvmGCOptions();
// Note: Used in unit tests (set to false in TestProperties) to avoid needing to deal with implicitly created node for logserver
default boolean useDedicatedNodeForLogserver() { return true; }
default boolean dedicatedClusterControllerCluster() { return false; }
}
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
@interface ModelFeatureFlag {
String[] owners();
String removeAfter() default ""; // On the form "7.100.10"
String comment() default "";
}
}
|
package de.bitbrain.braingdx.ai.pathfinding;
import java.util.ArrayList;
import java.util.Collections;
import de.bitbrain.braingdx.ai.pathfinding.heuristics.AStarHeuristic;
import de.bitbrain.braingdx.ai.pathfinding.heuristics.ClosestHeuristic;
import de.bitbrain.braingdx.tmx.IndexCalculator;
import de.bitbrain.braingdx.tmx.TiledMapAPI;
import de.bitbrain.braingdx.world.GameObject;
/**
* A path finder implementation that uses the AStar heuristic based algorithm to
* determine a path.
*
* @author Kevin Glass
*/
public class AStarPathFinder implements PathFinder {
/**
* The set of nodes that have been searched through
*/
private ArrayList<Node> closed = new ArrayList<Node>();
/**
* The set of nodes that we do not yet consider fully searched
*/
private SortedList open = new SortedList();
/**
* The map being searched
*/
private TiledMapAPI map;
/**
* The maximum depth of search we're willing to accept before giving up
*/
private int maxSearchDistance;
/**
* The complete set of nodes across the map
*/
private Node[][] nodes;
/**
* True if we allow diaganol movement
*/
private boolean allowDiagMovement;
/**
* The heuristic we're applying to determine which nodes to search first
*/
private AStarHeuristic heuristic;
/**
* Create a path finder with the default heuristic - closest to target.
*
* @param map
* The map to be searched
* @param maxSearchDistance
* The maximum depth we'll search before giving up
* @param allowDiagMovement
* True if the search should try diaganol movement
*/
public AStarPathFinder(TiledMapAPI map, int maxSearchDistance, boolean allowDiagMovement) {
this(map, maxSearchDistance, allowDiagMovement, new ClosestHeuristic());
}
/**
* Create a path finder
*
* @param heuristic
* The heuristic used to determine the search order of the map
* @param map
* The map to be searched
* @param maxSearchDistance
* The maximum depth we'll search before giving up
* @param allowDiagMovement
* True if the search should try diaganol movement
*/
public AStarPathFinder(TiledMapAPI map, int maxSearchDistance, boolean allowDiagMovement, AStarHeuristic heuristic) {
this.heuristic = heuristic;
this.map = map;
this.maxSearchDistance = maxSearchDistance;
this.allowDiagMovement = allowDiagMovement;
refresh();
}
public void refresh() {
nodes = new Node[map.getNumberOfColumns()][map.getNumberOfRows()];
for (int x = 0; x < map.getNumberOfColumns(); x++) {
for (int y = 0; y < map.getNumberOfRows(); y++) {
nodes[x][y] = new Node(x, y);
}
}
}
@Override
public Path findPath(GameObject mover, int tx, int ty) {
int sx = IndexCalculator.calculateIndex(mover.getLeft(), map.getCellWidth());
int sy = IndexCalculator.calculateIndex(mover.getTop(), map.getCellHeight());
// easy first check, if the destination is blocked, we can't get there
if (map.isCollision(tx, ty, map.layerIndexOf(mover), mover)) {
return null;
}
// initial state for A*. The closed group is empty. Only the starting
// tile is in the open list and it's cost is zero, i.e. we're already there
nodes[sx][sy].cost = 0;
nodes[sx][sy].depth = 0;
closed.clear();
open.clear();
open.add(nodes[sx][sy]);
nodes[tx][ty].parent = null;
// while we haven't found the goal and haven't exceeded our max search depth
int maxDepth = 0;
while ((maxDepth < maxSearchDistance) && (open.size() != 0)) {
// pull out the first node in our open list, this is determined to
// be the most likely to be the next step based on our heuristic
Node current = getFirstInOpen();
if (current == nodes[tx][ty]) {
break;
}
removeFromOpen(current);
addToClosed(current);
// search through all the neighbours of the current node evaluating
// them as next steps
for (int x = -1; x < 2; x++) {
for (int y = -1; y < 2; y++) {
// not a neighbour, its the current tile
if ((x == 0) && (y == 0)) {
continue;
}
// if we're not allowing diaganol movement then only
// one of x or y can be set
if (!allowDiagMovement) {
if ((x != 0) && (y != 0)) {
continue;
}
}
// determine the location of the neighbour and evaluate it
int xp = x + current.x;
int yp = y + current.y;
if (isValidLocation(mover, sx, sy, xp, yp)) {
// the cost to get to this node is cost the current plus the movement
// cost to reach this node. Note that the heursitic value is only used
// in the sorted open list
float nextStepCost = current.cost + getMovementCost(mover, current.x, current.y, xp, yp);
Node neighbour = nodes[xp][yp];
//map.pathFinderVisited(xp, yp);
// if the new cost we've determined for this node is lower than
// it has been previously makes sure the node hasn't been discarded. We've
// determined that there might have been a better path to get to
// this node so it needs to be re-evaluated
if (nextStepCost < neighbour.cost) {
if (inOpenList(neighbour)) {
removeFromOpen(neighbour);
}
if (inClosedList(neighbour)) {
removeFromClosed(neighbour);
}
}
// if the node hasn't already been processed and discarded then
// reset it's cost to our current cost and add it as a next possible
// step (i.e. to the open list)
if (!inOpenList(neighbour) && !(inClosedList(neighbour))) {
neighbour.cost = nextStepCost;
neighbour.heuristic = getHeuristicCost(mover, xp, yp, tx, ty);
maxDepth = Math.max(maxDepth, neighbour.setParent(current));
addToOpen(neighbour);
}
}
}
}
}
// since we've got an empty open list or we've run out of search
// there was no path. Just return null
if (nodes[tx][ty].parent == null) {
return null;
}
// At this point we've definitely found a path so we can uses the parent
// references of the nodes to find out way from the target location back
// to the start recording the nodes on the way.
Path path = new Path();
Node target = nodes[tx][ty];
while (target != nodes[sx][sy]) {
path.prependStep(target.x, target.y);
target = target.parent;
}
path.prependStep(sx, sy);
// thats it, we have our path
return path;
}
/**
* Get the first element from the open list. This is the next one to be
* searched.
*
* @return The first element in the open list
*/
protected Node getFirstInOpen() {
return (Node) open.first();
}
/**
* Add a node to the open list
*
* @param node
* The node to be added to the open list
*/
protected void addToOpen(Node node) {
open.add(node);
}
/**
* Check if a node is in the open list
*
* @param node
* The node to check for
* @return True if the node given is in the open list
*/
protected boolean inOpenList(Node node) {
return open.contains(node);
}
/**
* Remove a node from the open list
*
* @param node
* The node to remove from the open list
*/
protected void removeFromOpen(Node node) {
open.remove(node);
}
/**
* Add a node to the closed list
*
* @param node
* The node to add to the closed list
*/
protected void addToClosed(Node node) {
closed.add(node);
}
/**
* Check if the node supplied is in the closed list
*
* @param node
* The node to search for
* @return True if the node specified is in the closed list
*/
protected boolean inClosedList(Node node) {
return closed.contains(node);
}
/**
* Remove a node from the closed list
*
* @param node
* The node to remove from the closed list
*/
protected void removeFromClosed(Node node) {
closed.remove(node);
}
/**
* Check if a given location is valid for the supplied mover
*
* @param mover
* The mover that would hold a given location
* @param sx
* The starting x coordinate
* @param sy
* The starting y coordinate
* @param x
* The x coordinate of the location to check
* @param y
* The y coordinate of the location to check
* @return True if the location is valid for the given mover
*/
protected boolean isValidLocation(GameObject mover, int sx, int sy, int x, int y) {
boolean invalid = (x < 0) || (y < 0) || (x >= map.getNumberOfColumns()) || (y >= map.getNumberOfRows());
if ((!invalid) && ((sx != x) || (sy != y))) {
int widthCells = (int)Math.floor(mover.getWidth() / map.getCellWidth());
int heightCells = (int)Math.floor(mover.getHeight() / map.getCellHeight());
for (int xAddition = 0; xAddition < widthCells; ++xAddition) {
for (int yAddition = 0; yAddition < heightCells; ++yAddition) {
if (map.isCollision(x + xAddition, y + yAddition, map.layerIndexOf(mover), mover)) {
return false;
}
}
}
}
return !invalid;
}
/**
* Get the cost to move through a given location
*
* @param mover
* The entity that is being moved
* @param sx
* The x coordinate of the tile whose cost is being determined
* @param sy
* The y coordiante of the tile whose cost is being determined
* @param tx
* The x coordinate of the target location
* @param ty
* The y coordinate of the target location
* @return The cost of movement through the given tile
*/
public float getMovementCost(GameObject mover, int sx, int sy, int tx, int ty) {
// TODO: integrate costs
return 0f;
}
/**
* Get the heuristic cost for the given location. This determines in which order
* the locations are processed.
*
* @param mover
* The entity that is being moved
* @param x
* The x coordinate of the tile whose cost is being determined
* @param y
* The y coordiante of the tile whose cost is being determined
* @param tx
* The x coordinate of the target location
* @param ty
* The y coordinate of the target location
* @return The heuristic cost assigned to the tile
*/
public float getHeuristicCost(GameObject mover, int x, int y, int tx, int ty) {
return heuristic.getCost(map, mover, x, y, tx, ty);
}
/**
* A simple sorted list
*
* @author kevin
*/
private class SortedList {
/**
* The list of elements
*/
@SuppressWarnings("rawtypes")
private ArrayList list = new ArrayList();
/**
* Retrieve the first element from the list
*
* @return The first element from the list
*/
public Object first() {
return list.get(0);
}
/**
* Empty the list
*/
public void clear() {
list.clear();
}
/**
* Add an element to the list - causes sorting
*
* @param o
* The element to add
*/
@SuppressWarnings("unchecked")
public void add(Object o) {
list.add(o);
Collections.sort(list);
}
/**
* Remove an element from the list
*
* @param o
* The element to remove
*/
public void remove(Object o) {
list.remove(o);
}
/**
* Get the number of elements in the list
*
* @return The number of element in the list
*/
public int size() {
return list.size();
}
/**
* Check if an element is in the list
*
* @param o
* The element to search for
* @return True if the element is in the list
*/
public boolean contains(Object o) {
return list.contains(o);
}
}
/**
* A single node in the search graph
*/
private class Node implements Comparable<Object> {
/**
* The x coordinate of the node
*/
private int x;
/**
* The y coordinate of the node
*/
private int y;
/**
* The path cost for this node
*/
private float cost;
/**
* The parent of this node, how we reached it in the search
*/
private Node parent;
/**
* The heuristic cost of this node
*/
private float heuristic;
/**
* The search depth of this node
*/
private int depth;
/**
* Create a new node
*
* @param x
* The x coordinate of the node
* @param y
* The y coordinate of the node
*/
public Node(int x, int y) {
this.x = x;
this.y = y;
}
/**
* Set the parent of this node
*
* @param parent
* The parent node which lead us to this node
* @return The depth we have no reached in searching
*/
public int setParent(Node parent) {
depth = parent.depth + 1;
this.parent = parent;
return depth;
}
/**
* @see Comparable#compareTo(Object)
*/
@Override
public int compareTo(Object other) {
Node o = (Node) other;
float f = heuristic + cost;
float of = o.heuristic + o.cost;
if (f < of) {
return -1;
} else if (f > of) {
return 1;
} else {
return 0;
}
}
}
}
|
package org.hisp.dhis.android.core.event;
import android.support.annotation.NonNull;
import org.hisp.dhis.android.core.common.D2CallException;
import org.hisp.dhis.android.core.common.D2CallExecutor;
import org.hisp.dhis.android.core.common.SyncCall;
import org.hisp.dhis.android.core.data.api.OuMode;
import org.hisp.dhis.android.core.data.database.DatabaseAdapter;
import org.hisp.dhis.android.core.organisationunit.OrganisationUnitModel;
import org.hisp.dhis.android.core.program.ProgramStore;
import org.hisp.dhis.android.core.program.ProgramStoreInterface;
import org.hisp.dhis.android.core.user.UserOrganisationUnitLinkModel;
import org.hisp.dhis.android.core.user.UserOrganisationUnitLinkStore;
import org.hisp.dhis.android.core.user.UserOrganisationUnitLinkStoreInterface;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.Callable;
import retrofit2.Retrofit;
public final class EventWithLimitCall extends SyncCall<List<Event>> {
private final int eventLimit;
private final boolean limitByOrgUnit;
private final DatabaseAdapter databaseAdapter;
private final Retrofit retrofit;
private final UserOrganisationUnitLinkStoreInterface userOrganisationUnitLinkStore;
private final ProgramStoreInterface programStore;
private EventWithLimitCall(
@NonNull DatabaseAdapter databaseAdapter,
@NonNull Retrofit retrofit,
@NonNull UserOrganisationUnitLinkStoreInterface userOrganisationUnitLinkStore,
@NonNull ProgramStoreInterface programStore,
int eventLimit,
boolean limitByOrgUnit) {
this.databaseAdapter = databaseAdapter;
this.retrofit = retrofit;
this.userOrganisationUnitLinkStore = userOrganisationUnitLinkStore;
this.programStore = programStore;
this.eventLimit = eventLimit;
this.limitByOrgUnit = limitByOrgUnit;
}
@Override
public List<Event> call() throws D2CallException {
setExecuted();
return new D2CallExecutor().executeD2CallTransactionally(databaseAdapter, new Callable<List<Event>>() {
@Override
public List<Event> call() throws Exception {
return getEvents();
}
});
}
private List<Event> getEvents() throws D2CallException {
Set<String> organisationUnitUids;
Set<String> programUids = programStore.queryWithoutRegistrationProgramUids();
List<Event> events = new ArrayList<>();
EventQuery.Builder eventQueryBuilder = EventQuery.Builder.create();
int pageSize = eventQueryBuilder.build().getPageSize();
if (limitByOrgUnit) {
organisationUnitUids = getOrgUnitUids();
} else {
organisationUnitUids = userOrganisationUnitLinkStore.queryRootOrganisationUnitUids();
eventQueryBuilder.withOuMode(OuMode.DESCENDANTS);
}
for (String orgUnitUid : organisationUnitUids) {
if (!limitByOrgUnit && events.size() == eventLimit) {
break;
}
eventQueryBuilder.withOrgUnit(orgUnitUid);
events.addAll(getEventsWithPaging(eventQueryBuilder, pageSize, programUids, events.size()));
}
return events;
}
private List<Event> getEventsWithPaging(EventQuery.Builder eventQueryBuilder, int pageSize, Set<String> programUids,
int globalEventsSize) throws D2CallException {
List<Event> events = new ArrayList<>();
D2CallExecutor executor = new D2CallExecutor();
for (String programUid : programUids) {
eventQueryBuilder.withProgram(programUid);
int eventLimitForProgram = limitByOrgUnit ? eventLimit : eventLimit - globalEventsSize;
int numPages = (int) Math.ceil((double) (eventLimitForProgram - events.size()) / pageSize);
eventQueryBuilder.withPageLimit(50);
for (int page = 1; page <= numPages; page++) {
if (page == numPages) {
int pageLimit = Math.min(
eventLimitForProgram - ((page - 1) * pageSize),
eventLimitForProgram - events.size());
eventQueryBuilder.withPageLimit(pageLimit);
}
if (!limitByOrgUnit && eventQueryBuilder.pageLimit + events.size() > eventLimitForProgram) {
eventQueryBuilder.withPageLimit(eventLimitForProgram - events.size());
}
eventQueryBuilder.withPage(page);
List<Event> pageEvents = executor.executeD2Call(
EventEndpointCall.create(retrofit, eventQueryBuilder.build()));
events.addAll(pageEvents);
if (pageEvents.size() < pageSize) {
break;
}
}
if (events.size() == eventLimitForProgram) {
break;
}
}
executor.executeD2Call(EventPersistenceCall.create(databaseAdapter, retrofit, events));
return events;
}
private Set<String> getOrgUnitUids() {
Set<UserOrganisationUnitLinkModel> userOrganisationUnitLinks = userOrganisationUnitLinkStore.selectAll(
UserOrganisationUnitLinkModel.factory);
Set<String> organisationUnitUids = new HashSet<>();
for (UserOrganisationUnitLinkModel linkModel: userOrganisationUnitLinks) {
if (linkModel.organisationUnitScope().equals(
OrganisationUnitModel.Scope.SCOPE_DATA_CAPTURE.name())) {
organisationUnitUids.add(linkModel.organisationUnit());
}
}
return organisationUnitUids;
}
public static EventWithLimitCall create(DatabaseAdapter databaseAdapter, Retrofit retrofit,
int eventLimit, boolean limitByOrgUnit) {
return new EventWithLimitCall(
databaseAdapter,
retrofit,
UserOrganisationUnitLinkStore.create(databaseAdapter),
ProgramStore.create(databaseAdapter),
eventLimit,
limitByOrgUnit
);
}
}
|
package gc.david.dfm.daogenerator;
import org.greenrobot.greendao.generator.DaoGenerator;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class DFMDaoGenerator {
private static final String SCHEMA_OUTPUT_DIR = "app/src/main/java";
/**
* Generator main application which builds all of the schema versions
* (including older versions used for migration test purposes) and ensures
* business rules are met; these include ensuring we only have a single
* current schema instance and the version numbering is correct.
*
* @param args
* @throws Exception
* @throws IOException
*/
public static void main(String[] args) throws Exception {
final List<SchemaVersion> versions = new ArrayList<>();
versions.add(new Version1(false));
versions.add(new Version2(false));
// Workaround to have each version with its version number and final version outside
versions.add(new WorkingVersion(true));
validateSchemas(versions);
for (final SchemaVersion version : versions) {
// NB: Test output creates stubs, we have an established testing
// standard which should be followed in preference to generating
// these stubs.
new DaoGenerator().generateAll(version.getSchema(), SCHEMA_OUTPUT_DIR);
}
}
public static void validateSchemas(final List<SchemaVersion> versions) throws IllegalArgumentException {
int numCurrent = 0;
final Set<Integer> versionNumbers = new HashSet<>();
for (final SchemaVersion version : versions) {
if (version.isCurrent()) {
numCurrent++;
}
final int versionNumber = version.getVersionNumber();
versionNumbers.add(versionNumber);
}
if (numCurrent != 1) {
throw new IllegalArgumentException("Unable to generate schema, exactly one schema marked as current is required.");
}
}
}
|
// -*- mode:java; encoding:utf-8 -*-
// vim:set fileencoding=utf-8:
// @homepage@
package example;
import java.awt.*;
import java.util.stream.Stream;
import javax.swing.*;
public final class MainPanel extends JPanel {
private static final float[] DEFAULT_DASHARRAY = {1f};
private final JComboBox<JoinStyle> joinCombo = new JComboBox<>(JoinStyle.values());
private final JComboBox<EndCapStyle> endcapCombo = new JComboBox<>(EndCapStyle.values());
private final JTextField field = new JTextField("10, 20");
private final JLabel label = new JLabel();
private final JButton button = new JButton("Change");
private float[] getDashArray() {
// String[] slist = field.getText().split(","); // ErrorProne: StringSplitter
String[] slist = Stream.of(field.getText().split(","))
.map(String::trim)
.filter(s -> !s.isEmpty())
.toArray(String[]::new);
if (slist.length == 0) {
return DEFAULT_DASHARRAY;
}
float[] list = new float[slist.length];
int i = 0;
try {
for (String s: slist) {
String ss = s.trim();
if (!ss.isEmpty()) {
list[i++] = Float.parseFloat(ss);
}
}
} catch (NumberFormatException ex) {
EventQueue.invokeLater(() -> {
Toolkit.getDefaultToolkit().beep();
String msg = "Invalid input.\n" + ex.getMessage();
JOptionPane.showMessageDialog(getRootPane(), msg, "Error", JOptionPane.ERROR_MESSAGE);
});
return DEFAULT_DASHARRAY;
}
return i == 0 ? DEFAULT_DASHARRAY : list;
}
private MainPanel() {
super(new BorderLayout());
button.addActionListener(e -> {
int ecs = endcapCombo.getItemAt(endcapCombo.getSelectedIndex()).style;
int js = joinCombo.getItemAt(joinCombo.getSelectedIndex()).style;
BasicStroke dashedStroke = new BasicStroke(5f, ecs, js, 5f, getDashArray(), 0f);
label.setBorder(BorderFactory.createStrokeBorder(dashedStroke, Color.RED));
});
JPanel p = new JPanel(new BorderLayout(2, 2));
p.add(field);
p.add(button, BorderLayout.EAST);
p.setBorder(BorderFactory.createTitledBorder("Comma Separated Values"));
JPanel p1 = new JPanel(new GridLayout(2, 1));
p1.add(endcapCombo);
p1.add(joinCombo);
p.add(p1, BorderLayout.NORTH);
JPanel p2 = new JPanel(new BorderLayout());
p2.add(label);
p2.setBorder(BorderFactory.createEmptyBorder(8, 8, 8, 8));
add(p, BorderLayout.NORTH);
add(p2);
setPreferredSize(new Dimension(320, 240));
button.doClick();
EventQueue.invokeLater(() -> getRootPane().setDefaultButton(button));
}
public static void main(String[] args) {
EventQueue.invokeLater(MainPanel::createAndShowGui);
}
private static void createAndShowGui() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
Toolkit.getDefaultToolkit().beep();
}
JFrame frame = new JFrame("@title@");
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.getContentPane().add(new MainPanel());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
enum JoinStyle {
JOIN_BEVEL(BasicStroke.JOIN_BEVEL),
JOIN_MITER(BasicStroke.JOIN_MITER),
JOIN_ROUND(BasicStroke.JOIN_ROUND);
public final int style;
JoinStyle(int style) {
this.style = style;
}
}
enum EndCapStyle {
CAP_BUTT(BasicStroke.CAP_BUTT),
CAP_ROUND(BasicStroke.CAP_ROUND),
CAP_SQUARE(BasicStroke.CAP_SQUARE);
public final int style;
EndCapStyle(int style) {
this.style = style;
}
}
|
package org.treetank.sessionlayer;
import static org.junit.Assert.assertEquals;
import java.io.File;
import org.junit.Before;
import org.junit.Test;
import org.treetank.api.IConstants;
import org.treetank.api.IReadTransaction;
import org.treetank.api.ISession;
import org.treetank.api.IWriteTransaction;
import org.treetank.utils.UTF;
public class UpdateTest {
public static final String TEST_PATH = "generated/UpdateTest.tnk";
@Before
public void setUp() throws Exception {
new File(TEST_PATH).delete();
}
@Test
public void testInsertChild() throws Exception {
ISession session = new Session(TEST_PATH);
// Document root.
IWriteTransaction trx = session.beginWriteTransaction();
trx.insertRoot("test");
session.commit();
IReadTransaction rTrx = session.beginReadTransaction();
assertEquals(1L, rTrx.revisionSize());
assertEquals(1L, rTrx.revisionKey());
// Insert 100 children.
for (int i = 1; i <= 10; i++) {
session = new Session(TEST_PATH);
trx = session.beginWriteTransaction();
trx.moveToRoot();
trx.insertFirstChild(IConstants.TEXT, "", "", "", UTF.convert(Integer
.toString(i)));
session.commit();
session.close();
session = new Session(TEST_PATH);
rTrx = session.beginReadTransaction();
rTrx.moveToRoot();
rTrx.moveToFirstChild();
assertEquals(Integer.toString(i), new String(rTrx.getValue()));
assertEquals(i + 1L, rTrx.revisionSize());
assertEquals(i + 1L, rTrx.revisionKey());
}
session = new Session(TEST_PATH);
rTrx = session.beginReadTransaction();
rTrx.moveToRoot();
rTrx.moveToFirstChild();
assertEquals(Integer.toString(10), new String(rTrx.getValue()));
assertEquals(11L, rTrx.revisionSize());
assertEquals(11L, rTrx.revisionKey());
session.close();
}
@Test
public void testInsertPath() throws Exception {
final ISession session = new Session(TEST_PATH);
IWriteTransaction wtx = session.beginWriteTransaction();
assertEquals(0L, wtx.insertRoot("foo"));
session.commit();
wtx = session.beginWriteTransaction();
assertEquals(true, wtx.moveToRoot());
assertEquals(1L, wtx.insertFirstChild(
IConstants.ELEMENT,
"",
"",
"",
UTF.EMPTY));
assertEquals(2L, wtx.insertFirstChild(
IConstants.ELEMENT,
"",
"",
"",
UTF.EMPTY));
assertEquals(3L, wtx.insertFirstChild(
IConstants.ELEMENT,
"",
"",
"",
UTF.EMPTY));
assertEquals(true, wtx.moveToParent());
assertEquals(4L, wtx.insertRightSibling(
IConstants.ELEMENT,
"",
"",
"",
UTF.EMPTY));
session.commit();
final IWriteTransaction wtx2 = session.beginWriteTransaction();
assertEquals(true, wtx2.moveToRoot());
assertEquals(5L, wtx.insertFirstChild(
IConstants.ELEMENT,
"",
"",
"",
UTF.EMPTY));
session.commit();
session.close();
}
}
|
package org.lockss.plugin;
import java.io.*;
import java.net.MalformedURLException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.*;
import java.util.regex.*;
import java.lang.reflect.*;
import java.util.zip.*;
import org.lockss.test.*;
import org.lockss.daemon.*;
import org.lockss.plugin.simulated.*;
import org.lockss.util.*;
import org.lockss.app.*;
import org.lockss.config.*;
/**
* Utilities for manipulating plugins and their components in tests
*/
public class PluginTestUtil {
static Logger log = Logger.getLogger("PluginTestUtil");
static List aulist = new LinkedList();
public static void registerArchivalUnit(Plugin plug, ArchivalUnit au) {
PluginManager mgr = getPluginManager();
log.debug3(mgr.toString());
String plugid = au.getPluginId();
log.debug("registerArchivalUnit plugin = " + plug +
"au = " + au);
if (plug != mgr.getPlugin(plugid)) {
try {
PrivilegedAccessor.invokeMethod(mgr, "setPlugin",
ListUtil.list(plugid, plug).toArray());
} catch (Exception e) {
log.error("Couldn't register AU", e);
throw new RuntimeException(e.toString());
}
}
PluginTestable tp = (PluginTestable)plug;
tp.registerArchivalUnit(au);
try {
PrivilegedAccessor.invokeMethod(mgr, "putAuInMap",
ListUtil.list(au).toArray());
} catch (InvocationTargetException e) {
log.error("Couldn't register AU", e);
log.error("Nested", e.getTargetException());
throw new RuntimeException(e.toString());
} catch (Exception e) {
log.error("Couldn't register AU", e);
throw new RuntimeException(e.toString());
}
aulist.add(au);
}
public static void registerArchivalUnit(ArchivalUnit au) {
PluginManager mgr = getPluginManager();
String plugid = au.getPluginId();
Plugin plug = mgr.getPlugin(plugid);
log.debug("registerArchivalUnit id = " + au.getAuId() +
", pluginid = " + plugid + ", plugin = " + plug);
if (plug == null) {
MockPlugin mp = new MockPlugin();
mp.setPluginId(plugid);
plug = mp;
}
registerArchivalUnit(plug, au);
}
/*
public static void registerArchivalUnit(ArchivalUnit au) {
PluginManager mgr = getPluginManager();
log.debug(mgr.toString());
String plugid = au.getPluginId();
Plugin plug = mgr.getPlugin(plugid);
log.debug("registerArchivalUnit id = " + au.getAuId() +
", pluginid = " + plugid + ", plugin = " + plug);
if (plug == null) {
MockPlugin mp = new MockPlugin();
mp.setPluginId(plugid);
plug = mp;
try {
PrivilegedAccessor.invokeMethod(mgr, "setPlugin",
ListUtil.list(plugid, mp).toArray());
} catch (Exception e) {
log.error("Couldn't register AU", e);
throw new RuntimeException(e.toString());
}
}
PluginTestable tp = (PluginTestable)plug;
tp.registerArchivalUnit(au);
try {
PrivilegedAccessor.invokeMethod(mgr, "putAuMap",
ListUtil.list(plug, au).toArray());
} catch (Exception e) {
log.error("Couldn't register AU", e);
throw new RuntimeException(e.toString());
}
aulist.add(au);
}
*/
public static void unregisterArchivalUnit(ArchivalUnit au) {
PluginManager mgr = getPluginManager();
String plugid = au.getPluginId();
Plugin plug = mgr.getPlugin(plugid);
if (plug != null) {
PluginTestable tp = (PluginTestable)plug;
tp.unregisterArchivalUnit(au);
aulist.remove(au);
}
mgr.stopAu(au, new AuEvent(AuEvent.Type.Delete, false));
}
public static void unregisterAllArchivalUnits() {
log.debug("unregisterAllArchivalUnits()");
List aus = new ArrayList(aulist);
for (Iterator iter = aus.iterator(); iter.hasNext(); ) {
unregisterArchivalUnit((ArchivalUnit)iter.next());
}
}
public static Plugin findPlugin(String pluginName) {
PluginManager pluginMgr = getPluginManager();
String key = pluginMgr.pluginKeyFromName(pluginName);
pluginMgr.ensurePluginLoaded(key);
return pluginMgr.getPlugin(key);
}
public static Plugin findPlugin(Class pluginClass) {
return findPlugin(pluginClass.getName());
}
public static ArchivalUnit createAu(Plugin plugin,
Configuration auConfig)
throws ArchivalUnit.ConfigurationException {
return getPluginManager().createAu(plugin, auConfig,
new AuEvent(AuEvent.Type.Create, false));
}
public static ArchivalUnit createAndStartAu(Plugin plugin,
Configuration auConfig)
throws ArchivalUnit.ConfigurationException {
return startAu(createAu(plugin, auConfig));
}
static ArchivalUnit startAu(ArchivalUnit au) {
LockssDaemon daemon = au.getPlugin().getDaemon();
daemon.getHistoryRepository(au).startService();
daemon.getLockssRepository(au).startService();
daemon.getNodeManager(au).startService();
return au;
}
public static ArchivalUnit createAu(String pluginName,
Configuration auConfig)
throws ArchivalUnit.ConfigurationException {
return createAu(findPlugin(pluginName), auConfig);
}
public static ArchivalUnit createAndStartAu(String pluginName,
Configuration auConfig)
throws ArchivalUnit.ConfigurationException {
return createAndStartAu(findPlugin(pluginName), auConfig);
}
public static ArchivalUnit createAu(Class pluginClass,
Configuration auConfig)
throws ArchivalUnit.ConfigurationException {
return createAu(findPlugin(pluginClass.getName()), auConfig);
}
public static ArchivalUnit createAndStartAu(Class pluginClass,
Configuration auConfig)
throws ArchivalUnit.ConfigurationException {
return createAndStartAu(findPlugin(pluginClass.getName()), auConfig);
}
public static SimulatedArchivalUnit createSimAu(Configuration auConfig)
throws ArchivalUnit.ConfigurationException {
return (SimulatedArchivalUnit)createAu(findPlugin(SimulatedPlugin.class),
auConfig);
}
static Configuration getAuConfig(TdbAu tau) {
PluginManager mgr = getPluginManager();
Plugin plugin = tau.getPlugin(mgr);
TitleConfig tc = new TitleConfig(tau, plugin);
return tc.getConfig();
}
public static ArchivalUnit createAu(TdbAu tau)
throws ArchivalUnit.ConfigurationException {
PluginManager mgr = getPluginManager();
Plugin plugin = findPlugin(tau.getPluginId());
return createAu(plugin, getAuConfig(tau));
}
public static ArchivalUnit createAu(Plugin plugin, TdbAu tau)
throws ArchivalUnit.ConfigurationException {
return createAu(plugin, getAuConfig(tau));
}
public static ArchivalUnit createAndStartAu(TdbAu tau)
throws ArchivalUnit.ConfigurationException {
return startAu(createAu(tau));
}
public static ArchivalUnit createAndStartAu(Plugin plugin, TdbAu tau)
throws ArchivalUnit.ConfigurationException {
return startAu(createAu(plugin, tau));
}
public static SimulatedArchivalUnit
createAndStartSimAu(Configuration auConfig)
throws ArchivalUnit.ConfigurationException {
return createAndStartSimAu(SimulatedPlugin.class, auConfig);
}
public static SimulatedArchivalUnit
createAndStartSimAu(Class pluginClass, Configuration auConfig)
throws ArchivalUnit.ConfigurationException {
return (SimulatedArchivalUnit)createAndStartAu(pluginClass, auConfig);
}
public static void crawlSimAu(SimulatedArchivalUnit sau) {
if (!sau.hasContentTree()) {
// log.debug("Creating simulated content tree: " + sau.getParamMap());
sau.generateContentTree();
}
log.debug("Crawling simulated content");
NoCrawlEndActionsFollowLinkCrawler crawler =
new NoCrawlEndActionsFollowLinkCrawler(sau, new MockAuState());
//crawler.setCrawlManager(crawlMgr);
crawler.doCrawl();
}
/**
* {@code ifMatch, patRepPairs} defaults to {null}.
* {@code fromAu} defaults to {fromAu.getCachedUrlSet()}.
*
* @see PluginTestUtil#copyCus(CachedUrlSet, ArchivalUnit, String, List)
*/
public static boolean copyAu(ArchivalUnit fromAu, ArchivalUnit toAu) throws MalformedURLException {
return copyAu(fromAu, toAu, null, null, null);
}
/**
* {@code patRepPairs} defaults to {null}.
* {@code fromAu} defaults to {fromAu.getCachedUrlSet()}.
*
* @see PluginTestUtil#copyCus(CachedUrlSet, ArchivalUnit, String, List)
*/
public static boolean copyAu(ArchivalUnit fromAu, ArchivalUnit toAu, String ifMatch) throws MalformedURLException {
return copyAu(fromAu, toAu, ifMatch, null, null);
}
/**
* {@code pat, rep} converted to {PatternReplacements}.
* {@code fromAu} defaults to {fromAu.getCachedUrlSet()}.
*
* @see PluginTestUtil#copyCus(CachedUrlSet, ArchivalUnit, String, List)
*/
public static boolean copyAu(ArchivalUnit fromAu, ArchivalUnit toAu,
String ifMatch, String pat, String rep) throws MalformedURLException {
return copyCus(fromAu.getAuCachedUrlSet(), toAu, ifMatch, pat, rep);
}
/**
* {@code fromAu} defaults to {fromAu.getCachedUrlSet()}.
*
* @see PluginTestUtil#copyCus(CachedUrlSet, ArchivalUnit, String, List)
*/
public static boolean copyAu(ArchivalUnit fromAu,
ArchivalUnit toAu,
String ifMatch,
List<PatternReplacements> patRepPairs) throws MalformedURLException {
return copyCus(fromAu.getAuCachedUrlSet(), toAu, ifMatch, patRepPairs);
}
/**
* {@code ifMatch, patRepPairs} defaults to {null}.
*
* @see PluginTestUtil#copyCus(CachedUrlSet, ArchivalUnit, String, List)
*/
public static boolean copyCus(CachedUrlSet fromCus, ArchivalUnit toAu) throws MalformedURLException {
return copyCus(fromCus, toAu, null, null, null);
}
/**
* {@code pat, rep} converted to {PatternReplacements}.
*
* @param pat a regex used to match files in the simulated crawl
* @param rep regex replacement pattern(s) to rename the original file.
* @see PluginTestUtil#copyCus(CachedUrlSet, ArchivalUnit, String, List)
*/
public static boolean copyCus(CachedUrlSet fromCus, ArchivalUnit toAu,
String ifMatch, String pat, String rep) throws MalformedURLException {
List<PatternReplacements> patRepPairs;
if (pat == null) {
patRepPairs = null;
} else {
patRepPairs = Collections.singletonList(new PatternReplacements(pat, rep));
}
return copyCus(fromCus, toAu, ifMatch, patRepPairs);
}
/**
* Utility to copy files from a simulated crawl to a mock archival unit.
* For each file matched by ifMatch, the first Pattern matched will be copied for as many
* replacements as are associated with it.
* If only fromAu and toAu are provided, all files are copied without modification.
*
* @param fromCus the CachedUrlSet which has been crawled
* @param toAu the Archival Unit to copy content to
* @param ifMatch String, a regex to check on the url before pattern replacement transforming. e.g. .zip
* @param patRepPairs A List of PatternReplacements to rename files from matched patterns to replacements.
* @return true, if all copies attempted succeeded, false otherwise
*/
public static boolean copyCus(CachedUrlSet fromCus, ArchivalUnit toAu,
String ifMatch, List<PatternReplacements> patRepPairs)
throws MalformedURLException {
boolean res = true;
Pattern ifMatchPat = null;
if (ifMatch != null) {
ifMatchPat = Pattern.compile(ifMatch);
}
ArchiveFileTypes aft = toAu.getArchiveFileTypes();
String isArchive = null;
for (CachedUrl cu : fromCus.getCuIterable()) {
try {
String fromUrl = cu.getUrl();
String toUrl = fromUrl;
if (ifMatchPat != null) {
Matcher mat = ifMatchPat.matcher(fromUrl);
if (!mat.find()) {
log.debug3("no match: " + fromUrl + ", " + ifMatchPat);
continue;
}
}
if (aft != null) {
isArchive = aft.getFromCu(cu);
}
if (isArchive == null) {
if (patRepPairs != null) {
for (PatternReplacements prp : patRepPairs) {
Matcher mat = prp.pat.matcher(fromUrl);
if (mat.find()) {
for (String rep : prp.rep) {
toUrl = mat.replaceAll(rep);
doCopyCu(cu, toAu, fromUrl, toUrl);
}
break;
}
}
} else {
doCopyCu(cu, toAu, fromUrl, toUrl);
}
} else {
switch (isArchive) {
case ".zip":
copyZip(cu, toAu, patRepPairs);
break;
case ".tar":
//TODO
// com.ice.tar.TarInputStream
log.info("support for .tar coming");
throw new Exception("support for .tar coming");
//break;
case ".tar.gz":
case ".tgz":
//TODO
// double wrap - unwrap gzip, then TarInputStream
log.info("support for .tgz coming");
throw new Exception("support for .tgz coming");
//break;
default:
throw new Exception("Unexpected Archive file type: '" + isArchive + "'");
}
}
} catch (Exception e) {
log.error("Couldn't copy " + cu.getUrl(), e);
res = false;
} finally {
cu.release();
}
}
return res;
}
private static void doCopyCu(CachedUrl cu,
ArchivalUnit toAu,
String fromUrl,
String toUrl
) throws IOException {
CIProperties props = cu.getProperties();
if (props == null) {
log.debug3("in copyCus() props was null for url: " + fromUrl);
}
UrlCacher uc = toAu.makeUrlCacher(
new UrlData(cu.getUnfilteredInputStream(), props, toUrl));
uc.storeContent();
if (!toUrl.equals(fromUrl)) {
log.info("Copied " + fromUrl + " to " + toUrl);
} else {
log.debug2("Copied " + fromUrl);
}
}
/**
* Opens a single CachedUrl zip file, iterates over its contents and copies the contents if they pass
* given pattern(s) and replacements.
*
* Note: replacement(s) can rename the zip file, but all zip files should be the same in the replacement string(s)
*
* @param cu A CachedUrl of compressed content.
* @param toAu The ArchivalUnit to copy the cu into.
* @param patRepPairs A List of PatternReplacementss to selectively copy zipped content and rename it in the new zip.
* @throws IOException When I/O zip files encounter any number of problems.
*/
private static void copyZip(CachedUrl cu, ArchivalUnit toAu, List<PatternReplacements> patRepPairs)
throws IOException {
boolean doCache = false;
String zipUrl = cu.getUrl() + "!/";
String toUrl; String toFile; String zippedFile; String fromFile;
ZipInputStream zis = null;
ZipOutputStream zos;
String outZip = null;
try {
InputStream cuis = new ReaderInputStream(cu.openForReading());
zis = new ZipInputStream(cuis);
zos = new ZipOutputStream(Files.newOutputStream(
Paths.get(cu.getArchivalUnit().getProperties().getString("root") +
"temp.zip")));
zos.setMethod(ZipOutputStream.DEFLATED);
zos.setLevel(Deflater.BEST_COMPRESSION);
ZipEntry entry;
while ((entry = zis.getNextEntry()) != null) {
if (entry.isDirectory()) {
continue;
} else if (entry.getName().endsWith(".zip") ) {
// TODO recurse through nested
// zipCopy(cu, toAu, zipUrl + );
}
fromFile = entry.getName();
zippedFile = zipUrl + fromFile;
if (patRepPairs == null) {
doCache = true;
doCopyZip(zos, zis, zippedFile);
outZip = zippedFile.split("!/")[0];
} else {
for (PatternReplacements prp : patRepPairs) {
Matcher mat = prp.pat.matcher(zippedFile);
if (mat.find()) {
for (String rep : prp.rep) {
toUrl = mat.replaceAll(rep);
if (!toUrl.equals(zippedFile)) {
log.debug("Found a zipped file match: " + zippedFile + " -> " + toUrl);
doCache = true;
doCopyZip(zos, zis, toUrl);
outZip = toUrl.split("!/")[0];
}
}
break;
}
}
}
}
zos.close();
// any copied file triggers saving the new zip stream
// the output file name is parsed from the matched file
// it will be the last matched-replaced file.
if (doCache) {
FileInputStream is = new FileInputStream(new File(
cu.getArchivalUnit().getProperties().getString("root"),
"temp.zip"));
// save all the copied zip entries to a new zip on the toAu
CIProperties props = cu.getProperties();
if (props == null) {
log.debug3("in copyCus() props was null for url: " + cu.getUrl());
}
log.debug("Storing new cu: " + outZip);
UrlCacher uc = toAu.makeUrlCacher(
new UrlData(is, props, outZip));
uc.storeContent();
is.close();
}
} finally {
IOUtil.safeClose(zis);
}
}
private static void doCopyZip(ZipOutputStream zos, ZipInputStream zis, String toUrl) throws IOException {
String toFile = toUrl.split("!/")[1];
ZipEntry outEntry = new ZipEntry(toFile);
zos.putNextEntry(outEntry);
StreamUtil.copy(zis, zos);
zos.closeEntry();
}
public static List<String> urlsOf(final Iterable<CachedUrl> cus) {
return new ArrayList<String>() {{
for (CachedUrl cu : cus) {
add(cu.getUrl());
}
}};
}
private static PluginManager getPluginManager() {
return
(PluginManager)LockssDaemon.getManager(LockssDaemon.PLUGIN_MANAGER);
}
public static PatternReplacements makePatRep(String pat, String... rep) {
return new PatternReplacements(pat , rep);
}
public static class PatternReplacements {
public Pattern pat;
public String[] rep;
/**
* Simple Container class for Regex pattern -> Replacement associations.
* @param pat String regex, gets compiled to a Pattern
* @param rep Replacement string
*/
PatternReplacements(String pat, String... rep) {
this.pat = Pattern.compile(pat, Pattern.CASE_INSENSITIVE);
this.rep = rep;
}
}
}
|
package hudson.tasks;
import hudson.model.Build;
import hudson.model.FreeStyleProject;
import jenkins.mvn.DefaultGlobalSettingsProvider;
import jenkins.mvn.DefaultSettingsProvider;
import jenkins.mvn.FilePathGlobalSettingsProvider;
import jenkins.mvn.FilePathSettingsProvider;
import jenkins.mvn.GlobalMavenConfig;
import hudson.model.JDK;
import hudson.model.ParametersDefinitionProperty;
import hudson.model.Result;
import hudson.model.StringParameterDefinition;
import hudson.model.ParametersAction;
import hudson.model.StringParameterValue;
import hudson.model.Cause.LegacyCodeCause;
import hudson.slaves.EnvironmentVariablesNodeProperty;
import hudson.slaves.EnvironmentVariablesNodeProperty.Entry;
import hudson.tasks.Maven.MavenInstallation;
import hudson.tasks.Maven.MavenInstaller;
import hudson.tasks.Maven.MavenInstallation.DescriptorImpl;
import hudson.tools.ToolProperty;
import hudson.tools.ToolPropertyDescriptor;
import hudson.tools.InstallSourceProperty;
import hudson.util.DescribableList;
import java.util.Collections;
import com.gargoylesoftware.htmlunit.html.HtmlForm;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
import com.gargoylesoftware.htmlunit.html.HtmlButton;
import hudson.EnvVars;
import hudson.model.FreeStyleBuild;
import hudson.model.PasswordParameterDefinition;
import org.jvnet.hudson.test.Bug;
import static org.junit.Assert.*;
import org.junit.Rule;
import org.junit.Test;
import org.jvnet.hudson.test.ExtractResourceSCM;
import org.jvnet.hudson.test.JenkinsRule;
/**
* @author Kohsuke Kawaguchi
*/
public class MavenTest {
@Rule public JenkinsRule j = new JenkinsRule();
/**
* Tests the round-tripping of the configuration.
*/
@Test public void configRoundtrip() throws Exception {
j.jenkins.getDescriptorByType(Maven.DescriptorImpl.class).setInstallations(); // reset
FreeStyleProject p = j.createFreeStyleProject();
p.getBuildersList().add(new Maven("a", null, "b.pom", "c=d", "-e", true));
JenkinsRule.WebClient webClient = j.createWebClient();
HtmlPage page = webClient.getPage(p, "configure");
HtmlForm form = page.getFormByName("config");
j.submit(form);
Maven m = p.getBuildersList().get(Maven.class);
assertNotNull(m);
assertEquals("a", m.targets);
assertNull("found " + m.mavenName, m.mavenName);
assertEquals("b.pom", m.pom);
assertEquals("c=d", m.properties);
assertEquals("-e", m.jvmOptions);
assertTrue(m.usesPrivateRepository());
}
@Test public void withNodeProperty() throws Exception {
MavenInstallation maven = j.configureDefaultMaven();
String mavenHome = maven.getHome();
String mavenHomeVar = "${VAR_MAVEN}" + mavenHome.substring(3);
String mavenVar = mavenHome.substring(0, 3);
MavenInstallation varMaven = new MavenInstallation("varMaven", mavenHomeVar, JenkinsRule.NO_PROPERTIES);
j.jenkins.getDescriptorByType(Maven.DescriptorImpl.class).setInstallations(maven, varMaven);
JDK jdk = j.jenkins.getJDK("default");
String javaHome = jdk.getHome();
String javaHomeVar = "${VAR_JAVA}" + javaHome.substring(3);
String javaVar = javaHome.substring(0, 3);
JDK varJDK = new JDK("varJDK", javaHomeVar);
j.jenkins.getJDKs().add(varJDK);
j.jenkins.getNodeProperties().replaceBy(
Collections.singleton(new EnvironmentVariablesNodeProperty(
new Entry("VAR_MAVEN", mavenVar), new Entry("VAR_JAVA",
javaVar))));
FreeStyleProject project = j.createFreeStyleProject();
project.getBuildersList().add(new Maven("--help", varMaven.getName()));
project.setJDK(varJDK);
Build<?, ?> build = project.scheduleBuild2(0).get();
assertEquals(Result.SUCCESS, build.getResult());
}
@Test public void withParameter() throws Exception {
MavenInstallation maven = j.configureDefaultMaven();
String mavenHome = maven.getHome();
String mavenHomeVar = "${VAR_MAVEN}" + mavenHome.substring(3);
String mavenVar = mavenHome.substring(0, 3);
MavenInstallation varMaven = new MavenInstallation("varMaven",mavenHomeVar, JenkinsRule.NO_PROPERTIES);
j.jenkins.getDescriptorByType(Maven.DescriptorImpl.class).setInstallations(maven, varMaven);
JDK jdk = j.jenkins.getJDK("default");
String javaHome = jdk.getHome();
String javaHomeVar = "${VAR_JAVA}" + javaHome.substring(3);
String javaVar = javaHome.substring(0, 3);
JDK varJDK = new JDK("varJDK", javaHomeVar);
j.jenkins.getJDKs().add(varJDK);
FreeStyleProject project = j.createFreeStyleProject();
project.addProperty(new ParametersDefinitionProperty(
new StringParameterDefinition("VAR_MAVEN", "XXX"),
new StringParameterDefinition("VAR_JAVA", "XXX")));
project.getBuildersList().add(new Maven("--help", varMaven.getName()));
project.setJDK(varJDK);
FreeStyleBuild build = project.scheduleBuild2(0, new LegacyCodeCause(),
new ParametersAction(
new StringParameterValue("VAR_MAVEN", mavenVar),
new StringParameterValue("VAR_JAVA", javaVar))).get();
j.assertBuildStatusSuccess(build);
}
/**
* Simulates the addition of the new Maven via UI and makes sure it works.
*/
@Test public void globalConfigAjax() throws Exception {
HtmlPage p = j.createWebClient().goTo("configure");
HtmlForm f = p.getFormByName("config");
HtmlButton b = j.getButtonByCaption(f, "Add Maven");
b.click();
j.findPreviousInputElement(b,"name").setValueAttribute("myMaven");
j.findPreviousInputElement(b,"home").setValueAttribute("/tmp/foo");
j.submit(f);
verify();
// another submission and verfify it survives a roundtrip
p = j.createWebClient().goTo("configure");
f = p.getFormByName("config");
j.submit(f);
verify();
}
private void verify() throws Exception {
MavenInstallation[] l = j.get(DescriptorImpl.class).getInstallations();
assertEquals(1,l.length);
j.assertEqualBeans(l[0],new MavenInstallation("myMaven","/tmp/foo", JenkinsRule.NO_PROPERTIES),"name,home");
// by default we should get the auto installer
DescribableList<ToolProperty<?>,ToolPropertyDescriptor> props = l[0].getProperties();
assertEquals(1,props.size());
InstallSourceProperty isp = props.get(InstallSourceProperty.class);
assertEquals(1,isp.installers.size());
assertNotNull(isp.installers.get(MavenInstaller.class));
}
@Test public void sensitiveParameters() throws Exception {
FreeStyleProject project = j.createFreeStyleProject();
ParametersDefinitionProperty pdb = new ParametersDefinitionProperty(
new StringParameterDefinition("string", "defaultValue", "string description"),
new PasswordParameterDefinition("password", "12345", "password description"),
new StringParameterDefinition("string2", "Value2", "string description")
);
project.addProperty(pdb);
project.setScm(new ExtractResourceSCM(getClass().getResource("maven-empty.zip")));
project.getBuildersList().add(new Maven("clean package",null));
FreeStyleBuild build = project.scheduleBuild2(0).get();
@SuppressWarnings("deprecation")
String buildLog = build.getLog();
assertNotNull(buildLog);
System.out.println(buildLog);
assertFalse(buildLog.contains("-Dpassword=12345"));
}
@Test
public void parametersReferencedFromPropertiesShouldRetainBackslashes() throws Exception {
final String properties = "global.path=$GLOBAL_PATH\nmy.path=$PATH\\\\Dir";
final StringParameterDefinition parameter = new StringParameterDefinition("PATH", "C:\\Windows");
final Entry envVar = new Entry("GLOBAL_PATH", "D:\\Jenkins");
FreeStyleProject project = j.createFreeStyleProject();
project.getBuildersList().add(new Maven("--help",null,null,properties,null));
project.addProperty(new ParametersDefinitionProperty(parameter));
j.jenkins.getNodeProperties().replaceBy(Collections.singleton(
new EnvironmentVariablesNodeProperty(envVar)
));
FreeStyleBuild build = project.scheduleBuild2(0).get();
@SuppressWarnings("deprecation")
String buildLog = build.getLog();
assertNotNull(buildLog);
assertTrue(
"Parameter my.path should preserve backslashes in:\n" + buildLog,
buildLog.contains("-Dmy.path=C:\\Windows\\Dir")
);
assertTrue(
"Parameter global.path should preserve backslashes in:\n" + buildLog,
buildLog.contains("-Dglobal.path=D:\\Jenkins")
);
}
@Test public void defaultSettingsProvider() throws Exception {
{
FreeStyleProject p = j.createFreeStyleProject();
p.getBuildersList().add(new Maven("a", null, "a.pom", "c=d", "-e", true));
Maven m = p.getBuildersList().get(Maven.class);
assertNotNull(m);
assertEquals(DefaultSettingsProvider.class, m.getSettings().getClass());
assertEquals(DefaultGlobalSettingsProvider.class, m.getGlobalSettings().getClass());
}
{
GlobalMavenConfig globalMavenConfig = GlobalMavenConfig.get();
assertNotNull("No global Maven Config available", globalMavenConfig);
globalMavenConfig.setSettingsProvider(new FilePathSettingsProvider("/tmp/settigns.xml"));
globalMavenConfig.setGlobalSettingsProvider(new FilePathGlobalSettingsProvider("/tmp/global-settigns.xml"));
FreeStyleProject p = j.createFreeStyleProject();
p.getBuildersList().add(new Maven("b", null, "b.pom", "c=d", "-e", true));
Maven m = p.getBuildersList().get(Maven.class);
assertEquals(FilePathSettingsProvider.class, m.getSettings().getClass());
assertEquals("/tmp/settigns.xml", ((FilePathSettingsProvider)m.getSettings()).getPath());
assertEquals("/tmp/global-settigns.xml", ((FilePathGlobalSettingsProvider)m.getGlobalSettings()).getPath());
}
}
@Bug(18898)
public void testNullHome() throws Exception {
EnvVars env = new EnvVars();
new MavenInstallation("_", "", Collections.<ToolProperty<?>>emptyList()).buildEnvVars(env);
assertEquals("{}", env.toString());
}
@Issue("JENKINS-26684")
@Test public void specialCharsInBuildVariablesPassedAsProperties() throws Exception {
j.configureDefaultMaven();
FreeStyleProject p = j.createFreeStyleProject();
p.getBuildersList().add(new Maven("--help", null));
p.addProperty(new ParametersDefinitionProperty(
new StringParameterDefinition("tilde", "~"),
new StringParameterDefinition("exclamation_mark", "!"),
new StringParameterDefinition("at_sign", "@"),
new StringParameterDefinition("sharp", "
new StringParameterDefinition("dolar", "$"),
new StringParameterDefinition("percent", "%"),
new StringParameterDefinition("circumflex", "^"),
new StringParameterDefinition("ampersand", "&"),
new StringParameterDefinition("asterix", "*"),
new StringParameterDefinition("parentheses", "()"),
new StringParameterDefinition("underscore", "_"),
new StringParameterDefinition("plus", "+"),
new StringParameterDefinition("braces", "{}"),
new StringParameterDefinition("brackets", "[]"),
new StringParameterDefinition("colon", ":"),
new StringParameterDefinition("semicolon", ";"),
new StringParameterDefinition("quote", "\""),
new StringParameterDefinition("apostrophe", "'"),
new StringParameterDefinition("backslash", "\\"),
new StringParameterDefinition("pipe", "|"),
new StringParameterDefinition("angle_brackets", "<>"),
new StringParameterDefinition("comma", ","),
new StringParameterDefinition("period", "."),
new StringParameterDefinition("slash", "/"),
new StringParameterDefinition("question_mark", "?"),
new StringParameterDefinition("space", " ")
));
FreeStyleBuild build = j.buildAndAssertSuccess(p);
}
}
|
/*
* Class DebuggerTreeNodeImpl
* @author Jeka
*/
package com.intellij.debugger.ui.impl.watch;
import com.intellij.debugger.engine.evaluation.EvaluationContextImpl;
import com.intellij.debugger.engine.events.DebuggerContextCommandImpl;
import com.intellij.debugger.impl.DebuggerContextImpl;
import com.intellij.debugger.impl.InvokeThread;
import com.intellij.debugger.ui.impl.DebuggerTreeRenderer;
import com.intellij.debugger.ui.impl.tree.TreeBuilder;
import com.intellij.debugger.ui.impl.tree.TreeBuilderNode;
import com.intellij.debugger.ui.tree.DebuggerTreeNode;
import com.intellij.debugger.ui.tree.NodeDescriptor;
import com.intellij.debugger.ui.tree.render.DescriptorLabelListener;
import com.intellij.debugger.ui.tree.render.NodeRenderer;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Key;
import com.intellij.ui.SimpleColoredText;
import com.intellij.util.containers.HashMap;
import javax.swing.*;
import java.util.Map;
public class DebuggerTreeNodeImpl extends TreeBuilderNode implements DebuggerTreeNode{
private Icon myIcon;
private SimpleColoredText myText;
private DebuggerTree myTree;
private Map myProperties = new HashMap();
private DebuggerTreeNodeImpl(DebuggerTree tree, NodeDescriptor descriptor) {
super(descriptor);
myTree = tree;
}
public DebuggerTreeNodeImpl getParent() {
return (DebuggerTreeNodeImpl) super.getParent();
}
protected TreeBuilder getTreeBuilder() {
return myTree.getMutableModel();
}
public DebuggerTree getTree() {
return myTree;
}
public String toString() {
return myText != null? myText.toString() : "";
}
public NodeDescriptorImpl getDescriptor() {
return (NodeDescriptorImpl)getUserObject();
}
public Project getProject() {
return getTree().getProject();
}
public void setRenderer(NodeRenderer renderer) {
((ValueDescriptorImpl) getDescriptor()).setRenderer(renderer);
calcRepresentation();
}
private void updateCaches() {
final NodeDescriptorImpl descriptor = getDescriptor();
myIcon = DebuggerTreeRenderer.getDescriptorIcon(descriptor);
myText = DebuggerTreeRenderer.getDescriptorText(getTree().getDebuggerContext(), descriptor, false);
}
public Icon getIcon() {
return myIcon;
}
public SimpleColoredText getText() {
return myText;
}
public void clear() {
removeAllChildren();
myIcon = null;
myText = null;
super.clear();
}
private void update(final DebuggerContextImpl context, final Runnable runnable, boolean labelOnly) {
if(!labelOnly) {
clear();
}
if(context != null && context.getDebugProcess() != null) {
getTree().saveState(this);
myIcon = DebuggerTreeRenderer.getDescriptorIcon(MessageDescriptor.EVALUATING);
myText = DebuggerTreeRenderer.getDescriptorText(context, MessageDescriptor.EVALUATING, false);
context.getDebugProcess().getManagerThread().invoke(new DebuggerContextCommandImpl(context) {
public void threadAction() {
runnable.run();
}
protected void commandCancelled() {
clear();
getDescriptor().clear();
updateCaches();
labelChanged();
childrenChanged(true);
}
}, InvokeThread.Priority.NORMAL);
}
labelChanged();
if(!labelOnly) {
childrenChanged(true);
}
}
public void calcLabel() {
final DebuggerContextImpl context = getTree().getDebuggerContext();
update(context, new Runnable() {
public void run() {
getDescriptor().updateRepresentation(context.createEvaluationContext(), new DescriptorLabelListener() {
public void labelChanged() {
updateCaches();
DebuggerTreeNodeImpl.this.labelChanged();
}
});
}
}, true);
}
public void calcRepresentation() {
final DebuggerContextImpl context = getTree().getDebuggerContext();
update(context, new Runnable() {
public void run() {
getDescriptor().updateRepresentation(context.createEvaluationContext(), new DescriptorLabelListener() {
public void labelChanged() {
updateCaches();
DebuggerTreeNodeImpl.this.labelChanged();
}
});
}
}, false);
}
public void calcValue() {
final DebuggerContextImpl context = getTree().getDebuggerContext();
update(
context,
new Runnable() {
public void run() {
EvaluationContextImpl evaluationContext = context.createEvaluationContext();
getDescriptor().setContext(evaluationContext);
getDescriptor().updateRepresentation(evaluationContext, new DescriptorLabelListener() {
public void labelChanged() {
updateCaches();
DebuggerTreeNodeImpl.this.labelChanged();
}
});
DebuggerTreeNodeImpl.this.childrenChanged(true);
}
}, false);
}
private void invoke(Runnable r) {
if(ApplicationManager.getApplication().isDispatchThread()) {
r.run();
}
else {
SwingUtilities.invokeLater(r);
}
}
public void labelChanged() {
invoke(new Runnable() {
public void run() {
updateCaches();
getTree().getMutableModel().nodeChanged(DebuggerTreeNodeImpl.this);
}
});
}
public void childrenChanged(final boolean scrollToVisible) {
invoke(new Runnable() {
public void run() {
getTree().getMutableModel().nodeStructureChanged(DebuggerTreeNodeImpl.this);
getTree().restoreState(DebuggerTreeNodeImpl.this);
}
});
}
public DebuggerTreeNodeImpl add(MessageDescriptor message) {
DebuggerTreeNodeImpl node = getNodeFactory().createMessageNode(message);
add(node);
return node;
}
public NodeManagerImpl getNodeFactory() {
return myTree.getNodeFactory();
}
public Object getProperty(Key key) {
return myProperties.get(key);
}
public void putProperty(Key key, Object data) {
myProperties.put(key, data);
}
public static DebuggerTreeNodeImpl createNodeNoUpdate(DebuggerTree tree, NodeDescriptor descriptor) {
DebuggerTreeNodeImpl node = new DebuggerTreeNodeImpl(tree, descriptor);
node.updateCaches();
return node;
}
protected static DebuggerTreeNodeImpl createNode(DebuggerTree tree, NodeDescriptorImpl descriptor, EvaluationContextImpl evaluationContext) {
final DebuggerTreeNodeImpl node = new DebuggerTreeNodeImpl(tree, descriptor);
descriptor.updateRepresentationNoNotify(evaluationContext, new DescriptorLabelListener() {
public void labelChanged() {
node.updateCaches();
node.labelChanged();
}
});
node.updateCaches();
return node;
}
}
|
import akka.stream.IOResult;
import akka.stream.Materializer;
import akka.stream.javadsl.FileIO;
import akka.stream.javadsl.Sink;
import akka.stream.javadsl.Source;
import akka.util.ByteString;
import org.junit.Test;
import play.api.http.HttpErrorHandler;
import play.core.j.JavaHandlerComponents;
import play.core.parsers.Multipart;
import play.libs.streams.Accumulator;
import play.mvc.BodyParser;
import play.mvc.Controller;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.attribute.FileAttribute;
import java.nio.file.attribute.PosixFilePermission;
import java.nio.file.attribute.PosixFilePermissions;
import java.util.Collections;
import java.util.EnumSet;
import java.util.concurrent.CompletionStage;
import java.util.function.Function;
import play.mvc.Http;
import play.mvc.Http.MultipartFormData.FilePart;
import play.mvc.Result;
import play.test.WithApplication;
import javax.inject.Inject;
import static java.nio.file.attribute.PosixFilePermission.OWNER_READ;
import static java.nio.file.attribute.PosixFilePermission.OWNER_WRITE;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.junit.Assert.assertThat;
import static play.mvc.Results.ok;
import static play.test.Helpers.contentAsString;
import static play.test.Helpers.fakeRequest;
import static javaguide.testhelpers.MockJavaActionHelper.*;
public class JavaFileUpload extends WithApplication {
static class SyncUpload extends Controller {
//#syncUpload
public Result upload() {
Http.MultipartFormData<File> body = request().body().asMultipartFormData();
Http.MultipartFormData.FilePart<File> picture = body.getFile("picture");
if (picture != null) {
String fileName = picture.getFilename();
String contentType = picture.getContentType();
File file = picture.getFile();
return ok("File uploaded");
} else {
flash("error", "Missing file");
return badRequest();
}
}
//#syncUpload
}
static class AsyncUpload extends Controller {
//#asyncUpload
public Result upload() {
File file = request().body().asRaw().asFile();
return ok("File uploaded");
}
//#asyncUpload
}
//#customfileparthandler
public static class MultipartFormDataWithFileBodyParser extends BodyParser.DelegatingMultipartFormDataBodyParser<File> {
@Inject
public MultipartFormDataWithFileBodyParser(Materializer materializer, play.api.http.HttpConfiguration config, HttpErrorHandler errorHandler) {
super(materializer, config.parser().maxDiskBuffer(), errorHandler);
}
/**
* Creates a file part handler that uses a custom accumulator.
*/
@Override
public Function<Multipart.FileInfo, Accumulator<ByteString, FilePart<File>>> createFilePartHandler() {
return (Multipart.FileInfo fileInfo) -> {
final String filename = fileInfo.fileName();
final String partname = fileInfo.partName();
final String contentType = fileInfo.contentType().getOrElse(null);
final File file = generateTempFile();
final Sink<ByteString, CompletionStage<IOResult>> sink = FileIO.toFile(file);
return Accumulator.fromSink(
sink.mapMaterializedValue(completionStage ->
completionStage.thenApplyAsync(results ->
new Http.MultipartFormData.FilePart<>(partname,
filename,
contentType,
file))
));
};
}
/**
* Generates a temp file directly without going through TemporaryFile.
*/
private File generateTempFile() {
try {
final EnumSet<PosixFilePermission> attrs = EnumSet.of(OWNER_READ, OWNER_WRITE);
final FileAttribute<?> attr = PosixFilePermissions.asFileAttribute(attrs);
final Path path = Files.createTempFile("multipartBody", "tempFile", attr);
return path.toFile();
} catch (IOException e) {
throw new IllegalStateException(e);
}
}
}
//#customfileparthandler
@Test
public void testCustomMultipart() throws IOException {
play.libs.Files.TemporaryFileCreator tfc = play.libs.Files.singletonTemporaryFileCreator();
Source source = FileIO.fromPath(Files.createTempFile("temp", "txt"));
Http.MultipartFormData.FilePart dp = new Http.MultipartFormData.FilePart<Source>("name", "filename", "text/plain", source);
assertThat(contentAsString(call(new javaguide.testhelpers.MockJavaAction(instanceOf(JavaHandlerComponents.class)) {
@BodyParser.Of(MultipartFormDataWithFileBodyParser.class)
public Result uploadCustomMultiPart() throws Exception {
final Http.MultipartFormData<File> formData = request().body().asMultipartFormData();
final Http.MultipartFormData.FilePart<File> filePart = formData.getFile("name");
final File file = filePart.getFile();
final long size = Files.size(file.toPath());
Files.deleteIfExists(file.toPath());
return ok("Got: file size = " + size + "");
}
}, fakeRequest("POST", "/").bodyMultipart(Collections.singletonList(dp), tfc, mat), mat)),
equalTo("Got: file size = 0"));
}
}
|
package org.drools.scorecards;
import java.io.StringWriter;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import junit.framework.Assert;
import org.dmg.pmml_4_1.Attribute;
import org.dmg.pmml_4_1.Characteristics;
import org.dmg.pmml_4_1.DataDictionary;
import org.dmg.pmml_4_1.Header;
import org.dmg.pmml_4_1.MiningSchema;
import org.dmg.pmml_4_1.Output;
import org.dmg.pmml_4_1.PMML;
import org.dmg.pmml_4_1.Scorecard;
import org.drools.scorecards.pmml.PMMLExtensionNames;
import org.drools.scorecards.pmml.ScorecardPMMLUtils;
import org.junit.Before;
import org.junit.Test;
import static junit.framework.Assert.*;
public class PMMLDocumentTest {
private static PMML pmmlDocument;
@Before
public void setUp() throws Exception {
ScorecardCompiler scorecardCompiler = new ScorecardCompiler();
scorecardCompiler.compileFromExcel(PMMLDocumentTest.class.getResourceAsStream("/scoremodel_c.xls"));
pmmlDocument = scorecardCompiler.getPMMLDocument();
}
@Test
public void testPMMLDocument() throws Exception {
Assert.assertNotNull(pmmlDocument);
// create a JAXBContext for the PMML class
JAXBContext ctx = JAXBContext.newInstance(PMML.class);
Marshaller marshaller = ctx.createMarshaller();
// the property JAXB_FORMATTED_OUTPUT specifies whether or not the
// marshalled XML data is formatted with linefeeds and indentation
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
// marshal the data in the Java content tree
StringWriter stringWriter = new StringWriter();
marshaller.marshal(pmmlDocument, stringWriter);
assertTrue(stringWriter.toString().length() > 0);
System.out.println(stringWriter.toString());
}
@Test
public void testHeader() throws Exception {
Header header = pmmlDocument.getHeader();
assertNotNull(header);
assertNotNull(ScorecardPMMLUtils.getExtensionValue(header.getExtensions(), PMMLExtensionNames.SCORECARD_PACKAGE));
assertNotNull(ScorecardPMMLUtils.getExtensionValue(header.getExtensions(), PMMLExtensionNames.SCORECARD_IMPORTS));
}
@Test
public void testDataDictionary() throws Exception {
DataDictionary dataDictionary = pmmlDocument.getDataDictionary();
assertNotNull(dataDictionary);
assertEquals(3, dataDictionary.getNumberOfFields().intValue());
assertEquals("age", dataDictionary.getDataFields().get(0).getName());
assertEquals("occupation",dataDictionary.getDataFields().get(1).getName());
assertEquals("residenceState", dataDictionary.getDataFields().get(2).getName());
}
@Test
public void testMiningSchema() throws Exception {
for (Object serializable : pmmlDocument.getAssociationModelsAndBaselineModelsAndClusteringModels()){
if (serializable instanceof Scorecard){
for (Object obj :((Scorecard)serializable) .getExtensionsAndCharacteristicsAndMiningSchemas()){
if (obj instanceof MiningSchema){
MiningSchema miningSchema = ((MiningSchema)obj);
assertEquals(3, miningSchema.getMiningFields().size());
assertEquals("age", miningSchema.getMiningFields().get(0).getName());
assertEquals("occupation",miningSchema.getMiningFields().get(1).getName());
assertEquals("residenceState", miningSchema.getMiningFields().get(2).getName());
return;
}
}
}
}
fail();
}
@Test
public void testCharacteristicsAndAttributes() throws Exception {
for (Object serializable : pmmlDocument.getAssociationModelsAndBaselineModelsAndClusteringModels()){
if (serializable instanceof Scorecard){
for (Object obj :((Scorecard)serializable) .getExtensionsAndCharacteristicsAndMiningSchemas()){
if (obj instanceof Characteristics){
Characteristics characteristics = (Characteristics)obj;
assertEquals(3, characteristics.getCharacteristics().size());
assertEquals("AgeScore", characteristics.getCharacteristics().get(0).getName());
assertEquals("$B$11", ScorecardPMMLUtils.getExtensionValue(characteristics.getCharacteristics().get(0).getExtensions(), "cellRef"));
assertEquals("OccupationScore",characteristics.getCharacteristics().get(1).getName());
assertEquals("$B$19", ScorecardPMMLUtils.getExtensionValue(characteristics.getCharacteristics().get(1).getExtensions(), "cellRef"));
assertEquals("ResidenceStateScore",characteristics.getCharacteristics().get(2).getName());
assertEquals("$B$25", ScorecardPMMLUtils.getExtensionValue(characteristics.getCharacteristics().get(2).getExtensions(), "cellRef"));
return;
}
}
}
}
fail();
}
@Test
public void testAgeScoreCharacteristic() throws Exception {
for (Object serializable : pmmlDocument.getAssociationModelsAndBaselineModelsAndClusteringModels()){
if (serializable instanceof Scorecard){
for (Object obj :((Scorecard)serializable) .getExtensionsAndCharacteristicsAndMiningSchemas()){
if (obj instanceof Characteristics){
Characteristics characteristics = (Characteristics)obj;
assertEquals(3, characteristics.getCharacteristics().size());
assertEquals("AgeScore", characteristics.getCharacteristics().get(0).getName());
assertEquals("$B$11", ScorecardPMMLUtils.getExtensionValue(characteristics.getCharacteristics().get(0).getExtensions(), "cellRef"));
assertNotNull(characteristics.getCharacteristics().get(0).getAttributes());
assertEquals(4, characteristics.getCharacteristics().get(0).getAttributes().size());
Attribute attribute = characteristics.getCharacteristics().get(0).getAttributes().get(0);
assertEquals("$C$13", ScorecardPMMLUtils.getExtensionValue(attribute.getExtensions(), "cellRef"));
assertNotNull(attribute.getSimplePredicate());
attribute = characteristics.getCharacteristics().get(0).getAttributes().get(1);
assertEquals("$C$14", ScorecardPMMLUtils.getExtensionValue(attribute.getExtensions(), "cellRef"));
assertNotNull(attribute.getCompoundPredicate());
attribute = characteristics.getCharacteristics().get(0).getAttributes().get(2);
assertEquals("$C$15", ScorecardPMMLUtils.getExtensionValue(attribute.getExtensions(), "cellRef"));
assertNotNull(attribute.getCompoundPredicate());
attribute = characteristics.getCharacteristics().get(0).getAttributes().get(3);
assertEquals("$C$16", ScorecardPMMLUtils.getExtensionValue(attribute.getExtensions(), "cellRef"));
assertNotNull(attribute.getSimplePredicate());
return;
}
}
}
}
fail();
}
@Test
public void testOccupationScoreCharacteristic() throws Exception {
for (Object serializable : pmmlDocument.getAssociationModelsAndBaselineModelsAndClusteringModels()){
if (serializable instanceof Scorecard){
for (Object obj :((Scorecard)serializable) .getExtensionsAndCharacteristicsAndMiningSchemas()){
if (obj instanceof Characteristics){
Characteristics characteristics = (Characteristics)obj;
assertEquals(3, characteristics.getCharacteristics().size());
assertNotNull(characteristics.getCharacteristics().get(1).getAttributes());
assertEquals(3, characteristics.getCharacteristics().get(1).getAttributes().size());
Attribute attribute = characteristics.getCharacteristics().get(1).getAttributes().get(0);
assertEquals("$C$21", ScorecardPMMLUtils.getExtensionValue(attribute.getExtensions(), "cellRef"));
assertNotNull(ScorecardPMMLUtils.getExtensionValue(attribute.getExtensions(), "description"));
assertEquals("skydiving is a risky occupation", ScorecardPMMLUtils.getExtensionValue(attribute.getExtensions(), "description"));
assertNotNull(attribute.getSimplePredicate());
attribute = characteristics.getCharacteristics().get(1).getAttributes().get(1);
assertEquals("$C$22", ScorecardPMMLUtils.getExtensionValue(attribute.getExtensions(), "cellRef"));
assertNotNull(attribute.getSimpleSetPredicate());
attribute = characteristics.getCharacteristics().get(1).getAttributes().get(2);
assertEquals("$C$23", ScorecardPMMLUtils.getExtensionValue(attribute.getExtensions(), "cellRef"));
assertNotNull(attribute.getSimplePredicate());
return;
}
}
}
}
fail();
}
@Test
public void testResidenceStateScoreCharacteristic() throws Exception {
for (Object serializable : pmmlDocument.getAssociationModelsAndBaselineModelsAndClusteringModels()){
if (serializable instanceof Scorecard){
for (Object obj :((Scorecard)serializable) .getExtensionsAndCharacteristicsAndMiningSchemas()){
if (obj instanceof Characteristics){
Characteristics characteristics = (Characteristics)obj;
assertEquals(3, characteristics.getCharacteristics().size());
assertNotNull(characteristics.getCharacteristics().get(2).getAttributes());
assertEquals(3, characteristics.getCharacteristics().get(2).getAttributes().size());
Attribute attribute = characteristics.getCharacteristics().get(2).getAttributes().get(0);
assertEquals("$C$27", ScorecardPMMLUtils.getExtensionValue(attribute.getExtensions(), "cellRef"));
assertNotNull(attribute.getSimplePredicate());
attribute = characteristics.getCharacteristics().get(2).getAttributes().get(1);
assertEquals("$C$28", ScorecardPMMLUtils.getExtensionValue(attribute.getExtensions(), "cellRef"));
assertNotNull(attribute.getSimplePredicate());
attribute = characteristics.getCharacteristics().get(2).getAttributes().get(2);
assertEquals("$C$29", ScorecardPMMLUtils.getExtensionValue(attribute.getExtensions(), "cellRef"));
assertNotNull(attribute.getSimplePredicate());
return;
}
}
}
}
fail();
}
@Test
public void testScorecardWithExtensions() throws Exception {
for (Object serializable : pmmlDocument.getAssociationModelsAndBaselineModelsAndClusteringModels()){
if (serializable instanceof Scorecard){
Scorecard scorecard = (Scorecard)serializable;
assertEquals("Sample Score",scorecard.getModelName());
assertNotNull(ScorecardPMMLUtils.getExtension(scorecard.getExtensionsAndCharacteristicsAndMiningSchemas(), PMMLExtensionNames.SCORECARD_OBJECT_CLASS));
assertNotNull(ScorecardPMMLUtils.getExtension(scorecard.getExtensionsAndCharacteristicsAndMiningSchemas(), PMMLExtensionNames.SCORECARD_BOUND_VAR_NAME));
return;
}
}
fail();
}
@Test
public void testOutput() throws Exception {
for (Object serializable : pmmlDocument.getAssociationModelsAndBaselineModelsAndClusteringModels()){
if (serializable instanceof Scorecard){
Scorecard scorecard = (Scorecard)serializable;
for (Object obj :scorecard.getExtensionsAndCharacteristicsAndMiningSchemas()){
if ( obj instanceof Output) {
Output output = (Output)obj;
assertEquals(1, output.getOutputFields().size());
assertNotNull(output.getOutputFields().get(0));
assertEquals("totalScore", output.getOutputFields().get(0).getName());
assertEquals("Final Score", output.getOutputFields().get(0).getDisplayName());
assertEquals("double", output.getOutputFields().get(0).getDataType().value());
assertEquals("predictedValue", output.getOutputFields().get(0).getFeature().value());
return;
}
}
}
}
fail();
}
}
|
package io.kubernetes.client.examples;
import io.kubernetes.client.apis.CoreV1Api;
import io.kubernetes.client.extended.controller.Controller;
import io.kubernetes.client.extended.controller.ControllerManager;
import io.kubernetes.client.extended.controller.LeaderElectingController;
import io.kubernetes.client.extended.controller.builder.ControllerBuilder;
import io.kubernetes.client.extended.controller.reconciler.Reconciler;
import io.kubernetes.client.extended.controller.reconciler.Request;
import io.kubernetes.client.extended.controller.reconciler.Result;
import io.kubernetes.client.extended.leaderelection.LeaderElectionConfig;
import io.kubernetes.client.extended.leaderelection.LeaderElector;
import io.kubernetes.client.extended.leaderelection.resourcelock.EndpointsLock;
import io.kubernetes.client.informer.SharedIndexInformer;
import io.kubernetes.client.informer.SharedInformerFactory;
import io.kubernetes.client.informer.cache.Lister;
import io.kubernetes.client.models.V1Node;
import io.kubernetes.client.models.V1NodeList;
import io.kubernetes.client.util.CallGeneratorParams;
import java.io.IOException;
import java.time.Duration;
import java.util.concurrent.TimeUnit;
public class ControllerExample {
public static void main(String[] args) throws IOException {
CoreV1Api coreV1Api = new CoreV1Api();
coreV1Api
.getApiClient()
.getHttpClient()
.setReadTimeout(0, TimeUnit.SECONDS); // infinite timeout
// instantiating an informer-factory, and there should be only one informer-factory globally.
SharedInformerFactory informerFactory = new SharedInformerFactory();
// registering node-informer into the informer-factory.
SharedIndexInformer<V1Node> nodeInformer =
informerFactory.sharedIndexInformerFor(
(CallGeneratorParams params) -> {
return coreV1Api.listNodeCall(
null,
null,
null,
null,
null,
params.resourceVersion,
params.timeoutSeconds,
params.watch,
null,
null);
},
V1Node.class,
V1NodeList.class);
informerFactory.startAllRegisteredInformers();
// nodeReconciler prints node information on events
NodePrintingReconciler nodeReconciler = new NodePrintingReconciler(nodeInformer);
// Use builder library to construct a default controller.
Controller controller =
ControllerBuilder.defaultBuilder(informerFactory)
.watch(
(workQueue) ->
ControllerBuilder.controllerWatchBuilder(V1Node.class, workQueue)
.withWorkQueueKeyFunc(
(V1Node node) ->
new Request(node.getMetadata().getName())) // optional, default to
.withOnAddFilter(
(V1Node createdNode) ->
createdNode
.getMetadata()
.getName()
.startsWith("docker-")) // optional, set onAdd filter
.withOnUpdateFilter(
(V1Node oldNode, V1Node newNode) ->
newNode
.getMetadata()
.getName()
.startsWith("docker-")) // optional, set onUpdate filter
.withOnDeleteFilter(
(V1Node deletedNode, Boolean stateUnknown) ->
deletedNode
.getMetadata()
.getName()
.startsWith("docker-")) // optional, set onDelete filter
.build())
.withReconciler(nodeReconciler) // required, set the actual reconciler
.withName("node-printing-controller") // optional, set name for controller
.withWorkerCount(4) // optional, set worker thread count
.withReadyFunc(
nodeInformer
::hasSynced) // optional, only starts controller when the cache has synced up
.build();
// Use builder library to manage one or multiple controllers.
ControllerManager controllerManager =
ControllerBuilder.controllerManagerBuilder(informerFactory)
.addController(controller)
.build();
LeaderElectingController leaderElectingController =
new LeaderElectingController(
new LeaderElector(
new LeaderElectionConfig(
new EndpointsLock("kube-system", "leader-election", "foo"),
Duration.ofMillis(10000),
Duration.ofMillis(8000),
Duration.ofMillis(5000))),
controllerManager);
leaderElectingController.run();
}
static class NodePrintingReconciler implements Reconciler {
private Lister<V1Node> nodeLister;
public NodePrintingReconciler(SharedIndexInformer<V1Node> nodeInformer) {
this.nodeLister = new Lister<>(nodeInformer.getIndexer());
}
@Override
public Result reconcile(Request request) {
V1Node node = this.nodeLister.get(request.getName());
System.out.println("triggered reconciling " + node.getMetadata().getName());
return new Result(false);
}
}
}
|
/*
* $Author$
* $Revision$
* $Id$
* $Date$
*/
package frege.runtime;
import java.lang.annotation.*;
/**
* <p>Annotations for the class files produced by the frege compiler.</p>
* <p>The compiler annotates the class that corresponds to a module
* with the annotations defined here.<br>
* This makes it possible to recreate a symbol table of an imported package
* up to the expressions for variable symbols. Used in the compiler for imports,
* in the documentation tool, and possibly other tools.</p>
*/
public class Meta {
/**
* <p>General information for a frege package.</p>
*/
@Retention(RetentionPolicy.RUNTIME)
public @interface FregePackage {
/** <p>Name of the source file.</p> */
String source() default "";
/** <p>Compile time.</p> */
long time() default 0;
/** <p>The documentation of the package.</p> */
String doc() default "";
/** <p>Operator table.</p> */
Operator[] ops() default {};
/** <p>Name of imported packages.</p> */
String[] imps() default {};
/** <p>Namespaces of imported packages.</p> */
String[] nmss() default {};
/** <p>Table of Tau types.</p> */
Tau[] taus() default {};
/** <p>Table of Rho types.</p> */
Rho[] rhos() default {};
/** <p>Table of Sigma types.</p> */
Sigma[] sigmas() default {};
/** <p>Table of type aliases.</p> */
SymA[] symas() default {};
/** <p>Table of type classes.</p> */
SymC[] symcs() default {};
/** <p>Table of instances.</p> */
SymI[] symis() default {};
/** <p>Table of data types.</p> */
SymT[] symts() default {};
/** <p>Table of symbolic links.</p> */
SymL[] symls() default {};
/** <p>Table of values and functions.</p> */
SymV[] symvs() default {};
/** <p>Table of expressions.</p> */
Expr[] exprs() default {};
/** <p>Table of kinds.</p> */
Kind[] kinds() default {};
}
/**
* <p>Information from the infix* definitions.</p>
*/
@Retention(RetentionPolicy.RUNTIME)
public @interface Operator { // infix 10 `==`
/** <p>Operator name.</p> */
public String name();
/** <p>How the operator associates (0=left, 1=right, 2=none).</p> */
public int kind(); // 0=Left, 1=Right, 2=None
/** <p>Precedence 1 to 16.</p> */
public int prec();
}
/**
* <p>The equivalent to QName.</p>
*/
@Retention(RetentionPolicy.RUNTIME)
public @interface QName {
int kind() default 1; // 0 = TName, 1 = VName, 2 = MName
String pack() default "frege.Prelude";
String base();
String member() default ""; // only set when kind=2
}
/**
* <p>The equivalent for a Tau.</p>
* <p>References to other Tau's appear as indexes into the Tau table. </p>
*/
// public enum TKind {TApp, TFun, TCon, TVar, TMeta};
@Retention(RetentionPolicy.RUNTIME)
public @interface Tau {
int kind() default 3; // TApp=0, TFun=1, TCon=2, TVar=3
QName[] tcon() default {}; // TCon
int suba() default 0; // TApp a b or TFun a b, kind for TCon and TVar
int subb() default 0;
String tvar() default ""; // TVar
}
/**
* <p>The equivalent for a Kind.</p
* <p>References to other Kinds appear as indexes into the Kind table. </p>
* @author ingo
*
*/
@Retention(RetentionPolicy.RUNTIME)
public @interface Kind {
int kind() default 2; // KType, KRef, KVar, KApp
int suba() default 0; // 1st arg of KApp
int subb() default 0; // 2nd arg of KApp
}
/**
* the equivalent to a Sigma
*/
@Retention(RetentionPolicy.RUNTIME)
public @interface Sigma {
String[] bound() default {};
int[] kinds() default {};
int rho();
}
/**
* the equivalent to a Rho
*/
@Retention(RetentionPolicy.RUNTIME)
public @interface Rho {
boolean rhofun() default true; // RhoTau or RhoFun
Context[] cont() default {};
int sigma() default 0; // index into Sigma table
int rhotau() default 0; // index into rhofun?Rho:Tau table
}
/**
* the equivalent to a Context
*/
@Retention(RetentionPolicy.RUNTIME)
public @interface Context {
QName clas(); // class name
int tau() default 0; // index in Tau table
}
/**
* equivalent of a type definition
*/
@Retention(RetentionPolicy.RUNTIME)
public @interface SymA {
int offset() default 0;
QName name();
int[] vars() default {}; // tau indexes
int typ(); // sigma index
String doc() default "";
boolean publik() default true; // will it be imported by default?
int kind() default 0; // kind index
}
/**
* equivalent for a SymV
*/
@Retention(RetentionPolicy.RUNTIME)
public @interface SymV {
int offset() default 0;
QName name();
int sig(); // sigma index
String nativ() default "";
boolean pur() default false;
String doc() default "";
boolean abst() default false; // whether abstract
String stri(); // strictness encoded as string
int depth(); // number of arguments, i.e. FuncN class used
int rkind(); // dstawr - -00 no w-function, may return lazy
// -01 no w-function, returns value
// -10 worker function, may return lazy
// -11 worker function, returns value
// 1-0 return value is lazy in all cases
// 0-0 return value is lazy in some cases
// without fear of stack overflow
int expr() default 0; // index into expression table if >0
boolean publik() default true; // will it be imported by default
int[] throwing() default {}; // index of taus this function throws
QName[] over() default {}; // names of members this one overloads
int op() default 0; // operator associativity and precedence (TokenID.ord)
}
/**
* equivalent for a SymL
*/
@Retention(RetentionPolicy.RUNTIME)
public @interface SymL {
int offset() default 0;
QName name();
QName alias();
String doc() default "";
boolean publik() default true; // will it be imported by default
}
/**
* encoding for a field
*/
@Retention(RetentionPolicy.RUNTIME)
public @interface Field {
int offset() default 0;
String name() default "";
String doc() default "";
boolean privat() default false; // private or public
boolean strict() default true; // strict or lazy
int sigma(); // sigma index
}
/**
* equivalent for a SymD
*/
@Retention(RetentionPolicy.RUNTIME)
public @interface SymD {
int offset() default 0;
QName name();
int cid(); // constructor id
int typ(); // sigma index
Field[] fields() default {}; // empty if no fields at all
String doc() default "";
// String stri(); // strictness encoded as string
boolean priv() default false; // constructor is private
boolean publik() default true; // will it be imported by default
int op() default 0; // operator
}
/*
* equivalent for a SymC
*/
@Retention(RetentionPolicy.RUNTIME)
public @interface SymC {
int offset() default 0;
QName name();
int tau(); // tau index
QName[] sups() default {}; // super classes
QName[] ins1() default {}; // instantiated types
QName[] ins2() default {}; // instances for instantiated types
SymL[] lnks(); // aliases in environment
SymV[] funs(); // functions in environment
String doc() default "";
boolean publik() default true; // will it be imported by default
}
/*
* equivalent for a SymI
*/
@Retention(RetentionPolicy.RUNTIME)
public @interface SymI {
int offset() default 0;
QName name();
QName clas();
int typ(); // sigma index
SymL[] lnks(); // aliases in environment
SymV[] funs(); // functions in environment
String doc() default "";
}
/*
* equivalent for a SymT
*/
// doc::Maybe String, name::QName, typ::Sigma, env::Symtab, nativ::Maybe String}
@Retention(RetentionPolicy.RUNTIME)
public @interface SymT {
int offset() default 0;
QName name();
int typ(); // sigma index
SymD[] cons(); // constructors
SymL[] lnks(); // aliases in environment
SymV[] funs(); // functions in environment
String nativ() default ""; // java type
String doc() default "";
boolean prod() default false; // whether this is a product type
boolean isEnum() default false; // whether this is a enum type
boolean pur() default false; // whether this is a pure (immutable) native type
boolean newt() default false; // whether this is a new type (1-tuple)
boolean publik() default true; // will it be imported by default
int kind() default 0; // index of kind
boolean mutable() default false; // indicates IO mutability
}
@Retention(RetentionPolicy.RUNTIME)
/*
* encoding of expressions, no let allowed.
*/
public @interface Expr {
/*
* expression kind
* 0 - Ann
* 1 - App
* 2 - Case
* 3 - Con
* 4 - Ifte
* 5 - Lam
* 6 - Lit
* 7 - local Vbl
* 8 - global Vbl
* 9 - Let
*/
int xkind() default 7; // local Vbl
QName[] name() default {}; // set for global Vbl, Con
int lkind() default 0; // Lit: ord LiteralKind
// Ann: sigma index
// Case: ord CKind
String varval() default ""; // local Vbl name or Literal value
int[] alts() default {}; // case alternatives or lambda
// first half are expression indexes for patterns
// second half are expression indexes for expressions
// For Let, the number of elements is a multiple of 3
// and each value bound by the let is a triple (v, s, x)
// where v is an index of an Expr that describes the local variable
// s is a sigma index or -1 if v was not annotated
// x is the index of an Expr for the expression defining v
int subx1() default 0; // index of 1st subexpression, set for Ann, App, If, Case and Let
int subx2() default 0; // index of 2nd subexpression, set for App, If
int subx3() default 0; // index of 3rd subexpression, set fot If
}
@Retention(RetentionPolicy.RUNTIME)
public @interface FunctionPointers {
/** qualified names of functions */
QName[] qnames() default {};
String[] jnames() default {};
}
}
|
package xal.extension.fxapplication;
import java.io.File;
import java.io.IOException;
import javafx.application.Application;
import java.net.URL;
import javafx.beans.property.SimpleStringProperty;
import java.util.List;
import java.util.Optional;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.event.Event;
import javafx.event.EventHandler;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.control.MenuBar;
import javafx.scene.Scene;
import javafx.scene.control.Alert;
import javafx.scene.control.Alert.AlertType;
import javafx.scene.control.ButtonBar.ButtonData;
import javafx.scene.control.ButtonType;
import javafx.scene.control.Menu;
import javafx.scene.control.MenuItem;
import javafx.scene.control.RadioMenuItem;
import javafx.scene.control.SeparatorMenuItem;
import javafx.scene.control.ToggleGroup;
import javafx.scene.layout.VBox;
import javafx.stage.Modality;
import javafx.stage.Stage;
import javafx.stage.FileChooser;
import xal.smf.Accelerator;
import xal.smf.AcceleratorSeq;
import xal.smf.AcceleratorSeqCombo;
import xal.smf.data.XMLDataManager;
/**
* The Application class handles defines the core of an application. It is often
* the first handler of application wide events and typically forwards those events
* to the custom application adaptor for further processing. Every application has
* exactly one instance of this class.
*
* For now the FxApplication does nothing (except inheriting all from Application)
*
* @author Yngve Levinsen <yngve.levinsen@esss.se>
*/
abstract public class FxApplication extends Application {
protected String MAIN_SCENE = "/fxml/Scene.fxml";
protected String CSS_STYLE = "/styles/Styles.css";
protected String STAGE_TITLE = "Demo Application";
protected XalFxDocument DOCUMENT;
// Set to false if this application doesn't save/load xml files
protected boolean HAS_DOCUMENTS = true;
// Set to false if this application doesn't need the machine sequences
protected boolean HAS_SEQUENCE = true;
protected MenuBar MENU_BAR;
/**
* Application constructor.
* @param adaptor The application adaptor used for customization.
*/
protected FxApplication( ) {
this( new URL[]{} );
}
/**
* Application constructor.
* @param urls An array of document URLs to open upon startup.
*/
protected FxApplication( final URL[] urls ) {
super();
}
// Call this before start() (so that you can add items to MENU_BAR etc after)
protected void initialize() {
Logger.getLogger(FxApplication.class.getName()).log(Level.INFO, "Loading default accelerator {0}", XMLDataManager.defaultPath());
DOCUMENT.accelerator.setAccelerator(XMLDataManager.loadDefaultAccelerator());
MENU_BAR = new MenuBar();
Menu fileMenu = new Menu("File");
if (HAS_DOCUMENTS) {
MenuItem newFileMenu = new MenuItem("New");
newFileMenu.setOnAction(new NewFileMenu(DOCUMENT));
final MenuItem saveFileMenu = new MenuItem("Save");
saveFileMenu.setOnAction(new SaveFileMenu(DOCUMENT, false));
final MenuItem saveAsFileMenu = new MenuItem("Save as..");
saveAsFileMenu.setOnAction(new SaveFileMenu(DOCUMENT, true));
final MenuItem loadFileMenu = new MenuItem("Load");
loadFileMenu.setOnAction(new LoadFileMenu(DOCUMENT));
fileMenu.getItems().addAll( newFileMenu, saveFileMenu, saveAsFileMenu, loadFileMenu);
}
final MenuItem exitMenu = new MenuItem("Exit");
exitMenu.setOnAction(new ExitMenu());
fileMenu.getItems().addAll( exitMenu);
final Menu editMenu = new Menu("Edit");
final Menu acceleratorMenu = new Menu("Accelerator");
final MenuItem loadDefaultAcceleratorMenu = new MenuItem("Load Default Accelerator");
loadDefaultAcceleratorMenu.setOnAction(new LoadDefaultAcceleratorMenu(DOCUMENT));
final MenuItem loadAcceleratorMenu = new MenuItem("Load Accelerator ...");
loadAcceleratorMenu.setOnAction(new LoadAcceleratorMenu(DOCUMENT));
acceleratorMenu.getItems().addAll(loadDefaultAcceleratorMenu,loadAcceleratorMenu);
final Menu sequenceMenu = new Menu("Sequence");
final ToggleGroup groupSequence = new ToggleGroup();
if(HAS_SEQUENCE && DOCUMENT.accelerator.getAccelerator()!=null){
buildSequenceMenu(DOCUMENT.accelerator.getAccelerator(),sequenceMenu,groupSequence);
acceleratorMenu.getItems().addAll(new SeparatorMenuItem(),sequenceMenu);
final MenuItem addCombo = new MenuItem("Add new Combo Sequence");
addCombo.setOnAction(new AddCombo(DOCUMENT,groupSequence));
sequenceMenu.getItems().add(addCombo);
}
final Menu eLogMenu = new Menu("eLog");
final MenuItem openLogMenu = new MenuItem("Open");
openLogMenu.setOnAction(new UrlMenu(DOCUMENT));
final MenuItem makePostMenu = new MenuItem("Post");
makePostMenu.setOnAction(new ELogMenu(DOCUMENT));
eLogMenu.getItems().addAll(openLogMenu,makePostMenu);
final Menu helpMenu = new Menu("Help");
final MenuItem aboutMenu = new MenuItem("About");
aboutMenu.setOnAction(new HelpMenu(DOCUMENT));
helpMenu.getItems().add(aboutMenu);
MENU_BAR.getMenus().addAll( fileMenu, editMenu, acceleratorMenu, eLogMenu, helpMenu);
DOCUMENT.accelerator.addChangeListener((ChangeListener) (ObservableValue o, Object oldVal, Object newVal) -> {
if(HAS_SEQUENCE && DOCUMENT.accelerator.getAccelerator()!=null){
int menu_num = sequenceMenu.getItems().size();
sequenceMenu.getItems().remove(0, menu_num - 1);
groupSequence.getToggles().clear();
buildSequenceMenu(DOCUMENT.accelerator.getAccelerator(),sequenceMenu,groupSequence);
Logger.getLogger(FxApplication.class.getName()).log(Level.INFO, "Rebuilding Sequence Menu.");
}
});
}
@Override
public void start(Stage stage) throws IOException {
VBox root = new VBox();
FXMLLoader loader = new FXMLLoader(getClass().getResource(MAIN_SCENE));
root.getChildren().add(MENU_BAR);
root.getChildren().add(loader.load());
Scene scene = new Scene(root);
scene.getStylesheets().add(CSS_STYLE);
stage.getProperties().put("hostServices", this.getHostServices());
stage.setTitle(STAGE_TITLE);
stage.setScene(scene);
//YIL It is probably very bad to set this here but I am a stupid person.
DOCUMENT.sourceString = new SimpleStringProperty(DOCUMENT.DEFAULT_FILENAME);
DOCUMENT.sourceString.addListener((observable, oldValue, newValue) -> stage.setTitle(STAGE_TITLE+": "+newValue));
stage.show();
}
public void buildSequenceMenu(Accelerator accelerator, Menu sequenceMenu, ToggleGroup groupSequence){
//Populate the Sequence Menu with the sequences of the machine
List<AcceleratorSeq> seqItem = accelerator.getSequences();
int k = 0;
for (AcceleratorSeq item : seqItem) { //AddSequences
RadioMenuItem addedItem = new RadioMenuItem(item.toString());
sequenceMenu.getItems().add(k,addedItem);
addedItem.setToggleGroup(groupSequence);
addedItem.setOnAction(new SelectSequenceMenu(DOCUMENT));
k++;
}
sequenceMenu.getItems().add(new SeparatorMenuItem());
List<AcceleratorSeqCombo> seqCombo = accelerator.getComboSequences();
k++;
for (AcceleratorSeqCombo item : seqCombo) { //AddCombos
RadioMenuItem addedItem = new RadioMenuItem(item.toString());
sequenceMenu.getItems().add(k,addedItem);
addedItem.setToggleGroup(groupSequence);
addedItem.setOnAction(new SelectSequenceMenu(DOCUMENT));
k++;
}
sequenceMenu.getItems().add(k,new SeparatorMenuItem());
}
}
abstract class FileMenuItem implements EventHandler {
protected XalFxDocument document;
public FileMenuItem(XalFxDocument document) {
this.document = document;
}
@Override
public void handle(Event t) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
}
class NewFileMenu extends FileMenuItem {
public NewFileMenu(XalFxDocument document) {
super(document);
}
@Override
public void handle(Event t) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
}
class SaveFileMenu extends FileMenuItem {
private final boolean saveAs;
public SaveFileMenu(XalFxDocument document, boolean saveAs) {
super(document);
this.saveAs = saveAs;
}
@Override
public void handle(Event t) {
if (saveAs || !document.sourceSetAndValid()) {
FileChooser fileChooser = new FileChooser();
fileChooser.setTitle("Save Application State");
fileChooser.setInitialFileName(document.DEFAULT_FILENAME);
//Set extension filter
FileChooser.ExtensionFilter extFilter = new FileChooser.ExtensionFilter(document.FILETYPE_DESCRIPTION+" ("+document.WILDCARD_FILE_EXTENSION+")", document.WILDCARD_FILE_EXTENSION);
fileChooser.getExtensionFilters().add(extFilter);
//Show save file dialog
File selectedFile = fileChooser.showSaveDialog(null);
if (selectedFile != null) {
document.setSource(selectedFile);
} else {
Logger.getLogger(SaveFileMenu.class.getName()).log(Level.WARNING, "Selected file is null {0}",selectedFile);
}
} else {
Logger.getLogger(SaveFileMenu.class.getName()).log(Level.FINER, "Using existing file path {0}", document.source);
}
if (document.sourceSetAndValid()) {
document.saveDocument();
Logger.getLogger(SaveFileMenu.class.getName()).log(Level.FINEST, "Document saved");
} else {
Logger.getLogger(SaveFileMenu.class.getName()).log(Level.SEVERE, "Could not get a good document path {0}", document.source);
}
//saveDocumentAs( final URL url )
}
}
class LoadFileMenu extends FileMenuItem {
public LoadFileMenu(XalFxDocument document) {
super(document);
}
@Override
public void handle(Event t) {
FileChooser fileChooser = new FileChooser();
fileChooser.setTitle("Load Application State");
//fileChooser.setInitialFileName(document.DEFAULT_FILENAME);
//Set extension filter
FileChooser.ExtensionFilter extFilter = new FileChooser.ExtensionFilter(document.FILETYPE_DESCRIPTION+" ("+document.WILDCARD_FILE_EXTENSION+")", document.WILDCARD_FILE_EXTENSION);
fileChooser.getExtensionFilters().add(extFilter);
//Show save file dialog
File selectedFile = fileChooser.showOpenDialog(null);
if (selectedFile==null)
Logger.getLogger(LoadFileMenu.class.getName()).log(Level.INFO, "No file selected for loading");
else {
if (selectedFile.exists() && selectedFile.canRead()) {
document.setSource(selectedFile);
document.loadDocument(document.source);
}
else
Logger.getLogger(LoadFileMenu.class.getName()).log(Level.SEVERE, "Could not open {0}", document.source);
}
}
}
class ExitMenu implements EventHandler {
@Override
public void handle(Event t) {
Logger.getLogger(ExitMenu.class.getName()).log(Level.INFO, "Exit button clicked");
System.exit(0);
}
}
class LoadDefaultAcceleratorMenu implements EventHandler {
private final XalFxDocument document;
public LoadDefaultAcceleratorMenu(XalFxDocument document) {
this.document = document;
}
@Override
public void handle(Event t) {
Logger.getLogger(LoadDefaultAcceleratorMenu.class.getName()).log(Level.INFO, "Loading default accelerator.");
document.accelerator.setAccelerator(XMLDataManager.loadDefaultAccelerator());
}
}
class LoadAcceleratorMenu implements EventHandler {
private final XalFxDocument document;
public LoadAcceleratorMenu(XalFxDocument DOCUMENT) {
this.document = DOCUMENT;
}
@Override
public void handle(Event t) {
FileChooser fileChooser = new FileChooser();
fileChooser.setTitle("Load Accelerator");
//Set extension filter
FileChooser.ExtensionFilter extFilter = new FileChooser.ExtensionFilter("XAL files (*.xal)", "*.xal");
fileChooser.getExtensionFilters().add(extFilter);
//Show save file dialog
File selectedFile = fileChooser.showOpenDialog(null);
if (selectedFile != null) {
Logger.getLogger(LoadAcceleratorMenu.class.getName()).log(Level.INFO, "Loading accelerator from file.");
document.accelerator.setAccelerator(XMLDataManager.acceleratorWithPath(selectedFile.getAbsolutePath()));
} else {
Alert alert = new Alert(AlertType.WARNING);
alert.setTitle("Load Accelerator Warning");
alert.setHeaderText("Empty or invalid file selected");
alert.setContentText("How to proceed?");
ButtonType buttonTypeLoad = new ButtonType("Load Default Accelerator");
ButtonType buttonTypeCancel = new ButtonType("Cancel", ButtonData.CANCEL_CLOSE);
alert.getButtonTypes().setAll(buttonTypeLoad, buttonTypeCancel);
Optional<ButtonType> result = alert.showAndWait();
if (result.get() == buttonTypeLoad){
Logger.getLogger(LoadAcceleratorMenu.class.getName()).log(Level.INFO, "Loading default accelerator.");
document.accelerator.setAccelerator(XMLDataManager.loadDefaultAccelerator());
} else {
Logger.getLogger(LoadAcceleratorMenu.class.getName()).log(Level.INFO, "No accelerator selected.");
document.accelerator.setAccelerator(null);
}
}
}
}
class SelectSequenceMenu implements EventHandler {
protected final XalFxDocument document;
/*
* CONTRUCTOR
*/
public SelectSequenceMenu(XalFxDocument DOCUMENT){
this.document = DOCUMENT;
}
@Override
public void handle(Event t) {
final RadioMenuItem getSeqName = (RadioMenuItem) t.getSource();
document.setSequence(getSeqName.getText());
Logger.getLogger(FxApplication.class.getName()).log(Level.INFO, "Sequence Selected: {0}", document.getSequence());
}
}
class AddCombo implements EventHandler {
protected final XalFxDocument document;
protected final ToggleGroup groupSequence;
/*
* CONTRUCTOR
*/
public AddCombo(XalFxDocument DOCUMENT,ToggleGroup groupSequence){
this.document = DOCUMENT;
this.groupSequence = groupSequence;
}
@Override
public void handle(Event t) {
Stage stage;
Parent root;
URL url = null;
String sceneFile = "/xal/extension/fxapplication/resources/CreateComboSequence.fxml";
try {
stage = new Stage();
url = getClass().getResource(sceneFile);
FXMLLoader loader = new FXMLLoader();
loader.setLocation(FxApplication.class.getResource(sceneFile));
root = loader.load();
stage.setScene(new Scene(root));
stage.setTitle("Create a Combo Sequence");
stage.initModality(Modality.APPLICATION_MODAL);
CreateComboSequenceController loginController = loader.getController();
loginController.setProperties(document.accelerator.getAccelerator());
loginController.loggedInProperty().addListener((ObservableValue<? extends Boolean> obs, Boolean wasLoggedIn, Boolean isNowLoggedIn) -> {
if (isNowLoggedIn) {
if (loginController.getComboName() != null) {
AcceleratorSeqCombo comboSequence = new AcceleratorSeqCombo(loginController.getComboName(), loginController.getNewComboSequence());
MenuItem addComboMenu = (MenuItem) t.getSource();
RadioMenuItem addedItem = new RadioMenuItem(loginController.getComboName());
addedItem.setOnAction(new SelectSequenceMenu(document));
addedItem.setToggleGroup(groupSequence);
groupSequence.selectToggle(addedItem);
document.setSequence(loginController.getComboName());
Logger.getLogger(AddCombo.class.getName()).log(Level.INFO, "Sequence Selected: {0}", document.getSequence());
int index = addComboMenu.getParentMenu().getItems().size() - 2;
addComboMenu.getParentMenu().getItems().add(index, addedItem);
}
stage.close();
}
});
stage.showAndWait();
} catch (IOException ex) {
System.out.println("Exception on FXMLLoader.load()");
System.out.println(" * url: " + url);
System.out.println(" * " + ex);
System.out.println("
}
}
}
class ELogMenu implements EventHandler {
protected XalFxDocument document;
public ELogMenu(XalFxDocument document){
this.document = document;
}
@Override
public void handle(Event t) {
document.eLogPost();
}
}
class HelpMenu implements EventHandler {
protected XalFxDocument document;
public HelpMenu(XalFxDocument document){
this.document = document;
}
@Override
public void handle(Event t) {
document.help();
}
}
class UrlMenu implements EventHandler {
protected XalFxDocument document;
public UrlMenu(XalFxDocument document){
this.document = document;
}
@Override
public void handle(Event t) {
document.openUrl(xal.extension.jelog.ElogServer.getElogURL());
}
}
|
package org.exist.indexing.lucene;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.Reader;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.util.CharArraySet;
import org.apache.lucene.util.Version;
import org.exist.collections.CollectionConfiguration;
import org.exist.util.DatabaseConfigurationException;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.NodeList;
public class AnalyzerConfig {
/*
Supported configurations
<analyzer class="org.apache.lucene.analysis.standard.StandardAnalyzer"/>
<analyzer id="ws" class="org.apache.lucene.analysis.WhitespaceAnalyzer"/>
<analyzer id="stdstops" class="org.apache.lucene.analysis.standard.StandardAnalyzer">
..<param name="stopwords" type="java.io.File" value="/tmp/stop.txt"/>
</analyzer>
<analyzer id="stdstops" class="org.apache.lucene.analysis.standard.StandardAnalyzer">
..<param name="stopwords" type="java.util.Set">
.<value>the</value>
.<value>this</value>
.<value>and</value>
.<value>that</value>
..</param>
</analyzer>
<analyzer id="sbstops" class="org.apache.lucene.analysis.snowball.SnowballAnalyzer">
..<param name="name" value="English"/>
..<param name="stopwords" type="java.util.Set">
.<value>the</value>
.<value>this</value>
.<value>and</value>
.<value>that</value>
..</param>
</analyzer>
*/
private static final Logger LOG = Logger.getLogger(AnalyzerConfig.class);
private static final String ID_ATTRIBUTE = "id";
private static final String NAME_ATTRIBUTE = "name";
private static final String TYPE_ATTRIBUTE = "type";
private static final String CLASS_ATTRIBUTE = "class";
private static final String PARAM_VALUE_ENTRY = "value";
private static final String PARAM_ELEMENT_NAME = "param";
private Map<String, Analyzer> analyzers = new TreeMap<String, Analyzer>();
private Analyzer defaultAnalyzer = null;
public Analyzer getAnalyzerById(String id) {
return analyzers.get(id);
}
public Analyzer getDefaultAnalyzer() {
return defaultAnalyzer;
}
/**
* Parse <analyzer/> element and register configured analyzer.
*
* @param config The analyzer element from .xconf file.
*
* @throws DatabaseConfigurationException Something unexpected happened.
*/
public void addAnalyzer(Element config) throws DatabaseConfigurationException {
// Configure lucene analuzer with configuration
final Analyzer analyzer = configureAnalyzer(config);
if (analyzer == null) {
return;
}
// Get (optional) id-attribute of analyzer
final String id = config.getAttribute(ID_ATTRIBUTE);
// If no ID is provided, register as default analyzer
// else register analyzer
if (StringUtils.isBlank(id)) {
setDefaultAnalyzer(analyzer);
} else {
analyzers.put(id, analyzer);
}
}
/**
* Set default the analyzer.
*
* @param analyzer Lucene analyzer
*/
public void setDefaultAnalyzer(Analyzer analyzer) {
defaultAnalyzer = analyzer;
}
/**
* Parse <analyzer/> element from xconf and initialize an analyzer with the
* parameters.
*
* @param config The analyzer element
* @return Initialized Analyzer object
*
* @throws DatabaseConfigurationException Something unexpected happened.
*/
protected static Analyzer configureAnalyzer(Element config) throws DatabaseConfigurationException {
// Get classname from attribute
final String className = config.getAttribute(CLASS_ATTRIBUTE);
Analyzer newAnalyzer=null;
if (StringUtils.isBlank(className)) {
// No classname is defined.
LOG.error("Missing class attribute or attribute is empty.");
// DW: throw exception?
} else {
// Classname is defined.
// Probe class
Class<?> clazz = null;
try {
clazz = Class.forName(className);
} catch (ClassNotFoundException e) {
LOG.error(String.format("Lucene index: analyzer class %s not found. (%s)", className, e.getMessage()));
return newAnalyzer;
}
// CHeck if class is an Analyzer
if (!Analyzer.class.isAssignableFrom(clazz)) {
LOG.error(String.format("Lucene index: analyzer class has to be a subclass of %s", Analyzer.class.getName()));
return newAnalyzer;
}
// Get list of parameters
List<KeyTypedValue> cParams;
try {
cParams = getAllConstructorParameters(config);
} catch (ParameterException pe) {
// Unable to parse parameters.
LOG.error(String.format("Unable to get parameters for %s: %s", className, pe.getMessage()), pe);
cParams = new ArrayList<KeyTypedValue>();
}
// Iterate over all parameters, convert data to two arrays
// that can be used in the reflection code
final Class<?> cParamClasses[] = new Class<?>[cParams.size()];
final Object cParamValues[] = new Object[cParams.size()];
for (int i = 0; i < cParams.size(); i++) {
KeyTypedValue ktv = cParams.get(i);
cParamClasses[i] = ktv.getValueClass();
cParamValues[i] = ktv.getValue();
}
// Create new analyzer
if (cParamClasses.length > 0 && cParamClasses[0] == Version.class) {
if (LOG.isDebugEnabled()) {
Version version = (Version) cParamValues[0];
LOG.debug(String.format("An explicit Version %s of lucene has been specified.", version.toString()));
}
// A lucene Version object has been provided, so it shall be used
newAnalyzer = createInstance(clazz, cParamClasses, cParamValues);
} else {
// Either no parameters have been provided or more than one parameter
// Extend arrays with (default) Version object info, add to front.
Class<?>[] vcParamClasses = addVersionToClasses(cParamClasses);
Object[] vcParamValues = addVersionValueToValues(cParamValues);
// Finally create Analyzer
newAnalyzer = createInstance(clazz, vcParamClasses, vcParamValues);
// Fallback scenario: a special (not standard type of) Analyzer has been specified without
// a 'Version' argument on purpose. For this (try) to create the Analyzer with
// the original parameters.
if (newAnalyzer == null) {
newAnalyzer = createInstance(clazz, cParamClasses, cParamValues);
}
}
}
if (newAnalyzer == null) {
LOG.error(String.format("Unable to create analyzer '%s'", className));
}
return newAnalyzer;
}
/**
* Create instance of the lucene analyzer with provided arguments
*
* @param clazz The analyzer class
* @param vcParamClasses The parameter classes
* @param vcParamValues The parameter values
* @return The lucene analyzer
*/
private static Analyzer createInstance(Class<?> clazz, Class<?>[] vcParamClasses, Object[] vcParamValues) {
String className = clazz.getName();
try {
final Constructor<?> cstr = clazz.getDeclaredConstructor(vcParamClasses);
cstr.setAccessible(true);
if(LOG.isDebugEnabled()){
LOG.debug(String.format("Using analyzer %s", className));
}
return (Analyzer) cstr.newInstance(vcParamValues);
} catch (IllegalArgumentException e) {
LOG.error(String.format("Exception while instantiating analyzer class %s: %s", className, e.getMessage()), e);
} catch (IllegalAccessException e) {
LOG.error(String.format("Exception while instantiating analyzer class %s: %s", className, e.getMessage()), e);
} catch (InstantiationException e) {
LOG.error(String.format("Exception while instantiating analyzer class %s: %s", className, e.getMessage()), e);
} catch (InvocationTargetException ite) {
LOG.error(String.format("Exception while instantiating analyzer class %s: %s", className, ite.getMessage()), ite);
} catch (NoSuchMethodException ex) {
LOG.error(String.format("Could not find matching analyzer class constructor%s: %s", className, ex.getMessage()), ex);
} catch (SecurityException ex) {
LOG.error(String.format("Exception while instantiating analyzer class %s: %s", className, ex.getMessage()), ex);
}
return null;
}
/**
* Extend list of values, add version-value to front
*/
private static Object[] addVersionValueToValues(final Object[] cParamValues) {
final Object vcParamValues[] = new Object[cParamValues.length + 1];
vcParamValues[0] = LuceneIndex.LUCENE_VERSION_IN_USE;
System.arraycopy(cParamValues, 0, vcParamValues, 1, cParamValues.length);
return vcParamValues;
}
/**
* Extend list of classes, add version-class to front
*/
private static Class<?>[] addVersionToClasses(final Class<?>[] cParamClasses) {
final Class<?> vcParamClasses[] = new Class<?>[cParamClasses.length + 1];
vcParamClasses[0] = Version.class;
System.arraycopy(cParamClasses, 0, vcParamClasses, 1, cParamClasses.length);
return vcParamClasses;
}
/**
* Retrieve parameter info from all <param/> elements.
*
* @param config The <analyzer/> element from the provided configuration
* @return List of triples key-value-valueType
* @throws org.exist.indexing.lucene.AnalyzerConfig.ParameterException
*/
private static List<KeyTypedValue> getAllConstructorParameters(Element config) throws ParameterException {
final List<KeyTypedValue> parameters = new ArrayList<KeyTypedValue>();
final NodeList params = config.getElementsByTagNameNS(CollectionConfiguration.NAMESPACE, PARAM_ELEMENT_NAME);
// iterate over all <param/> elements
for (int i = 0; i < params.getLength(); i++) {
parameters.add(getConstructorParameter((Element) params.item(i)));
}
return parameters;
}
/**
* Retrieve configuration information from one <param/> element. Type
* information is used to construct actual data containing objects.
*
* @param param Element that represents <param/>
* @return Triple key-value-value-type
* @throws org.exist.indexing.lucene.AnalyzerConfig.ParameterException
*/
private static KeyTypedValue getConstructorParameter(Element param) throws ParameterException {
// Get attributes
final NamedNodeMap attrs = param.getAttributes();
// Get name of parameter, NULL when no value is present
final String name;
if (attrs.getNamedItem(NAME_ATTRIBUTE) != null) {
name = attrs.getNamedItem(NAME_ATTRIBUTE).getNodeValue();
} else {
// DW: TODO need to check if the NULL value is safe to use.
name = null;
}
// Get value type information of parameter, NULL when not available
final String type;
if (attrs.getNamedItem(TYPE_ATTRIBUTE) != null) {
type = attrs.getNamedItem(TYPE_ATTRIBUTE).getNodeValue();
} else {
// Safe to use, NULL check done.
type = null;
}
// Get actual value from attribute, or NULL when not available.
final String value;
if (attrs.getNamedItem(PARAM_VALUE_ENTRY) != null) {
value = attrs.getNamedItem(PARAM_VALUE_ENTRY).getNodeValue();
} else {
// DW: TODO need to check if the NULL value is safe to use.
// This is dangerous, unless a Set is filled
value = null;
}
// Place holder return value
KeyTypedValue parameter = null;
if(StringUtils.isBlank(type)){
// No type is provided, assume string.
parameter = new KeyTypedValue(name, value);
} else if ("java.lang.reflect.Field".equals(type)) {
if (value == null) {
throw new ParameterException("The 'value' attribute must exist and must contain a full classname.");
}
// Use reflection
// - retrieve classname from the value field
// - retrieve fieldname from the value field
final String clazzName = value.substring(0, value.lastIndexOf("."));
final String fieldName = value.substring(value.lastIndexOf(".") + 1);
try {
// Retrieve value from Field
final Class fieldClazz = Class.forName(clazzName);
final Field field = fieldClazz.getField(fieldName);
field.setAccessible(true);
final Object fValue = field.get(fieldClazz.newInstance());
parameter = new KeyTypedValue(name, fValue);
} catch (NoSuchFieldException nsfe) {
throw new ParameterException(nsfe.getMessage(), nsfe);
} catch (ClassNotFoundException nsfe) {
throw new ParameterException(nsfe.getMessage(), nsfe);
} catch (InstantiationException nsfe) {
throw new ParameterException(nsfe.getMessage(), nsfe);
} catch (IllegalAccessException nsfe) {
throw new ParameterException(nsfe.getMessage(), nsfe);
}
} else if ("java.io.File".equals(type)) {
// This is actually decrecated now, "Reader" must be used
final File f = new File(value);
parameter = new KeyTypedValue(name, f, File.class);
} else if ("java.io.FileReader".equals(type) || "file".equals(type)) {
// DW: Experimental
File f = new File(value);
Reader fileReader = null;
try {
fileReader = new FileReader(f);
parameter = new KeyTypedValue(name, fileReader, Reader.class);
} catch (FileNotFoundException ex) {
LOG.error(String.format("File %s could not be found.", f.getAbsolutePath()), ex);
IOUtils.closeQuietly(fileReader);
}
} else if ("java.util.Set".equals(type)) {
// This is actually deprecated now, Lucene4 requires CharArraySet
final Set s = getConstructorParameterSetValues(param);
parameter = new KeyTypedValue(name, s, Set.class);
} else if ("org.apache.lucene.analysis.util.CharArraySet".equals(type)) {
// This is mandatory to use iso a normal Set since Lucene 4
final CharArraySet s = getConstructorParameterCharArraySetValues(param);
parameter = new KeyTypedValue(name, s, CharArraySet.class);
} else if ("java.lang.Integer".equals(type) || "int".equals(type)) {
try {
final Integer n = Integer.parseInt(value);
parameter = new KeyTypedValue(name, n);
} catch (NumberFormatException ex) {
LOG.error(String.format("Value %s could not be converted to an integer.", value));
}
} else if ("java.lang.Boolean".equals(type) || "boolean".equals(type)) {
// Straight forward
final boolean b = Boolean.parseBoolean(value);
parameter = new KeyTypedValue(name, b);
} else {
// FallBack type == null or did not match
try {
//if the type is an Enum then use valueOf()
final Class clazz = Class.forName(type);
if (clazz.isEnum()) {
parameter = new KeyTypedValue(name, Enum.valueOf(clazz, value), clazz);
} else {
//default, assume java.lang.String
parameter = new KeyTypedValue(name, value);
}
} catch (ClassNotFoundException cnfe) {
throw new ParameterException(String.format("Class for type: %s not found. %s", type, cnfe.getMessage()), cnfe);
}
}
return parameter;
}
/**
* Get parameter configuration data as standard Java (Hash)Set.
*
* @param param The parameter-configuration element.
* @return Set of parameter values
*/
private static Set<String> getConstructorParameterSetValues(Element param) {
final Set<String> set = new HashSet<String>();
final NodeList values = param.getElementsByTagNameNS(CollectionConfiguration.NAMESPACE, PARAM_VALUE_ENTRY);
for (int i = 0; i < values.getLength(); i++) {
final Element value = (Element) values.item(i);
//TODO getNodeValue() on org.exist.dom.ElementImpl should return null according to W3C spec!
if (value instanceof org.exist.dom.ElementImpl) {
set.add(value.getNodeValue());
} else {
set.add(value.getTextContent());
}
}
return set;
}
/**
* Get parameter configuration data as a Lucene CharArraySet.
*
* @param param The parameter-configuration element.
* @return Parameter data as Lucene CharArraySet
*/
private static CharArraySet getConstructorParameterCharArraySetValues(Element param) {
final Set<String> set = getConstructorParameterSetValues(param);
return CharArraySet.copy(LuceneIndex.LUCENE_VERSION_IN_USE, set);
}
/**
* CLass for containing the Triple : key (name), corresponding value and
* class type of value.
*/
private static class KeyTypedValue {
private final String key;
private final Object value;
private final Class<?> valueClass;
public KeyTypedValue(String key, Object value) {
this(key, value, value.getClass());
}
public KeyTypedValue(String key, Object value, Class<?> valueClass) {
this.key = key;
this.value = value;
this.valueClass = valueClass;
}
public String getKey() {
return key;
}
public Object getValue() {
return value;
}
public Class<?> getValueClass() {
return valueClass;
}
}
/**
* Exception class to for reporting problems with the parameters.
*/
private static class ParameterException extends Exception {
public ParameterException(String message) {
super(message);
}
public ParameterException(String message, Throwable cause) {
super(message, cause);
}
}
}
|
package edu.umd.cs.findbugs.ba;
import org.apache.bcel.Repository;
import org.apache.bcel.classfile.JavaClass;
/**
* @author pugh
*/
public class CheckReturnAnnotationDatabase extends AnnotationDatabase<CheckReturnValueAnnotation> {
private JavaClass throwableClass, threadClass;
public CheckReturnAnnotationDatabase() {
setAddClassOnly(true);
loadAuxiliaryAnnotations();
setAddClassOnly(false);
}
@Override
public void loadAuxiliaryAnnotations() {
if (IGNORE_BUILTIN_ANNOTATIONS) return;
boolean missingClassWarningsSuppressed = AnalysisContext.currentAnalysisContext().setMissingClassWarningsSuppressed(true);
addMethodAnnotation("java.util.Iterator","hasNext", "()Z", false, CheckReturnValueAnnotation.CHECK_RETURN_VALUE_LOW);
addMethodAnnotation("java.io.File","createNewFile", "()Z", false, CheckReturnValueAnnotation.CHECK_RETURN_VALUE_LOW);
addMethodAnnotation("java.util.Enumeration","hasMoreElements", "()Z", false, CheckReturnValueAnnotation.CHECK_RETURN_VALUE_MEDIUM);
addMethodAnnotation("java.security.MessageDigest","digest", "([B)[B", false, CheckReturnValueAnnotation.CHECK_RETURN_VALUE_MEDIUM);
addMethodAnnotation("java.util.concurrent.locks.ReadWriteLock","readLock", "()Ljava/util/concurrent/locks/Lock;", false, CheckReturnValueAnnotation.CHECK_RETURN_VALUE_HIGH);
addMethodAnnotation("java.util.concurrent.locks.ReadWriteLock","writeLock", "()Ljava/util/concurrent/locks/Lock;", false, CheckReturnValueAnnotation.CHECK_RETURN_VALUE_HIGH);
addMethodAnnotation("java.util.concurrent.locks.Condition", "await", "(JLjava/util/concurrent/TimeUnit;)Z", false, CheckReturnValueAnnotation.CHECK_RETURN_VALUE_MEDIUM);
addMethodAnnotation("java.util.concurrent.locks.Condition", "awaitUtil", "(Ljava/util/Date;)Z", false, CheckReturnValueAnnotation.CHECK_RETURN_VALUE_MEDIUM);
addMethodAnnotation("java.util.concurrent.locks.Condition", "awaitNanos", "(J)Z", false, CheckReturnValueAnnotation.CHECK_RETURN_VALUE_MEDIUM);
addMethodAnnotation("java.util.concurrent.Semaphore", "tryAcquire", "(JLjava/util/concurrent/TimeUnit;)Z", false, CheckReturnValueAnnotation.CHECK_RETURN_VALUE_HIGH);
addMethodAnnotation("java.util.concurrent.Semaphore", "tryAcquire", "()Z", false, CheckReturnValueAnnotation.CHECK_RETURN_VALUE_HIGH);
addMethodAnnotation("java.util.concurrent.locks.Lock", "tryLock", "(JLjava/util/concurrent/TimeUnit;)Z", false, CheckReturnValueAnnotation.CHECK_RETURN_VALUE_HIGH);
addMethodAnnotation("java.util.concurrent.locks.Lock", "newCondition","()Ljava/util/concurrent/locks/Condition;", false, CheckReturnValueAnnotation.CHECK_RETURN_VALUE_HIGH);
addMethodAnnotation("java.util.concurrent.locks.Lock", "tryLock", "()Z", false, CheckReturnValueAnnotation.CHECK_RETURN_VALUE_HIGH);
addMethodAnnotation("java.util.concurrent.BlockingQueue", "offer", "(Ljava/lang/Object;JLjava/util/concurrent/TimeUnit;)Z", false, CheckReturnValueAnnotation.CHECK_RETURN_VALUE_MEDIUM);
addMethodAnnotation("java.util.ConcurrentLinkedQueue", "offer", "(Ljava/lang/Object;)Z", false, CheckReturnValueAnnotation.CHECK_RETURN_VALUE_IGNORE);
addMethodAnnotation("java.util.DelayQueue", "offer", "(Ljava/lang/Object;)Z", false, CheckReturnValueAnnotation.CHECK_RETURN_VALUE_IGNORE);
addMethodAnnotation("java.util.LinkedBlockingQueue", "offer", "(Ljava/lang/Object;)Z", false, CheckReturnValueAnnotation.CHECK_RETURN_VALUE_LOW);
addMethodAnnotation("java.util.LinkedList", "offer", "(Ljava/lang/Object;)Z", false, CheckReturnValueAnnotation.CHECK_RETURN_VALUE_IGNORE);
addMethodAnnotation("java.util.Queue", "offer", "(Ljava/lang/Object;)Z", false, CheckReturnValueAnnotation.CHECK_RETURN_VALUE_LOW);
addMethodAnnotation("java.util.ArrayBlockingQueue", "offer", "(Ljava/lang/Object;)Z", false, CheckReturnValueAnnotation.CHECK_RETURN_VALUE_MEDIUM);
addMethodAnnotation("java.util.SynchronousQueue", "offer", "(Ljava/lang/Object;)Z", false, CheckReturnValueAnnotation.CHECK_RETURN_VALUE_MEDIUM);
addMethodAnnotation("java.util.PriorityQueue", "offer", "(Ljava/lang/Object;)Z", false, CheckReturnValueAnnotation.CHECK_RETURN_VALUE_IGNORE);
addMethodAnnotation("java.util.PriorityBlockingQueue", "offer", "(Ljava/lang/Object;)Z", false, CheckReturnValueAnnotation.CHECK_RETURN_VALUE_IGNORE);
addMethodAnnotation("java.util.concurrent.BlockingQueue", "poll", "(JLjava/util/concurrent/TimeUnit;)Ljava/lang/Object;", false, CheckReturnValueAnnotation.CHECK_RETURN_VALUE_MEDIUM);
addMethodAnnotation("java.util.Queue", "poll", "()Ljava/lang/Object;", false, CheckReturnValueAnnotation.CHECK_RETURN_VALUE_LOW);
addDefaultMethodAnnotation("java.lang.String", CheckReturnValueAnnotation.CHECK_RETURN_VALUE_HIGH);
addMethodAnnotation("java.lang.String", "getBytes", "(Ljava/lang/String;)[B", false, CheckReturnValueAnnotation.CHECK_RETURN_VALUE_IGNORE);
addMethodAnnotation("java.lang.String", "charAt", "(I)C", false, CheckReturnValueAnnotation.CHECK_RETURN_VALUE_LOW);
addMethodAnnotation("java.lang.String", "length", "()I", false, CheckReturnValueAnnotation.CHECK_RETURN_VALUE_LOW);
addMethodAnnotation("java.lang.String", "<init>", "([BLjava/lang/String;)V", false, CheckReturnValueAnnotation.CHECK_RETURN_VALUE_IGNORE);
addMethodAnnotation("java.lang.String", "<init>", "(Ljava/lang/String;)V", false, CheckReturnValueAnnotation.CHECK_RETURN_VALUE_LOW);
addMethodAnnotation("java.lang.String", "<init>", "()V", false, CheckReturnValueAnnotation.CHECK_RETURN_VALUE_LOW);
addDefaultMethodAnnotation("java.math.BigDecimal", CheckReturnValueAnnotation.CHECK_RETURN_VALUE_HIGH);
addMethodAnnotation("java.math.BigDecimal", "inflate", "()Ljava/math/BigDecimal;", false, CheckReturnValueAnnotation.CHECK_RETURN_VALUE_IGNORE);
addDefaultMethodAnnotation("java.math.BigInteger", CheckReturnValueAnnotation.CHECK_RETURN_VALUE_HIGH);
addMethodAnnotation("java.math.BigInteger", "addOne", "([IIII)I", true, CheckReturnValueAnnotation.CHECK_RETURN_VALUE_IGNORE);
addMethodAnnotation("java.math.BigInteger", "subN", "([I[II)I", true, CheckReturnValueAnnotation.CHECK_RETURN_VALUE_IGNORE);
addDefaultMethodAnnotation("java.sql.Connection", CheckReturnValueAnnotation.CHECK_RETURN_VALUE_MEDIUM);
addDefaultMethodAnnotation("java.net.InetAddress", CheckReturnValueAnnotation.CHECK_RETURN_VALUE_MEDIUM);
addMethodAnnotation("java.util.InetAddress", "getByName", "(Ljava/lang/String;)Ljava/util/InetAddress;", true, CheckReturnValueAnnotation.CHECK_RETURN_VALUE_IGNORE);
AnalysisContext.currentAnalysisContext().setMissingClassWarningsSuppressed(missingClassWarningsSuppressed);
try {
throwableClass = Repository.lookupClass("java.lang.Throwable");
} catch (ClassNotFoundException e) {
AnalysisContext.reportMissingClass(e);
}
try {
threadClass = Repository.lookupClass("java.lang.Thread");
} catch (ClassNotFoundException e) {
AnalysisContext.reportMissingClass(e);
}
}
@Override
public CheckReturnValueAnnotation getResolvedAnnotation(Object o, boolean getMinimal) {
if (!(o instanceof XMethod))
return null;
XMethod m = (XMethod) o;
if (m.getName().startsWith("access$")) return null;
else if (m.getName().equals("<init>")) {
try {
if (throwableClass != null && Repository.instanceOf(m.getClassName(), throwableClass))
return CheckReturnValueAnnotation.CHECK_RETURN_VALUE_VERY_HIGH;
} catch (ClassNotFoundException e) {
AnalysisContext.reportMissingClass(e);
}
if (m.getClassName().equals("java.lang.Thread"))
return CheckReturnValueAnnotation.CHECK_RETURN_VALUE_VERY_HIGH;
try {
if (threadClass != null && Repository.instanceOf(m.getClassName(), threadClass))
return CheckReturnValueAnnotation.CHECK_RETURN_VALUE_LOW;
} catch (ClassNotFoundException e) {
AnalysisContext.reportMissingClass(e);
}
} else if (m.getName().equals("equals") && m.getSignature().equals("(Ljava/lang/Object;)Z")
&& !m.isStatic())
return CheckReturnValueAnnotation.CHECK_RETURN_VALUE_MEDIUM;
else if (m.getSignature().endsWith(")Ljava/lang/String;")
&& (m.getClassName().equals("java.lang.StringBuffer") || m.getClassName().equals(
"java.lang.StringBuilder")))
return CheckReturnValueAnnotation.CHECK_RETURN_VALUE_MEDIUM;
return super.getResolvedAnnotation(o, getMinimal);
}
}
|
package edu.umd.cs.findbugs.detect;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Set;
import java.util.Map;
import edu.umd.cs.findbugs.*;
import edu.umd.cs.findbugs.ba.XFactory;
import edu.umd.cs.findbugs.ba.XField;
import org.apache.bcel.classfile.*;
import org.jaxen.function.StringLengthFunction;
public class HugeSharedStringConstants extends BytecodeScanningDetector {
private static final int SIZE_OF_HUGE_CONSTANT = 500;
String getStringKey(String s) {
return s.length() + ":" + s.hashCode();
}
HashMap<String, Set<String>> map = new HashMap<String, Set<String>>();
HashMap<String, XField> definition = new HashMap<String, XField>();
HashMap<String, Integer> stringSize = new HashMap<String, Integer>();
BugReporter bugReporter;
public HugeSharedStringConstants(BugReporter bugReporter) {
this.bugReporter = bugReporter;
}
@Override
public void visit(ConstantString s) {
String value = s.getBytes(getConstantPool());
if (value.length() < SIZE_OF_HUGE_CONSTANT)
return;
String key = getStringKey(value);
Set<String> set = map.get(key);
if (set == null) {
set = new HashSet<String>();
map.put(key, set);
}
set.add(getDottedClassName());
}
@Override
public void visit(ConstantValue s) {
if (!visitingField())
return;
int i = s.getConstantValueIndex();
Constant c = getConstantPool().getConstant(i);
if (c instanceof ConstantString) {
String value = ((ConstantString) c).getBytes(getConstantPool());
if (value.length() < SIZE_OF_HUGE_CONSTANT)
return;
String key = getStringKey(value);
definition.put(key, XFactory.createXField(this));
stringSize.put(key, value.length());
}
}
@Override
public void report() {
for (Map.Entry<String, Set<String>> e : map.entrySet()) {
Set<String> occursIn = e.getValue();
if (occursIn.size() == 1)
continue;
XField field = definition.get(e.getKey());
if (field == null) continue;
Integer length = stringSize.get(e.getKey());
int overhead = length * (occursIn.size()-1);
if (overhead < 3*SIZE_OF_HUGE_CONSTANT) continue;
String className = field.getClassName();
BugInstance bug = new BugInstance(this, "HSC_HUGE_SHARED_STRING_CONSTANT",
overhead > 20*SIZE_OF_HUGE_CONSTANT ? HIGH_PRIORITY :
( overhead > 8*SIPUSH ? NORMAL_PRIORITY : LOW_PRIORITY))
.addClass(className).addField(field).addInt(length);
for (String c : occursIn)
if (!c.equals(className))
bug.addClass(c);
bugReporter.reportBug(bug);
}
}
}
|
package org.opendaylight.protocol.framework;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.util.concurrent.DefaultPromise;
import io.netty.util.concurrent.Future;
import io.netty.util.concurrent.GlobalEventExecutor;
import io.netty.util.concurrent.Promise;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
public class ServerTest {
SimpleDispatcher clientDispatcher, dispatcher;
final SimpleSessionListener pce = new SimpleSessionListener();
SimpleSession session = null;
ChannelFuture server = null;
InetSocketAddress serverAddress;
@Before
public void setUp() {
final int port = 10000 + (int)(10000 * Math.random());
serverAddress = new InetSocketAddress("127.0.0.5", port);
}
@Test
public void testConnectionEstablished() throws Exception {
final Promise<Boolean> p = new DefaultPromise<>(GlobalEventExecutor.INSTANCE);
this.dispatcher = new SimpleDispatcher(new SessionNegotiatorFactory<SimpleMessage, SimpleSession, SimpleSessionListener>() {
@Override
public SessionNegotiator<SimpleSession> getSessionNegotiator(final SessionListenerFactory<SimpleSessionListener> factory,
final Channel channel, final Promise<SimpleSession> promise) {
p.setSuccess(true);
return new SimpleSessionNegotiator(promise, channel);
}
}, new ProtocolHandlerFactory<>(new MessageFactory()), new DefaultPromise<SimpleSession>(GlobalEventExecutor.INSTANCE));
this.server = this.dispatcher.createServer(this.serverAddress, new SessionListenerFactory<SimpleSessionListener>() {
@Override
public SimpleSessionListener getSessionListener() {
return new SimpleSessionListener();
}
});
this.server.get();
this.clientDispatcher = new SimpleDispatcher(new SessionNegotiatorFactory<SimpleMessage, SimpleSession, SimpleSessionListener>() {
@Override
public SessionNegotiator<SimpleSession> getSessionNegotiator(final SessionListenerFactory<SimpleSessionListener> factory,
final Channel channel, final Promise<SimpleSession> promise) {
return new SimpleSessionNegotiator(promise, channel);
}
}, new ProtocolHandlerFactory<>(new MessageFactory()), new DefaultPromise<SimpleSession>(GlobalEventExecutor.INSTANCE));
this.session = (SimpleSession) this.clientDispatcher.createClient(this.serverAddress,
new NeverReconnectStrategy(GlobalEventExecutor.INSTANCE, 5000), new SessionListenerFactory<SimpleSessionListener>() {
@Override
public SimpleSessionListener getSessionListener() {
return new SimpleSessionListener();
}
}).get(6, TimeUnit.SECONDS);
assertEquals(true, p.get(3, TimeUnit.SECONDS));
}
@Test
public void testConnectionFailed() throws IOException, InterruptedException, ExecutionException, TimeoutException {
final Promise<Boolean> p = new DefaultPromise<>(GlobalEventExecutor.INSTANCE);
this.dispatcher = new SimpleDispatcher(new SessionNegotiatorFactory<SimpleMessage, SimpleSession, SimpleSessionListener>() {
@Override
public SessionNegotiator<SimpleSession> getSessionNegotiator(final SessionListenerFactory<SimpleSessionListener> factory,
final Channel channel, final Promise<SimpleSession> promise) {
p.setSuccess(true);
return new SimpleSessionNegotiator(promise, channel);
}
}, new ProtocolHandlerFactory<>(new MessageFactory()), new DefaultPromise<SimpleSession>(GlobalEventExecutor.INSTANCE));
this.server = this.dispatcher.createServer(this.serverAddress, new SessionListenerFactory<SimpleSessionListener>() {
@Override
public SimpleSessionListener getSessionListener() {
return new SimpleSessionListener();
}
});
this.server.get();
this.clientDispatcher = new SimpleDispatcher(new SessionNegotiatorFactory<SimpleMessage, SimpleSession, SimpleSessionListener>() {
@Override
public SessionNegotiator<SimpleSession> getSessionNegotiator(final SessionListenerFactory<SimpleSessionListener> factory,
final Channel channel, final Promise<SimpleSession> promise) {
return new SimpleSessionNegotiator(promise, channel);
}
}, new ProtocolHandlerFactory<>(new MessageFactory()), new DefaultPromise<SimpleSession>(GlobalEventExecutor.INSTANCE));
this.session = (SimpleSession) this.clientDispatcher.createClient(this.serverAddress,
new NeverReconnectStrategy(GlobalEventExecutor.INSTANCE, 5000), new SessionListenerFactory<SimpleSessionListener>() {
@Override
public SimpleSessionListener getSessionListener() {
return new SimpleSessionListener();
}
}).get(6, TimeUnit.SECONDS);
final Future<?> session = this.clientDispatcher.createClient(this.serverAddress,
new NeverReconnectStrategy(GlobalEventExecutor.INSTANCE, 5000), new SessionListenerFactory<SimpleSessionListener>() {
@Override
public SimpleSessionListener getSessionListener() {
return new SimpleSessionListener();
}
});
assertFalse(session.isSuccess());
}
@After
public void tearDown() throws IOException {
this.server.channel().close();
this.dispatcher.close();
this.clientDispatcher.close();
try {
Thread.sleep(100);
} catch (final InterruptedException e) {
throw new RuntimeException(e);
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.