answer
stringlengths
17
10.2M
package com.komanov.offheap; import com.komanov.offheap.alloc.Allocator; import java.util.AbstractSet; import java.util.Iterator; import java.util.UUID; public class OffHeapBasedUuidSet extends AbstractSet<UUID> { private final long address; private final int size; OffHeapBasedUuidSet(long address, int size) { this.address = address; this.size = size; } @Override public boolean contains(Object o) { return contains((UUID) o); } public boolean contains(UUID value) { int found = binarySearch0(value); return found >= 0 && found < size; } private int binarySearch0(UUID key) { int low = 0; int high = size - 1; while (low <= high) { int mid = (low + high) >>> 1; long current = address + 16L * mid; long mostBits = Allocator.getLong(current); if (mostBits < key.getMostSignificantBits()) low = mid + 1; else if (mostBits > key.getMostSignificantBits()) high = mid - 1; else { long leastBits = Allocator.getLong(current + 8); if (leastBits < key.getLeastSignificantBits()) low = mid + 1; else if (leastBits > key.getLeastSignificantBits()) high = mid - 1; else return mid; // key found } } return -(low + 1); // key not found. } @Override public Iterator<UUID> iterator() { throw new IllegalStateException("not implemented"); } @Override public int size() { return this.size; } public void destroy() { Allocator.release(address); } }
package com.lpii.evma.controller; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.HashMap; import java.util.List; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.client.HttpClient; import org.apache.http.client.ResponseHandler; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpPost; import org.apache.http.conn.ClientConnectionManager; import org.apache.http.impl.client.BasicResponseHandler; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager; import org.apache.http.message.BasicNameValuePair; import org.apache.http.params.HttpParams; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import com.lpii.evma.EvmaApp; import com.lpii.evma.model.Event; import com.lpii.evma.model.User; import android.util.Log; public class UserController { HttpPost httppost; StringBuffer buffer; HttpClient httpclient; List<NameValuePair> nameValuePairs; private static String TAG = "UserController"; public boolean loginEvuser(String url,String us,String pw){ try{ httpclient = new DefaultHttpClient(); httppost = new HttpPost(url); // make sure the url is correct. //httppost.setHeader( "Content-Type", "application/json" ); nameValuePairs = new ArrayList<NameValuePair>(2); nameValuePairs.add(new BasicNameValuePair("username",us)); // $Edittext_value = $_POST['Edittext_value']; nameValuePairs.add(new BasicNameValuePair("password",pw)); httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); HttpResponse response = getThreadSafeClient().execute(httppost); System.out.println("ksx"); ResponseHandler<String> responseHandler = new BasicResponseHandler(); final String responsex = httpclient.execute(httppost, responseHandler); Log.d(TAG ," Response : "+response + " == <" +responsex); /* runOnUiThread(new Runnable() { public void run() { tv.setText("Response from PHP : " + response); dialog.dismiss(); } });*/ response.getEntity().consumeContent(); if(responsex.equalsIgnoreCase("false")){ EvmaApp.isError = true; return false; }else{ JSONArray jsonArr; JSONArray jsonArrx; JSONObject jsonObj; System.out.println("response> " + responsex); // JSONArray("[{\"full_name\":\"Med\",\"user_id\":\"1\"},{\"full_name\":\"Med AL\",\"user_id\":\"10\"}]"); jsonObj = new JSONObject(responsex.toString()); try{ HashMap<String, String> pariticpant = new HashMap<String, String>(); System.out.println(jsonObj); System.out.println(jsonObj); String user_id = jsonObj.get("user_id").toString(); String username = jsonObj.get("username").toString(); String password = jsonObj.get("password").toString(); String role = jsonObj.get("role").toString(); String full_name = jsonObj.get("full_name").toString(); String email = jsonObj.get("email").toString(); String d_created = jsonObj.get("d_created").toString(); String d_modified = jsonObj.get("d_modified").toString(); User m_Us = new User(user_id, username, password, role, full_name, email, d_created, d_modified); System.out.println(m_Us); EvmaApp.CurrentUser = m_Us; EvmaApp.isError = false; return true; } catch (JSONException e) { e.printStackTrace(); } //showAlert(); EvmaApp.isError = true; return false; } }catch(Exception e){ Log.d(TAG ,"Exception : " + e.getMessage() + e); } return false; } public void AddUser(User us,String Action){ // Create a new HttpClient and Post Header HttpClient httpclient = getThreadSafeClient(); HttpPost httppost = null; if (Action.equals("AddUser")) { httppost = new HttpPost(EvmaApp.AddUserUrl); }else{ httppost = new HttpPost(EvmaApp.EventEditUrl); } System.out.println(us.toString()); String DateEv = us.getD_created(); String DateEvmodified = us.getD_modified(); String str = "2014-06-09 10:23:56"; String[] _dateSplitter = DateEv.split(" "); String[] eventDAteTimeTab = str.split("-"); System.out.println(eventDAteTimeTab); String[] _time =_dateSplitter[1].split(":"); System.out.println(_time); //String[] eventDAteTimeTab = DateEv.split("x"); System.out.println(eventDAteTimeTab.toString() +" ;;"); String meridian = null; meridian = "am"; meridian = "pm"; try { List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1); nameValuePairs.add(new BasicNameValuePair("User_password",us.getPassword())); nameValuePairs.add(new BasicNameValuePair("User_username", us.getUsername()+ "")); nameValuePairs.add(new BasicNameValuePair("User_name_user", us.getFull_name()+ "")); nameValuePairs.add(new BasicNameValuePair("User_email", us.getEmail()+ "")); nameValuePairs.add(new BasicNameValuePair("User_role", us.getRole()+ "")); nameValuePairs.add(new BasicNameValuePair("User_modified_DateTime_month", eventDAteTimeTab[1])); nameValuePairs.add(new BasicNameValuePair("User_modified_DateTime_day", eventDAteTimeTab[0]+ "")); nameValuePairs.add(new BasicNameValuePair("User_modified_DateTime_year", eventDAteTimeTab[2]+ "")); nameValuePairs.add(new BasicNameValuePair("User_modified_DateTime_hour",_time[0])); nameValuePairs.add(new BasicNameValuePair("User_modified_DateTime_min", _time[1])); nameValuePairs.add(new BasicNameValuePair("User_modified_DateTime_meridian", meridian)); nameValuePairs.add(new BasicNameValuePair("User_created_DateTime_month", eventDAteTimeTab[1])); nameValuePairs.add(new BasicNameValuePair("User_created_DateTime_day", eventDAteTimeTab[0]+ "")); nameValuePairs.add(new BasicNameValuePair("User_created_DateTime_year", eventDAteTimeTab[2]+ "")); nameValuePairs.add(new BasicNameValuePair("User_created_DateTime_hour",_time[0])); nameValuePairs.add(new BasicNameValuePair("User_created_DateTime_min", _time[1])); nameValuePairs.add(new BasicNameValuePair("User_created_DateTime_meridian", meridian)); httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); HttpResponse response = httpclient.execute(httppost); BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); String line = ""; while ((line = rd.readLine()) != null) { System.out.println(line); if (!line.equals("error") && line.length() < 4) { if (Action.equals("AddUser")) { EvmaApp.CurrentUsernameID = Integer.valueOf(line); EvmaApp.CurrentUsername = us.getUsername(); } EvmaApp.isError = false; }else{ EvmaApp.isError = true; } } } catch (IOException e) { e.printStackTrace(); } } private HttpClient getThreadSafeClient() { // TODO Auto-generated method stub DefaultHttpClient client = new DefaultHttpClient(); ClientConnectionManager mgr = client.getConnectionManager(); HttpParams params = client.getParams(); client = new DefaultHttpClient(new ThreadSafeClientConnManager(params,mgr.getSchemeRegistry()), params); return client; } }
package com.redpois0n.gitj.ui; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; import javax.swing.GroupLayout; import javax.swing.GroupLayout.Alignment; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTextPane; import javax.swing.LayoutStyle.ComponentPlacement; import com.redpois0n.git.CommitOption; import com.redpois0n.gitj.Main; import com.redpois0n.gitj.utils.DialogUtils; @SuppressWarnings("serial") public class CommitButtonPanel extends JPanel { private CommitPanel parent; private JLabel lblAuthor; private JComboBox<String> comboBox; private JTextPane textPane; private JButton btnCommit; public CommitButtonPanel(CommitPanel p) { this.parent = p; try { lblAuthor = new JLabel(parent.getRepository().getAuthorString()); } catch (Exception e) { e.printStackTrace(); lblAuthor = new JLabel("Failed to load author: " + e.getClass().getSimpleName() + ", " + e.getMessage()); Main.displayError(e); } comboBox = new JComboBox<String>(); for (CommitOption o : CommitOption.values()) { comboBox.addItem(o.getTextual() + " - " + o.getDescription()); } comboBox.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent event) { String selected = comboBox.getSelectedItem().toString(); if (selected.startsWith(CommitOption.AMEND.getTextual())) { if (DialogUtils.confirm("Do you want to replace the commit message with the message from your latest commit?", "Amend Commit")) { try { textPane.setText(parent.getRepository().getCommits().get(0).getComment()); btnCommit.setEnabled(true); } catch (Exception e) { e.printStackTrace(); Main.displayError(e); } } } } }); JButton btnCancel = new JButton("Cancel"); btnCancel.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { cancel(); } }); btnCommit = new JButton("Commit"); btnCommit.setEnabled(false); btnCommit.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { commit(); } }); JScrollPane scrollPane = new JScrollPane(); GroupLayout groupLayout = new GroupLayout(this); groupLayout.setHorizontalGroup( groupLayout.createParallelGroup(Alignment.TRAILING) .addGroup(groupLayout.createSequentialGroup() .addContainerGap() .addGroup(groupLayout.createParallelGroup(Alignment.LEADING) .addComponent(scrollPane, GroupLayout.DEFAULT_SIZE, 480, Short.MAX_VALUE) .addGroup(groupLayout.createSequentialGroup() .addComponent(lblAuthor) .addPreferredGap(ComponentPlacement.RELATED, 205, Short.MAX_VALUE) .addComponent(comboBox, GroupLayout.PREFERRED_SIZE, 220, GroupLayout.PREFERRED_SIZE)) .addGroup(groupLayout.createSequentialGroup() .addComponent(btnCommit) .addPreferredGap(ComponentPlacement.RELATED) .addComponent(btnCancel))) .addContainerGap()) ); groupLayout.setVerticalGroup( groupLayout.createParallelGroup(Alignment.LEADING) .addGroup(groupLayout.createSequentialGroup() .addContainerGap() .addGroup(groupLayout.createParallelGroup(Alignment.BASELINE) .addComponent(lblAuthor) .addComponent(comboBox, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)) .addPreferredGap(ComponentPlacement.RELATED) .addComponent(scrollPane, GroupLayout.DEFAULT_SIZE, 73, Short.MAX_VALUE) .addPreferredGap(ComponentPlacement.RELATED) .addGroup(groupLayout.createParallelGroup(Alignment.BASELINE) .addComponent(btnCancel) .addComponent(btnCommit)) .addContainerGap()) ); textPane = new JTextPane(); textPane.addKeyListener(new KeyAdapter() { @Override public void keyTyped(KeyEvent arg0) { update(); } }); scrollPane.setViewportView(textPane); setLayout(groupLayout); textPane.requestFocusInWindow(); } public void commit() { String item = comboBox.getSelectedItem().toString(); CommitOption mode = null; for (CommitOption o : CommitOption.values()) { if (o.getTextual().equals(item.split(" - ")[0])) { mode = o; break; } } try { parent.getRepository().commit(textPane.getText().trim(), mode); parent.cancel(); } catch (Exception e) { e.printStackTrace(); Main.displayError(e); } } public void cancel() { parent.cancel(); } public void update() { btnCommit.setEnabled(textPane.getText().trim().length() > 0); } }
package com.xnx3.j2ee.controller; import java.io.File; import java.io.IOException; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.annotation.Resource; import javax.servlet.ServletContext; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.io.FileUtils; import org.apache.shiro.authz.annotation.RequiresPermissions; import org.apache.shiro.crypto.hash.Md5Hash; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.multipart.MultipartFile; import com.xnx3.j2ee.Global; import com.xnx3.j2ee.entity.User; import com.xnx3.j2ee.service.LogService; import com.xnx3.j2ee.service.MessageService; import com.xnx3.j2ee.service.UserService; import com.xnx3.j2ee.vo.BaseVO; import com.xnx3.net.MailUtil; /** * User * @author */ @Controller @RequestMapping("/user") public class UserController extends BaseController { @Resource private MessageService messageService; @Resource private UserService userService; @Resource private LogService logService; /** * * @return View */ @RequiresPermissions("userInfo") @RequestMapping("/info") public String userInfo(){ return "user/info"; } /** * * @param file {@link MultipartFile} * @param request {@link HttpServletRequest} * @param response {@link HttpServletResponse} * @throws IOException * @return View */ @RequiresPermissions("userUploadHead") @RequestMapping("/uploadHead") public String uploadHead(@RequestParam("head") MultipartFile file, HttpServletRequest request , HttpServletResponse response,Model model) throws IOException{ if(!file.isEmpty()){ ServletContext sc = request.getSession().getServletContext(); String dir=sc.getRealPath("/upload/userHead"); String fileSuffix=com.xnx3.Lang.subString(file.getOriginalFilename(), ".", null, 3); String fileName=getUser().getId()+"."+fileSuffix; if(fileSuffix.equals("png")||fileSuffix.equals("jpg")){ FileUtils.writeByteArrayToFile(new File(dir,fileName), file.getBytes()); User user =userService.findById(getUser().getId()); user.setHead(fileName); userService.save(user); setUserForSession(user); logService.insert("USER_UPDATEHEAD"); return success(model, "", "user/info.do"); }else{ return error(model, ""+fileSuffix+"pngjpg"); } }else{ return error(model, ""); } } /** * ,nickname * @param user {@link User} * @param model {@link Model} * @return View */ @RequiresPermissions("userUpdateNickName") @RequestMapping("updateNickName") public String updateNickName(HttpServletRequest request,Model model){ BaseVO baseVO = userService.updateNickName(request); if(baseVO.getResult() == BaseVO.FAILURE){ return error(model, baseVO.getInfo()); }else{ return success(model, "", "user/info.do"); } } /** * * @param oldPassword * @param newPassword * @param model {@link Model} * @return {@link BaseVO} */ @RequiresPermissions("userUpdatePassword") @RequestMapping("updatePassword") public BaseVO updatePassword(String oldPassword,String newPassword,Model model){ BaseVO baseVO = new BaseVO(); if(oldPassword==null||newPassword==null){ baseVO.setResult(BaseVO.FAILURE); baseVO.setInfo(""); }else{ User uu=userService.findById(getUser().getId()); if(oldPassword.equals(uu.getPassword())){ String md5Password = new Md5Hash(newPassword, uu.getSalt(),Global.USER_PASSWORD_SALT_NUMBER).toString(); uu.setPassword(md5Password); userService.save(uu); logService.insert("USER_UPDATEPASSWORD"); }else{ baseVO.setResult(BaseVO.FAILURE); baseVO.setInfo(""); } } return baseVO; } /** * * @return View */ @RequiresPermissions("userInvite") @RequestMapping("invite") public String invite(){ return "user/invite"; } /** * * @param email * @param text * @param model {@link Model} */ @RequiresPermissions("userInviteEmail") @RequestMapping("inviteEmail") public String inviteEmail( @RequestParam(value = "email", required = true) String email, @RequestParam(value = "text", required = true) String text, Model model){ Pattern pattern = Pattern.compile("^([a-zA-Z0-9_\\-\\.]+)@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.)|(([a-zA-Z0-9\\-]+\\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\\]?)$"); Matcher matcher = pattern.matcher(email); if(matcher.matches()){ MailUtil.sendMail(email, "", ""); logService.insert("USER_EMAIL_INVITE", email); return success(model, "", "user/info.do"); }else{ return error(model, ""); } } /** * * @param model {@link Model} * @return View */ @RequiresPermissions("userLogout") @RequestMapping("logout") public String logout(Model model){ userService.logout(); return success(model, "", "login.do"); } }
package edu.cmu.cs.glacier; import org.checkerframework.common.basetype.BaseTypeChecker; import org.checkerframework.common.basetype.BaseTypeValidator; import org.checkerframework.common.basetype.BaseTypeVisitor; import org.checkerframework.framework.source.Result; import org.checkerframework.framework.type.AnnotatedTypeFactory; import org.checkerframework.framework.type.AnnotatedTypeMirror; import org.checkerframework.javacutil.TypesUtils; import com.sun.source.tree.Tree; import edu.cmu.cs.glacier.qual.Immutable; public class GlacierTypeValidator extends BaseTypeValidator { public GlacierTypeValidator(BaseTypeChecker checker, BaseTypeVisitor<?> visitor, AnnotatedTypeFactory atypeFactory) { super(checker, visitor, atypeFactory); } /** * @return true if the effective annotations on the upperBound are above those on the lowerBound */ @Override public boolean areBoundsValid(final AnnotatedTypeMirror upperBound, final AnnotatedTypeMirror lowerBound) { if (TypesUtils.isObject(upperBound.getUnderlyingType()) && !upperBound.hasAnnotation(Immutable.class)) { // If the upper bound is Object, it'll default to Mutable, in which case an Immutable lower bound is acceptable. return true; } return super.areBoundsValid(upperBound, lowerBound); } protected void reportValidityResult( final /*@CompilerMessageKey*/ String errorType, final AnnotatedTypeMirror type, final Tree p) { checker.report(Result.failure(errorType, type.getAnnotations(), type.getUnderlyingType().toString()), p); isValid = false; } }
package edu.wustl.xipHost.worklist; import java.io.File; import java.io.InputStream; import java.net.MalformedURLException; import java.net.URL; import java.util.List; import javax.jws.WebService; import org.apache.log4j.Logger; import edu.wustl.xipHost.application.Application; import edu.wustl.xipHost.application.ApplicationManager; import edu.wustl.xipHost.application.ApplicationManagerFactory; /** * @author Jaroslaw Krych * */ @WebService( serviceName = "Worklist", portName="WorklistPort", targetNamespace = "http://edu.wustl.xipHost.worklist/", endpointInterface = "edu.wustl.xipHost.worklist.Worklist") public class WorklistImpl implements Worklist { final static Logger logger = Logger.getLogger(WorklistImpl.class); ApplicationManager appMgr = ApplicationManagerFactory.getInstance(); @Override public boolean addWorklistEntry(final WorklistEntry entry) { final String studyInstanceUID = entry.getStudyInstanceUID(); if(studyInstanceUID == null || studyInstanceUID.isEmpty()){ logger.warn("Worklist recieved StudyInstanceUID: " + studyInstanceUID); return false; } Runnable runner = new Runnable() { @Override public void run() { Application app = entry.getApplication(); if(logger.isDebugEnabled()){ logger.debug("Worklist recieved StudyInstanceUID: " + studyInstanceUID); if(app != null){ logger.debug("Worklist recieved application: "); logger.debug("ID: " + app.getId()); logger.debug("Name: " + app.getName()); logger.debug("Type:" + app.getType()); logger.debug("Requires GUI: " + app.isRequiresGUI()); logger.debug("Iteration target: " + app.getIterationTarget().toString()); logger.debug("Allowable concurrent instances: " + app.getConcurrentInstances()); logger.debug("WG-23 data model type: " + app.getWg23DataModelType()); } else { logger.debug("Worklist recieved application: " + app); } } if(app != null && appMgr.hasApplication(app.getId()) == false){ appMgr.addApplication(app); } InputStream inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream("xipConfig.xml"); appMgr.loadHostConfigParameters(inputStream); File tmpDir = appMgr.getTmpDir(); File outDir = appMgr.getOutputDir(); logger.debug("Application tmp dir: " + tmpDir.getAbsolutePath()); app.setApplicationTmpDir(tmpDir); app.setApplicationOutputDir(outDir); URL hostServiceURL = null; try { hostServiceURL = new URL("http://localhost:8080/xiphostservice/host"); } catch (MalformedURLException e) { logger.error(e, e); } URL appServiceURL = appMgr.generateNewApplicationServiceURL(); app.launch(hostServiceURL, appServiceURL); app.setWorklistEntry(entry); } }; Thread t = new Thread(runner); t.start(); return true; } @Override public boolean deleteWorkListEntry(WorklistEntry entry) { // TODO Auto-generated method stub return false; } @Override public int getNumberOfWorklistEntries() { return 1; } @Override public List<WorklistEntry> getWorklistEntries() { // TODO Auto-generated method stub return null; } @Override public WorklistEntry getWorklistEntry(int i) { // TODO Auto-generated method stub return null; } @Override public boolean modifyWorklistEntry(WorklistEntry entry) { // TODO Auto-generated method stub return false; } }
package foam.nanos.bench.benchmarks; import foam.core.X; import foam.nanos.bench.Benchmark; import foam.nanos.bench.BenchmarkRunner; import foam.nanos.bench.BenchmarkRunner.Builder; import foam.nanos.pm.PM; import java.util.Map; public class PMBenchmark implements Benchmark { @Override public void setup(X x) { } @Override public void teardown(X x, Map stats) { } @Override public void execute(X x) { PM pm = new PM(Object.class,"def"); pm.log(x); } }
package org.voltdb.types; import java.text.SimpleDateFormat; import java.util.Date; import org.json_voltpatches.JSONString; import org.voltdb.common.Constants; /** * Represent a microsecond-accurate VoltDB timestamp type. */ public class TimestampType implements JSONString, Comparable<TimestampType> { /** * Create a TimestampType from microseconds from epoch. * @param timestamp microseconds since epoch. */ public TimestampType(long timestamp) { m_usecs = (short) (timestamp % 1000); long millis = (timestamp - m_usecs) / 1000; m_date = new Date(millis); } /** * Create a TimestampType from a Java Date class. * Microseconds will be rounded to zero. * @param date Java Date instance. */ public TimestampType(Date date) { m_usecs = 0; m_date = (Date) date.clone(); } private static long microsFromJDBCformat(String param){ java.sql.Timestamp sqlTS; if (param.length() == 10) { sqlTS = java.sql.Timestamp.valueOf(param + " 00:00:00.000"); } else { sqlTS = java.sql.Timestamp.valueOf(param); } final long timeInMillis = sqlTS.getTime(); final long fractionalSecondsInNanos = sqlTS.getNanos(); // Fractional microseconds would get truncated so flag them as an error. if ((fractionalSecondsInNanos % 1000) != 0) { throw new IllegalArgumentException("Can't convert from String to TimestampType with fractional microseconds"); } // Milliseconds would be doubly counted as millions of nanos if they weren't truncated out via %. return (timeInMillis * 1000) + ((fractionalSecondsInNanos % 1000000)/1000); } public static long millisFromJDBCformat(String param) { java.sql.Timestamp sqlTS = java.sql.Timestamp.valueOf(param); final long fractionalSecondsInNanos = sqlTS.getNanos(); // Fractional milliseconds would get truncated so flag them as an error. if ((fractionalSecondsInNanos % 1000000) != 0) { throw new IllegalArgumentException("Can't convert from String to Date with fractional milliseconds"); } return sqlTS.getTime(); } /** * Construct from a timestamp string in a complete date or time format. * This is typically used for reading CSV data or data output * from {@link java.sql.Timestamp}'s string format. * * @param param A string in one of these formats: * "YYYY-MM-DD", "YYYY-MM-DD HH:MM:SS", * OR "YYYY-MM-DD HH:MM:SS.sss" with sss * allowed to be from 0 up to 6 significant digits. */ public TimestampType(String param) { this(microsFromJDBCformat(param)); } /** * Create a TimestampType instance for the current time. */ public TimestampType() { m_usecs = 0; m_date = new Date(); } /** * Read the microsecond in time stored by this timestamp. * @return microseconds */ public long getTime() { long millis = m_date.getTime(); return millis * 1000 + m_usecs; } /** * Get the microsecond portion of this timestamp * @return Microsecond portion of timestamp as a short */ public short getUSec() { return m_usecs; } /** * Equality. * @return true if equal. */ @Override public boolean equals(Object o) { if (!(o instanceof TimestampType)) return false; TimestampType ts = (TimestampType)o; if (!ts.m_date.equals(this.m_date)) return false; if (!(ts.m_usecs == this.m_usecs)) return false; return true; } /** * toString for debugging and printing VoltTables */ @Override public String toString() { SimpleDateFormat sdf = new SimpleDateFormat(Constants.ODBC_DATE_FORMAT_STRING); Date dateToMillis = m_date; short usecs = m_usecs; if (usecs < 0) { // Negative usecs can occur for dates before 1970. // To be expressed as positive decimals, they must "borrow" a milli from the date // and convert it to 1000 micros. dateToMillis.setTime(dateToMillis.getTime()-1); usecs += 1000; } assert(usecs >= 0); String format = sdf.format(dateToMillis); // zero-pad so 1 or 2 digit usecs get appended correctly return format + String.format("%03d", usecs); } /** * Hashcode with the same uniqueness as a Java Date. */ @Override public int hashCode() { long usec = this.getTime(); return (int) usec ^ (int) (usec >> 32); } /** * CompareTo - to mimic Java Date */ @Override public int compareTo(TimestampType dateval) { int comp = m_date.compareTo(dateval.m_date); if (comp == 0) { return m_usecs - dateval.m_usecs; } else { return comp; } } /** * Retrieve a copy of the approximate Java date. * The returned date is a copy; this object will not be affected by * modifications of the returned instance. * @return Clone of underlying Date object. */ public Date asApproximateJavaDate() { return (Date) m_date.clone(); } /** * Retrieve a copy of the Java date for a TimeStamp with millisecond granularity. * The returned date is a copy; this object will not be affected by * modifications of the returned instance. * @return Clone of underlying Date object. */ public Date asExactJavaDate() { if (m_usecs != 0) { throw new RuntimeException("Can't convert to java Date from TimestampType with fractional milliseconds"); } return (Date) m_date.clone(); } /** * Retrieve a properly typed copy of the Java date for a TimeStamp with millisecond granularity. * The returned date is a copy; this object will not be affected by * modifications of the returned instance. * @return specifically typed copy of underlying Date object. */ public java.sql.Date asExactJavaSqlDate() { if (m_usecs != 0) { throw new RuntimeException("Can't convert to sql Date from TimestampType with fractional milliseconds"); } return new java.sql.Date(m_date.getTime()); } /** * Retrieve a properly typed copy of the Java Timestamp for the VoltDB TimeStamp. * The returned Timestamp is a copy; this object will not be affected by * modifications of the returned instance. * @return reformatted Timestamp expressed internally as 1000s of nanoseconds. */ public java.sql.Timestamp asJavaTimestamp() { java.sql.Timestamp result = new java.sql.Timestamp(m_date.getTime()); result.setNanos(result.getNanos() + m_usecs * 1000); return result; } @Override public String toJSONString() { return String.valueOf(getTime()); } private final Date m_date; // stores milliseconds from epoch. private final short m_usecs; // stores microsecond within date's millisecond. }
package cpw.mods.fml.relauncher; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.net.URLClassLoader; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.logging.Level; public class RelaunchClassLoader extends URLClassLoader { private static String[] excludedPackages = { "java.", "sun.", "cpw.mods.fml.relauncher.", "net.minecraftforge.classloading." }; private static String[] transformerExclusions = { "org.objectweb.asm.", "com.google.common.", "cpw.mods.fml.", "javax." }; private List<URL> sources; private ClassLoader parent; private List<IClassTransformer> transformers; private Map<String, Class> cachedClasses; public RelaunchClassLoader(URL[] sources) { super(sources, null); this.sources = new ArrayList<URL>(Arrays.asList(sources)); this.parent = getClass().getClassLoader(); this.cachedClasses = new HashMap<String,Class>(1000); this.transformers = new ArrayList<IClassTransformer>(2); // ReflectionHelper.setPrivateValue(ClassLoader.class, null, this, "scl"); Thread.currentThread().setContextClassLoader(this); } public void registerTransformer(String transformerClassName) { try { transformers.add((IClassTransformer) loadClass(transformerClassName).newInstance()); } catch (Exception e) { FMLRelaunchLog.log(Level.SEVERE, e, "A critical problem occured registering the ASM transformer class %s", transformerClassName); } } @Override public Class<?> findClass(String name) throws ClassNotFoundException { for (String st : excludedPackages) { if (name.startsWith(st)) { return parent.loadClass(name); } } if (cachedClasses.containsKey(name)) { return cachedClasses.get(name); } for (String st : transformerExclusions) { if (name.startsWith(st)) { Class<?> cl = super.findClass(name); cachedClasses.put(name, cl); return cl; } } try { int lastDot = name.lastIndexOf('.'); if (lastDot > -1) { String pkgname = name.substring(0, lastDot); if (getPackage(pkgname)==null) { definePackage(pkgname, null, null, null, null, null, null, null); } } byte[] basicClass = getClassBytes(name); byte[] transformedClass = runTransformers(name, basicClass); Class<?> cl = defineClass(name, transformedClass, 0, transformedClass.length); cachedClasses.put(name, cl); return cl; } catch (Throwable e) { throw new ClassNotFoundException(name, e); } } /** * @param name * @return * @throws IOException */ public byte[] getClassBytes(String name) throws IOException { InputStream classStream = null; try { URL classResource = findResource(name.replace('.', '/').concat(".class")); if (classResource == null) { return null; } classStream = classResource.openStream(); return readFully(classStream); } finally { if (classStream != null) { try { classStream.close(); } catch (IOException e) { // Swallow the close exception } } } } private byte[] runTransformers(String name, byte[] basicClass) { for (IClassTransformer transformer : transformers) { basicClass = transformer.transform(name, basicClass); } return basicClass; } @Override public void addURL(URL url) { super.addURL(url); sources.add(url); } public List<URL> getSources() { return sources; } private byte[] readFully(InputStream stream) { try { ByteArrayOutputStream bos = new ByteArrayOutputStream(stream.available()); int r; while ((r = stream.read()) != -1) { bos.write(r); } return bos.toByteArray(); } catch (Throwable t) { /// HMMM return new byte[0]; } } public List<IClassTransformer> getTransformers() { return Collections.unmodifiableList(transformers); } }
package org.broadinstitute.sting.utils; import cern.jet.random.ChiSquare; import cern.jet.math.Arithmetic; import com.google.java.contract.Requires; import net.sf.samtools.SAMRecord; import org.apache.lucene.messages.NLS; import org.broadinstitute.sting.gatk.GenomeAnalysisEngine; import org.broadinstitute.sting.utils.exceptions.ReviewedStingException; import org.broadinstitute.sting.utils.exceptions.UserException; import java.math.BigDecimal; import java.util.*; /** * MathUtils is a static class (no instantiation allowed!) with some useful math methods. * * @author Kiran Garimella */ public class MathUtils { /** Public constants - used for the Lanczos approximation to the factorial function * (for the calculation of the binomial/multinomial probability in logspace) * @param LANC_SEQ[] - an array holding the constants which correspond to the product * of Chebyshev Polynomial coefficients, and points on the Gamma function (for interpolation) * [see A Precision Approximation of the Gamma Function J. SIAM Numer. Anal. Ser. B, Vol. 1 1964. pp. 86-96] * @param LANC_G - a value for the Lanczos approximation to the gamma function that works to * high precision */ /** Private constructor. No instantiating this class! */ private MathUtils() {} @Requires({"d > 0.0"}) public static int fastPositiveRound(double d) { return (int) (d + 0.5); } public static int fastRound(double d) { if ( d > 0.0 ) { return fastPositiveRound(d); } else { return -1*fastPositiveRound(-1*d); } } public static double sum(Collection<Number> numbers) { return sum(numbers,false); } public static double sum( Collection<Number> numbers, boolean ignoreNan ) { double sum = 0; for ( Number n : numbers ) { if ( ! ignoreNan || ! Double.isNaN(n.doubleValue())) { sum += n.doubleValue(); } } return sum; } public static int nonNanSize(Collection<Number> numbers) { int size = 0; for ( Number n : numbers) { size += Double.isNaN(n.doubleValue()) ? 0 : 1; } return size; } public static double average( Collection<Number> numbers, boolean ignoreNan) { if ( ignoreNan ) { return sum(numbers,true)/nonNanSize(numbers); } else { return sum(numbers,false)/nonNanSize(numbers); } } public static double variance( Collection<Number> numbers, Number mean, boolean ignoreNan ) { double mn = mean.doubleValue(); double var = 0; for ( Number n : numbers ) { var += ( ! ignoreNan || ! Double.isNaN(n.doubleValue())) ? (n.doubleValue()-mn)*(n.doubleValue()-mn) : 0; } if ( ignoreNan ) { return var/(nonNanSize(numbers)-1); } return var/(numbers.size()-1); } public static double variance(Collection<Number> numbers, Number mean) { return variance(numbers,mean,false); } public static double variance(Collection<Number> numbers, boolean ignoreNan) { return variance(numbers,average(numbers,ignoreNan),ignoreNan); } public static double variance(Collection<Number> numbers) { return variance(numbers,average(numbers,false),false); } public static double sum(double[] values) { double s = 0.0; for ( double v : values) s += v; return s; } /** * Calculates the log10 cumulative sum of an array with log10 probabilities * @param log10p the array with log10 probabilites * @param upTo index in the array to calculate the cumsum up to * @return the log10 of the cumulative sum */ public static double log10CumulativeSumLog10(double [] log10p, int upTo) { return log10sumLog10(log10p, 0, upTo); } /** * Converts a real space array of probabilities into a log10 array * @param prRealSpace * @return */ public static double[] toLog10(double[] prRealSpace) { double[] log10s = new double[prRealSpace.length]; for ( int i = 0; i < prRealSpace.length; i++ ) log10s[i] = Math.log10(prRealSpace[i]); return log10s; } public static double log10sumLog10(double[] log10p, int start) { return log10sumLog10(log10p, start, log10p.length); } public static double log10sumLog10(double[] log10p, int start, int finish) { double sum = 0.0; double maxValue = Utils.findMaxEntry(log10p); for ( int i = start; i < finish; i++ ) { sum += Math.pow(10.0, log10p[i] - maxValue); } return Math.log10(sum) + maxValue; } public static double sumDoubles(List<Double> values) { double s = 0.0; for ( double v : values) s += v; return s; } public static int sumIntegers(List<Integer> values) { int s = 0; for ( int v : values) s += v; return s; } public static double sumLog10(double[] log10values) { return Math.pow(10.0, log10sumLog10(log10values)); // double s = 0.0; // for ( double v : log10values) s += Math.pow(10.0, v); // return s; } public static double log10sumLog10(double[] log10values) { return log10sumLog10(log10values, 0); } public static boolean wellFormedDouble(double val) { return ! Double.isInfinite(val) && ! Double.isNaN(val); } public static boolean isBounded(double val, double lower, double upper) { return val >= lower && val <= upper; } public static boolean isPositive(double val) { return ! isNegativeOrZero(val); } public static boolean isPositiveOrZero(double val) { return isBounded(val, 0.0, Double.POSITIVE_INFINITY); } public static boolean isNegativeOrZero(double val) { return isBounded(val, Double.NEGATIVE_INFINITY, 0.0); } public static boolean isNegative(double val) { return ! isPositiveOrZero(val); } /** * Compares double values for equality (within 1e-6), or inequality. * * @param a the first double value * @param b the second double value * @return -1 if a is greater than b, 0 if a is equal to be within 1e-6, 1 if b is greater than a. */ public static byte compareDoubles(double a, double b) { return compareDoubles(a, b, 1e-6); } /** * Compares double values for equality (within epsilon), or inequality. * * @param a the first double value * @param b the second double value * @param epsilon the precision within which two double values will be considered equal * @return -1 if a is greater than b, 0 if a is equal to be within epsilon, 1 if b is greater than a. */ public static byte compareDoubles(double a, double b, double epsilon) { if (Math.abs(a - b) < epsilon) { return 0; } if (a > b) { return -1; } return 1; } /** * Compares float values for equality (within 1e-6), or inequality. * * @param a the first float value * @param b the second float value * @return -1 if a is greater than b, 0 if a is equal to be within 1e-6, 1 if b is greater than a. */ public static byte compareFloats(float a, float b) { return compareFloats(a, b, 1e-6f); } /** * Compares float values for equality (within epsilon), or inequality. * * @param a the first float value * @param b the second float value * @param epsilon the precision within which two float values will be considered equal * @return -1 if a is greater than b, 0 if a is equal to be within epsilon, 1 if b is greater than a. */ public static byte compareFloats(float a, float b, float epsilon) { if (Math.abs(a - b) < epsilon) { return 0; } if (a > b) { return -1; } return 1; } public static double NormalDistribution(double mean, double sd, double x) { double a = 1.0 / (sd*Math.sqrt(2.0 * Math.PI)); double b = Math.exp(-1.0 * (Math.pow(x - mean,2.0)/(2.0 * sd * sd))); return a * b; } public static double binomialCoefficient (int n, int k) { return Math.pow(10, log10BinomialCoefficient(n, k)); } /** * Computes a binomial probability. This is computed using the formula * * B(k; n; p) = [ n! / ( k! (n - k)! ) ] (p^k)( (1-p)^k ) * * where n is the number of trials, k is the number of successes, and p is the probability of success * * @param n number of Bernoulli trials * @param k number of successes * @param p probability of success * * @return the binomial probability of the specified configuration. Computes values down to about 1e-237. */ public static double binomialProbability (int n, int k, double p) { return Math.pow(10, log10BinomialProbability(n, k, Math.log10(p))); } /** * Performs the cumulative sum of binomial probabilities, where the probability calculation is done in log space. * @param start - start of the cumulant sum (over hits) * @param end - end of the cumulant sum (over hits) * @param total - number of attempts for the number of hits * @param probHit - probability of a successful hit * @return - returns the cumulative probability */ public static double binomialCumulativeProbability(int start, int end, int total, double probHit) { double cumProb = 0.0; double prevProb; BigDecimal probCache = BigDecimal.ZERO; for(int hits = start; hits < end; hits++) { prevProb = cumProb; double probability = binomialProbability(total, hits, probHit); cumProb += probability; if ( probability > 0 && cumProb - prevProb < probability/2 ) { // loss of precision probCache = probCache.add(new BigDecimal(prevProb)); cumProb = 0.0; hits--; // repeat loop // prevProb changes at start of loop } } return probCache.add(new BigDecimal(cumProb)).doubleValue(); } /** * Computes a multinomial coefficient efficiently avoiding overflow even for large numbers. * This is computed using the formula: * * M(x1,x2,...,xk; n) = [ n! / (x1! x2! ... xk!) ] * * where xi represents the number of times outcome i was observed, n is the number of total observations. * In this implementation, the value of n is inferred as the sum over i of xi. * * @param k an int[] of counts, where each element represents the number of times a certain outcome was observed * @return the multinomial of the specified configuration. */ public static double multinomialCoefficient (int [] k) { int n = 0; for (int xi : k) { n += xi; } return Math.pow(10, log10MultinomialCoefficient(n, k)); } /** * Computes a multinomial probability efficiently avoiding overflow even for large numbers. * This is computed using the formula: * * M(x1,x2,...,xk; n; p1,p2,...,pk) = [ n! / (x1! x2! ... xk!) ] (p1^x1)(p2^x2)(...)(pk^xk) * * where xi represents the number of times outcome i was observed, n is the number of total observations, and * pi represents the probability of the i-th outcome to occur. In this implementation, the value of n is * inferred as the sum over i of xi. * * @param k an int[] of counts, where each element represents the number of times a certain outcome was observed * @param p a double[] of probabilities, where each element represents the probability a given outcome can occur * @return the multinomial probability of the specified configuration. */ public static double multinomialProbability (int[] k, double[] p) { if (p.length != k.length) throw new UserException.BadArgumentValue("p and k", "Array of log10 probabilities must have the same size as the array of number of sucesses: " + p.length + ", " + k.length); int n = 0; double [] log10P = new double[p.length]; for (int i=0; i<p.length; i++) { log10P[i] = Math.log10(p[i]); n += k[i]; } return Math.pow(10,log10MultinomialProbability(n, k, log10P)); } /** * calculate the Root Mean Square of an array of integers * @param x an byte[] of numbers * @return the RMS of the specified numbers. */ public static double rms(byte[] x) { if ( x.length == 0 ) return 0.0; double rms = 0.0; for (int i : x) rms += i * i; rms /= x.length; return Math.sqrt(rms); } /** * calculate the Root Mean Square of an array of integers * @param x an int[] of numbers * @return the RMS of the specified numbers. */ public static double rms(int[] x) { if ( x.length == 0 ) return 0.0; double rms = 0.0; for (int i : x) rms += i * i; rms /= x.length; return Math.sqrt(rms); } /** * calculate the Root Mean Square of an array of doubles * @param x a double[] of numbers * @return the RMS of the specified numbers. */ public static double rms(Double[] x) { if ( x.length == 0 ) return 0.0; double rms = 0.0; for (Double i : x) rms += i * i; rms /= x.length; return Math.sqrt(rms); } public static double distanceSquared( final double[] x, final double[] y ) { double dist = 0.0; for(int iii = 0; iii < x.length; iii++) { dist += (x[iii] - y[iii]) * (x[iii] - y[iii]); } return dist; } public static double round(double num, int digits) { double result = num * Math.pow(10.0, (double)digits); result = Math.round(result); result = result / Math.pow(10.0, (double)digits); return result; } /** * normalizes the log10-based array. ASSUMES THAT ALL ARRAY ENTRIES ARE <= 0 (<= 1 IN REAL-SPACE). * * @param array the array to be normalized * @param takeLog10OfOutput if true, the output will be transformed back into log10 units * * @return a newly allocated array corresponding the normalized values in array, maybe log10 transformed */ public static double[] normalizeFromLog10(double[] array, boolean takeLog10OfOutput) { double[] normalized = new double[array.length]; // for precision purposes, we need to add (or really subtract, since they're // all negative) the largest value; also, we need to convert to normal-space. double maxValue = Utils.findMaxEntry(array); for (int i = 0; i < array.length; i++) normalized[i] = Math.pow(10, array[i] - maxValue); // normalize double sum = 0.0; for (int i = 0; i < array.length; i++) sum += normalized[i]; for (int i = 0; i < array.length; i++) { double x = normalized[i] / sum; if ( takeLog10OfOutput ) x = Math.log10(x); normalized[i] = x; } return normalized; } public static double[] normalizeFromLog10(List<Double> array, boolean takeLog10OfOutput) { double[] normalized = new double[array.size()]; // for precision purposes, we need to add (or really subtract, since they're // all negative) the largest value; also, we need to convert to normal-space. double maxValue = MathUtils.arrayMaxDouble( array ); for (int i = 0; i < array.size(); i++) normalized[i] = Math.pow(10, array.get(i) - maxValue); // normalize double sum = 0.0; for (int i = 0; i < array.size(); i++) sum += normalized[i]; for (int i = 0; i < array.size(); i++) { double x = normalized[i] / sum; if ( takeLog10OfOutput ) x = Math.log10(x); normalized[i] = x; } return normalized; } /** * normalizes the log10-based array. ASSUMES THAT ALL ARRAY ENTRIES ARE <= 0 (<= 1 IN REAL-SPACE). * * @param array the array to be normalized * * @return a newly allocated array corresponding the normalized values in array */ public static double[] normalizeFromLog10(double[] array) { return normalizeFromLog10(array, false); } public static double[] normalizeFromLog10(List<Double> array) { return normalizeFromLog10(array, false); } public static int maxElementIndex(double[] array) { if ( array == null ) throw new IllegalArgumentException("Array cannot be null!"); int maxI = -1; for ( int i = 0; i < array.length; i++ ) { if ( maxI == -1 || array[i] > array[maxI] ) maxI = i; } return maxI; } public static int maxElementIndex(int[] array) { if ( array == null ) throw new IllegalArgumentException("Array cannot be null!"); int maxI = -1; for ( int i = 0; i < array.length; i++ ) { if ( maxI == -1 || array[i] > array[maxI] ) maxI = i; } return maxI; } public static double arrayMax(double[] array) { return array[maxElementIndex(array)]; } public static double arrayMin(double[] array) { return array[minElementIndex(array)]; } public static byte arrayMin(byte[] array) { return array[minElementIndex(array)]; } public static int minElementIndex(double[] array) { if ( array == null ) throw new IllegalArgumentException("Array cannot be null!"); int minI = -1; for ( int i = 0; i < array.length; i++ ) { if ( minI == -1 || array[i] < array[minI] ) minI = i; } return minI; } public static int minElementIndex(byte[] array) { if ( array == null ) throw new IllegalArgumentException("Array cannot be null!"); int minI = -1; for ( int i = 0; i < array.length; i++ ) { if ( minI == -1 || array[i] < array[minI] ) minI = i; } return minI; } public static int arrayMaxInt(List<Integer> array) { if ( array == null ) throw new IllegalArgumentException("Array cannot be null!"); if ( array.size() == 0 ) throw new IllegalArgumentException("Array size cannot be 0!"); int m = array.get(0); for ( int e : array ) m = Math.max(m, e); return m; } public static double arrayMaxDouble(List<Double> array) { if ( array == null ) throw new IllegalArgumentException("Array cannot be null!"); if ( array.size() == 0 ) throw new IllegalArgumentException("Array size cannot be 0!"); double m = array.get(0); for ( double e : array ) m = Math.max(m, e); return m; } public static double average(List<Long> vals, int maxI) { long sum = 0L; int i = 0; for (long x : vals) { if (i > maxI) break; sum += x; i++; //System.out.printf(" %d/%d", sum, i); } //System.out.printf("Sum = %d, n = %d, maxI = %d, avg = %f%n", sum, i, maxI, (1.0 * sum) / i); return (1.0 * sum) / i; } public static double averageDouble(List<Double> vals, int maxI) { double sum = 0.0; int i = 0; for (double x : vals) { if (i > maxI) break; sum += x; i++; } return (1.0 * sum) / i; } public static double average(List<Long> vals) { return average(vals, vals.size()); } public static byte average(byte[] vals) { int sum = 0; for (byte v : vals) { sum += v; } return (byte) Math.floor(sum/vals.length); } public static double averageDouble(List<Double> vals) { return averageDouble(vals, vals.size()); } // Java Generics can't do primitive types, so I had to do this the simplistic way public static Integer[] sortPermutation(final int[] A) { class comparator implements Comparator<Integer> { public int compare(Integer a, Integer b) { if (A[a.intValue()] < A[b.intValue()]) { return -1; } if (A[a.intValue()] == A[b.intValue()]) { return 0; } if (A[a.intValue()] > A[b.intValue()]) { return 1; } return 0; } } Integer[] permutation = new Integer[A.length]; for (int i = 0; i < A.length; i++) { permutation[i] = i; } Arrays.sort(permutation, new comparator()); return permutation; } public static Integer[] sortPermutation(final double[] A) { class comparator implements Comparator<Integer> { public int compare(Integer a, Integer b) { if (A[a.intValue()] < A[b.intValue()]) { return -1; } if (A[a.intValue()] == A[b.intValue()]) { return 0; } if (A[a.intValue()] > A[b.intValue()]) { return 1; } return 0; } } Integer[] permutation = new Integer[A.length]; for (int i = 0; i < A.length; i++) { permutation[i] = i; } Arrays.sort(permutation, new comparator()); return permutation; } public static <T extends Comparable> Integer[] sortPermutation(List<T> A) { final Object[] data = A.toArray(); class comparator implements Comparator<Integer> { public int compare(Integer a, Integer b) { return ((T) data[a]).compareTo(data[b]); } } Integer[] permutation = new Integer[A.size()]; for (int i = 0; i < A.size(); i++) { permutation[i] = i; } Arrays.sort(permutation, new comparator()); return permutation; } public static int[] permuteArray(int[] array, Integer[] permutation) { int[] output = new int[array.length]; for (int i = 0; i < output.length; i++) { output[i] = array[permutation[i]]; } return output; } public static double[] permuteArray(double[] array, Integer[] permutation) { double[] output = new double[array.length]; for (int i = 0; i < output.length; i++) { output[i] = array[permutation[i]]; } return output; } public static Object[] permuteArray(Object[] array, Integer[] permutation) { Object[] output = new Object[array.length]; for (int i = 0; i < output.length; i++) { output[i] = array[permutation[i]]; } return output; } public static String[] permuteArray(String[] array, Integer[] permutation) { String[] output = new String[array.length]; for (int i = 0; i < output.length; i++) { output[i] = array[permutation[i]]; } return output; } public static <T> List<T> permuteList(List<T> list, Integer[] permutation) { List<T> output = new ArrayList<T>(); for (int i = 0; i < permutation.length; i++) { output.add(list.get(permutation[i])); } return output; } /** Draw N random elements from list. */ public static <T> List<T> randomSubset(List<T> list, int N) { if (list.size() <= N) { return list; } int idx[] = new int[list.size()]; for (int i = 0; i < list.size(); i++) { idx[i] = GenomeAnalysisEngine.getRandomGenerator().nextInt(); } Integer[] perm = sortPermutation(idx); List<T> ans = new ArrayList<T>(); for (int i = 0; i < N; i++) { ans.add(list.get(perm[i])); } return ans; } public static double percentage(double x, double base) { return (base > 0 ? (x / base) * 100.0 : 0); } public static double percentage(int x, int base) { return (base > 0 ? ((double) x / (double) base) * 100.0 : 0); } public static double percentage(long x, long base) { return (base > 0 ? ((double) x / (double) base) * 100.0 : 0); } public static int countOccurrences(char c, String s) { int count = 0; for (int i = 0; i < s.length(); i++) { count += s.charAt(i) == c ? 1 : 0; } return count; } public static <T> int countOccurrences(T x, List<T> l) { int count = 0; for (T y : l) { if (x.equals(y)) count++; } return count; } public static int countOccurrences(byte element, byte [] array) { int count = 0; for (byte y : array) { if (element == y) count++; } return count; } /** * Returns the top (larger) N elements of the array. Naive n^2 implementation (Selection Sort). * Better than sorting if N (number of elements to return) is small * * @param array the array * @param n number of top elements to return * @return the n larger elements of the array */ public static Collection<Double> getNMaxElements(double [] array, int n) { ArrayList<Double> maxN = new ArrayList<Double>(n); double lastMax = Double.MAX_VALUE; for (int i=0; i<n; i++) { double max = Double.MIN_VALUE; for (double x : array) { max = Math.min(lastMax, Math.max(x, max)); } maxN.add(max); lastMax = max; } return maxN; } /** * Returns n random indices drawn with replacement from the range 0..(k-1) * * @param n the total number of indices sampled from * @param k the number of random indices to draw (with replacement) * @return a list of k random indices ranging from 0 to (n-1) with possible duplicates */ static public ArrayList<Integer> sampleIndicesWithReplacement(int n, int k) { ArrayList<Integer> chosen_balls = new ArrayList <Integer>(k); for (int i=0; i< k; i++) { //Integer chosen_ball = balls[rand.nextInt(k)]; chosen_balls.add(GenomeAnalysisEngine.getRandomGenerator().nextInt(n)); //balls.remove(chosen_ball); } return chosen_balls; } /** * Returns n random indices drawn without replacement from the range 0..(k-1) * * @param n the total number of indices sampled from * @param k the number of random indices to draw (without replacement) * @return a list of k random indices ranging from 0 to (n-1) without duplicates */ static public ArrayList<Integer> sampleIndicesWithoutReplacement(int n, int k) { ArrayList<Integer> chosen_balls = new ArrayList<Integer>(k); for (int i = 0; i < n; i++) { chosen_balls.add(i); } Collections.shuffle(chosen_balls, GenomeAnalysisEngine.getRandomGenerator()); //return (ArrayList<Integer>) chosen_balls.subList(0, k); return new ArrayList<Integer>(chosen_balls.subList(0, k)); } /** * Given a list of indices into a list, return those elements of the list with the possibility of drawing list elements multiple times * @param indices the list of indices for elements to extract * @param list the list from which the elements should be extracted * @param <T> the template type of the ArrayList * @return a new ArrayList consisting of the elements at the specified indices */ static public <T> ArrayList<T> sliceListByIndices(List<Integer> indices, List<T> list) { ArrayList<T> subset = new ArrayList<T>(); for (int i : indices) { subset.add(list.get(i)); } return subset; } public static Comparable orderStatisticSearch(int orderStat, List<Comparable> list) { // this finds the order statistic of the list (kth largest element) // the list is assumed *not* to be sorted final Comparable x = list.get(orderStat); ListIterator iterator = list.listIterator(); ArrayList lessThanX = new ArrayList(); ArrayList equalToX = new ArrayList(); ArrayList greaterThanX = new ArrayList(); for(Comparable y : list) { if(x.compareTo(y) > 0) { lessThanX.add(y); } else if(x.compareTo(y) < 0) { greaterThanX.add(y); } else equalToX.add(y); } if(lessThanX.size() > orderStat) return orderStatisticSearch(orderStat, lessThanX); else if(lessThanX.size() + equalToX.size() >= orderStat) return orderStat; else return orderStatisticSearch(orderStat - lessThanX.size() - equalToX.size(), greaterThanX); } public static Object getMedian(List<Comparable> list) { return orderStatisticSearch((int) Math.ceil(list.size()/2), list); } /* public static byte getQScoreOrderStatistic(List<SAMRecord> reads, List<Integer> offsets, int k) { // version of the order statistic calculator for SAMRecord/Integer lists, where the // list index maps to a q-score only through the offset index // returns the kth-largest q-score. if( reads.size() == 0) { return 0; } ArrayList lessThanQReads = new ArrayList(); ArrayList equalToQReads = new ArrayList(); ArrayList greaterThanQReads = new ArrayList(); ArrayList lessThanQOffsets = new ArrayList(); ArrayList greaterThanQOffsets = new ArrayList(); final byte qk = reads.get(k).getBaseQualities()[offsets.get(k)]; for(int iter = 0; iter < reads.size(); iter ++) { SAMRecord read = reads.get(iter); int offset = offsets.get(iter); byte quality = read.getBaseQualities()[offset]; if(quality < qk) { lessThanQReads.add(read); lessThanQOffsets.add(offset); } else if(quality > qk) { greaterThanQReads.add(read); greaterThanQOffsets.add(offset); } else { equalToQReads.add(reads.get(iter)); } } if(lessThanQReads.size() > k) return getQScoreOrderStatistic(lessThanQReads, lessThanQOffsets, k); else if(equalToQReads.size() + lessThanQReads.size() >= k) return qk; else return getQScoreOrderStatistic(greaterThanQReads, greaterThanQOffsets, k - lessThanQReads.size() - equalToQReads.size()); } public static byte getQScoreMedian(List<SAMRecord> reads, List<Integer> offsets) { return getQScoreOrderStatistic(reads, offsets, (int)Math.floor(reads.size()/2.)); }*/ public static class RunningAverage { private double mean = 0.0; private double s = 0.0; private long obs_count = 0; public void add(double obs) { obs_count++; double oldMean = mean; mean += ( obs - mean ) / obs_count; // update mean s += ( obs - oldMean ) * ( obs - mean ); } public void addAll(Collection<Number> col) { for ( Number o : col ) { add(o.doubleValue()); } } public double mean() { return mean; } public double stddev() { return Math.sqrt(s/(obs_count - 1)); } public double var() { return s/(obs_count - 1); } public long observationCount() { return obs_count; } public RunningAverage clone() { RunningAverage ra = new RunningAverage(); ra.mean = this.mean; ra.s = this.s; ra.obs_count = this.obs_count; return ra; } public void merge(RunningAverage other) { if ( this.obs_count > 0 || other.obs_count > 0 ) { // if we have any observations at all this.mean = ( this.mean * this.obs_count + other.mean * other.obs_count ) / ( this.obs_count + other.obs_count ); this.s += other.s; } this.obs_count += other.obs_count; } } // useful common utility routines public static double rate(long n, long d) { return n / (1.0 * Math.max(d, 1)); } public static double rate(int n, int d) { return n / (1.0 * Math.max(d, 1)); } public static long inverseRate(long n, long d) { return n == 0 ? 0 : d / Math.max(n, 1); } public static long inverseRate(int n, int d) { return n == 0 ? 0 : d / Math.max(n, 1); } public static double ratio(int num, int denom) { return ((double)num) / (Math.max(denom, 1)); } public static double ratio(long num, long denom) { return ((double)num) / (Math.max(denom, 1)); } public static final double[] log10Cache; public static final double[] jacobianLogTable; public static final int JACOBIAN_LOG_TABLE_SIZE = 101; public static final double JACOBIAN_LOG_TABLE_STEP = 0.1; public static final double INV_JACOBIAN_LOG_TABLE_STEP = 1.0/JACOBIAN_LOG_TABLE_STEP; public static final double MAX_JACOBIAN_TOLERANCE = 10.0; private static final int MAXN = 10000; static { log10Cache = new double[2*MAXN]; jacobianLogTable = new double[JACOBIAN_LOG_TABLE_SIZE]; log10Cache[0] = Double.NEGATIVE_INFINITY; for (int k=1; k < 2*MAXN; k++) log10Cache[k] = Math.log10(k); for (int k=0; k < JACOBIAN_LOG_TABLE_SIZE; k++) { jacobianLogTable[k] = Math.log10(1.0+Math.pow(10.0,-((double)k) * JACOBIAN_LOG_TABLE_STEP)); } } static public double softMax(final double[] vec) { double acc = vec[0]; for (int k=1; k < vec.length; k++) acc = softMax(acc,vec[k]); return acc; } static public double max(double x0, double x1, double x2) { double a = Math.max(x0,x1); return Math.max(a,x2); } static public double softMax(final double x0, final double x1, final double x2) { // compute naively log10(10^x[0] + 10^x[1]+...) // return Math.log10(MathUtils.sumLog10(vec)); // better approximation: do Jacobian logarithm function on data pairs double a = softMax(x0,x1); return softMax(a,x2); } static public double softMax(final double x, final double y) { if (Double.isInfinite(x)) return y; if (Double.isInfinite(y)) return x; if (y >= x + MAX_JACOBIAN_TOLERANCE) return y; if (x >= y + MAX_JACOBIAN_TOLERANCE) return x; // OK, so |y-x| < tol: we use the following identity then: // we need to compute log10(10^x + 10^y) // By Jacobian logarithm identity, this is equal to // max(x,y) + log10(1+10^-abs(x-y)) // we compute the second term as a table lookup // with integer quantization //double diff = Math.abs(x-y); double diff = x-y; double t1 =x; if (diff<0) { t1 = y; diff= -diff; } // t has max(x,y), diff has abs(x-y) // we have pre-stored correction for 0,0.1,0.2,... 10.0 //int ind = (int)Math.round(diff*INV_JACOBIAN_LOG_TABLE_STEP); int ind = (int)(diff*INV_JACOBIAN_LOG_TABLE_STEP+0.5); // gdebug+ //double z =Math.log10(1+Math.pow(10.0,-diff)); //System.out.format("x: %f, y:%f, app: %f, true: %f ind:%d\n",x,y,t2,z,ind); //gdebug- return t1+jacobianLogTable[ind]; // return Math.log10(Math.pow(10.0,x) + Math.pow(10.0,y)); } public static double phredScaleToProbability (byte q) { return Math.pow(10,(-q)/10.0); } public static double phredScaleToLog10Probability (byte q) { return ((-q)/10.0); } /** * Returns the phred scaled value of probability p * @param p probability (between 0 and 1). * @return phred scaled probability of p */ public static byte probabilityToPhredScale (double p) { return (byte) ((-10) * Math.log10(p)); } public static double log10ProbabilityToPhredScale (double log10p) { return (-10) * log10p; } /** * Converts LN to LOG10 * @param ln log(x) * @return log10(x) */ public static double lnToLog10 (double ln) { return ln * Math.log10(Math.exp(1)); } /** * Constants to simplify the log gamma function calculation. */ private static final double zero = 0.0, one = 1.0, half = .5, a0 = 7.72156649015328655494e-02, a1 = 3.22467033424113591611e-01, a2 = 6.73523010531292681824e-02, a3 = 2.05808084325167332806e-02, a4 = 7.38555086081402883957e-03, a5 = 2.89051383673415629091e-03, a6 = 1.19270763183362067845e-03, a7 = 5.10069792153511336608e-04, a8 = 2.20862790713908385557e-04, a9 = 1.08011567247583939954e-04, a10 = 2.52144565451257326939e-05, a11 = 4.48640949618915160150e-05, tc = 1.46163214496836224576e+00, tf = -1.21486290535849611461e-01, tt = -3.63867699703950536541e-18, t0 = 4.83836122723810047042e-01, t1 = -1.47587722994593911752e-01, t2 = 6.46249402391333854778e-02, t3 = -3.27885410759859649565e-02, t4 = 1.79706750811820387126e-02, t5 = -1.03142241298341437450e-02, t6 = 6.10053870246291332635e-03, t7 = -3.68452016781138256760e-03, t8 = 2.25964780900612472250e-03, t9 = -1.40346469989232843813e-03, t10 = 8.81081882437654011382e-04, t11 = -5.38595305356740546715e-04, t12 = 3.15632070903625950361e-04, t13 = -3.12754168375120860518e-04, t14 = 3.35529192635519073543e-04, u0 = -7.72156649015328655494e-02, u1 = 6.32827064025093366517e-01, u2 = 1.45492250137234768737e+00, u3 = 9.77717527963372745603e-01, u4 = 2.28963728064692451092e-01, u5 = 1.33810918536787660377e-02, v1 = 2.45597793713041134822e+00, v2 = 2.12848976379893395361e+00, v3 = 7.69285150456672783825e-01, v4 = 1.04222645593369134254e-01, v5 = 3.21709242282423911810e-03, s0 = -7.72156649015328655494e-02, s1 = 2.14982415960608852501e-01, s2 = 3.25778796408930981787e-01, s3 = 1.46350472652464452805e-01, s4 = 2.66422703033638609560e-02, s5 = 1.84028451407337715652e-03, s6 = 3.19475326584100867617e-05, r1 = 1.39200533467621045958e+00, r2 = 7.21935547567138069525e-01, r3 = 1.71933865632803078993e-01, r4 = 1.86459191715652901344e-02, r5 = 7.77942496381893596434e-04, r6 = 7.32668430744625636189e-06, w0 = 4.18938533204672725052e-01, w1 = 8.33333333333329678849e-02, w2 = -2.77777777728775536470e-03, w3 = 7.93650558643019558500e-04, w4 = -5.95187557450339963135e-04, w5 = 8.36339918996282139126e-04, w6 = -1.63092934096575273989e-03; /** * Efficient rounding functions to simplify the log gamma function calculation * double to long with 32 bit shift */ private static final int HI (double x) { return (int)(Double.doubleToLongBits(x) >> 32); } /** * Efficient rounding functions to simplify the log gamma function calculation * double to long without shift */ private static final int LO (double x) { return (int)Double.doubleToLongBits(x); } /** * Most efficent implementation of the lnGamma (FDLIBM) * Use via the log10Gamma wrapper method. */ private static double lnGamma (double x) { double t,y,z,p,p1,p2,p3,q,r,w; int i; int hx = HI(x); int lx = LO(x); /* purge off +-inf, NaN, +-0, and negative arguments */ int ix = hx&0x7fffffff; if (ix >= 0x7ff00000) return Double.POSITIVE_INFINITY; if ((ix|lx)==0 || hx < 0) return Double.NaN; if (ix<0x3b900000) { /* |x|<2**-70, return -log(|x|) */ return -Math.log(x); } /* purge off 1 and 2 */ if((((ix-0x3ff00000)|lx)==0)||(((ix-0x40000000)|lx)==0)) r = 0; /* for x < 2.0 */ else if(ix<0x40000000) { if(ix<=0x3feccccc) { /* lgamma(x) = lgamma(x+1)-log(x) */ r = -Math.log(x); if(ix>=0x3FE76944) {y = one-x; i= 0;} else if(ix>=0x3FCDA661) {y= x-(tc-one); i=1;} else {y = x; i=2;} } else { r = zero; if(ix>=0x3FFBB4C3) {y=2.0-x;i=0;} /* [1.7316,2] */ else if(ix>=0x3FF3B4C4) {y=x-tc;i=1;} /* [1.23,1.73] */ else {y=x-one;i=2;} } switch(i) { case 0: z = y*y; p1 = a0+z*(a2+z*(a4+z*(a6+z*(a8+z*a10)))); p2 = z*(a1+z*(a3+z*(a5+z*(a7+z*(a9+z*a11))))); p = y*p1+p2; r += (p-0.5*y); break; case 1: z = y*y; w = z*y; p1 = t0+w*(t3+w*(t6+w*(t9 +w*t12))); /* parallel comp */ p2 = t1+w*(t4+w*(t7+w*(t10+w*t13))); p3 = t2+w*(t5+w*(t8+w*(t11+w*t14))); p = z*p1-(tt-w*(p2+y*p3)); r += (tf + p); break; case 2: p1 = y*(u0+y*(u1+y*(u2+y*(u3+y*(u4+y*u5))))); p2 = one+y*(v1+y*(v2+y*(v3+y*(v4+y*v5)))); r += (-0.5*y + p1/p2); } } else if(ix<0x40200000) { /* x < 8.0 */ i = (int)x; t = zero; y = x-(double)i; p = y*(s0+y*(s1+y*(s2+y*(s3+y*(s4+y*(s5+y*s6)))))); q = one+y*(r1+y*(r2+y*(r3+y*(r4+y*(r5+y*r6))))); r = half*y+p/q; z = one; /* lgamma(1+s) = log(s) + lgamma(s) */ switch(i) { case 7: z *= (y+6.0); /* FALLTHRU */ case 6: z *= (y+5.0); /* FALLTHRU */ case 5: z *= (y+4.0); /* FALLTHRU */ case 4: z *= (y+3.0); /* FALLTHRU */ case 3: z *= (y+2.0); /* FALLTHRU */ r += Math.log(z); break; } /* 8.0 <= x < 2**58 */ } else if (ix < 0x43900000) { t = Math.log(x); z = one/x; y = z*z; w = w0+z*(w1+y*(w2+y*(w3+y*(w4+y*(w5+y*w6))))); r = (x-half)*(t-one)+w; } else /* 2**58 <= x <= inf */ r = x*(Math.log(x)-one); return r; } /** * Calculates the log10 of the gamma function for x using the efficient FDLIBM * implementation to avoid overflows and guarantees high accuracy even for large * numbers. * * @param x the x parameter * @return the log10 of the gamma function at x. */ public static double log10Gamma (double x) { return lnToLog10(lnGamma(x)); } /** * Calculates the log10 of the binomial coefficient. Designed to prevent * overflows even with very large numbers. * * @param n total number of trials * @param k number of successes * @return the log10 of the binomial coefficient */ public static double log10BinomialCoefficient (int n, int k) { return log10Gamma(n+1) - log10Gamma(k+1) - log10Gamma(n-k+1); } public static double log10BinomialProbability (int n, int k, double log10p) { double log10OneMinusP = Math.log10(1-Math.pow(10,log10p)); return log10BinomialCoefficient(n, k) + log10p*k + log10OneMinusP*(n-k); } /** * Calculates the log10 of the multinomial coefficient. Designed to prevent * overflows even with very large numbers. * * @param n total number of trials * @param k array of any size with the number of successes for each grouping (k1, k2, k3, ..., km) * @return */ public static double log10MultinomialCoefficient (int n, int [] k) { double denominator = 0.0; for (int x : k) { denominator += log10Gamma(x+1); } return log10Gamma(n+1) - denominator; } /** * Computes the log10 of the multinomial distribution probability given a vector * of log10 probabilities. Designed to prevent overflows even with very large numbers. * * @param n number of trials * @param k array of number of successes for each possibility * @param log10p array of log10 probabilities * @return */ public static double log10MultinomialProbability (int n, int [] k, double [] log10p) { if (log10p.length != k.length) throw new UserException.BadArgumentValue("p and k", "Array of log10 probabilities must have the same size as the array of number of sucesses: " + log10p.length + ", " + k.length); double log10Prod = 0.0; for (int i=0; i<log10p.length; i++) { log10Prod += log10p[i]*k[i]; } return log10MultinomialCoefficient(n, k) + log10Prod; } public static double factorial (int x) { return Math.pow(10, log10Gamma(x+1)); } public static double log10Factorial (int x) { return log10Gamma(x+1); } /** * Computes the p-value for the null hypothesis that the rows of the table are i.i.d. using a pearson chi-square test * @param contingencyTable - a contingency table * @return - the ensuing p-value (via chi-square) */ public static double contingencyChiSquare(short[][] contingencyTable ) { int[] rowSum = new int[contingencyTable.length]; int[] colSum = new int[contingencyTable[0].length]; int total = 0; for ( int i = 0; i < contingencyTable.length; i++ ) { for ( int j = 0; j < contingencyTable[0].length; j++ ) { rowSum[i] += contingencyTable[i][j]; colSum[j] += contingencyTable[i][j]; total += contingencyTable[i][j]; } } double chi = 0; for ( int i = 0; i < contingencyTable.length; i ++ ) { for ( int j = 0; j < contingencyTable[0].length; j++ ) { double expected = (((double) colSum[j])/total)*rowSum[i]; double resid = contingencyTable[i][j] - expected; chi += resid*resid/expected; } } return 1.0-(new ChiSquare(contingencyTable.length*contingencyTable[0].length,null)).cdf(chi); } /** * Exactly the same as above, but using int arrays rather than short arrays on input * @param contingencyTable * @return */ public static double contingencyChiSquare(int[][] contingencyTable ) { int[] rowSum = new int[contingencyTable.length]; int[] colSum = new int[contingencyTable[0].length]; int total = 0; for ( int i = 0; i < contingencyTable.length; i++ ) { for ( int j = 0; j < contingencyTable[0].length; j++ ) { rowSum[i] += contingencyTable[i][j]; colSum[j] += contingencyTable[i][j]; total += contingencyTable[i][j]; } } double chi = 0; for ( int i = 0; i < contingencyTable.length; i ++ ) { for ( int j = 0; j < contingencyTable[0].length; j++ ) { double expected = (((double) colSum[j])/total)*rowSum[i]; double resid = contingencyTable[i][j] - expected; chi += resid*resid/expected; } } return 1.0-(new ChiSquare(contingencyTable.length*contingencyTable[0].length,null)).cdf(chi); } public static double marginalizedFisherExact(double[] spectrum1, double[] spectrum2, int ns1, int ns2) { int N = ns1 + ns2; int[] rowSums = { ns1, ns2 }; double logP = Double.NEGATIVE_INFINITY; // todo -- sorting and strobing should chage this n^2 loop to a nlog(n) algorithm for ( int ac1 = 0; ac1 < spectrum1.length; ac1++ ) { for ( int ac2 = 0; ac2 < spectrum2.length; ac2++ ) { double logPTable = spectrum1[ac1] + spectrum2[ac2]; int[][] table = { { ac1, ns1-ac1 }, { ac2, ns2-ac2 } }; int[] colSums = { ac1 + ac2, N-ac1-ac2}; double logPH0 = Math.log10(fisherExact(table,rowSums,colSums,N)); logP = log10sumLog10(new double[]{logP,logPTable+logPH0}); } } return Math.pow(10,logP); } /** * Calculates the p-value for a fisher exact test for a 2x2 contingency table */ public static double fisherExact(int[][] table) { if ( table.length > 2 || table[0].length > 2 ) { throw new ReviewedStingException("Fisher exact is only implemented for 2x2 contingency tables"); } int[] rowSums = { sumRow(table, 0), sumRow(table, 1) }; int[] colSums = { sumColumn(table, 0), sumColumn(table, 1) }; int N = rowSums[0] + rowSums[1]; return fisherExact(table,rowSums,colSums,N); } public static double fisherExact(int[][] table, int[] rowSums, int[] colSums, int N ) { // calculate in log space so we don't die with high numbers double pCutoff = Arithmetic.logFactorial(rowSums[0]) + Arithmetic.logFactorial(rowSums[1]) + Arithmetic.logFactorial(colSums[0]) + Arithmetic.logFactorial(colSums[1]) - Arithmetic.logFactorial(table[0][0]) - Arithmetic.logFactorial(table[0][1]) - Arithmetic.logFactorial(table[1][0]) - Arithmetic.logFactorial(table[1][1]) - Arithmetic.logFactorial(N); return Math.exp(pCutoff); } public static int sumRow(int[][] table, int column) { int sum = 0; for (int r = 0; r < table.length; r++) { sum += table[r][column]; } return sum; } public static int sumColumn(int[][] table, int row) { int sum = 0; for (int c = 0; c < table[row].length; c++) { sum += table[row][c]; } return sum; } }
package com.ea.orbit.concurrent; import java.util.Collection; import java.util.List; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletionStage; import java.util.concurrent.Executor; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.RejectedExecutionException; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.function.BiConsumer; import java.util.function.BiFunction; import java.util.function.Consumer; import java.util.function.Function; import java.util.function.Supplier; import java.util.stream.Collectors; import java.util.stream.Stream; /** * Task are CompletableFutures were with a few changes. * <p> * <ul> * <li>complete and completeExceptionally are not publicly accessible.</li> * <li>few utility methods (thenRun, thenReturn)</li> * <li>TODO: all callbacks are async by default using the current executor</li> * </ul> * </p> * * @param <T> the type of the returned object. * @see java.util.concurrent.CompletableFuture */ public class Task<T> extends CompletableFuture<T> { private static Void NIL = null; private static Executor commonPool = ExecutorUtils.newScalingThreadPool(100); private static final ScheduledExecutorService schedulerExecutor = Executors.newScheduledThreadPool(10); // TODO: make all callbacks async by default and using the current executor // what "current executor' means will have to be defined. // the idea is to use a framework supplied executor to serve // single point to capture all activity derived from the execution // of one application request. // Including logs, stats, exception and timing information. // TODO: add here or elsewhere a method to wrap a task with timeout // example: Task result = aTask.timeout(60, TimeUnit.SECONDS); // TODO: consider implementing CompletionStage instead of deriving from CompletableFuture. // TODO: consider creating a public class CTask = "Completable Task" /** * Creates an already completed task from the given value. * * @param value the value to be wrapped with a task */ public static <T> Task<T> fromValue(T value) { final Task<T> t = new Task<>(); t.internalComplete(value); return t; } public static <T> Task<T> fromException(Throwable ex) { final Task<T> t = new Task<>(); t.internalCompleteExceptionally(ex); return t; } protected boolean internalComplete(T value) { return super.complete(value); } protected boolean internalCompleteExceptionally(Throwable ex) { return super.completeExceptionally(ex); } /** * This completableFuture derived method is not available for Tasks. */ @Override @Deprecated public boolean complete(T value) { // TODO: throw an exception return super.complete(value); } /** * This completableFuture derived method is not available for Tasks. */ @Override @Deprecated public boolean completeExceptionally(Throwable ex) { // TODO: throw an exception return super.completeExceptionally(ex); } /** * Wraps a CompletionStage as a Task or just casts it if it is already a Task. * * @param stage the stage to be wrapped or casted to Task * @return stage cast as Task of a new Task that is dependent on the completion of that stage. */ public static <T> Task<T> from(CompletionStage<T> stage) { if (stage instanceof Task) { return (Task<T>) stage; } final Task<T> t = new Task<>(); stage.handle((T v, Throwable ex) -> { if (ex != null) { t.internalCompleteExceptionally(ex); } else { t.internalComplete(v); } return null; }); return t; } /** * Wraps a Future as a Task or just casts it if it is already a Task. * <p>If future implements CompletionStage CompletionStage.handle will be used.</p> * <p> * If future is a plain old future, a runnable will executed using a default task pool. * This runnable will wait on the future using Future.get(timeout,timeUnit), with a timeout of 5ms. * Every time this task times out it will be rescheduled. * Starvation of the pool is prevented by the rescheduling behaviour. * </p> * * @param future the future to be wrapped or casted to Task * @return future cast as Task of a new Task that is dependent on the completion of that future. */ @SuppressWarnings("unchecked") public static <T> Task<T> fromFuture(Future<T> future) { if (future instanceof Task) { return (Task<T>) future; } if (future instanceof CompletionStage) { return from((CompletionStage<T>) future); } final Task<T> t = new Task<>(); if (future.isDone()) { try { t.internalComplete(future.get()); } catch (Throwable ex) { t.internalCompleteExceptionally(ex); } return t; } // potentially very expensive commonPool.execute(new TaskFutureAdapter<>(t, future, commonPool, 5, TimeUnit.MILLISECONDS)); return t; } /** * Returns a new task that will fail if the original is not completed withing the given timeout. * This doesn't modify the original task in any way. * * @param timeout the time from now * @param timeUnit the time unit of the timeout parameter * @return a new task */ public Task<T> failAfter(final long timeout, final TimeUnit timeUnit) { final Task<T> t = new Task<>(); // TODO: find a way to inject time for testing // also consider letting the application override this with the TaskContext final ScheduledFuture<?> rr = schedulerExecutor.schedule( () -> { // using t.isDone insteadof this.isDone // because the propagation of this.isDone can be delayed by slow listeners. if (!t.isDone()) { t.internalCompleteExceptionally(new TimeoutException()); } }, timeout, timeUnit); this.handle((T v, Throwable ex) -> { // removing the scheduled timeout to clear some memory rr.cancel(false); if (!t.isDone()) { if (ex != null) { t.internalCompleteExceptionally(ex); } else { t.internalComplete(v); } } return null; }); return t; } static class TaskFutureAdapter<T> implements Runnable { Task<T> task; Future<T> future; Executor executor; long waitTimeout; TimeUnit waitTimeoutUnit; public TaskFutureAdapter( final Task<T> task, final Future<T> future, final Executor executor, long waitTimeout, TimeUnit waitTimeoutUnit) { this.task = task; this.future = future; this.executor = executor; this.waitTimeout = waitTimeout; this.waitTimeoutUnit = waitTimeoutUnit; } public void run() { try { while (!task.isDone()) { try { task.internalComplete(future.get(waitTimeout, waitTimeoutUnit)); return; } catch (TimeoutException ex) { if (future.isDone()) { // in this case something completed the future with a timeout exception. try { task.internalComplete(future.get(waitTimeout, waitTimeoutUnit)); return; } catch (Throwable tex0) { task.internalCompleteExceptionally(tex0); } return; } try { // reschedule // potentially very expensive, might limit request throughput executor.execute(this); return; } catch (RejectedExecutionException rex) { // ignoring and continuing. // might potentially worsen an already starving system. // adding the redundant continue here to highlight the code path continue; } catch (Throwable tex) { task.internalCompleteExceptionally(tex); return; } } catch (Throwable ex) { task.internalCompleteExceptionally(ex); return; } } } catch (Throwable ex) { task.internalCompleteExceptionally(ex); } } } public static Task<Void> done() { final Task<Void> task = new Task<>(); task.internalComplete(NIL); return task; } @Override public <U> Task<U> thenApply(final Function<? super T, ? extends U> fn) { final Function<? super T, ? extends U> wrap = TaskContext.wrap(fn); return from(super.thenApply(wrap)); } @Override public Task<Void> thenAccept(final Consumer<? super T> action) { return from(super.thenAccept(TaskContext.wrap(action))); } @Override public Task<T> whenComplete(final BiConsumer<? super T, ? super Throwable> action) { return from(super.whenComplete(TaskContext.wrap(action))); } /** * Returns a new Task that is executed when this task completes normally. * The result of the new Task will be the result of the Supplier passed as parameter. * <p/> * See the {@link CompletionStage} documentation for rules * covering exceptional completion. * * @param supplier the Supplier that will provider the value * the returned Task * @param <U> the supplier's return type * @return the new Task */ public <U> Task<U> thenReturn(final Supplier<U> supplier) { // must be separated otherwise the execution of the wrap could happen in another thread final Supplier<U> wrap = TaskContext.wrap(supplier); return from(super.thenApply(x -> wrap.get())); } public <U> Task<U> thenCompose(Function<? super T, ? extends CompletionStage<U>> fn) { final Function<? super T, ? extends CompletionStage<U>> wrap = TaskContext.wrap(fn); return Task.from(super.thenCompose(wrap)); } public <U> Task<U> thenCompose(Supplier<? extends CompletionStage<U>> fn) { // must be separated otherwise the execution of the wrap could happen in another thread final Supplier<? extends CompletionStage<U>> wrap = TaskContext.wrap(fn); return Task.from(super.thenCompose((T x) -> wrap.get())); } @Override public <U> Task<U> handle(final BiFunction<? super T, Throwable, ? extends U> fn) { final BiFunction<? super T, Throwable, ? extends U> wrap = TaskContext.wrap(fn); return from(super.handle(wrap)); } @Override public Task<T> exceptionally(final Function<Throwable, ? extends T> fn) { return from(super.exceptionally(TaskContext.wrap(fn))); } @Override public Task<Void> thenRun(final Runnable action) { return from(super.thenRun(TaskContext.wrap(action))); } @Override public Task<java.lang.Void> acceptEither(CompletionStage<? extends T> completionStage, Consumer<? super T> consumer) { final Consumer<? super T> wrap = TaskContext.wrap(consumer); return Task.from(super.acceptEither(completionStage, wrap)); } @Override public Task<java.lang.Void> acceptEitherAsync(CompletionStage<? extends T> completionStage, Consumer<? super T> consumer) { final Consumer<? super T> wrap = TaskContext.wrap(consumer); return Task.from(super.acceptEitherAsync(completionStage, wrap)); } @Override public Task<java.lang.Void> acceptEitherAsync(CompletionStage<? extends T> completionStage, Consumer<? super T> consumer, Executor executor) { return Task.from(super.acceptEitherAsync(completionStage, TaskContext.wrap(consumer), executor)); } @Override public <U> Task<U> applyToEither(CompletionStage<? extends T> completionStage, Function<? super T, U> function) { return Task.from(super.applyToEither(completionStage, TaskContext.wrap(function))); } @Override public <U> Task<U> applyToEitherAsync(CompletionStage<? extends T> completionStage, Function<? super T, U> function, Executor executor) { return Task.from(super.applyToEitherAsync(completionStage, TaskContext.wrap(function), executor)); } @Override public <U> Task<U> applyToEitherAsync(CompletionStage<? extends T> completionStage, Function<? super T, U> function) { return Task.from(super.applyToEitherAsync(completionStage, TaskContext.wrap(function))); } @Override public <U> Task<U> handleAsync(BiFunction<? super T, java.lang.Throwable, ? extends U> biFunction, Executor executor) { final BiFunction<? super T, Throwable, ? extends U> wrap = TaskContext.wrap(biFunction); return Task.from(super.handleAsync(wrap, executor)); } @Override public <U> Task<U> handleAsync(BiFunction<? super T, java.lang.Throwable, ? extends U> biFunction) { final BiFunction<? super T, Throwable, ? extends U> wrap = TaskContext.wrap(biFunction); return Task.from(super.handleAsync(wrap)); } @Override public Task<java.lang.Void> runAfterBoth(CompletionStage<?> completionStage, Runnable runnable) { return Task.from(super.runAfterBoth(completionStage, TaskContext.wrap(runnable))); } @Override public Task<java.lang.Void> runAfterBothAsync(CompletionStage<?> completionStage, Runnable runnable) { return Task.from(super.runAfterBothAsync(completionStage, TaskContext.wrap(runnable))); } @Override public Task<java.lang.Void> runAfterBothAsync(CompletionStage<?> completionStage, Runnable runnable, Executor executor) { return Task.from(super.runAfterBothAsync(completionStage, TaskContext.wrap(runnable), executor)); } @Override public Task<java.lang.Void> runAfterEither(CompletionStage<?> completionStage, Runnable runnable) { return Task.from(super.runAfterEither(completionStage, TaskContext.wrap(runnable))); } @Override public Task<java.lang.Void> runAfterEitherAsync(CompletionStage<?> completionStage, Runnable runnable) { return Task.from(super.runAfterEitherAsync(completionStage, TaskContext.wrap(runnable))); } @Override public Task<java.lang.Void> runAfterEitherAsync(CompletionStage<?> completionStage, Runnable runnable, Executor executor) { return Task.from(super.runAfterEitherAsync(completionStage, TaskContext.wrap(runnable), executor)); } public static Task<java.lang.Void> runAsync(Runnable runnable) { return Task.from(CompletableFuture.runAsync(TaskContext.wrap(runnable))); } public static Task<java.lang.Void> runAsync(Runnable runnable, Executor executor) { return Task.from(CompletableFuture.runAsync(TaskContext.wrap(runnable), executor)); } public static <U> Task<U> supplyAsync(Supplier<U> supplier) { return Task.from(CompletableFuture.supplyAsync(TaskContext.wrap(supplier))); } public static <U> Task<U> supplyAsync(Supplier<U> supplier, Executor executor) { return Task.from(CompletableFuture.supplyAsync(TaskContext.wrap(supplier), executor)); } @Override public Task<java.lang.Void> thenAcceptAsync(Consumer<? super T> consumer, Executor executor) { return Task.from(super.thenAcceptAsync(TaskContext.wrap(consumer), executor)); } @Override public Task<java.lang.Void> thenAcceptAsync(Consumer<? super T> consumer) { return Task.from(super.thenAcceptAsync(TaskContext.wrap(consumer))); } @Override public <U> Task<java.lang.Void> thenAcceptBoth(CompletionStage<? extends U> completionStage, BiConsumer<? super T, ? super U> biConsumer) { return Task.from(super.thenAcceptBoth(completionStage, TaskContext.wrap(biConsumer))); } @Override public <U> Task<java.lang.Void> thenAcceptBothAsync(CompletionStage<? extends U> completionStage, BiConsumer<? super T, ? super U> biConsumer, Executor executor) { return Task.from(super.thenAcceptBothAsync(completionStage, TaskContext.wrap(biConsumer), executor)); } @Override public <U> Task<java.lang.Void> thenAcceptBothAsync(CompletionStage<? extends U> completionStage, BiConsumer<? super T, ? super U> biConsumer) { return Task.from(super.thenAcceptBothAsync(completionStage, TaskContext.wrap(biConsumer))); } @Override public <U> Task<U> thenApplyAsync(Function<? super T, ? extends U> function, Executor executor) { final Function<? super T, ? extends U> wrap = TaskContext.wrap(function); return Task.from(super.thenApplyAsync(wrap, executor)); } @Override public <U> Task<U> thenApplyAsync(Function<? super T, ? extends U> function) { final Function<? super T, ? extends U> wrap = TaskContext.wrap(function); return Task.from(super.thenApplyAsync(wrap)); } @Override public <U, V> Task<V> thenCombine(CompletionStage<? extends U> completionStage, BiFunction<? super T, ? super U, ? extends V> biFunction) { final BiFunction<? super T, ? super U, ? extends V> wrap = TaskContext.wrap(biFunction); return Task.from(super.thenCombine(completionStage, wrap)); } @Override public <U, V> Task<V> thenCombineAsync(CompletionStage<? extends U> completionStage, BiFunction<? super T, ? super U, ? extends V> biFunction, Executor executor) { final BiFunction<? super T, ? super U, ? extends V> wrap = TaskContext.wrap(biFunction); return Task.from(super.thenCombineAsync(completionStage, wrap, executor)); } @Override public <U, V> Task<V> thenCombineAsync(CompletionStage<? extends U> completionStage, BiFunction<? super T, ? super U, ? extends V> biFunction) { final BiFunction<? super T, ? super U, ? extends V> wrap = TaskContext.wrap(biFunction); return Task.from(super.thenCombineAsync(completionStage, wrap)); } @Override public <U> Task<U> thenComposeAsync(Function<? super T, ? extends java.util.concurrent.CompletionStage<U>> function, Executor executor) { final Function<? super T, ? extends CompletionStage<U>> wrap = TaskContext.wrap(function); return Task.from(super.thenComposeAsync(wrap, executor)); } @Override public <U> Task<U> thenComposeAsync(Function<? super T, ? extends java.util.concurrent.CompletionStage<U>> function) { final Function<? super T, ? extends CompletionStage<U>> wrap = TaskContext.wrap(function); return Task.from(super.thenComposeAsync(wrap)); } @Override public Task<java.lang.Void> thenRunAsync(Runnable runnable) { return Task.from(super.thenRunAsync(TaskContext.wrap(runnable))); } @Override public Task<java.lang.Void> thenRunAsync(Runnable runnable, Executor executor) { return Task.from(super.thenRunAsync(TaskContext.wrap(runnable), executor)); } @Override public Task<T> whenCompleteAsync(BiConsumer<? super T, ? super java.lang.Throwable> biConsumer) { return Task.from(super.whenCompleteAsync(TaskContext.wrap(biConsumer))); } @Override public Task<T> whenCompleteAsync(BiConsumer<? super T, ? super java.lang.Throwable> biConsumer, Executor executor) { return Task.from(super.whenCompleteAsync(TaskContext.wrap(biConsumer), executor)); } /** * @throws NullPointerException if the array or any of its elements are * {@code null} */ public static Task<Void> allOf(CompletableFuture<?>... cfs) { return from(CompletableFuture.allOf(cfs)); } /** * @throws NullPointerException if the collection or any of its elements are * {@code null} */ public static <F extends CompletableFuture<?>, C extends Collection<F>> Task<C> allOf(C cfs) { return from(CompletableFuture.allOf(cfs.toArray(new CompletableFuture[cfs.size()])) .thenApply(x -> cfs)); } /** * @throws NullPointerException if the stream or any of its elements are * {@code null} */ public static <F extends CompletableFuture<?>> Task<List<F>> allOf(Stream<F> cfs) { final List<F> futureList = cfs.collect(Collectors.toList()); @SuppressWarnings("rawtypes") final CompletableFuture[] futureArray = futureList.toArray(new CompletableFuture[futureList.size()]); return from(CompletableFuture.allOf(futureArray).thenApply(x -> futureList)); } /** * @throws NullPointerException if the array or any of its elements are * {@code null} */ public static Task<Object> anyOf(CompletableFuture<?>... cfs) { return from(CompletableFuture.anyOf(cfs)); } /** * @throws NullPointerException if the collection or any of its elements are * {@code null} */ public static <F extends CompletableFuture<?>> Task<Object> anyOf(Collection<F> cfs) { return from(CompletableFuture.anyOf(cfs.toArray(new CompletableFuture[cfs.size()]))); } /** * @throws NullPointerException if the stream or any of its elements are * {@code null} */ public static <F extends CompletableFuture<?>> Task<Object> anyOf(Stream<F> cfs) { return from(CompletableFuture.anyOf((CompletableFuture[]) cfs.toArray(size -> new CompletableFuture[size]))); } }
package ro.undef.patois; import android.R.color; import android.app.Activity; import android.content.res.Resources; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.widget.EditText; import android.widget.LinearLayout; import java.util.ArrayList; /** * Activity for editting the list of languages. */ public class EditLanguagesActivity extends Activity { private LinearLayout mLayout; private LayoutInflater mInflater; private PatoisDatabase mDb; private ArrayList<Language> mLanguages; /** * Called when the activity is first created. */ @Override public void onCreate(Bundle inState) { super.onCreate(inState); mInflater = getLayoutInflater(); setContentView(R.layout.edit_languages); mDb = new PatoisDatabase(this); mDb.open(); mLanguages = mDb.getLanguages(); mLayout = (LinearLayout) findViewById(R.id.list); buildViews(); } private void buildViews() { final LinearLayout layout = mLayout; layout.removeAllViews(); for (Language language : mLanguages) { layout.addView(buildViewForLanguage(language)); } // Add an empty language entry for new languages. // TODO: Maybe replace this with a "add language" button. layout.addView(buildViewForLanguage(null)); } private View buildViewForLanguage(final Language language) { View view = mInflater.inflate(R.layout.edit_language_entry, mLayout, false); EditText code_textbox = (EditText) view.findViewById(R.id.language_code); EditText name_textbox = (EditText) view.findViewById(R.id.language_name); if (language == null) { Resources res = getResources(); code_textbox.setText(res.getString(R.string.language_code)); code_textbox.setTextColor(res.getColor(android.R.color.tertiary_text_light)); name_textbox.setText(res.getString(R.string.language_name)); name_textbox.setTextColor(res.getColor(android.R.color.tertiary_text_light)); } else { code_textbox.setText(language.code); name_textbox.setText(language.name); } return view; } @Override protected void onSaveInstanceState(Bundle outState) { // TODO: Save the edits made by the user to outState. } }
package com.couchbase.lite; import com.couchbase.lite.listener.LiteListener; import com.couchbase.test.lite.*; import com.couchbase.lite.internal.Body; import com.couchbase.lite.replicator.Replication; import com.couchbase.lite.router.*; import com.couchbase.lite.router.Router; import com.couchbase.lite.storage.Cursor; import com.couchbase.lite.support.FileDirUtils; import com.couchbase.lite.util.Log; import junit.framework.Assert; import org.apache.commons.io.IOUtils; import org.codehaus.jackson.map.ObjectMapper; import org.codehaus.jackson.type.TypeReference; import java.io.ByteArrayInputStream; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.UUID; import java.util.concurrent.CountDownLatch; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; public abstract class LiteTestCase extends LiteTestCaseBase { public static final String TAG = "LiteTestCase"; private static boolean initializedUrlHandler = false; protected static LiteListener testListener = null; protected ObjectMapper mapper = new ObjectMapper(); protected Manager manager = null; protected Database database = null; protected String DEFAULT_TEST_DB = "cblite-test"; @Override protected void setUp() throws Exception { Log.v(TAG, "setUp"); super.setUp(); //for some reason a traditional static initializer causes junit to die if(!initializedUrlHandler) { URLStreamHandlerFactory.registerSelfIgnoreError(); initializedUrlHandler = true; } loadCustomProperties(); startCBLite(); startDatabase(); if (Boolean.parseBoolean(System.getProperty("LiteListener"))) { startListener(); } } protected InputStream getAsset(String name) { return this.getClass().getResourceAsStream("/assets/" + name); } protected void startCBLite() throws IOException { LiteTestContext context = new LiteTestContext(); Manager.enableLogging(Log.TAG, Log.VERBOSE); Manager.enableLogging(Log.TAG_SYNC, Log.VERBOSE); Manager.enableLogging(Log.TAG_QUERY, Log.VERBOSE); Manager.enableLogging(Log.TAG_VIEW, Log.VERBOSE); Manager.enableLogging(Log.TAG_CHANGE_TRACKER, Log.VERBOSE); Manager.enableLogging(Log.TAG_BLOB_STORE, Log.VERBOSE); Manager.enableLogging(Log.TAG_DATABASE, Log.VERBOSE); Manager.enableLogging(Log.TAG_LISTENER, Log.VERBOSE); Manager.enableLogging(Log.TAG_MULTI_STREAM_WRITER, Log.VERBOSE); Manager.enableLogging(Log.TAG_REMOTE_REQUEST, Log.VERBOSE); Manager.enableLogging(Log.TAG_ROUTER, Log.VERBOSE); manager = new Manager(context, Manager.DEFAULT_OPTIONS); } protected void stopCBLite() { if(manager != null) { manager.close(); } } protected void startListener() throws IOException, CouchbaseLiteException { // In theory we only set up the listener once across all tests because this mimics the behavior // of the sync gateway which was the original server these tests are run against which has a single // instance used all the time. But the other reason we only start the listener once is that // keeps the listener from stopping even when you tell it to stop. if (testListener == null) { LiteTestContext context = new LiteTestContext("testlistener"); Manager listenerManager = new Manager(context, Manager.DEFAULT_OPTIONS); listenerManager.getDatabase(getReplicationDatabase()); testListener = new LiteListener(listenerManager, getReplicationPort(), null); testListener.start(); } } protected Database startDatabase() throws CouchbaseLiteException { database = ensureEmptyDatabase(DEFAULT_TEST_DB); return database; } protected void stopDatabase() { if(database != null) { database.close(); } } protected Database ensureEmptyDatabase(String dbName) throws CouchbaseLiteException { Database db = manager.getExistingDatabase(dbName); if(db != null) { db.delete(); } db = manager.getDatabase(dbName); return db; } protected void loadCustomProperties() throws IOException { Properties systemProperties = System.getProperties(); InputStream mainProperties = getAsset("test.properties"); if(mainProperties != null) { systemProperties.load(mainProperties); } try { InputStream localProperties = getAsset("local-test.properties"); if(localProperties != null) { systemProperties.load(localProperties); } } catch (IOException e) { Log.w(TAG, "Error trying to read from local-test.properties, does this file exist?"); } } protected String getReplicationProtocol() { return System.getProperty("replicationProtocol"); } protected String getReplicationServer() { return System.getProperty("replicationServer"); } protected int getReplicationPort() { return Integer.parseInt(System.getProperty("replicationPort")); } protected String getReplicationAdminUser() { return System.getProperty("replicationAdminUser"); } protected String getReplicationAdminPassword() { return System.getProperty("replicationAdminPassword"); } protected String getReplicationDatabase() { return System.getProperty("replicationDatabase"); } protected URL getReplicationURL() { try { if(getReplicationAdminUser() != null && getReplicationAdminUser().trim().length() > 0) { return new URL(String.format("%s://%s:%s@%s:%d/%s", getReplicationProtocol(), getReplicationAdminUser(), getReplicationAdminPassword(), getReplicationServer(), getReplicationPort(), getReplicationDatabase())); } else { return new URL(String.format("%s://%s:%d/%s", getReplicationProtocol(), getReplicationServer(), getReplicationPort(), getReplicationDatabase())); } } catch (MalformedURLException e) { throw new IllegalArgumentException(e); } } protected boolean isTestingAgainstSyncGateway() { return getReplicationPort() == 4984; } protected URL getReplicationURLWithoutCredentials() throws MalformedURLException { return new URL(String.format("%s://%s:%d/%s", getReplicationProtocol(), getReplicationServer(), getReplicationPort(), getReplicationDatabase())); } @Override protected void tearDown() throws Exception { Log.v(TAG, "tearDown"); super.tearDown(); stopDatabase(); stopCBLite(); } protected Map<String,Object> userProperties(Map<String,Object> properties) { Map<String,Object> result = new HashMap<String,Object>(); for (String key : properties.keySet()) { if(!key.startsWith("_")) { result.put(key, properties.get(key)); } } return result; } public Map<String, Object> getReplicationAuthParsedJson() throws IOException { String authJson = "{\n" + " \"facebook\" : {\n" + " \"email\" : \"jchris@couchbase.com\"\n" + " }\n" + " }\n"; ObjectMapper mapper = new ObjectMapper(); Map<String,Object> authProperties = mapper.readValue(authJson, new TypeReference<HashMap<String,Object>>(){}); return authProperties; } public Map<String, Object> getPushReplicationParsedJson() throws IOException { Map<String,Object> authProperties = getReplicationAuthParsedJson(); Map<String,Object> targetProperties = new HashMap<String,Object>(); targetProperties.put("url", getReplicationURL().toExternalForm()); targetProperties.put("auth", authProperties); Map<String,Object> properties = new HashMap<String,Object>(); properties.put("source", DEFAULT_TEST_DB); properties.put("target", targetProperties); return properties; } public Map<String, Object> getPullReplicationParsedJson() throws IOException { Map<String,Object> authProperties = getReplicationAuthParsedJson(); Map<String,Object> sourceProperties = new HashMap<String,Object>(); sourceProperties.put("url", getReplicationURL().toExternalForm()); sourceProperties.put("auth", authProperties); Map<String,Object> properties = new HashMap<String,Object>(); properties.put("source", sourceProperties); properties.put("target", DEFAULT_TEST_DB); return properties; } protected URLConnection sendRequest(String method, String path, Map<String, String> headers, Object bodyObj) { try { URL url = new URL("cblite://" + path); URLConnection conn = (URLConnection)url.openConnection(); conn.setDoOutput(true); conn.setRequestMethod(method); if(headers != null) { for (String header : headers.keySet()) { conn.setRequestProperty(header, headers.get(header)); } } Map<String, List<String>> allProperties = conn.getRequestProperties(); if(bodyObj != null) { conn.setDoInput(true); ByteArrayInputStream bais = new ByteArrayInputStream(mapper.writeValueAsBytes(bodyObj)); conn.setRequestInputStream(bais); } Router router = new com.couchbase.lite.router.Router(manager, conn); router.start(); return conn; } catch (MalformedURLException e) { fail(); } catch(IOException e) { fail(); } return null; } protected Object parseJSONResponse(URLConnection conn) { Object result = null; Body responseBody = conn.getResponseBody(); if(responseBody != null) { byte[] json = responseBody.getJson(); String jsonString = null; if(json != null) { jsonString = new String(json); try { result = mapper.readValue(jsonString, Object.class); } catch (Exception e) { fail(); } } } return result; } protected Object sendBody(String method, String path, Object bodyObj, int expectedStatus, Object expectedResult) { URLConnection conn = sendRequest(method, path, null, bodyObj); Object result = parseJSONResponse(conn); Log.v(TAG, String.format("%s %s --> %d", method, path, conn.getResponseCode())); Assert.assertEquals(expectedStatus, conn.getResponseCode()); if(expectedResult != null) { Assert.assertEquals(expectedResult, result); } return result; } protected Object send(String method, String path, int expectedStatus, Object expectedResult) { return sendBody(method, path, null, expectedStatus, expectedResult); } public static void createDocuments(final Database db, final int n) { //TODO should be changed to use db.runInTransaction for (int i=0; i<n; i++) { Map<String,Object> properties = new HashMap<String,Object>(); properties.put("testName", "testDatabase"); properties.put("sequence", i); createDocumentWithProperties(db, properties); } }; static Future createDocumentsAsync(final Database db, final int n) { return db.runAsync(new AsyncTask() { @Override public void run(Database database) { db.beginTransaction(); createDocuments(db, n); db.endTransaction(true); } }); }; public static Document createDocumentWithProperties(Database db, Map<String,Object> properties) { Document doc = db.createDocument(); Assert.assertNotNull(doc); Assert.assertNull(doc.getCurrentRevisionId()); Assert.assertNull(doc.getCurrentRevision()); Assert.assertNotNull("Document has no ID", doc.getId()); // 'untitled' docs are no longer untitled (8/10/12) try{ doc.putProperties(properties); } catch( Exception e){ Log.e(TAG, "Error creating document", e); assertTrue("can't create new document in db:" + db.getName() + " with properties:" + properties.toString(), false); } Assert.assertNotNull(doc.getId()); Assert.assertNotNull(doc.getCurrentRevisionId()); Assert.assertNotNull(doc.getUserProperties()); // should be same doc instance, since there should only ever be a single Document instance for a given document Assert.assertEquals(db.getDocument(doc.getId()), doc); Assert.assertEquals(db.getDocument(doc.getId()).getId(), doc.getId()); return doc; } public static Document createDocWithAttachment(Database database, String attachmentName, String content) throws Exception { Map<String,Object> properties = new HashMap<String, Object>(); properties.put("foo", "bar"); Document doc = createDocumentWithProperties(database, properties); SavedRevision rev = doc.getCurrentRevision(); assertEquals(rev.getAttachments().size(), 0); assertEquals(rev.getAttachmentNames().size(), 0); assertNull(rev.getAttachment(attachmentName)); ByteArrayInputStream body = new ByteArrayInputStream(content.getBytes()); UnsavedRevision rev2 = doc.createRevision(); rev2.setAttachment(attachmentName, "text/plain; charset=utf-8", body); SavedRevision rev3 = rev2.save(); assertNotNull(rev3); assertEquals(rev3.getAttachments().size(), 1); assertEquals(rev3.getAttachmentNames().size(), 1); Attachment attach = rev3.getAttachment(attachmentName); assertNotNull(attach); assertEquals(doc, attach.getDocument()); assertEquals(attachmentName, attach.getName()); List<String> attNames = new ArrayList<String>(); attNames.add(attachmentName); assertEquals(rev3.getAttachmentNames(), attNames); assertEquals("text/plain; charset=utf-8", attach.getContentType()); InputStream attachInputStream = attach.getContent(); assertEquals(IOUtils.toString(attachInputStream, "UTF-8"), content); attachInputStream.close(); assertEquals(content.getBytes().length, attach.getLength()); return doc; } public void stopReplication(Replication replication) throws Exception { CountDownLatch replicationDoneSignal = new CountDownLatch(1); ReplicationStoppedObserver replicationStoppedObserver = new ReplicationStoppedObserver(replicationDoneSignal); replication.addChangeListener(replicationStoppedObserver); replication.stop(); boolean success = replicationDoneSignal.await(30, TimeUnit.SECONDS); assertTrue(success); // give a little padding to give it a chance to save a checkpoint Thread.sleep(2 * 1000); } public void runReplication(Replication replication) { CountDownLatch replicationDoneSignal = new CountDownLatch(1); ReplicationFinishedObserver replicationFinishedObserver = new ReplicationFinishedObserver(replicationDoneSignal); replication.addChangeListener(replicationFinishedObserver); replication.start(); CountDownLatch replicationDoneSignalPolling = replicationWatcherThread(replication); Log.d(TAG, "Waiting for replicator to finish"); try { boolean success = replicationDoneSignal.await(120, TimeUnit.SECONDS); assertTrue(success); success = replicationDoneSignalPolling.await(120, TimeUnit.SECONDS); assertTrue(success); Log.d(TAG, "replicator finished"); } catch (InterruptedException e) { e.printStackTrace(); } replication.removeChangeListener(replicationFinishedObserver); } public CountDownLatch replicationWatcherThread(final Replication replication) { final CountDownLatch doneSignal = new CountDownLatch(1); new Thread(new Runnable() { @Override public void run() { boolean started = false; boolean done = false; while (!done) { if (replication.isRunning()) { started = true; } final boolean statusIsDone = (replication.getStatus() == Replication.ReplicationStatus.REPLICATION_STOPPED || replication.getStatus() == Replication.ReplicationStatus.REPLICATION_IDLE); if (started && statusIsDone) { done = true; } try { Thread.sleep(500); } catch (InterruptedException e) { e.printStackTrace(); } } doneSignal.countDown(); } }).start(); return doneSignal; } public static class ReplicationFinishedObserver implements Replication.ChangeListener { public boolean replicationFinished = false; private CountDownLatch doneSignal; public ReplicationFinishedObserver(CountDownLatch doneSignal) { this.doneSignal = doneSignal; } @Override public void changed(Replication.ChangeEvent event) { Replication replicator = event.getSource(); Log.d(TAG, replicator + " changed. " + replicator.getCompletedChangesCount() + " / " + replicator.getChangesCount()); if (replicator.getCompletedChangesCount() < 0) { String msg = String.format("%s: replicator.getCompletedChangesCount() < 0", replicator); Log.d(TAG, msg); throw new RuntimeException(msg); } if (replicator.getChangesCount() < 0) { String msg = String.format("%s: replicator.getChangesCount() < 0", replicator); Log.d(TAG, msg); throw new RuntimeException(msg); } if (replicator.getCompletedChangesCount() > replicator.getChangesCount()) { String msg = String.format("replicator.getCompletedChangesCount() - %d > replicator.getChangesCount() - %d", replicator.getCompletedChangesCount(), replicator.getChangesCount()); Log.d(TAG, msg); throw new RuntimeException(msg); } if (!replicator.isRunning()) { replicationFinished = true; String msg = String.format("ReplicationFinishedObserver.changed called, set replicationFinished to: %b", replicationFinished); Log.d(TAG, msg); doneSignal.countDown(); } else { String msg = String.format("ReplicationFinishedObserver.changed called, but replicator still running, so ignore it"); Log.d(TAG, msg); } } boolean isReplicationFinished() { return replicationFinished; } } public static class ReplicationRunningObserver implements Replication.ChangeListener { private CountDownLatch doneSignal; public ReplicationRunningObserver(CountDownLatch doneSignal) { this.doneSignal = doneSignal; } @Override public void changed(Replication.ChangeEvent event) { Replication replicator = event.getSource(); if (replicator.isRunning()) { doneSignal.countDown(); } } } public static class ReplicationIdleObserver implements Replication.ChangeListener { private CountDownLatch doneSignal; public ReplicationIdleObserver(CountDownLatch doneSignal) { this.doneSignal = doneSignal; } @Override public void changed(Replication.ChangeEvent event) { Replication replicator = event.getSource(); if (replicator.getStatus() == Replication.ReplicationStatus.REPLICATION_IDLE) { doneSignal.countDown(); } } } public static class ReplicationStoppedObserver implements Replication.ChangeListener { private CountDownLatch doneSignal; public ReplicationStoppedObserver(CountDownLatch doneSignal) { this.doneSignal = doneSignal; } @Override public void changed(Replication.ChangeEvent event) { Replication replicator = event.getSource(); if (replicator.getStatus() == Replication.ReplicationStatus.REPLICATION_STOPPED) { doneSignal.countDown(); } } } public static class ReplicationErrorObserver implements Replication.ChangeListener { private CountDownLatch doneSignal; public ReplicationErrorObserver(CountDownLatch doneSignal) { this.doneSignal = doneSignal; } @Override public void changed(Replication.ChangeEvent event) { Replication replicator = event.getSource(); if (replicator.getLastError() != null) { doneSignal.countDown(); } } } public void dumpTableMaps() throws Exception { Cursor cursor = database.getDatabase().rawQuery( "SELECT * FROM maps", null); while (cursor.moveToNext()) { int viewId = cursor.getInt(0); int sequence = cursor.getInt(1); byte[] key = cursor.getBlob(2); String keyStr = null; if (key != null) { keyStr = new String(key); } byte[] value = cursor.getBlob(3); String valueStr = null; if (value != null) { valueStr = new String(value); } Log.d(TAG, String.format("Maps row viewId: %s seq: %s, key: %s, val: %s", viewId, sequence, keyStr, valueStr)); } } public void dumpTableRevs() throws Exception { Cursor cursor = database.getDatabase().rawQuery( "SELECT * FROM revs", null); while (cursor.moveToNext()) { int sequence = cursor.getInt(0); int doc_id = cursor.getInt(1); byte[] revid = cursor.getBlob(2); String revIdStr = null; if (revid != null) { revIdStr = new String(revid); } int parent = cursor.getInt(3); int current = cursor.getInt(4); int deleted = cursor.getInt(5); Log.d(TAG, String.format("Revs row seq: %s doc_id: %s, revIdStr: %s, parent: %s, current: %s, deleted: %s", sequence, doc_id, revIdStr, parent, current, deleted)); } } public static SavedRevision createRevisionWithRandomProps(SavedRevision createRevFrom, boolean allowConflict) throws Exception { Map<String, Object> properties = new HashMap<String, Object>(); properties.put(UUID.randomUUID().toString(), "val"); UnsavedRevision unsavedRevision = createRevFrom.createRevision(); unsavedRevision.setUserProperties(properties); return unsavedRevision.save(allowConflict); } }
package com.plpatterns.status; import static org.apache.commons.lang.StringUtils.isBlank; import java.util.Calendar; import java.util.Date; import java.util.Iterator; import java.util.LinkedList; import java.util.concurrent.Callable; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.commons.lang.ObjectUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.log4j.AppenderSkeleton; import org.apache.log4j.spi.LoggingEvent; import org.jivesoftware.smack.Chat; import org.jivesoftware.smack.ChatManagerListener; import org.jivesoftware.smack.ConnectionConfiguration; import org.jivesoftware.smack.MessageListener; import org.jivesoftware.smack.SASLAuthentication; import org.jivesoftware.smack.XMPPConnection; import org.jivesoftware.smack.packet.Message; /** * @author Jonathan Tran */ public class XmppAppender extends AppenderSkeleton { private static final Log LOG = LogFactory.getLog(XmppAppender.class); private static final int MAX_CONVERSATIONS = 50; //public static String TOP_LEVEL_LOGGER_NAME = "status"; // TODO: {change this to a timestamp, and retry after a while. Ideally, // exponential back-off.} private boolean _notificationFailedRecently; private String _serverHostname; private int _serverPort; private String _serviceName; private ConnectionConfiguration _conConfig; private String _fromAddress; private String _password; private String _resource; private XMPPConnection _con; private LinkedList<Conversation> _conversations = new LinkedList<Conversation>(); public XmppAppender() { // Default constructor for log4j. LOG.warn("XMPP Appender created"); } public XmppAppender(String serverHostname, int serverPort, String serviceName, String fromAddress, String password, String resource) { this(new ConnectionConfiguration(serverHostname, serverPort, serviceName), fromAddress, password, resource); } public XmppAppender(ConnectionConfiguration conConfig, String fromAddress, String password, String resource) { _conConfig = conConfig; _fromAddress = fromAddress; _password = password; _resource = resource; LOG.warn("XMPP Appender created with good constructor!"); } public void connect() { LOG.warn("Trying to connect..."); // Must synchronize since this gets called from multiple threads. synchronized (this) { XMPPConnection con = getConnection(); if (con == null) { LOG.debug("created new XMPPConnection object"); con = new XMPPConnection(getConnectionConfiguration()); setConnection(con); } LOG.warn("Authenticated? " + con.isAuthenticated() + " con: " + _con); if (con.isAuthenticated()) return; try { // Connect to server. LOG.warn("Connecting..."); con.connect(); // Add listener to capture IMs sent to us. LOG.warn("Adding chat listener..."); con.getChatManager().addChatListener(new XmppChatManagerListener()); // Login. LOG.warn("Logging in..."); SASLAuthentication.supportSASLMechanism("PLAIN", 0); con.login(getFromAddress(), getPassword(), getResource()); LOG.warn("Logged in! Authenticated? " + con.isAuthenticated()); } catch (Throwable t) { LOG.warn("connecting and logging in to XMPP server failed using connection configuration host: " + _conConfig.getHost() + " port: " + _conConfig.getPort() + " serviceName: " + _conConfig.getServiceName(), t); setNotificationFailedRecently(true); } } } @Override public void close() { if (getConnection() != null) { LOG.debug("Disconnecting..."); getConnection().disconnect(); } } @Override protected void append(LoggingEvent event) { if (!shouldNotify()) return; String msg = getMessage(event); if (isBlank(msg)) return; // Return if we have not connected or logged in yet. if (getConnection() == null || !getConnection().isAuthenticated()) { if (LOG.isDebugEnabled()) { LOG.debug(String.format( "Dropping notification since we are not authenticated. Did you remember to call connect()? If you did call connect(), this could be a connection problem with the server. msg: %s, conConfig", msg, _conConfig)); } return; } // TODO: Should the failure of one message prevent the others from being attempted? try { // Send notification to all conversations. for (Conversation conversation : getConversations()) { if (!conversation.shouldNotify()) continue; // Send the IM. conversation.sendIm(msg, true); } } catch (Throwable t) { // We had an error in sending the message. Don't try to send again. setNotificationFailedRecently(true); } } /** * Gets the message of an event. If the message is a {@link Callable}, calls * it and returns {@code toString()} of the result. Otherwise simply calls * {@code toString()} of the message. */ private static String getMessage(LoggingEvent event) { Object msg = event.getMessage(); if (msg instanceof Callable) { try { return ObjectUtils.toString(((Callable<?>)msg).call()); } catch (Throwable t) { return ""; } } return ObjectUtils.toString(msg); } /** * As far as I understand, there is no way using log4j to know when all the * properties have been set and there is no initialize method that is called. * So we have to require that all properties be set and when they are, then * connect. */ private void attemptToConnect() { LOG.warn("Attempting to connect...."); if (// No connection configuration getConnectionConfiguration() == null && (getServerHostname() == null || getServerPort() == 0 || getServiceName() == null || getFromAddress() == null || getPassword() == null || getResource() == null) || // Already logged in. getConnection() != null && getConnection().isAuthenticated()) { return; } try { if (getConnectionConfiguration() == null) { setConnectionConfiguration(new ConnectionConfiguration( getServerHostname(), getServerPort(), getServiceName())); } connect(); } catch (Throwable t) { LOG.error(t); } } public LinkedList<Conversation> getConversations() { return _conversations; } public XMPPConnection getConnection() { return _con; } private void setConnection(XMPPConnection con) { _con = con; } public ConnectionConfiguration getConnectionConfiguration() { return _conConfig; } public void setConnectionConfiguration(ConnectionConfiguration conConfig) { _conConfig = conConfig; // Refresh connection. close(); setConnection(null); attemptToConnect(); } public boolean getNotificationFailedRecently() { return _notificationFailedRecently; } public void setNotificationFailedRecently(boolean notificationFailedRecently) { _notificationFailedRecently = notificationFailedRecently; } public String getServerHostname() { return _serverHostname; } public void setServerHostname(String serverHostname) { _serverHostname = serverHostname; attemptToConnect(); } public int getServerPort() { return _serverPort; } public void setServerPort(int serverPort) { _serverPort = serverPort; attemptToConnect(); } public String getServiceName() { return _serviceName; } public void setServiceName(String serviceName) { _serviceName = serviceName; attemptToConnect(); } public String getFromAddress() { return _fromAddress; } public void setFromAddress(String fromAddress) { _fromAddress = fromAddress; attemptToConnect(); } public String getPassword() { return _password; } public void setPassword(String password) { _password = password; attemptToConnect(); } public String getResource() { return _resource; } public void setResource(String resource) { _resource = resource; attemptToConnect(); } public boolean shouldNotify() { return !getNotificationFailedRecently(); } @Override public boolean requiresLayout() { return false; } private Conversation removeConversation(String participant) { Iterator<Conversation> it = getConversations().iterator(); while (it.hasNext()) { Conversation convo = it.next(); if (participant.equals(convo.getChat().getParticipant())) { it.remove(); return convo; } } return null; } /** * Formats the given milliseconds into a human-readable amount. * * @param millis must be greater than zero. */ private static String formatPeriod(long millis) { double seconds = millis / 1000.0d; double minutes = seconds / 60.0d; double hours = minutes / 60.0d; if (hours >= 10d) return String.format("%d hours", Math.round(hours)); if (hours > 1d) return String.format("%.1f hours", hours); if (hours == 1d) return "hour"; if (minutes >= 2d) return String.format("%d minutes", Math.round(minutes)); if (minutes > 1d) return String.format("%.1f minutes", minutes); if (minutes == 1d) return "minute"; if (seconds >= 2d) return String.format("%d seconds", Math.round(seconds)); if (seconds > 1d) return String.format("%.1f seconds", seconds); if (seconds == 1d) return "second"; if (millis > 1 ) return String.format("%d milliseconds", millis); return "millisecond"; } private class XmppChatManagerListener implements ChatManagerListener { public void chatCreated(Chat chat, boolean createdLocally) { LOG.debug("chatCreated chat.participant: " + chat.getParticipant() + " chat.threadID: " + chat.getThreadID() + " createdLocally: " + createdLocally); chat.addMessageListener(new XmppMessageListener()); } } private class XmppMessageListener implements MessageListener { /** I wanted this to last over a long weekend, so it is {@value} */ private static final int MAX_DAYS_TO_NOTIFY_OF_EVICTION = 4; /** * Event fired whenever we receive an IM. */ public void processMessage(Chat chat, Message message) { LOG.debug("processMessage chat.threadID: " + chat.getThreadID() + " message.from: " + message.getFrom() + " message.body: " + message.getBody() + " message.subject: " + message.getSubject() + " message: " + message); Conversation convo; boolean newConvo = false; Conversation oldConvo = null; try { // To allow this to be called from multiple threads, we must lock the // conversations when we muck with them. LOG.debug("getting lock on conversations..."); synchronized (getConversations()) { LOG.debug("got lock on conversations"); // Get the conversation. convo = removeConversation(chat.getParticipant()); if (convo == null) { LOG.debug("new conversation with participant " + chat.getParticipant()); convo = new Conversation(chat); newConvo = true; } // Add this conversation to the front of the list. getConversations().addFirst(convo); // Evict old conversations. LOG.debug("number of conversations: " + getConversations().size()); if (getConversations().size() > MAX_CONVERSATIONS) { oldConvo = getConversations().removeLast(); } } // Track when we've heard from this person. LOG.debug("setting last heard from..."); convo.setLastHeardFrom(new Date()); // Process the message itself. reactToIm(convo, newConvo, message); // Let the person know we're evicting them. if (oldConvo != null) { // Don't send this if we haven't heard from this person in a long time. Calendar cal = Calendar.getInstance(); cal.add(Calendar.DATE, -MAX_DAYS_TO_NOTIFY_OF_EVICTION); if (oldConvo.getLastHeardFrom().after(cal.getTime())) { oldConvo.sendIm("I'm holding a conversation with " + MAX_CONVERSATIONS + " other people, so I'll talk to you later."); } } } catch (Throwable t) { LOG.error(t); } } /** * This function processes commands in an incoming message. The responses * are purposely lower-case and casual form to mimic the way people usually * type IMs. To a user, it shouldn't feel like they are talking to a bot, * but rather someone on the other end helping them. */ private void reactToIm(Conversation convo, boolean newConvo, Message message) { String msg = message.getBody(); LOG.debug("reacting to IM... convo: " + convo + " newConvo: " + newConvo + " msg: " + msg); if (isBlank(msg)) return; if (msg.equalsIgnoreCase("pause") || msg.equalsIgnoreCase("stop")) { convo.setPaused(true); } else if (msg.equalsIgnoreCase("resume") || msg.equalsIgnoreCase("start")) { convo.sendIm("i'll start sending updates every " + formatPeriod(convo.getMinMillisecondsBetweenMessages())); convo.setPaused(false); } else if (msg.startsWith("every ")) { // Change the period at which IMs are sent. final String iDontUnderstand = "I don't understand. If you'd rather I sent you IMs more often or less often, just let me know by saying \"every 5 minutes\", for example."; final Pattern everyPattern = Pattern.compile("every\\s+(\\w+)\\s+(\\w+)\\s*"); // Try to match the basic format. LOG.debug("Trying to parse change in interval."); Matcher matcher = everyPattern.matcher(msg); if (!matcher.matches()) { convo.sendIm(iDontUnderstand); return; } // Try to parse the number and units. LOG.debug("Basic structure found. Trying to parse number and unit."); String strNumber = matcher.group(1).toLowerCase(); String strUnits = matcher.group(2).toLowerCase(); Double num = Double.valueOf(strNumber); if (num == null || !strUnits.startsWith("s") && !strUnits.startsWith("m")) { convo.sendIm(iDontUnderstand); return; } // Convert to milliseconds. LOG.debug("Interval found: " + num + " " + strUnits); if (strUnits.startsWith("m")) { num *= 60d; } num *= 1000d; long period = Math.round(num); // Prevent people from setting this too low. period = Math.max(period, 500); // Set new period. convo.sendIm("ok, i'll send updates every " + formatPeriod(period)); convo.setMinMillisecondsBetweenMessages(period); } else if (msg.startsWith("echo")) { convo.sendIm(msg); } else if (newConvo) { convo.sendIm("hi, i'll start sending updates every " + formatPeriod(convo.getMinMillisecondsBetweenMessages())); } else { convo.sendIm("huh? the commands I understand are: start, stop, every N s[econds], every N m[inutes]."); } } } }
package api.web.gw2.mapping.core; import api.web.gw2.mapping.v2.account.wallet.CurrencyAmount; import java.io.IOException; import java.io.InputStream; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Type; import java.net.MalformedURLException; import java.net.URL; import java.time.Duration; import java.time.ZonedDateTime; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Currency; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.OptionalDouble; import java.util.OptionalInt; import java.util.ServiceLoader; import java.util.Set; import java.util.logging.Level; import java.util.logging.Logger; abstract class JsonpAbstractMarshaller { /** * The logger instance. */ protected final Logger logger = Logger.getLogger(getClass().getName()); /** * Creates a new empty instance. */ public JsonpAbstractMarshaller() { } /** * Load an object from JSON. * @param <T> The type to use. * @param targetClass The target class. * @param input The source stream. * @return A {@code T} instance, may be {@code null}. * @throws NullPointerException If {@code targetClass} or {@code input} is {@code null}/ * @throws IOException In case of IO error. */ public abstract <T> T loadObject(final Class<T> targetClass, final InputStream input) throws NullPointerException, IOException; /** * Load a collection from JSON. * @param <T> The type to use. * @param targetClass The target class. * @param input The source stream. * @return A {@code Collection<T>} instance, may be {@code null}. * @throws NullPointerException If {@code targetClass} or {@code input} is {@code null}/ * @throws IOException In case of IO error. */ public abstract <T> Collection<T> loadObjectArray(final Class<T> targetClass, final InputStream input) throws IOException; /** * Load a runtime object from JSON. * @param <T> The type to use. * @param selector The name of the selector value. * @param pattern The pattern which allows to construct the class name. * @param input The source stream. * @return A {@code T} instance, may be {@code null}. * @throws NullPointerException If {@code targetClass} or {@code input} is {@code null}/ * @throws IOException In case of IO error. */ public abstract <T> T loadRuntimeObject(final String selector, final String pattern, final InputStream input) throws IOException; /** * Creates a concrete instance of the desired interface using the {@code ServiceManager}. * @param <T> The target type. * @param targetClass The target class. * @return A {@code T} instance, may be {@code null}. */ protected final <T> T createConcreteEmptyInstance(final Class<T> targetClass) { // Get service loader for target class. final ServiceLoader serviceLoader = ServiceLoader.load(targetClass); // Get concrete instance for target class. final Iterator<T> iterator = serviceLoader.iterator(); T result = null; while (iterator.hasNext()) { if (result == null) { result = (T) iterator.next(); } } return result; } /** * Tries to locate given field in selected class or it's ancestor classes. * @param fieldName The field name. * @param targetClass The target class. * @return A {@code Field} instance, may be {@code null} if field was not found. */ protected final Field lookupField(final String fieldName, final Class targetClass) { Field field = null; for (Class aClass = targetClass; aClass != null && field == null; aClass = aClass.getSuperclass()) { try { field = aClass.getDeclaredField(fieldName); } catch (NoSuchFieldException ex) { logger.log(Level.FINEST, "Could not find field \"{0}\" in class {1}, attenpting to use class hierachy.", new Object[]{fieldName, targetClass}); } } return field; } /** * Converts a JSON key into a Java field name. * @param key The JSON key. * @return A {@code String}, never {@code null}. * @throws NullPointerException If {@code key} is {@code null}. */ protected static final String jsonKeyToJavaFieldName(final String key) throws NullPointerException { Objects.requireNonNull(key); final String[] tokens = key.split("_"); // NOI18N. final StringBuilder buffer = new StringBuilder(key.length()); buffer.append(tokens[0]); Arrays.stream(tokens, 1, tokens.length) .forEach(token -> { final String head = token.substring(0, 1).toUpperCase(); final String tail = token.substring(1, token.length()); buffer.append(head); buffer.append(tail); }); return buffer.toString(); } /** * Convert an enum value to a proper Java class name (by removing '_' and setting the proper letter case). * @param value The source enum value. * @return A {@code String} instance, never {@code null}. * @throws NullPointerException If {@code value} is {@code null}. */ protected static final String javaEnumToJavaClassName(final Enum value) throws NullPointerException { Objects.requireNonNull(value); final String name = value.name().toLowerCase(); final String[] tokens = name.split("_"); // NOI18N. final StringBuilder buffer = new StringBuilder(name.length()); Arrays.stream(tokens) .forEach(token -> { String head = token.substring(0, 1).toUpperCase(); String tail = token.substring(1, token.length()); buffer.append(head); buffer.append(tail); }); return buffer.toString(); } /** * Gets the default value for given field. * <br/>This method is usually called when encountering a {@code null} value. * @param field The field on which the value will be set. * @return An {@code Object} instance, may be {@code null}. * <br/>The value to return will be determined from the annotations and the class of the target field. * @throws NullPointerException If {@code field} is {@code null}. */ protected final Object defaultValueForField(final Field field) throws NullPointerException { Objects.requireNonNull(field); final Type fieldType = field.getType(); boolean isOptional = field.getAnnotation(OptionalValue.class) != null; boolean isId = field.getAnnotation(IdValue.class) != null; boolean isLevel = field.getAnnotation(LevelValue.class) != null; boolean isCurrency = field.getAnnotation(CoinValue.class) != null; // boolean isDistance = field.getAnnotation(DistanceValue.class) != null; boolean isLocalizedResource = field.getAnnotation(LocalizedResource.class) != null; boolean isQuantity = field.getAnnotation(QuantityValue.class) != null; boolean isDate = field.getAnnotation(DateValue.class) != null; boolean isDuration = field.getAnnotation(DurationValue.class) != null; boolean isURL = field.getAnnotation(URLValue.class) != null; boolean isPercent = field.getAnnotation(PercentValue.class) != null; boolean isList = field.getAnnotation(ListValue.class) != null; boolean isSet = field.getAnnotation(SetValue.class) != null; boolean isMap = field.getAnnotation(MapValue.class) != null; boolean isCoord2D = field.getAnnotation(Coord2DValue.class) != null; boolean isCoord3D = field.getAnnotation(Coord3DValue.class) != null; Object result = null; // Use the annotation of the field. if (isOptional) { if (isList || isSet || isMap) { result = Optional.empty(); } else if (isQuantity || isLevel) { result = OptionalInt.empty(); } else if (isPercent) { result = OptionalDouble.empty(); } else if (isId) { final boolean isIntegerId = field.getAnnotation(IdValue.class).flavor() == IdValue.Flavor.INTEGER; result = isIntegerId ? OptionalInt.empty() : Optional.empty(); } else { result = Optional.empty(); } } else if (isLevel) { result = LevelValue.MIN_LEVEL; } else if (isCurrency) { result = CoinAmount.ZERO; // } else if (isDistance) { // result = QuantityAmount.ZERO; } else if (isCoord2D) { result = Point2D.ORIGIN; } else if (isCoord3D) { result = Point3D.ORIGIN; } else if (isQuantity) { result = 0; // result = DistanceAmount.ZERO; } else if (isDate) { result = DateValue.DEFAULT; } else if (isDuration) { result = Duration.ZERO; } // Now use the class of the field. else if (isLocalizedResource || fieldType == String.class) { result = ""; // NOI8N. } else if (fieldType == Integer.TYPE) { result = 0; } else if (fieldType == Long.TYPE) { result = 0L; } else if (fieldType == Float.TYPE) { result = 0F; } else if (fieldType == Double.TYPE) { result = 0D; } else if (fieldType == Boolean.TYPE) { result = Boolean.FALSE; } else if (isSet || fieldType == Set.class) { result = Collections.EMPTY_SET; } else if (isList || fieldType == List.class) { result = Collections.EMPTY_LIST; } else if (isMap || fieldType == Map.class) { result = Collections.EMPTY_MAP; } return result; } /** * Convert a value obtained from JSON to value that can suit the target field. * <br/>This method is called before setting a value into a field. * @param field The target field. * @param value The value obtained from JSON. * @return An {@code Object}, may be [@code null}. * <br/>The value to return will be determined from the annotations and the class of the target field. * @throws NullPointerException If {@code field} is {@code null}. * @throws MalformedURLException If URL cannot be parsed from input object. */ protected final Object valueForField(final Field field, final Object value) throws NullPointerException, MalformedURLException, IllegalAccessException, IllegalArgumentException, NoSuchMethodException, InvocationTargetException, ClassNotFoundException { Objects.requireNonNull(field); // @todo Not all types used yet. boolean isOptional = field.getAnnotation(OptionalValue.class) != null; boolean isId = field.getAnnotation(IdValue.class) != null; boolean isLevel = field.getAnnotation(LevelValue.class) != null; boolean isCurrency = field.getAnnotation(CoinValue.class) != null; // boolean isDistance = field.getAnnotation(DistanceValue.class) != null; boolean isLocalizedResource = field.getAnnotation(LocalizedResource.class) != null; boolean isQuantity = field.getAnnotation(QuantityValue.class) != null; boolean isDate = field.getAnnotation(DateValue.class) != null; boolean isDuration = field.getAnnotation(DurationValue.class) != null; boolean isURL = field.getAnnotation(URLValue.class) != null; boolean isPercent = field.getAnnotation(PercentValue.class) != null; boolean isList = field.getAnnotation(ListValue.class) != null; boolean isSet = field.getAnnotation(SetValue.class) != null; boolean isMap = field.getAnnotation(MapValue.class) != null; boolean isEnum = field.getAnnotation(EnumValue.class) != null; boolean isCoord2D = field.getAnnotation(Coord2DValue.class) != null; boolean isCoord3D = field.getAnnotation(Coord3DValue.class) != null; Object result = value; // Base types. if (isOptional && value == null) { result = null; } else if (isURL) { final String path = (String) value; result = new URL(path); } else if (isDuration) { final Number number = (Number) value; // @todo In game, some skill cast time can be 3/4 seconds. Need to check if it's the same for buffs. final int quantity = number.intValue(); final DurationValue durationValueAnnotation = field.getAnnotation(DurationValue.class); final DurationValue.Flavor flavor = durationValueAnnotation.flavor(); switch (flavor) { case MILLIS: { result = Duration.ofMillis(quantity); } break; case SECONDS: default: { result = Duration.ofSeconds(quantity); } } } else if (isDate) { final String string = (String) value; result = ZonedDateTime.parse(string); } else if (isList) { final List list = (List) value; result = Collections.unmodifiableList(list); } else if (isSet) { final Set set = new HashSet((List) value); result = Collections.unmodifiableSet(set); } else if (isMap) { final Map map = (Map) value; result = Collections.unmodifiableMap(map); } else if (isCurrency) { final Number number = (Number) value; result = CoinAmount.ofCopper(number.intValue()); } else if (isCoord2D) { final List<? extends Number> list = (List) value; final double x = list.get(0).doubleValue(); final double y = list.get(1).doubleValue(); result = new Point2D(x, y); } else if (isCoord3D) { final List<? extends Number> list = (List) value; final double x = list.get(0).doubleValue(); final double y = list.get(1).doubleValue(); final double z = list.get(2).doubleValue(); result = new Point3D(x, y, z); } // As we rely heavily on enums, we need to convert base types obtained from JSON into valid enum values. if (isEnum) { // Do a second pass on the collection to marshall its content into enum values. if (isSet || isList) { final Collection<?> source = (Collection) result; final List destination = new ArrayList(source.size()); // Cannot use stream because of exceptions raised in marshallEnumValue(). for (final Object v : source) { final Object target = marshallEnumValue(field, v); destination.add(target); } result = (isList) ? Collections.unmodifiableList(destination) : Collections.unmodifiableSet(new HashSet(destination)); } // @todo What about maps? // Single value. else { result = marshallEnumValue(field, value); } } // Wrap the result into an Optional instance. // Provided default values may already be wrapped into Optional instances. if (isOptional && !(result instanceof Optional || result instanceof OptionalInt)) { if (isList || isSet || isMap) { result = Optional.ofNullable(result); } else if (isQuantity || isLevel) { result = OptionalInt.of((Integer) result); } else if (isPercent) { result = OptionalDouble.of((Double) result); } else if (isId) { final boolean isIntegerId = field.getAnnotation(IdValue.class).flavor() == IdValue.Flavor.INTEGER; result = isIntegerId ? OptionalInt.of((Integer) result) : Optional.ofNullable(result); } else { result = Optional.ofNullable(result); } } // LOGGER.log(Level.INFO, "{0} declaring class: {1}", new Object[]{field.getName(), field.getDeclaringClass()}); // LOGGER.log(Level.INFO, "{0} type: {1}", new Object[]{field.getName(), field.getType()}); // LOGGER.log(Level.INFO, "{0} annotated type: {1}", new Object[]{field.getName(), field.getAnnotatedType()}); // LOGGER.log(Level.INFO, "{0} value returned as: {1} ({2})", new Object[]{field.getName(), result, result.getClass()}); return result; } protected final Object marshallEnumValue(final Field field, final Object value) throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { Objects.requireNonNull(field); Objects.requireNonNull(value); // For simple field this should be the enum type. // The class obtained here is not good when the field holds an optional or a collection. Class enumClass = field.getType(); final boolean isList = field.getAnnotation(ListValue.class) != null; final boolean isSet = field.getAnnotation(SetValue.class) != null; final boolean isMap = field.getAnnotation(MapValue.class) != null; final boolean isOptional = field.getAnnotation(OptionalValue.class) != null; if (isList || isSet || isMap || isOptional) { final Class[] classes = findClassesForField(field); enumClass = classes[0]; } // Will not work if value is not of the proper type (usually String or integer). final Object result = EnumValueFactory.INSTANCE.mapEnumValue(enumClass, value); Objects.requireNonNull(result); // Issue a warning if the value returned is the unkown value. if ("UNKOWN".equals(((Enum) result).name())) { // NOI18N. logger.log(Level.WARNING, "Field \"{0}\": unable to marshall enum value \"{1}\", defaulting to value \"{2}\" instead.", new Object[]{field.getName(), value, result}); // NOI18N. } logger.log(Level.FINEST, "Field \"{0}\": marshalled enum value \"{1}\" into value \"{2}\".", new Object[]{field.getName(), value, result}); // NOI18N. return result; } /** * Common method used to retrieve proper class(es) for a given field. * <br>Classes for the fields are determined by the annotations set on this field. * <br>Currently this method is able to process the following annotations: * <ul> * <li>{@code OptionalValue}</li> * <li>{@code ListValue}</li> * <li>{@code SetValue}</li> * <li>{@code MapValue}</li> * </ul> * @param field The source field. * @return A {@code Class[]} instance, never {@code null} * <br>If the given field is marked with the {@code MapValue} annotation, the array will be of size 2: * <ul> * <li>Class at index 0 is the class of the keys to the map.</li> * <li>Class at index 1 is the class of the values to the map.</li> * </ul> * Otherwise the array returned will be of size 1. * @throws ClassNotFoundException If one of the target classes cannot be found. * @throws NullPointerException If {@code field} is {@code null}. * @see OptionalValue * @see ListValue * @see SetValue * @see MapValue */ protected Class[] findClassesForField(final Field field) throws ClassNotFoundException, NullPointerException { Objects.requireNonNull(field); // @todo Find interface class. // @todo Check the validity this. final boolean isList = field.getAnnotation(ListValue.class) != null; final boolean isSet = field.getAnnotation(SetValue.class) != null; final boolean isMap = field.getAnnotation(MapValue.class) != null; final boolean isOptional = field.getAnnotation(OptionalValue.class) != null; String typename = field.getGenericType().getTypeName(); if (isOptional) { typename = typename.replaceAll("java\\.util\\.Optional<", ""); // NOI18N. } if (isSet) { typename = typename.replaceAll("java\\.util\\.Set<", ""); // NOI18N. } if (isList) { typename = typename.replaceAll("java\\.util\\.List<", ""); // NOI18N. } if (isMap) { typename = typename.replaceAll("java\\.util\\.Map<", ""); // NOI18N. } // Remove trailing >. typename = typename.replaceAll(">+", ""); // NOI18N. final String[] subTargetClassNames = typename.split(",\\s*"); final Class[] subTargetClasses = new Class[subTargetClassNames.length]; for (int index = 0; index < subTargetClassNames.length; index++) { subTargetClasses[index] = Class.forName(subTargetClassNames[index]); } return subTargetClasses; } /** * Logs a warning about a missing field. * @param key The source key from the JSON. * @param fieldName The name of the target field that is missing. * @param targetClass The target class. */ protected final void logWarningMissingField(final String key, final String fieldName, final Class targetClass) { final String message = String.format("No matching field \"%s\" found for JSON key \"%s\" in class %s.", fieldName, key, targetClass.getName()); // NOI18N. logger.warning(message); } }
package fr.paris.lutece.util.bean; import fr.paris.lutece.portal.service.util.AppLogService; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; import javax.servlet.http.HttpServletRequest; import org.apache.commons.beanutils.BeanUtils; /** * Bean Utils */ public final class BeanUtil { private static final char UNDERSCORE = '_'; /** Private constructor */ private BeanUtil( ) { } /** * Populate a bean using parameters in http request * * @param bean bean to populate * @param request http request */ public static void populate( Object bean, HttpServletRequest request ) { for ( Field field : bean.getClass( ).getDeclaredFields( ) ) { try { // for all boolean field, init to false if ( field.getType( ).getName( ).equals( Boolean.class.getName( ) ) || field.getType( ).getName( ).equals( boolean.class.getName( ) ) ) { field.setAccessible( true ); field.set( bean, false ); } } catch ( Exception e ) { String error = "La valeur du champ " + field.getName( ) + " de la classe " + bean.getClass( ).getName( ) + " n'a pas pu être récupéré "; AppLogService.error( error ); throw new RuntimeException( error, e ); } } try { BeanUtils.populate( bean, convertMap( request.getParameterMap( ) ) ); } catch ( IllegalAccessException e ) { AppLogService.error( "Unable to fetch data from request", e ); } catch ( InvocationTargetException e ) { AppLogService.error( "Unable to fetch data from request", e ); } } /** * Convert map by casifying parameters names. * @param mapInput The input map * @return The output map */ public static Map<String, Object> convertMap( Map<String, Object> mapInput ) { Map<String, Object> mapOutput = new HashMap<String, Object>( ); for ( Entry<String, Object> entry : mapInput.entrySet( ) ) { mapOutput.put( convertUnderscores( entry.getKey( ) ), entry.getValue( ) ); } return mapOutput; } /** * Remove underscore and set the next letter in caps * @param strSource The source * @return The converted string */ public static String convertUnderscores( String strSource ) { StringBuilder sb = new StringBuilder( ); boolean bCapitalizeNext = false; for ( char c : strSource.toCharArray( ) ) { if ( c == UNDERSCORE ) { bCapitalizeNext = true; } else { if ( bCapitalizeNext ) { sb.append( Character.toUpperCase( c ) ); bCapitalizeNext = false; } else { sb.append( c ); } } } return sb.toString( ); } }
package lbms.plugins.mldht.kad; import java.net.Inet6Address; import java.net.InetAddress; import java.net.NetworkInterface; import java.net.SocketException; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.concurrent.ConcurrentHashMap; import java.util.stream.Collectors; import lbms.plugins.mldht.kad.utils.AddressUtils; import lbms.plugins.mldht.kad.utils.ThreadLocalUtils; public class RPCServerManager { boolean destroyed; public RPCServerManager(DHT dht) { this.dht = dht; updateBindAddrs(); } DHT dht; private ConcurrentHashMap<InetAddress,RPCServer> interfacesInUse = new ConcurrentHashMap<>(); private List<InetAddress> validBindAddresses = Collections.emptyList(); private volatile RPCServer[] activeServers = new RPCServer[0]; public void refresh(long now) { if(destroyed) return; startNewServers(); List<RPCServer> reachableServers = new ArrayList<>(interfacesInUse.values().size()); for(Iterator<RPCServer> it = interfacesInUse.values().iterator();it.hasNext();) { RPCServer srv = it.next(); srv.checkReachability(now); if(srv.isReachable()) reachableServers.add(srv); } activeServers = reachableServers.toArray(new RPCServer[reachableServers.size()]); } private void updateBindAddrs() { try { Class<? extends InetAddress> type = dht.getType().PREFERRED_ADDRESS_TYPE; List<InetAddress> newBindAddrs = Collections.list(NetworkInterface.getNetworkInterfaces()).stream() .flatMap(iface -> iface.getInterfaceAddresses().stream()) .map(ifa -> ifa.getAddress()) .filter(addr -> type.isInstance(addr)) .distinct() .collect(Collectors.toCollection(() -> new ArrayList<>())); newBindAddrs.add(AddressUtils.getAnyLocalAddress(type)); validBindAddresses = newBindAddrs; } catch (SocketException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public void doBindChecks() { updateBindAddrs(); getAllServers().forEach(srv -> { if(!validBindAddresses.contains(srv.getBindAddress())) { srv.stop(); } }); } private void startNewServers() { boolean multihome = dht.config.allowMultiHoming(); Class<? extends InetAddress> addressType = dht.getType().PREFERRED_ADDRESS_TYPE; if(multihome) { // we only consider global unicast addresses in multihoming mode // this is mostly meant for server configurations List<InetAddress> addrs = new ArrayList<>(AddressUtils.getAvailableGloballyRoutableAddrs(addressType)); addrs.removeAll(interfacesInUse.keySet()); // create new servers for all IPs we aren't currently haven't bound addrs.forEach(addr -> newServer(addr)); return; } // single home RPCServer current = interfacesInUse.values().stream().findAny().orElse(null); // check if we have bound to an anylocaladdress because we didn't know any better and consensus converged on a local address // that's mostly going to happen on v6 if we can't find a default route for v6 if(current != null && current.getBindAddress().isAnyLocalAddress() && current.getConsensusExternalAddress() != null && AddressUtils.isValidBindAddress(current.getConsensusExternalAddress().getAddress())) { InetAddress rebindAddress = current.getConsensusExternalAddress().getAddress(); current.stop(); newServer(rebindAddress); return; } // single homed & already have a server -> no need for another one if(current != null) return; // this is our default strategy. try to determine the default route InetAddress defaultBind = AddressUtils.getDefaultRoute(addressType); if(defaultBind != null) { newServer(defaultBind); return; } // last resort for v6, try a random global unicast address, otherwise anylocal if(addressType.isAssignableFrom(Inet6Address.class)) { InetAddress addr = AddressUtils.getAvailableGloballyRoutableAddrs(addressType).stream().findAny().orElse(AddressUtils.getAnyLocalAddress(addressType)); newServer(addr); return; } // last resort for v4, bind to anylocal address since we don't know how to pick among multiple NATed routes newServer(AddressUtils.getAnyLocalAddress(addressType)); } private void newServer(InetAddress addr) { RPCServer srv = new RPCServer(this,addr,dht.config.getListeningPort(), dht.serverStats); // doing the socket setup takes time, do it in the background dht.getScheduler().execute(srv::start); interfacesInUse.put(addr, srv); } void serverRemoved(RPCServer srv) { interfacesInUse.remove(srv.getBindAddress(),srv); refresh(System.currentTimeMillis()); } public void destroy() { destroyed = true; new ArrayList<>(interfacesInUse.values()).parallelStream().forEach(RPCServer::stop); } public int getServerCount() { return interfacesInUse.size(); } public int getActiveServerCount() { return activeServers.length; } /** * @param fallback tries to return an inactive server if no active one can be found * @return a random active server, or <code>null</code> if none can be found */ public RPCServer getRandomActiveServer(boolean fallback) { RPCServer[] srvs = activeServers; if(srvs.length == 0) return fallback ? getRandomServer() : null; return srvs[ThreadLocalUtils.getThreadLocalRandom().nextInt(srvs.length)]; } /** * may return null */ public RPCServer getRandomServer() { List<RPCServer> servers = getAllServers(); if(servers.isEmpty()) return null; return servers.get(ThreadLocalUtils.getThreadLocalRandom().nextInt(servers.size())); } public List<RPCServer> getAllServers() { return new ArrayList<>(interfacesInUse.values()); } }
package com.ecyrd.jspwiki.util; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.util.Properties; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; public class CommentedPropertiesTest extends TestCase { Properties m_props = new CommentedProperties(); public void setUp() throws IOException { InputStream in = CommentedPropertiesTest.class.getClassLoader().getResourceAsStream( "test.properties" ); m_props.load( in ); in.close(); } public void testLoadProperties() { assertEquals( 5, m_props.keySet().size() ); assertEquals( "Foo", m_props.get( "testProp1" ) ); assertEquals( "Bar", m_props.get( "testProp2" ) ); assertEquals( "", m_props.get( "testProp3" ) ); assertEquals( "FooAgain", m_props.get( "testProp4" ) ); assertEquals( "BarAgain", m_props.get( "testProp5" ) ); assertNull( m_props.get( "testProp6" ) ); // String we read in, including comments is 208 bytes assertEquals( 208, m_props.toString().length() ); } public void testSetProperty() { m_props.setProperty( "testProp1", "newValue" ); // Length of stored string should now be 5 bytes more assertEquals( 208+5, m_props.toString().length() ); assertTrue( m_props.toString().indexOf( "newValue" ) != -1 ); // Create new property; should add 21 (1+7+3+9+1) bytes m_props.setProperty( "newProp", "newValue2" ); m_props.containsKey( "newProp" ); m_props.containsValue( "newValue2" ); assertEquals( 208+5+21, m_props.toString().length() ); assertTrue( m_props.toString().indexOf( "newProp = newValue2" ) != -1 ); } public void testRemove() { // Remove prop 1; length of stored string should be 14 (1+9+1+3) bytes less m_props.remove( "testProp1" ); assertFalse( m_props.containsKey( "testProp1" ) ); assertEquals( 208-14, m_props.toString().length() ); // Remove prop 2; length of stored string should be 15 (1+9+2+3) bytes less m_props.remove( "testProp2" ); assertFalse( m_props.containsKey( "testProp2" ) ); assertEquals( 208-14-15, m_props.toString().length() ); // Remove prop 3; length of stored string should be 11 (1+9+1) bytes less m_props.remove( "testProp3" ); assertFalse( m_props.containsKey( "testProp3" ) ); assertEquals( 208-14-15-11, m_props.toString().length() ); // Remove prop 4; length of stored string should be 19 (1+9+1+8) bytes less m_props.remove( "testProp4" ); assertFalse( m_props.containsKey( "testProp4" ) ); assertEquals( 208-14-15-11-19, m_props.toString().length() ); // Remove prop 5; length of stored string should be 19 (1+9+1+8) bytes less m_props.remove( "testProp5" ); assertFalse( m_props.containsKey( "testProp5" ) ); assertEquals( 208-14-15-11-19-19, m_props.toString().length() ); } public void testStore() throws Exception { // Write results to a new file File outFile = createFile( "test2.properties" ); OutputStream out = new FileOutputStream( outFile ); m_props.store( out, null ); // Load the file into new props object; should return identical strings Properties props2 = new CommentedProperties(); InputStream in = CommentedPropertiesTest.class.getClassLoader().getResourceAsStream( "test2.properties" ); props2.load( in ); in.close(); assertEquals( m_props.toString(), props2.toString() ); // Remove props1, 2, 3 & resave props to new file m_props.remove( "testProp1" ); m_props.remove( "testProp2" ); m_props.remove( "testProp3" ); outFile = createFile( "test3.properties" ); out = new FileOutputStream( outFile ); m_props.store( out, null ); // Load the new file; should not have props1/2/3 & is shorter Properties props3 = new CommentedProperties(); in = CommentedPropertiesTest.class.getClassLoader().getResourceAsStream( "test3.properties" ); props3.load( in ); in.close(); assertNotSame( m_props.toString(), props3.toString() ); assertFalse( props3.containsKey( "testProp1" ) ); assertFalse( props3.containsKey( "testProp2" ) ); assertFalse( props3.containsKey( "testProp3" ) ); assertTrue( props3.containsKey( "testProp4" ) ); assertTrue( props3.containsKey( "testProp5" ) ); // Clean up File file = getFile( "test2.properties" ); if ( file != null && file.exists() ) { file.delete(); } file = getFile( "test3.properties" ); if ( file != null && file.exists() ) { file.delete(); } } private File createFile( String file ) throws URISyntaxException { // Get the test.properties file URL url = CommentedPropertiesTest.class.getClassLoader().getResource( "test.properties" ); if ( url == null ) { throw new IllegalStateException( "Very odd. We can't find test.properties!" ); } // Construct new file in same directory File testFile = new File( new URI(url.toString()) ); File dir = testFile.getParentFile(); return new File( dir, file ); } private File getFile( String name ) { // Get the test.properties file URL url = CommentedPropertiesTest.class.getClassLoader().getResource( name ); if ( url == null ) { throw new IllegalStateException( "Very odd. We can't find test.properties!" ); } // Return the file File file = null; try { file = new File( new URI(url.toString()) ); } catch (URISyntaxException e) { // TODO Auto-generated catch block e.printStackTrace(); } return file; } public static Test suite() { return new TestSuite( CommentedPropertiesTest.class ); } }
package br.com.caelum.tubaina; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStreamReader; import java.io.Reader; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.CommandLineParser; import org.apache.commons.cli.HelpFormatter; import org.apache.commons.cli.OptionBuilder; import org.apache.commons.cli.Options; import org.apache.commons.cli.ParseException; import org.apache.commons.cli.PosixParser; import org.apache.commons.io.FileUtils; import org.apache.commons.io.filefilter.SuffixFileFilter; import org.apache.log4j.Logger; import br.com.caelum.tubaina.builder.BookBuilder; import br.com.caelum.tubaina.parser.Parser; import br.com.caelum.tubaina.parser.RegexConfigurator; import br.com.caelum.tubaina.parser.Tag; import br.com.caelum.tubaina.parser.html.HtmlGenerator; import br.com.caelum.tubaina.parser.html.HtmlParser; import br.com.caelum.tubaina.parser.latex.LatexGenerator; import br.com.caelum.tubaina.parser.latex.LatexParser; import br.com.caelum.tubaina.resources.ResourceLocator; public class Tubaina { public static final File DEFAULT_TEMPLATE_DIR = new File("src/templates"); public static final Logger LOG = Logger.getLogger(Tubaina.class); public static final int MAX_LINE_LENGTH = 93; // believe us... this is what // fits in Latex A4 // templates. private static File inputDir = new File("."); private static File outputDir = new File("."); private static String bookName; // TODO listar todos private static boolean listTodos; private static boolean strictXhtml; private static File templateDir = DEFAULT_TEMPLATE_DIR; private static boolean html; private static boolean latex; private static boolean showNotes; private static boolean dontCare; private static boolean noAnswer; private static String outputFileName; public static void main(final String[] args) throws IOException { CommandLineParser parser = new PosixParser(); Options options = registerOptions(); try { LOG.debug("Parsing arguments " + Arrays.toString(args)); CommandLine cmd = parser.parse(options, args); parseOptions(cmd, options); } catch (ParseException e) { System.err.println("Parsing failed. Reason: " + e.getMessage()); printUsage(options); System.exit(-1); } generate(); } private static void generate() throws IOException { ResourceLocator.initialize(inputDir); List<Reader> readers = getAfcsFrom(inputDir); BookBuilder builder = new BookBuilder(bookName); builder.addAll(readers); Book b = null; try { b = builder.build(); } catch (TubainaException e) { if (dontCare) { LOG.warn(e); } else { e.printStackTrace(); System.exit(-1); } } RegexConfigurator conf = new RegexConfigurator(); if (latex) { List<Tag> tags = conf.read("/regex.properties", "/latex.properties"); Parser parser = new LatexParser(tags, showNotes, noAnswer); LatexGenerator generator = new LatexGenerator(parser, templateDir, noAnswer); File file = new File(outputDir, "latex"); FileUtils.forceMkdir(file); try { generator.generate(b, file, outputFileName); } catch (TubainaException e) { LOG.warn(e.getMessage()); } } if (html) { HtmlParser htmlParser = new HtmlParser(conf.read("/regex.properties", "/html.properties"), noAnswer); HtmlGenerator generator = new HtmlGenerator(htmlParser, strictXhtml, templateDir); File file = new File(outputDir, "html"); FileUtils.forceMkdir(file); try { generator.generate(b, file); } catch (TubainaException e) { LOG.warn(e.getMessage()); } } } private static void parseOptions(final CommandLine cmd, final Options options) { if (cmd.hasOption("h")) { printUsage(options); } else { if (cmd.hasOption('i')) { inputDir = new File(cmd.getOptionValue('i')); } if (cmd.hasOption('o')) { outputDir = new File(cmd.getOptionValue('o')); } if (cmd.hasOption('t')) { templateDir = new File(cmd.getOptionValue('t')); } bookName = cmd.getOptionValue('n'); listTodos = cmd.hasOption('l'); strictXhtml = cmd.hasOption('x'); showNotes = cmd.hasOption('s'); html = cmd.hasOption("html"); latex = cmd.hasOption("latex"); dontCare = cmd.hasOption("d"); noAnswer = cmd.hasOption("a"); if (cmd.hasOption('f')) { outputFileName = cmd.getOptionValue('f'); } else { outputFileName = "book.tex"; } } } @SuppressWarnings("static-access") private static Options registerOptions() { Options options = new Options(); options.addOption("latex", "latex", false, "generates an latex output on given outputdir"); options.addOption("html", "html", false, "generates an html output on given outputdir"); options.addOption("h", "help", false, "print this message"); // inputdir options.addOption(OptionBuilder.withArgName("inputDirectory").withLongOpt("input-dir").hasArg() .withDescription("directory where you have your .afc files").create('i')); // outputdir options.addOption(OptionBuilder.withArgName("outputDirectory").withLongOpt("output-dir").hasArg().isRequired() .withDescription("directory where you want the output files").create('o')); // name options.addOption(OptionBuilder.withArgName("bookName").withLongOpt("name").hasArg().isRequired() .withDescription("name of your book").create('n')); // optional options.addOption("l", "list-todos", false, "lists todos from all files"); options.addOption("x", "strict-xhtml", false, "perform an xhtml validation"); options.addOption("s", "show-notes", false, "shows notes in Latex output"); options.addOption("d", "dontcare", false, "ignore all errors"); options.addOption("a", "no-answers", false, "don't make the answers booklet"); options.addOption(OptionBuilder.withArgName("directory").withLongOpt("template-dir").hasArg().withDescription( "directory where you have your template files").create('t')); options.addOption(OptionBuilder.withArgName("outputFileName").withLongOpt("output-file").hasArg() .withDescription("name for generated latex file (ignored for html output)").create('f')); return options; } private static void printUsage(final Options options) { // automatically generate the help statement HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("tubaina [-html|-latex] -i <inputdir> -o <outputdir> -n <bookname>", options); } static List<Reader> getAfcsFrom(final File file) throws UnsupportedEncodingException, FileNotFoundException { List<Reader> readers = new ArrayList<Reader>(); List<String> files = new ArrayList<String>(); Collections.addAll(files, file.list(new SuffixFileFilter(".afc"))); Collections.sort(files); for (String s : files) { readers.add(new InputStreamReader(new FileInputStream(new File(file, s)), "UTF-8")); } return readers; } }
package com.oreilly.rdf.tenuki; import java.sql.Connection; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.CommandLineParser; import org.apache.commons.cli.HelpFormatter; import org.apache.commons.cli.OptionBuilder; import org.apache.commons.cli.Options; import org.apache.commons.cli.ParseException; import org.apache.commons.cli.PosixParser; import org.apache.commons.configuration.HierarchicalINIConfiguration; import org.apache.commons.dbcp.BasicDataSource; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import com.hp.hpl.jena.sdb.SDBFactory; import com.hp.hpl.jena.sdb.Store; import com.hp.hpl.jena.sdb.StoreDesc; public class Tenuki { private static Log log = LogFactory.getLog(Tenuki.class); /** * @param args * @throws Exception */ @SuppressWarnings("static-access") public static void main(String[] args) throws Exception { CommandLineParser parser = new PosixParser(); Options options = new Options(); options.addOption("h", "help", false, "show this message"); options.addOption(OptionBuilder.withLongOpt("port").withDescription( "use PORT for server").hasArg().withArgName("PORT") .create("p")); options.addOption(OptionBuilder.withLongOpt("password") .withDescription("SQL database password").hasArg().withArgName( "PASSWORD").create()); options.addOption("c", "create", false, "Create a new Datastore if one does not exist"); try { CommandLine line = parser.parse(options, args); if (line.hasOption("help")) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("tenuki-server", options); return; } log.info("Starting Tenuki..."); Integer port = 7070; String logPath = "./logs/"; String driver = "org.postgresql.Driver"; String url = "jdbc:postgresql:sdb"; String username = "sdb"; String password = null; Integer maxConnections = 8; String sdbLayout = "layout2/index"; String dbType = "postgresql"; if (line.getArgList().size() > 0) { String configFilePath = line.getArgs()[0]; HierarchicalINIConfiguration config = new HierarchicalINIConfiguration( configFilePath); port = config.getInt("server.port", port); password = config.getString("datasource.password", password); driver = config.getString("datasource.driver", driver); dbType = config.getString("datasource.dbtype", dbType); dbType = config.getString("datasource.dbtype", sdbLayout); username = config.getString("datasource.username", username); url = config.getString("datasource.url", url); maxConnections = config.getInt("datasource.maxconnections", maxConnections); logPath = config.getString("server.logpath", logPath); } port = Integer.parseInt(line .getOptionValue("port", port.toString())); password = line.getOptionValue("password", password); boolean create = line.hasOption("create"); BasicDataSource dataSource = configureDataSource(driver, url, username, password, maxConnections); StoreDesc storeDesc = new StoreDesc(sdbLayout, dbType); log.info("... configuration complete ..."); if (create) { Connection connection = dataSource.getConnection(); Store store = SDBFactory.connectStore(connection, storeDesc); try { store.getSize(); } catch (Exception e) { store.getTableFormatter().create(); } connection.close(); } TenukiSever server = new TenukiSever(); server.setDatasource(dataSource); server.setStoreDesc(storeDesc); server.setLogPath(logPath); server.setPort(port); server.start(); log.info("... Tenuki Server started."); } catch (ParseException e) { System.out.println("Unexpected exception:" + e.getMessage()); } } private static BasicDataSource configureDataSource(String driver, String url, String username, String password, Integer maxConnections) { BasicDataSource dataSource = new BasicDataSource(); dataSource.setDriverClassName(driver); dataSource.setUrl(url); dataSource.setUsername(username); dataSource.setValidationQuery("SELECT 1 AS test"); dataSource.setTestOnBorrow(true); dataSource.setTestOnReturn(true); dataSource.setMaxActive(maxConnections); dataSource.setMaxIdle(maxConnections); if (password != null) { dataSource.setPassword(password); } return dataSource; } }
package com.quantum.utils; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.net.InetAddress; import java.net.URI; import java.net.URISyntaxException; import java.nio.charset.Charset; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; import java.util.HashMap; import java.util.Map; import org.apache.commons.io.IOUtils; import org.apache.commons.lang.exception.ExceptionUtils; import org.apache.http.HttpHost; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; import org.apache.http.auth.AuthScope; import org.apache.http.auth.NTCredentials; import org.apache.http.client.CredentialsProvider; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpRequestBase; import org.apache.http.client.utils.URIBuilder; import org.apache.http.impl.client.BasicCredentialsProvider; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.impl.client.ProxyAuthenticationStrategy; import org.apache.http.util.EntityUtils; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonArray; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.perfecto.reportium.client.ReportiumClient; import com.qmetry.qaf.automation.core.ConfigurationManager; import com.qmetry.qaf.automation.core.QAFTestBase; import com.qmetry.qaf.automation.core.TestBaseProvider; import com.quantum.listeners.QuantumReportiumListener; public class ReportUtils { public static final String PERFECTO_REPORT_CLIENT = "perfecto.report.client"; public static ReportiumClient getReportClient() { return (ReportiumClient) ConfigurationManager.getBundle().getObject(PERFECTO_REPORT_CLIENT); } public static void logStepStart(String message) { ConsoleUtils.logInfoBlocks(message, ConsoleUtils.lower_block + " ", 10); QuantumReportiumListener.logStepStart(message); } // The Perfecto Continuous Quality Lab you work with public static final String CQL_NAME = (ConfigurationManager.getBundle().getString("remote.server").split("\\.")[0]) .replace("http: private static String getToken() { return ConfigurationManager.getBundle().getString("perfecto.offlineToken").trim(); } // The reporting Server address depends on the location of the lab. Please // refer to the documentation at // http://developers.perfectomobile.com/display/PD/Reporting#Reporting-ReportingserverAccessingthereports // to find your relevant address // For example the following is used for US: public static final String REPORTING_SERVER_URL = "https://" + CQL_NAME + ".reporting.perfectomobile.com"; public static final String CQL_SERVER_URL = "https://" + CQL_NAME + ".perfectomobile.com"; public static void generateSummaryReports(String executionId) throws Exception { // Use your personal offline token to obtain an access token // Retrieve a list of the test executions in your lab (as a json) JsonObject executions = retrieveTestExecutions(getToken(), executionId); int counter = 0; while ((!executions.get("metadata").getAsJsonObject().get("processingStatus").getAsString() .equalsIgnoreCase("PROCESSING_COMPLETE") || executions.getAsJsonArray("resources").size() == 0) && counter < 60) { Thread.sleep(1000); executions = retrieveTestExecutions(getToken(), executionId); counter++; } JsonObject resources = executions.getAsJsonArray("resources").get(0).getAsJsonObject(); JsonObject platforms = resources.getAsJsonArray("platforms").get(0).getAsJsonObject(); String deviceId = platforms.get("deviceId").getAsString(); downloadExecutionSummaryReport(deviceId, executionId, getToken()); } public static void generateTestReport(String executionId) throws Exception { JsonObject executions = retrieveTestExecutions(getToken(), executionId); int counter = 0; while ((!executions.get("metadata").getAsJsonObject().get("processingStatus").getAsString() .equalsIgnoreCase("PROCESSING_COMPLETE") || executions.getAsJsonArray("resources").size() == 0) && counter < 60) { Thread.sleep(1000); executions = retrieveTestExecutions(getToken(), executionId); counter++; } for (int i = 0; i < executions.getAsJsonArray("resources").size(); i++) { JsonObject testExecution = executions.getAsJsonArray("resources").get(i).getAsJsonObject(); String testId = testExecution.get("id").getAsString(); String testName = testExecution.get("name").getAsString().replace(" ", "_"); JsonObject platforms = testExecution.getAsJsonArray("platforms").get(0).getAsJsonObject(); String deviceName = platforms.get("deviceId").getAsString(); downloadTestReport(testId, deviceName + "_" + (testName.length() >= 100 ? testName.substring(1, 100) : testName), getToken()); } } public static void downloadReportVideo(String executionId) throws URISyntaxException, IOException, InterruptedException { JsonObject executions = retrieveTestExecutions(getToken(), executionId); int counter = 0; while ((!executions.get("metadata").getAsJsonObject().get("processingStatus").getAsString() .equalsIgnoreCase("PROCESSING_COMPLETE") || executions.getAsJsonArray("resources").size() == 0) && counter < 60) { Thread.sleep(1000); executions = retrieveTestExecutions(getToken(), executionId); counter++; } for (int i = 0; i < executions.getAsJsonArray("resources").size(); i++) { JsonObject testExecution = executions.getAsJsonArray("resources").get(i).getAsJsonObject(); String testId = testExecution.get("id").getAsString(); String testName = testExecution.get("name").getAsString().replace(" ", "_"); JsonObject platforms = testExecution.getAsJsonArray("platforms").get(0).getAsJsonObject(); String deviceName = platforms.get("deviceId").getAsString(); downloadVideo(deviceName + "_" + (testName.length() >= 100 ? testName.substring(1, 100) : testName), executions); } } public static void downloadReportAttachments(String executionId) throws URISyntaxException, IOException, InterruptedException { JsonObject executions = retrieveTestExecutions(getToken(), executionId); int counter = 0; while ((!executions.get("metadata").getAsJsonObject().get("processingStatus").getAsString() .equalsIgnoreCase("PROCESSING_COMPLETE") || executions.getAsJsonArray("resources").size() == 0) && counter < 60) { Thread.sleep(1000); executions = retrieveTestExecutions(getToken(), executionId); counter++; } for (int i = 0; i < executions.getAsJsonArray("resources").size(); i++) { JsonObject testExecution = executions.getAsJsonArray("resources").get(i).getAsJsonObject(); String testId = testExecution.get("id").getAsString(); String testName = testExecution.get("name").getAsString().replace(" ", "_"); JsonObject platforms = testExecution.getAsJsonArray("platforms").get(0).getAsJsonObject(); String deviceName = platforms.get("deviceId").getAsString(); downloadAttachments(deviceName + "_" + (testName.length() >= 100 ? testName.substring(1, 100) : testName), executions); } } private static JsonObject retrieveTestExecutions(String accessToken, String executionId) throws URISyntaxException, IOException { URIBuilder uriBuilder = new URIBuilder(REPORTING_SERVER_URL + "/export/api/v1/test-executions"); // Optional: Filter by range. In this example: retrieve test executions // of the past month (result may contain tests of multiple driver // executions) // Optional: Filter by a specific driver execution ID that you can // obtain at script execution uriBuilder.addParameter("externalId[0]", executionId); HttpGet getExecutions = new HttpGet(uriBuilder.build()); addDefaultRequestHeaders(getExecutions, accessToken); HttpResponse getExecutionsResponse = null; if (ConfigurationManager.getBundle().getString("proxyHost") != null && !ConfigurationManager.getBundle().getString("proxyHost").toString().equals("")) { InetAddress addr; addr = InetAddress.getLocalHost(); String hostname = addr.getHostName(); NTCredentials ntCreds = new NTCredentials( ConfigurationManager.getBundle().getString("proxyUser").toString(), ConfigurationManager.getBundle().getString("proxyPassword").toString(), hostname, ConfigurationManager.getBundle().getString("proxyDomain").toString()); CredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider .setCredentials( new AuthScope(ConfigurationManager.getBundle().getString("proxyHost").toString(), Integer.parseInt( ConfigurationManager.getBundle().getString("proxyPort").toString())), ntCreds); HttpClientBuilder clientBuilder = HttpClientBuilder.create(); clientBuilder.useSystemProperties(); clientBuilder.setProxy(new HttpHost(ConfigurationManager.getBundle().getString("proxyHost").toString(), Integer.parseInt(ConfigurationManager.getBundle().getString("proxyPort").toString()))); clientBuilder.setDefaultCredentialsProvider(credsProvider); clientBuilder.setProxyAuthenticationStrategy(new ProxyAuthenticationStrategy()); CloseableHttpClient httpClient = clientBuilder.build(); getExecutionsResponse = httpClient.execute(getExecutions); } else { HttpClient httpClient = HttpClientBuilder.create().build(); getExecutionsResponse = httpClient.execute(getExecutions); } JsonObject executions; try (InputStreamReader inputStreamReader = new InputStreamReader( getExecutionsResponse.getEntity().getContent())) { Gson gson = new GsonBuilder().setPrettyPrinting().create(); executions = gson.fromJson(IOUtils.toString(inputStreamReader), JsonObject.class); // System.out.println("\nList of test executions response:\n" + // gson.toJson(executions)); } return executions; } @SuppressWarnings("unused") private static String retrieveTestCommands(String testId, String accessToken) throws URISyntaxException, IOException { HttpGet getCommands = new HttpGet( new URI(REPORTING_SERVER_URL + "/export/api/v1/test-executions/" + testId + "/commands")); addDefaultRequestHeaders(getCommands, accessToken); HttpResponse getCommandsResponse = null; if (ConfigurationManager.getBundle().getString("proxyHost") != null && !ConfigurationManager.getBundle().getString("proxyHost").toString().equals("")) { InetAddress addr; addr = InetAddress.getLocalHost(); String hostname = addr.getHostName(); NTCredentials ntCreds = new NTCredentials( ConfigurationManager.getBundle().getString("proxyUser").toString(), ConfigurationManager.getBundle().getString("proxyPassword").toString(), hostname, ConfigurationManager.getBundle().getString("proxyDomain").toString()); CredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider .setCredentials( new AuthScope(ConfigurationManager.getBundle().getString("proxyHost").toString(), Integer.parseInt( ConfigurationManager.getBundle().getString("proxyPort").toString())), ntCreds); HttpClientBuilder clientBuilder = HttpClientBuilder.create(); clientBuilder.useSystemProperties(); clientBuilder.setProxy(new HttpHost(ConfigurationManager.getBundle().getString("proxyHost").toString(), Integer.parseInt(ConfigurationManager.getBundle().getString("proxyPort").toString()))); clientBuilder.setDefaultCredentialsProvider(credsProvider); clientBuilder.setProxyAuthenticationStrategy(new ProxyAuthenticationStrategy()); CloseableHttpClient httpClient = clientBuilder.build(); getCommandsResponse = httpClient.execute(getCommands); } else { HttpClient httpClient = HttpClientBuilder.create().build(); getCommandsResponse = httpClient.execute(getCommands); } try (InputStreamReader inputStreamReader = new InputStreamReader( getCommandsResponse.getEntity().getContent())) { Gson gson = new GsonBuilder().setPrettyPrinting().create(); JsonObject commands = gson.fromJson(IOUtils.toString(inputStreamReader), JsonObject.class); System.out.println("\nList of commands response:\n" + gson.toJson(commands)); return gson.toJson(commands); } } private static void downloadExecutionSummaryReport(String deviceId, String driverExecutionId, String accessToken) throws URISyntaxException, IOException { URIBuilder uriBuilder = new URIBuilder(REPORTING_SERVER_URL + "/export/api/v1/test-executions/pdf"); uriBuilder.addParameter("externalId[0]", driverExecutionId); // downloadFileAuthenticated(driverExecutionId, uriBuilder.build(), // ".pdf", "execution summary PDF report", // accessToken); downloadFileAuthenticated(deviceId + "_ExecutionSummaryReport", uriBuilder.build(), ".pdf", "execution summary PDF report", accessToken); } private static void downloadTestReport(String testId, String fileName, String accessToken) throws URISyntaxException, IOException { URIBuilder uriBuilder = new URIBuilder(REPORTING_SERVER_URL + "/export/api/v1/test-executions/pdf/" + testId); downloadFileAuthenticated(fileName, uriBuilder.build(), ".pdf", "test PDF report", accessToken); } @SuppressWarnings("unused") private static void downloadVideo(String deviceId, JsonObject testExecution) throws IOException, URISyntaxException { JsonObject resources = testExecution.getAsJsonArray("resources").get(0).getAsJsonObject(); JsonArray videos = resources.getAsJsonArray("videos"); if (videos.size() > 0) { JsonObject video = videos.get(0).getAsJsonObject(); String downloadVideoUrl = video.get("downloadUrl").getAsString(); String format = "." + video.get("format").getAsString(); String testId = resources.get("id").getAsString(); // downloadFile(testId, URI.create(downloadVideoUrl), format, // "video"); downloadFile(deviceId + "_Video", URI.create(downloadVideoUrl), format, "video"); } else { System.out.println("\nNo videos found for test execution"); } } @SuppressWarnings("unused") private static void downloadAttachments(String deviceId, JsonObject testExecution) throws IOException, URISyntaxException { // Example for downloading device logs JsonObject resources = testExecution.getAsJsonArray("resources").get(0).getAsJsonObject(); JsonArray artifacts = resources.getAsJsonArray("artifacts"); for (JsonElement artifactElement : artifacts) { JsonObject artifact = artifactElement.getAsJsonObject(); String artifactType = artifact.get("type").getAsString(); if (artifactType.equals("DEVICE_LOGS")) { String testId = resources.get("id").getAsString(); String path = artifact.get("path").getAsString(); URIBuilder uriBuilder = new URIBuilder(path); downloadFile(deviceId + "_" + testId, uriBuilder.build(), "_device_logs.zip", "device logs"); } else if (artifactType.equals("NETWORK")) { String testId = resources.get("id").getAsString(); String path = artifact.get("path").getAsString(); URIBuilder uriBuilder = new URIBuilder(path); downloadFile(deviceId + "_" + testId, uriBuilder.build(), "_network_logs.zip", "network logs"); } else if (artifactType.equals("VITALS")) { String testId = resources.get("id").getAsString(); String path = artifact.get("path").getAsString(); URIBuilder uriBuilder = new URIBuilder(path); downloadFile(deviceId + "_" + testId, uriBuilder.build(), "_vitals_logs.zip", "vitals logs"); } } } private static void downloadFile(String fileName, URI uri, String suffix, String description) throws IOException { downloadFileToFS(new HttpGet(uri), fileName, suffix, description); } private static void downloadFileAuthenticated(String fileName, URI uri, String suffix, String description, String accessToken) throws IOException { HttpGet httpGet = new HttpGet(uri); addDefaultRequestHeaders(httpGet, accessToken); downloadFileToFS(httpGet, fileName, suffix, description); } private static String getReportDirectory() { try { ConfigurationManager.getBundle().getString("perfecto.report.location"); if (!ConfigurationManager.getBundle().getString("perfecto.report.location").equals("")) { return ConfigurationManager.getBundle().getString("perfecto.report.location"); } else { return "perfectoReports"; } } catch (Exception ex) { return "perfectoReports"; } } private static void downloadFileToFS(HttpGet httpGet, String fileName, String suffix, String description) throws IOException { HttpResponse response = null; if (ConfigurationManager.getBundle().getString("proxyHost") != null && !ConfigurationManager.getBundle().getString("proxyHost").toString().equals("")) { InetAddress addr; addr = InetAddress.getLocalHost(); String hostname = addr.getHostName(); NTCredentials ntCreds = new NTCredentials( ConfigurationManager.getBundle().getString("proxyUser").toString(), ConfigurationManager.getBundle().getString("proxyPassword").toString(), hostname, ConfigurationManager.getBundle().getString("proxyDomain").toString()); CredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider .setCredentials( new AuthScope(ConfigurationManager.getBundle().getString("proxyHost").toString(), Integer.parseInt( ConfigurationManager.getBundle().getString("proxyPort").toString())), ntCreds); HttpClientBuilder clientBuilder = HttpClientBuilder.create(); clientBuilder.useSystemProperties(); clientBuilder.setProxy(new HttpHost(ConfigurationManager.getBundle().getString("proxyHost").toString(), Integer.parseInt(ConfigurationManager.getBundle().getString("proxyPort").toString()))); clientBuilder.setDefaultCredentialsProvider(credsProvider); clientBuilder.setProxyAuthenticationStrategy(new ProxyAuthenticationStrategy()); CloseableHttpClient httpClient = clientBuilder.build(); response = httpClient.execute(httpGet); } else { HttpClient httpClient = HttpClientBuilder.create().build(); response = httpClient.execute(httpGet); } FileOutputStream fileOutputStream = null; try { if (HttpStatus.SC_OK == response.getStatusLine().getStatusCode()) { String dir = getReportDirectory(); DateFormat dateFormat = new SimpleDateFormat("MMddyyyyHHmmss"); Date date = new Date(); if (!new File(dir).exists()) { new File(dir).mkdir(); } File file = new File(dir, fileName + "_" + dateFormat.format(date) + suffix); fileOutputStream = new FileOutputStream(file); IOUtils.copy(response.getEntity().getContent(), fileOutputStream); System.out.println("\nSaved " + description + " to: " + file.getAbsolutePath()); } else { String errorMsg = IOUtils.toString(response.getEntity().getContent(), Charset.defaultCharset()); System.err.println( "Error downloading file. Status: " + response.getStatusLine() + ".\nInfo: " + errorMsg); } } finally { EntityUtils.consumeQuietly(response.getEntity()); IOUtils.closeQuietly(fileOutputStream); } } private static void addDefaultRequestHeaders(HttpRequestBase request, String accessToken) { request.addHeader("PERFECTO_AUTHORIZATION", accessToken); } public static void reportComment(String message) { Map<String, Object> params = new HashMap<>(); params.put("text", message); DeviceUtils.getQAFDriver().executeScript("mobile:comment", params); } /** * Using this method will continue the scenario execution on failure, but it * will mark the scenario as failed at the end and also display all the failure * messages * * @param message * - Assertion message to be displayed in the DZ * @param status * - Assertion flag status - true or false (pass or fail) */ public static void logVerify(String message, boolean status) { try { if (!status) { TestBaseProvider.instance().get().addVerificationError(message); } getReportClient().reportiumAssert(message, status); } catch (Exception e) { // ignore... } } /** * Added this method to report verifications with throwable exception. * * @param message * - Assertion message to be displayed in the DZ * @param status * - Assertion flag status - true or false (pass or fail) * @param e * - If the exception will be passed then the stacktrace will be * attached on failure flag in DZ */ public static void logVerify(String message, boolean status, Throwable e) { try { if (!status) { TestBaseProvider.instance().get().addVerificationError(e); getReportClient().reportiumAssert(message + "\n" + ExceptionUtils.getFullStackTrace(e), status); } else { getReportClient().reportiumAssert(message, status); } } catch (Exception ex) { // ignore... } } /** * Using this method will add an assertion and stop the execution of the * scenario in case of failure. * * @param message * - Assertion message to be displayed in the DZ * @param status * - Assertion flag status - true or false (pass or fail) */ public static void logAssert(String message, boolean status) { logVerify(message, status); if (!status) { throw new AssertionError(message); } } /** * Added this method to report assertions with throwable exception. * * @param message * - Assertion message to be displayed in the DZ * @param status * - Assertion flag status - true or false (pass or fail) * @param e- * If the exception will be passed then the stacktrace will be * attached on failure flag in DZ */ public static void logAssert(String message, boolean status, Throwable e) { logVerify(message, status, e); if (!status) { throw new AssertionError(message); } } }
package com.yunpian.sdk; import java.io.File; import java.io.InputStream; import java.nio.charset.Charset; import java.nio.charset.CodingErrorAction; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; import java.util.Properties; import java.util.concurrent.Future; import javax.annotation.PostConstruct; import javax.annotation.PreDestroy; import org.apache.http.HttpResponse; import org.apache.http.client.methods.HttpPost; import org.apache.http.config.ConnectionConfig; import org.apache.http.entity.ContentType; import org.apache.http.entity.StringEntity; import org.apache.http.impl.nio.client.CloseableHttpAsyncClient; import org.apache.http.impl.nio.client.HttpAsyncClients; import org.apache.http.impl.nio.conn.PoolingNHttpClientConnectionManager; import org.apache.http.impl.nio.reactor.DefaultConnectingIOReactor; import org.apache.http.impl.nio.reactor.IOReactorConfig; import org.apache.http.nio.client.HttpAsyncClient; import org.apache.http.nio.reactor.ConnectingIOReactor; import org.apache.http.nio.reactor.IOReactorException; import org.apache.http.util.EntityUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.yunpian.sdk.api.ApiFactory; import com.yunpian.sdk.api.CallApi; import com.yunpian.sdk.api.FlowApi; import com.yunpian.sdk.api.SignApi; import com.yunpian.sdk.api.SmsApi; import com.yunpian.sdk.api.TplApi; import com.yunpian.sdk.api.UserApi; import com.yunpian.sdk.api.VoiceApi; import com.yunpian.sdk.constant.YunpianConstant; /** * : * * <pre> * YunpianClient yp = new YunpianClient("apikey").init(); * yp.sms().* * yp.sign().* * yp.tpl().* * yp.sms().* * yp.voice().* * yp.flow().* * yp.call().* * yp.close(); * </pre> * * @author dzh * @date Nov 17, 2016 5:17:47 PM * @since 1.2.0 */ public class YunpianClient implements YunpianConstant { static final Logger LOG = LoggerFactory.getLogger(YunpianClient.class); private CloseableHttpAsyncClient clnt; private YunpianConf conf = new YunpianConf(); private ApiFactory api; /** * key, */ public YunpianClient() { this(System.getProperty(YunpianConf.YP_APIKEY), System.getProperty(YunpianConf.YP_FILE)); } public YunpianClient(String apikey) { this(apikey, System.getProperty(YunpianConf.YP_FILE)); } public YunpianClient(String apikey, String file) { conf.with(apikey); if (file != null) conf.with(new File(System.getProperty(YunpianConf.YP_FILE, file))); } public YunpianClient(String apikey, InputStream in) { conf.with(apikey).with(in); } public YunpianClient(String apikey, Properties props) { conf.with(apikey).with(props); } public UserApi user() { return api.<UserApi> api(UserApi.NAME); } public CallApi call() { return api.<CallApi> api(CallApi.NAME); } public FlowApi flow() { return api.<FlowApi> api(FlowApi.NAME); } public SignApi sign() { return api.<SignApi> api(SignApi.NAME); } public SmsApi sms() { return api.<SmsApi> api(SmsApi.NAME); } public TplApi tpl() { return api.<TplApi> api(TplApi.NAME); } public VoiceApi voice() { return api.<VoiceApi> api(VoiceApi.NAME); } private static ContentType DefaultContentType; @PostConstruct public YunpianClient init() { LOG.info("YunpianClient is initing!"); try { if (clnt != null) close(); clnt = createHttpAsyncClient(conf.build()); DefaultContentType = ContentType.create("application/x-www-form-urlencoded", Charset.forName(conf.getConf(YunpianConf.HTTP_CHARSET, "utf-8"))); api = new ApiFactory(this); } catch (Exception e) { LOG.error(e.getMessage(), e.fillInStackTrace()); } return this; } public YunpianConf getConf() { return conf; } private CloseableHttpAsyncClient createHttpAsyncClient(YunpianConf conf) throws IOReactorException { IOReactorConfig ioReactorConfig = IOReactorConfig.custom().setIoThreadCount(Runtime.getRuntime().availableProcessors()) .setConnectTimeout(conf.getConfInt(YunpianConf.HTTP_CONN_TIMEOUT, "10000")) .setSoTimeout(conf.getConfInt(YunpianConf.HTTP_SO_TIMEOUT, "30000")).build(); ConnectingIOReactor ioReactor = new DefaultConnectingIOReactor(ioReactorConfig); PoolingNHttpClientConnectionManager connManager = new PoolingNHttpClientConnectionManager(ioReactor); ConnectionConfig connectionConfig = ConnectionConfig.custom().setMalformedInputAction(CodingErrorAction.IGNORE) .setUnmappableInputAction(CodingErrorAction.IGNORE) .setCharset(Charset.forName(conf.getConf(YunpianConf.HTTP_CHARSET, YunpianConf.HTTP_CHARSET_DEFAULT))).build(); connManager.setDefaultConnectionConfig(connectionConfig); connManager.setMaxTotal(conf.getConfInt(YunpianConf.HTTP_CONN_MAXTOTAL, "100")); connManager.setDefaultMaxPerRoute(conf.getConfInt(YunpianConf.HTTP_CONN_MAXPERROUTE, "10")); CloseableHttpAsyncClient httpclient = HttpAsyncClients.custom().setConnectionManager(connManager).build(); httpclient.start(); return httpclient; } static Map<String, String> HEADERS = new HashMap<>(1, 1); static { HEADERS.put("Api-Lang", "java"); } public final Map<String, String> newParam(int size) { return size <= 0 ? Collections.<String, String> emptyMap() : new HashMap<String, String>(size + 1, 1); } /** * * @param uri * @param data */ public Future<HttpResponse> post(String uri, String data) { return post(uri, data, DefaultContentType.getMimeType(), DefaultContentType.getCharset(), HEADERS); } public void closeResponse(HttpResponse rsp) { EntityUtils.consumeQuietly(rsp.getEntity()); } public Future<HttpResponse> post(String uri, String data, String mimeType, Charset charset, Map<String, String> headers) { HttpPost req = new HttpPost(uri); req.setEntity(new StringEntity(data, ContentType.create(mimeType == null ? DefaultContentType.getMimeType() : mimeType, charset == null ? DefaultContentType.getCharset() : charset))); if (headers == null) headers = HEADERS; for (Entry<String, String> e : headers.entrySet()) { req.setHeader(e.getKey(), e.getValue()); } return clnt.execute(req, null); } public HttpAsyncClient http() { return clnt; } @PreDestroy public void close() { LOG.info("YunpianClient is closing!"); if (clnt != null) { try { clnt.close(); } catch (Exception e) { LOG.error(e.getMessage(), e); } } } @Override public String toString() { return conf.toString(); } }
package io.nats.client; import static io.nats.client.Nats.ConnState; import static io.nats.client.Nats.ConnState.CLOSED; import static io.nats.client.Nats.ConnState.CONNECTED; import static io.nats.client.Nats.ConnState.CONNECTING; import static io.nats.client.Nats.ConnState.DISCONNECTED; import static io.nats.client.Nats.ConnState.RECONNECTING; import static io.nats.client.Nats.ERR_BAD_SUBJECT; import static io.nats.client.Nats.ERR_BAD_SUBSCRIPTION; import static io.nats.client.Nats.ERR_BAD_TIMEOUT; import static io.nats.client.Nats.ERR_CONNECTION_CLOSED; import static io.nats.client.Nats.ERR_CONNECTION_READ; import static io.nats.client.Nats.ERR_MAX_PAYLOAD; import static io.nats.client.Nats.ERR_NO_INFO_RECEIVED; import static io.nats.client.Nats.ERR_NO_SERVERS; import static io.nats.client.Nats.ERR_RECONNECT_BUF_EXCEEDED; import static io.nats.client.Nats.ERR_SECURE_CONN_REQUIRED; import static io.nats.client.Nats.ERR_SECURE_CONN_WANTED; import static io.nats.client.Nats.ERR_SLOW_CONSUMER; import static io.nats.client.Nats.ERR_STALE_CONNECTION; import static io.nats.client.Nats.ERR_TCP_FLUSH_FAILED; import static io.nats.client.Nats.ERR_TIMEOUT; import static io.nats.client.Nats.PERMISSIONS_ERR; import static io.nats.client.Nats.TLS_SCHEME; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.annotations.SerializedName; import com.sun.corba.se.spi.orbutil.threadpool.ThreadPool; import java.io.BufferedReader; import java.io.ByteArrayOutputStream; import java.io.EOFException; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.URI; import java.nio.BufferOverflowException; import java.nio.ByteBuffer; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.Random; import java.util.TimerTask; import java.util.concurrent.BlockingQueue; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.ScheduledThreadPoolExecutor; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicLong; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import org.slf4j.Logger; import org.slf4j.LoggerFactory; class ConnectionImpl implements Connection { private final Logger logger = LoggerFactory.getLogger(ConnectionImpl.class); private String version = null; private static final String INBOX_PREFIX = "_INBOX."; private ConnState status = DISCONNECTED; protected static final String STALE_CONNECTION = "Stale Connection"; // Default language string for CONNECT message protected static final String LANG_STRING = "java"; // The size of the read buffer in readLoop. protected static final int DEFAULT_BUF_SIZE = 65536; // The size of the BufferedInputStream and BufferedOutputStream on top of the socket. protected static final int DEFAULT_STREAM_BUF_SIZE = 65536; // The buffered size of the flush "kick" channel protected static final int FLUSH_CHAN_SIZE = 1; // The number of msec the flusher will wait between flushes private long flushTimerInterval = 1; private TimeUnit flushTimerUnit = TimeUnit.MICROSECONDS; protected static final String _CRLF_ = "\r\n"; protected static final String _EMPTY_ = ""; protected static final String _SPC_ = " "; protected static final String _PUB_P_ = "PUB "; // Operations protected static final String _OK_OP_ = "+OK"; protected static final String _ERR_OP_ = "-ERR"; protected static final String _MSG_OP_ = "MSG"; protected static final String _PING_OP_ = "PING"; protected static final String _PONG_OP_ = "PONG"; protected static final String _INFO_OP_ = "INFO"; // Message Prototypes protected static final String CONN_PROTO = "CONNECT %s" + _CRLF_; protected static final String PING_PROTO = "PING" + _CRLF_; protected static final String PONG_PROTO = "PONG" + _CRLF_; protected static final String PUB_PROTO = "PUB %s %s %d" + _CRLF_; protected static final String SUB_PROTO = "SUB %s%s %d" + _CRLF_; protected static final String UNSUB_PROTO = "UNSUB %d %s" + _CRLF_; protected static final String OK_PROTO = _OK_OP_ + _CRLF_; enum ClientProto { CLIENT_PROTO_ZERO(0), // CLIENT_PROTO_ZERO is the original client protocol from 2009. CLIENT_PROTO_INFO(1); // clientProtoInfo signals a client can receive more then the original // INFO block. This can be used to update clients on other cluster // members, etc. private final int value; ClientProto(int value) { this.value = value; } public int getValue() { return value; } } private ConnectionImpl nc = null; final Lock mu = new ReentrantLock(); // protected final Lock mu = new AlternateDeadlockDetectingLock(true, true); private final AtomicLong sidCounter = new AtomicLong(); private URI url = null; private Options opts = null; private TcpConnectionFactory tcf = null; private TcpConnection conn = null; // Prepare protocol messages for efficiency private ByteBuffer pubProtoBuf = null; // we have a buffered reader for writing, and reading. // This is for both performance, and having to work around // interlinked read/writes (supported by the underlying network // stream, but not the BufferedStream). private OutputStream bw = null; private InputStream br = null; private ByteArrayOutputStream pending = null; private Map<Long, SubscriptionImpl> subs = new ConcurrentHashMap<Long, SubscriptionImpl>(); private List<Srv> srvPool = null; private Map<String, URI> urls = null; private Exception lastEx = null; private ServerInfo info = null; private int pout; private Parser parser = new Parser(this); private byte[] pingProtoBytes = null; private int pingProtoBytesLen = 0; private byte[] pongProtoBytes = null; private int pongProtoBytesLen = 0; private byte[] pubPrimBytes = null; private int pubPrimBytesLen = 0; private byte[] crlfProtoBytes = null; private int crlfProtoBytesLen = 0; private Statistics stats = null; private List<BlockingQueue<Boolean>> pongs; private static final int NUM_CORE_THREADS = 4; // The main executor service for core threads and timers private ScheduledExecutorService exec; static final String EXEC_NAME = "jnats-exec"; // Executor for subscription threads private ExecutorService subexec; static final String SUB_EXEC_NAME = "jnats-subscriptions"; // Executor for async connection callbacks private ExecutorService cbexec; static final String CB_EXEC_NAME = "jnats-callbacks"; // The ping timer task private ScheduledFuture<?> ptmr = null; static final String PINGTIMER = "pingtimer"; static final String READLOOP = "readloop"; static final String FLUSHER = "flusher"; private final Map<String, Future<?>> tasks = new HashMap<>(); private static final int NUM_WATCHER_THREADS = 2; private CountDownLatch socketWatchersStartLatch = new CountDownLatch(NUM_WATCHER_THREADS); private CountDownLatch socketWatchersDoneLatch = null; // The flusher signalling channel private BlockingQueue<Boolean> fch; ConnectionImpl() { } ConnectionImpl(Options opts) { Properties props = this.getProperties(Nats.PROP_PROPERTIES_FILENAME); version = props.getProperty(Nats.PROP_CLIENT_VERSION); this.nc = this; this.opts = opts; this.stats = new Statistics(); if (opts.getFactory() != null) { tcf = opts.getFactory(); } else { tcf = new TcpConnectionFactory(); } setTcpConnection(tcf.createConnection()); sidCounter.set(0); pingProtoBytes = PING_PROTO.getBytes(); pingProtoBytesLen = pingProtoBytes.length; pongProtoBytes = PONG_PROTO.getBytes(); pongProtoBytesLen = pongProtoBytes.length; pubPrimBytes = _PUB_P_.getBytes(); pubPrimBytesLen = pubPrimBytes.length; crlfProtoBytes = _CRLF_.getBytes(); crlfProtoBytesLen = crlfProtoBytes.length; // predefine the start of the publish protocol message. buildPublishProtocolBuffer(Parser.MAX_CONTROL_LINE_SIZE); setupServerPool(); } ScheduledExecutorService createScheduler() { ScheduledThreadPoolExecutor sexec = (ScheduledThreadPoolExecutor) Executors.newScheduledThreadPool(NUM_CORE_THREADS, new NatsThreadFactory(EXEC_NAME)); // sexec.setExecuteExistingDelayedTasksAfterShutdownPolicy(false); // sexec.setContinueExistingPeriodicTasksAfterShutdownPolicy(false); sexec.setRemoveOnCancelPolicy(true); return sexec; // return Executors.newScheduledThreadPool(NUM_CORE_THREADS, new NatsThreadFactory(EXEC_NAME)); } ExecutorService createSubscriptionScheduler() { return Executors.newCachedThreadPool(new NatsThreadFactory(SUB_EXEC_NAME)); } ExecutorService createCallbackScheduler() { return Executors.newSingleThreadExecutor(new NatsThreadFactory(CB_EXEC_NAME)); } void setup() { exec = createScheduler(); cbexec = createCallbackScheduler(); subexec = createSubscriptionScheduler(); fch = createFlushChannel(); pongs = createPongs(); subs.clear(); } Properties getProperties(InputStream inputStream) { Properties rv = new Properties(); try { if (inputStream == null) { rv = null; } else { rv.load(inputStream); } } catch (IOException e) { logger.warn("nats: error loading properties from InputStream", e); rv = null; } return rv; } Properties getProperties(String resourceName) { InputStream is = getClass().getClassLoader().getResourceAsStream(resourceName); return getProperties(is); } private void buildPublishProtocolBuffer(int size) { pubProtoBuf = ByteBuffer.allocate(size); pubProtoBuf.put(pubPrimBytes, 0, pubPrimBytesLen); pubProtoBuf.mark(); // System.arraycopy(pubPrimBytes, 0, pubProtoBuf, 0, pubPrimBytesLen); } /* * Create the server pool using the options given. We will place a Url option first, followed by * any Srv Options. We will randomize the server pool (except Url) unless the NoRandomize flag * is set. */ void setupServerPool() { final URI url; if (opts.getUrl() != null) { url = URI.create(opts.getUrl()); } else { url = null; } List<URI> servers = opts.getServers(); srvPool = new ArrayList<Srv>(); urls = new ConcurrentHashMap<String, URI>(); if (servers != null) { for (URI s : servers) { addUrlToPool(s, false); } } if (!opts.isNoRandomize()) { // Randomize the order Collections.shuffle(srvPool, new Random(System.nanoTime())); } /* * Insert the supplied url, if not null or empty, at the beginning of the list. Normally, if * this is set, then opts.servers should NOT be set, and vice versa. However, we always * allowed both to be set before, so we'll continue to do so. */ if (url != null) { srvPool.add(0, new Srv(url, false)); urls.put(url.getAuthority(), url); } // If the pool is empty, add the default URL if (srvPool.isEmpty()) { addUrlToPool(Nats.DEFAULT_URL, false); } /* * At this point, srvPool being empty would be programmer error. */ // Return the first server in the list this.setUrl(srvPool.get(0).url); } /* Add a string URL to the server pool */ void addUrlToPool(String srvUrl, boolean implicit) { URI uri = URI.create(srvUrl); srvPool.add(new Srv(uri, implicit)); urls.put(uri.getAuthority(), uri); } /* Add a URL to the server pool */ void addUrlToPool(URI uri, boolean implicit) { srvPool.add(new Srv(uri, implicit)); urls.put(uri.getAuthority(), uri); } Srv currentServer() { Srv rv = null; for (Srv s : srvPool) { if (s.url.equals(this.getUrl())) { rv = s; break; } } return rv; } Srv selectNextServer() throws IOException { Srv srv = currentServer(); if (srv == null) { throw new IOException(ERR_NO_SERVERS); } /* * Pop the current server and put onto the end of the list. Select head of list as long as * number of reconnect attempts under MaxReconnect. */ srvPool.remove(srv); /* * if the maxReconnect is unlimited, or the number of reconnect attempts is less than * maxReconnect, move the current server to the end of the list. * */ int maxReconnect = opts.getMaxReconnect(); if ((maxReconnect < 0) || (srv.reconnects < maxReconnect)) { srvPool.add(srv); } if (srvPool.isEmpty()) { this.setUrl(null); throw new IOException(ERR_NO_SERVERS); } return srvPool.get(0); } Connection connect() throws IOException { // Create actual socket connection // For first connect we walk all servers in the pool and try // to connect immediately. IOException returnedErr = null; mu.lock(); try { for (Srv srv : srvPool) { this.setUrl(srv.url); try { logger.debug("Connecting to {}", this.getUrl()); createConn(); logger.debug("Connected to {}", this.getUrl()); this.setup(); try { processConnectInit(); srv.reconnects = 0; returnedErr = null; break; } catch (IOException e) { returnedErr = e; mu.unlock(); close(DISCONNECTED, false); mu.lock(); this.setUrl(null); } catch (InterruptedException e) { returnedErr = new IOException(e); mu.unlock(); close(DISCONNECTED, false); mu.lock(); this.setUrl(null); } } catch (IOException e) { // createConn failed // Cancel out default connection refused, will trigger the // No servers error conditional if (e.getMessage() != null && e.getMessage().contains("Connection refused")) { setLastError(null); } } } // for if ((returnedErr == null) && (this.status != CONNECTED)) { returnedErr = new IOException(ERR_NO_SERVERS); } if (returnedErr != null) { throw (returnedErr); } cbexec = createCallbackScheduler(); return this; } finally { mu.unlock(); } } /* * createConn will connect to the server and wrap the appropriate bufio structures. A new * connection is always created. */ void createConn() throws IOException { if (opts.getConnectionTimeout() < 0) { logger.warn("{}: {}", ERR_BAD_TIMEOUT, opts.getConnectionTimeout()); throw new IOException(ERR_BAD_TIMEOUT); } Srv srv = currentServer(); if (srv == null) { throw new IOException(ERR_NO_SERVERS); } else { srv.updateLastAttempt(); } try { logger.debug("Opening {}", srv.url); conn = tcf.createConnection(); conn.open(srv.url.toString(), opts.getConnectionTimeout()); logger.trace("Opened {} as TcpConnection ({})", srv.url, conn); } catch (IOException e) { logger.debug("Couldn't establish connection to {}: {}", srv.url, e.getMessage()); throw (e); } if ((pending != null) && (bw != null)) { try { bw.flush(); } catch (IOException e) { logger.warn(ERR_TCP_FLUSH_FAILED); } } bw = conn.getOutputStream(DEFAULT_STREAM_BUF_SIZE); br = conn.getInputStream(DEFAULT_STREAM_BUF_SIZE); } BlockingQueue<Message> createMsgChannel() { return createMsgChannel(Integer.MAX_VALUE); } BlockingQueue<Message> createMsgChannel(int size) { int theSize = size; if (theSize <= 0) { theSize = 1; } return new LinkedBlockingQueue<Message>(theSize); } BlockingQueue<Boolean> createBooleanChannel() { return new LinkedBlockingQueue<Boolean>(); } BlockingQueue<Boolean> createBooleanChannel(int size) { int theSize = size; if (theSize <= 0) { theSize = 1; } return new LinkedBlockingQueue<Boolean>(theSize); } BlockingQueue<Boolean> createFlushChannel() { return new LinkedBlockingQueue<Boolean>(FLUSH_CHAN_SIZE); // return new SynchronousQueue<Boolean>(); } // This will clear any pending flush calls and release pending calls. // Lock is assumed to be held by the caller. void clearPendingFlushCalls() { // Clear any queued pongs, e.g. pending flush calls. if (pongs == null) { return; } for (BlockingQueue<Boolean> ch : pongs) { if (ch != null) { ch.clear(); // Signal other waiting threads that we're done ch.add(false); } } pongs.clear(); pongs = null; } @Override public void close() { close(CLOSED, true); } /* * Low level close call that will do correct cleanup and set desired status. Also controls * whether user defined callbacks will be triggered. The lock should not be held entering this * method. This method will handle the locking manually. */ private void close(ConnState closeState, boolean doCBs) { logger.debug("close({}, {})", closeState, String.valueOf(doCBs)); final ConnectionImpl nc = this; mu.lock(); try { if (closed()) { this.status = closeState; return; } this.status = CLOSED; // Kick the Flusher routine so it falls out. kickFlusher(); } finally { mu.unlock(); } mu.lock(); try { // Clear any queued pongs, e.g. pending flush calls. clearPendingFlushCalls(); // Go ahead and make sure we have flushed the outbound if (conn != null) { try { if (bw != null) { bw.flush(); } } catch (IOException e) { /* NOOP */ } } // Close sync subscribers and release any pending nextMsg() calls. for (Map.Entry<Long, SubscriptionImpl> entry : subs.entrySet()) { SubscriptionImpl sub = entry.getValue(); // for (Long key : subs.keySet()) { // SubscriptionImpl sub = subs.get(key); sub.lock(); try { sub.closeChannel(); // Mark as invalid, for signaling to deliverMsgs sub.closed = true; // Mark connection closed in subscription sub.connClosed = true; // Terminate thread exec sub.close(); } finally { sub.unlock(); } } subs.clear(); // perform appropriate callback if needed for a disconnect; if (doCBs) { if (opts.getDisconnectedCallback() != null && conn != null) { cbexec.submit(new Runnable() { @Override public void run() { opts.getDisconnectedCallback().onDisconnect(new ConnectionEvent(nc)); logger.trace("executed DisconnectedCB"); } }); } if (opts.getClosedCallback() != null) { cbexec.submit(new Runnable() { @Override public void run() { opts.getClosedCallback().onClose(new ConnectionEvent(nc)); logger.trace("executed ClosedCB"); } }); } if (cbexec != null) { cbexec.shutdown(); } } this.status = closeState; if (conn != null) { conn.close(); } if (exec != null) { shutdownAndAwaitTermination(exec, EXEC_NAME); } if (subexec != null) { shutdownAndAwaitTermination(subexec, SUB_EXEC_NAME); } } finally { mu.unlock(); } } void shutdownAndAwaitTermination(ExecutorService pool, String name) { try { pool.shutdownNow(); if (!pool.awaitTermination(10, TimeUnit.SECONDS)) { logger.error("{} did not terminate", name); ThreadPoolExecutor poolExec = (ThreadPoolExecutor) pool; logger.error("{} tasks still active", poolExec.getActiveCount()); } } catch (InterruptedException ie) { // (Re-)Cancel if current thread also interrupted pool.shutdownNow(); // Preserve interrupt status Thread.currentThread().interrupt(); } } void processConnectInit() throws IOException, InterruptedException { // Set our status to connecting. status = CONNECTING; // Process the INFO protocol that we should be receiving processExpectedInfo(); // Send the CONNECT and PING protocol, and wait for the PONG. sendConnect(); // Reset the number of PINGs sent out this.setActualPingsOutstanding(0); // Start the readLoop and flusher threads spinUpSocketWatchers(); } // This will check to see if the connection should be // secure. This can be dictated from either end and should // only be called after the INIT protocol has been received. void checkForSecure() throws IOException { // Check to see if we need to engage TLS // Check for mismatch in setups if (opts.isSecure() && !info.isTlsRequired()) { throw new IOException(ERR_SECURE_CONN_WANTED); } else if (info.isTlsRequired() && !opts.isSecure()) { throw new IOException(ERR_SECURE_CONN_REQUIRED); } // Need to rewrap with bufio if (opts.isSecure() || TLS_SCHEME.equals(this.getUrl().getScheme())) { makeTlsConn(); } } // makeSecureConn will wrap an existing Conn using TLS void makeTlsConn() throws IOException { conn.setTlsDebug(opts.isTlsDebug()); conn.makeTls(opts.getSslContext()); bw = conn.getOutputStream(DEFAULT_STREAM_BUF_SIZE); br = conn.getInputStream(DEFAULT_STREAM_BUF_SIZE); } void processExpectedInfo() throws IOException, InterruptedException { Control control; try { // Read the protocol control = readOp(); } catch (IOException e) { processOpError(e); return; } // The nats protocol should send INFO first always. if (!control.op.equals(_INFO_OP_)) { throw new IOException(ERR_NO_INFO_RECEIVED); } // Parse the protocol processInfo(control.args); checkForSecure(); } // processPing will send an immediate pong protocol response to the // server. The server uses this mechanism to detect dead clients. void processPing() { try { sendProto(pongProtoBytes, pongProtoBytesLen); } catch (IOException e) { setLastError(e); // e.printStackTrace(); } } // processPong is used to process responses to the client's ping // messages. We use pings for the flush mechanism as well. void processPong() throws InterruptedException { BlockingQueue<Boolean> ch = null; mu.lockInterruptibly(); try { if (pongs != null && pongs.size() > 0) { ch = pongs.get(0); pongs.remove(0); } setActualPingsOutstanding(0); } finally { mu.unlock(); } if (ch != null) { ch.add(true); } } // processOK is a placeholder for processing OK messages. void processOk() { // NOOP; } // processInfo is used to parse the info messages sent // from the server. void processInfo(String infoString) { if ((infoString == null) || infoString.isEmpty()) { return; } setConnectedServerInfo(ServerInfo.createFromWire(infoString)); boolean updated = false; if (info.getConnectUrls() != null) { for (String s : info.getConnectUrls()) { if (!urls.containsKey(s)) { this.addUrlToPool(String.format("nats://%s", s), true); updated = true; } } if (updated && !opts.isNoRandomize()) { Collections.shuffle(srvPool); } } } // processAsyncInfo does the same as processInfo, but is called // from the parser. Calls processInfo under connection's lock // protection. void processAsyncInfo(byte[] asyncInfo, int offset, int length) { mu.lock(); try { String theInfo = new String(asyncInfo, offset, length); // Ignore errors, we will simply not update the server pool... processInfo(theInfo); } finally { mu.unlock(); } } // processOpError handles errors from reading or parsing the protocol. // This is where disconnect/reconnect is initially handled. // The lock should not be held entering this function. void processOpError(Exception err) throws InterruptedException { mu.lockInterruptibly(); try { if (connecting() || closed() || reconnecting()) { return; } logger.debug("Connection terminated: {}", err.getMessage()); if (opts.isReconnectAllowed() && status == CONNECTED) { // Set our new status status = RECONNECTING; if (ptmr != null) { ptmr.cancel(true); tasks.remove(ptmr); } if (this.conn != null) { try { bw.flush(); } catch (IOException e1) { logger.warn("I/O error during flush"); } conn.close(); } if (fch != null && !fch.offer(false)) { logger.debug("Coudn't shut down flusher following connection error"); } // Create a new pending buffer to underpin the buffered output // stream while we are reconnecting. setPending(new ByteArrayOutputStream(opts.getReconnectBufSize())); setOutputStream(getPending()); if (exec.isShutdown()) { exec = createScheduler(); } exec.submit(new Runnable() { public void run() { Thread.currentThread().setName("reconnect"); try { doReconnect(); } catch (InterruptedException e) { logger.warn("nats: interrupted while reonnecting"); } } }); if (cbexec.isShutdown()) { cbexec = createCallbackScheduler(); } } else { processDisconnect(); setLastError(err); close(); } } finally { mu.unlock(); } } protected void processDisconnect() { logger.debug("processDisconnect()"); status = DISCONNECTED; } @Override public boolean isReconnecting() { mu.lock(); try { return reconnecting(); } finally { mu.unlock(); } } boolean reconnecting() { return (status == RECONNECTING); } @Override public boolean isConnected() { mu.lock(); try { return connected(); } finally { mu.unlock(); } } boolean connected() { return (status == CONNECTED); } @Override public boolean isClosed() { mu.lock(); try { return closed(); } finally { mu.unlock(); } } boolean closed() { return (status == CLOSED); } // flushReconnectPending will push the pending items that were // gathered while we were in a RECONNECTING state to the socket. void flushReconnectPendingItems() { if (pending == null) { return; } if (pending.size() > 0) { try { bw.write(pending.toByteArray(), 0, pending.size()); bw.flush(); } catch (IOException e) { logger.error("Error flushing pending items", e); } } pending = null; } // Try to reconnect using the option parameters. // This function assumes we are allowed to reconnect. void doReconnect() throws InterruptedException { logger.trace("doReconnect()"); // We want to make sure we have the other watchers shutdown properly // here before we proceed past this point waitForExits(); logger.trace("Old threads have exited, proceeding with reconnect"); // FIXME(dlc) - We have an issue here if we have // outstanding flush points (pongs) and they were not // sent out, but are still in the pipe. // Hold the lock manually and release where needed below. mu.lockInterruptibly(); try { // Clear any queued pongs, e.g. pending flush calls. nc.clearPendingFlushCalls(); // Clear any errors. setLastError(null); // Perform appropriate callback if needed for a disconnect if (opts.getDisconnectedCallback() != null) { logger.trace("Spawning disconnectCB from doReconnect()"); cbexec.submit(new Runnable() { public void run() { opts.getDisconnectedCallback().onDisconnect(new ConnectionEvent(nc)); } }); logger.trace("Spawned disconnectCB from doReconnect()"); } while (!srvPool.isEmpty()) { Srv cur; try { cur = selectNextServer(); this.setUrl(cur.url); } catch (IOException nse) { setLastError(nse); break; } long sleepTime = 0L; // Sleep appropriate amount of time before the // connection attempt if connecting to same server // we just got disconnected from. long timeSinceLastAttempt = cur.timeSinceLastAttempt(); if (timeSinceLastAttempt < opts.getReconnectWait()) { sleepTime = opts.getReconnectWait() - timeSinceLastAttempt; } if (sleepTime > 0) { mu.unlock(); Thread.sleep(sleepTime); mu.lockInterruptibly(); } // Check if we have been closed first. if (isClosed()) { logger.debug("Connection has been closed while in doReconnect()"); break; } // Mark that we tried a reconnect cur.reconnects++; // try to create a new connection try { conn.teardown(); createConn(); } catch (Exception e) { conn.teardown(); logger.trace("doReconnect: createConn() failed for {}", cur); logger.trace("createConn failed", e); // not yet connected, retry and hold // the lock. setLastError(null); continue; } // We are reconnected. stats.incrementReconnects(); // Process connect logic try { processConnectInit(); } catch (IOException e) { conn.teardown(); logger.warn("couldn't connect to {} ({})", cur.url, e.getMessage()); setLastError(e); status = RECONNECTING; continue; } logger.trace("Successful reconnect; Resetting reconnects for {}", cur); // Clear out server stats for the server we connected to.. // cur.didConnect = true; cur.reconnects = 0; // Send existing subscription state resendSubscriptions(); // Now send off and clear pending buffer flushReconnectPendingItems(); // Flush the buffer try { getOutputStream().flush(); } catch (IOException e) { logger.warn("Error flushing output stream"); setLastError(e); status = RECONNECTING; continue; } // Done with the pending buffer setPending(null); // This is where we are truly connected. status = CONNECTED; // Queue up the reconnect callback. if (opts.getReconnectedCallback() != null) { logger.trace("Scheduling reconnectedCb from doReconnect()"); cbexec.submit(new Runnable() { public void run() { opts.getReconnectedCallback().onReconnect(new ConnectionEvent(nc)); } }); logger.trace("Scheduled reconnectedCb from doReconnect()"); } // Release the lock here, we will return below mu.unlock(); try { // Make sure to flush everything flush(); } catch (IOException e) { if (status == CONNECTED) { logger.warn("Error flushing connection", e); } } // finally { // mu.lockInterruptibly(); return; } // while logger.trace("Reconnect FAILED"); // Call into close.. We have no servers left. if (getLastException() == null) { setLastError(new IOException(ERR_NO_SERVERS)); } } finally { mu.unlock(); } close(); } boolean connecting() { return (status == CONNECTING); } ConnState status() { return status; } static String normalizeErr(String error) { String str = error; if (str != null) { str = str.replaceFirst(_ERR_OP_ + "\\s+", "").toLowerCase(); str = str.replaceAll("^\'|\'$", ""); } return str; } static String normalizeErr(ByteBuffer error) { String str = Parser.bufToString(error); if (str != null) { str = str.trim(); } return normalizeErr(str); } // processErr processes any error messages from the server and // sets the connection's lastError. void processErr(ByteBuffer error) throws InterruptedException { // boolean doCBs = false; NATSException ex; String err = normalizeErr(error); if (STALE_CONNECTION.equalsIgnoreCase(err)) { processOpError(new IOException(ERR_STALE_CONNECTION)); } else if (err.startsWith(PERMISSIONS_ERR)) { processPermissionsViolation(err); } else { ex = new NATSException("nats: " + err); ex.setConnection(this); mu.lock(); try { setLastError(ex); } finally { mu.unlock(); } close(); } } // caller must lock protected void sendConnect() throws IOException { String line; // Send CONNECT bw.write(connectProto().getBytes()); bw.flush(); // Process +OK if (opts.isVerbose()) { line = readLine(); if (!_OK_OP_.equals(line)) { throw new IOException( String.format("nats: expected '%s', got '%s'", _OK_OP_, line)); } } // Send PING bw.write(pingProtoBytes, 0, pingProtoBytesLen); bw.flush(); // Now read the response from the server. try { line = readLine(); } catch (IOException e) { throw new IOException(ERR_CONNECTION_READ, e); } // We expect a PONG if (!PONG_PROTO.trim().equals(line)) { // But it could be something else, like -ERR // If it's a server error... if (line.startsWith(_ERR_OP_)) { // Remove -ERR, trim spaces and quotes, and convert to lower case. line = normalizeErr(line); throw new IOException("nats: " + line); } // Notify that we got an unexpected protocol. throw new IOException(String.format("nats: expected '%s', got '%s'", _PONG_OP_, line)); } // This is where we are truly connected. status = CONNECTED; } // This function is only used during the initial connection process String readLine() throws IOException { BufferedReader breader = conn.getBufferedReader(); String line; line = breader.readLine(); if (line == null) { throw new EOFException(ERR_CONNECTION_CLOSED); } return line; } /* * This method is only used by processPing. It is also used in the gnatsd tests. */ void sendProto(byte[] value, int length) throws IOException { mu.lock(); try { bw.write(value, 0, length); kickFlusher(); } finally { mu.unlock(); } } // Generate a connect protocol message, issuing user/password if // applicable. The lock is assumed to be held upon entering. String connectProto() { String userInfo = getUrl().getUserInfo(); String user = null; String pass = null; String token = null; if (userInfo != null) { // if no password, assume username is authToken String[] userpass = userInfo.split(":"); if (userpass[0].length() > 0) { switch (userpass.length) { case 1: token = userpass[0]; break; case 2: user = userpass[0]; pass = userpass[1]; break; default: break; } } } else { // Take from options (possibly all empty strings) user = opts.getUsername(); pass = opts.getPassword(); token = opts.getToken(); } ConnectInfo info = new ConnectInfo(opts.isVerbose(), opts.isPedantic(), user, pass, token, opts.isSecure(), opts.getConnectionName(), LANG_STRING, version, ClientProto.CLIENT_PROTO_INFO); return String.format(CONN_PROTO, info); } Control readOp() throws IOException { // This is only used when creating a connection, so simplify // life and just create a BufferedReader to read the incoming // info string. // Do not close the BufferedReader; let TcpConnection manage it. String str = readLine(); return new Control(str); } // waitForExits will wait for all socket watcher threads to // complete before proceeding. private void waitForExits() throws InterruptedException { // Kick old flusher forcefully. kickFlusher(); if (socketWatchersDoneLatch != null) { logger.debug("nats: waiting for watcher threads to exit"); socketWatchersDoneLatch.await(); } } protected void spinUpSocketWatchers() throws InterruptedException { // Make sure everything has exited. waitForExits(); socketWatchersDoneLatch = new CountDownLatch(NUM_WATCHER_THREADS); socketWatchersStartLatch = new CountDownLatch(NUM_WATCHER_THREADS); Future<?> task = exec.submit(new Runnable() { public void run() { Thread.currentThread().setName(READLOOP); logger.debug("{} starting...", READLOOP); socketWatchersStartLatch.countDown(); try { socketWatchersStartLatch.await(); readLoop(); } catch (InterruptedException e) { logger.debug("{} interrupted", READLOOP); Thread.currentThread().interrupt(); } catch (Exception e) { logger.error("Unexpected exception in {}", READLOOP, e); } finally { socketWatchersDoneLatch.countDown(); } logger.debug("{} exiting", READLOOP); } }); tasks.put(READLOOP, task); task = exec.submit(new Runnable() { public void run() { Thread.currentThread().setName(FLUSHER); logger.debug("{} starting...", FLUSHER); socketWatchersStartLatch.countDown(); try { socketWatchersStartLatch.await(); flusher(); } catch (InterruptedException e) { logger.debug("{} interrupted", FLUSHER); Thread.currentThread().interrupt(); } catch (Exception e) { logger.error("Unexpected exception in {}", FLUSHER, e); } finally { socketWatchersDoneLatch.countDown(); } logger.debug("{} exiting", FLUSHER); } }); tasks.put(FLUSHER, task); // resetFlushTimer(); // socketWatchersDoneLatch.countDown(); socketWatchersStartLatch.countDown(); resetPingTimer(); } void readLoop() throws InterruptedException { Parser parser; int len; boolean sb; TcpConnection conn = null; mu.lockInterruptibly(); try { parser = this.parser; if (parser.ps == null) { parser.ps = new Parser.ParseState(); } } finally { mu.unlock(); } // Stack based buffer. byte[] buffer = new byte[DEFAULT_BUF_SIZE]; while (!Thread.currentThread().isInterrupted()) { mu.lockInterruptibly(); try { sb = (closed() || reconnecting()); if (sb) { parser.ps = new Parser.ParseState(); } conn = this.conn; } finally { mu.unlock(); } if (sb || conn == null) { break; } try { len = br.read(buffer); if (len == -1) { throw new IOException(ERR_STALE_CONNECTION); } parser.parse(buffer, len); } catch (IOException | ParseException e) { logger.debug("Exception in readloop(): '{}' (state: {})", e.getMessage(), status); if (status != CLOSED) { processOpError(e); } break; } } mu.lockInterruptibly(); try { parser.ps = null; } finally { mu.unlock(); } } /** * waitForMsgs waits on the conditional shared with readLoop and processMsg. It is used to * deliver messages to asynchronous subscribers. * * @param sub the asynchronous subscriber * @throws InterruptedException if the thread is interrupted */ void waitForMsgs(AsyncSubscriptionImpl sub) throws InterruptedException { boolean closed; long delivered = 0L; long max; Message msg; MessageHandler mcb; BlockingQueue<Message> mch; while (true) { sub.lock(); try { mch = sub.getChannel(); while (mch.size() == 0 && !sub.isClosed()) { sub.pCond.await(); } msg = mch.poll(); if (msg != null) { sub.pMsgs sub.pBytes -= (msg.getData() == null ? 0 : msg.getData().length); } mcb = sub.getMessageHandler(); max = sub.max; closed = sub.isClosed(); if (!closed) { sub.delivered++; delivered = sub.delivered; } } finally { sub.unlock(); } if (closed) { break; } // Deliver the message. if (msg != null && (max <= 0 || delivered <= max)) { mcb.onMessage(msg); } // If we have hit the max for delivered msgs, remove sub. if (max > 0 && delivered >= max) { mu.lock(); try { removeSub(sub); } finally { mu.unlock(); } break; } } } /** * processMsg is called by parse and will place the msg on the appropriate channel/pending queue * for processing. If the channel is full, or the pending queue is over the pending limits, the * connection is considered a slow consumer. * * @param data the buffer containing the message body * @param offset the offset within this buffer of the beginning of the message body * @param length the length of the message body */ void processMsg(byte[] data, int offset, int length) { SubscriptionImpl sub; mu.lock(); try { stats.incrementInMsgs(); stats.incrementInBytes(length); sub = subs.get(parser.ps.ma.sid); if (sub == null) { return; } // Doing message create outside of the sub's lock to reduce contention. // It's possible that we end up not using the message, but that's ok. Message msg = new Message(parser.ps.ma, sub, data, offset, length); sub.lock(); try { sub.pMsgs++; if (sub.pMsgs > sub.pMsgsMax) { sub.pMsgsMax = sub.pMsgs; } sub.pBytes += (msg.getData() == null ? 0 : msg.getData().length); if (sub.pBytes > sub.pBytesMax) { sub.pBytesMax = sub.pBytes; } // Check for a Slow Consumer if ((sub.pMsgsLimit > 0 && sub.pMsgs > sub.pMsgsLimit) || (sub.pBytesLimit > 0 && sub.pBytes > sub.pBytesLimit)) { handleSlowConsumer(sub, msg); } else { // We use mch for everything, unlike Go client if (sub.getChannel() != null) { if (sub.getChannel().add(msg)) { sub.pCond.signal(); // Clear Slow Consumer status sub.setSlowConsumer(false); } else { handleSlowConsumer(sub, msg); } } } } finally { sub.unlock(); } } finally { mu.unlock(); } } // Assumes you already have the lock void handleSlowConsumer(SubscriptionImpl sub, Message msg) { sub.dropped++; processSlowConsumer(sub); sub.pMsgs if (msg.getData() != null) { sub.pBytes -= msg.getData().length; } } void removeSub(SubscriptionImpl sub) { subs.remove(sub.getSid()); sub.lock(); try { if (sub.getChannel() != null) { sub.mch.clear(); sub.mch = null; } // Mark as invalid sub.setConnection(null); sub.closed = true; } finally { sub.unlock(); } } // processSlowConsumer will set SlowConsumer state and fire the // async error handler if registered. void processSlowConsumer(SubscriptionImpl sub) { final IOException ex = new IOException(ERR_SLOW_CONSUMER); final NATSException nex = new NATSException(ex, this, sub); setLastError(ex); if (opts.getExceptionHandler() != null && !sub.isSlowConsumer()) { cbexec.submit(new Runnable() { public void run() { opts.getExceptionHandler().onException(nex); } }); } sub.setSlowConsumer(true); } void processPermissionsViolation(String err) { final IOException serverEx = new IOException("nats: " + err); final NATSException nex = new NATSException(serverEx); nex.setConnection(this); setLastError(serverEx); if (opts.getExceptionHandler() != null) { cbexec.submit(new Runnable() { public void run() { opts.getExceptionHandler().onException(nex); } }); } } // FIXME: This is a hack // removeFlushEntry is needed when we need to discard queued up responses // for our pings as part of a flush call. This happens when we have a flush // call outstanding and we call close. boolean removeFlushEntry(BlockingQueue<Boolean> ch) throws InterruptedException { mu.lockInterruptibly(); try { if (pongs == null) { return false; } for (BlockingQueue<Boolean> c : pongs) { if (c.equals(ch)) { c.clear(); pongs.remove(c); return true; } } return false; } finally { mu.unlock(); } } // The lock must be held entering this function. void sendPing(BlockingQueue<Boolean> ch) { if (pongs == null) { pongs = createPongs(); } if (ch != null) { pongs.add(ch); } try { bw.write(pingProtoBytes, 0, pingProtoBytesLen); bw.flush(); } catch (IOException e) { setLastError(e); } } List<BlockingQueue<Boolean>> createPongs() { return new ArrayList<BlockingQueue<Boolean>>(); } ScheduledFuture<?> createPingTimer() { PingTimerTask pinger = new PingTimerTask(); return exec.scheduleWithFixedDelay(pinger, opts.getPingInterval(), opts.getPingInterval(), TimeUnit.MILLISECONDS); } void resetPingTimer() { mu.lock(); try { if (ptmr != null) { ptmr.cancel(true); tasks.remove(ptmr); } if (opts.getPingInterval() > 0) { ptmr = createPingTimer(); tasks.put("pingtimer", ptmr); } } finally { mu.unlock(); } } void writeUnsubProto(SubscriptionImpl sub, long max) throws IOException { String str = String.format(UNSUB_PROTO, sub.getSid(), max > 0 ? Long.toString(max) : ""); str = str.replaceAll(" +\r\n", "\r\n"); byte[] unsub = str.getBytes(); bw.write(unsub); } void unsubscribe(SubscriptionImpl sub, int max) throws IOException { unsubscribe(sub, (long) max); } // unsubscribe performs the low level unsubscribe to the server. // Use SubscriptionImpl.unsubscribe() protected void unsubscribe(SubscriptionImpl sub, long max) throws IOException { mu.lock(); try { if (isClosed()) { throw new IllegalStateException(ERR_CONNECTION_CLOSED); } SubscriptionImpl subscription = subs.get(sub.getSid()); // already unsubscribed if (subscription == null) { return; } // If the autounsubscribe max is > 0, set that on the subscription if (max > 0) { subscription.setMax(max); } else { removeSub(subscription); } // We will send all subscriptions when reconnecting // so that we can suppress here. if (!reconnecting()) { writeUnsubProto(subscription, max); } kickFlusher(); } finally { mu.unlock(); } } protected void kickFlusher() { if (bw != null && fch != null) { fch.offer(true); } } // This is the loop of the flusher thread protected void flusher() throws InterruptedException { // snapshot the bw and conn since they can change from underneath of us. mu.lockInterruptibly(); final OutputStream bw = this.bw; final TcpConnection conn = this.conn; final BlockingQueue<Boolean> fch = this.fch; mu.unlock(); if (conn == null || bw == null) { return; } while (fch.take()) { mu.lockInterruptibly(); try { // Check to see if we should bail out. if (!connected() || connecting() || bw != this.bw || conn != this.conn) { return; } bw.flush(); stats.incrementFlushes(); } catch (IOException e) { logger.debug("I/O exception encountered during flush"); this.setLastError(e); } finally { mu.unlock(); } Thread.sleep(flushTimerUnit.toMillis(flushTimerInterval)); } logger.debug("flusher id:{} exiting", Thread.currentThread().getId()); } /* * (non-Javadoc) * * @see io.nats.client.AbstractConnection#flush(int) */ @Override public void flush(int timeout) throws IOException, InterruptedException { if (timeout <= 0) { throw new IllegalArgumentException(ERR_BAD_TIMEOUT); } BlockingQueue<Boolean> ch = null; mu.lockInterruptibly(); try { if (closed()) { throw new IllegalStateException(ERR_CONNECTION_CLOSED); } ch = createBooleanChannel(1); sendPing(ch); } finally { mu.unlock(); } Boolean rv = ch.poll(timeout, TimeUnit.MILLISECONDS); if (rv == null) { this.removeFlushEntry(ch); throw new IOException(ERR_TIMEOUT); } else if (rv) { ch.clear(); } else { throw new IllegalStateException(ERR_CONNECTION_CLOSED); } } /// Flush will perform a round trip to the server and return when it /// receives the internal reply. @Override public void flush() throws IOException, InterruptedException { // 60 second default. flush(60000); } // resendSubscriptions will send our subscription state back to the // server. Used in reconnects void resendSubscriptions() { long adjustedMax = 0L; for (Map.Entry<Long, SubscriptionImpl> entry : subs.entrySet()) { SubscriptionImpl sub = entry.getValue(); sub.lock(); try { if (sub.max > 0) { if (sub.delivered < sub.max) { adjustedMax = sub.max - sub.delivered; } // adjustedMax could be 0 here if the number of delivered msgs // reached the max, if so unsubscribe. if (adjustedMax == 0) { // s.mu.unlock(); try { unsubscribe(sub, 0); } catch (Exception e) { /* NOOP */ } continue; } } } finally { sub.unlock(); } sendSubscriptionMessage(sub); if (adjustedMax > 0) { try { // cannot call unsubscribe here. Need to just send proto writeUnsubProto(sub, adjustedMax); } catch (Exception e) { logger.debug("nats: exception while writing UNSUB proto"); } } } } /** * subscribe is the internal subscribe function that indicates interest in a subject. * * @param subject the subject * @param queue an optional subscription queue * @param cb async callback * @param ch channel * @return the Subscription object */ SubscriptionImpl subscribe(String subject, String queue, MessageHandler cb, BlockingQueue<Message> ch) { final SubscriptionImpl sub; mu.lock(); try { // Check for some error conditions. if (closed()) { throw new IllegalStateException(ERR_CONNECTION_CLOSED); } if (cb == null && ch == null) { throw new IllegalArgumentException(ERR_BAD_SUBSCRIPTION); } if (cb != null) { sub = new AsyncSubscriptionImpl(this, subject, queue, cb); // If we have an async callback, start up a sub specific Runnable to deliver the // messages logger.debug("Starting subscription for subject '{}'", subject); subexec.submit(new Runnable() { public void run() { try { waitForMsgs((AsyncSubscriptionImpl) sub); } catch (InterruptedException e) { logger.debug("Interrupted in waitForMsgs"); Thread.currentThread().interrupt(); } } }); } else { sub = new SyncSubscriptionImpl(this, subject, queue); sub.setChannel(ch); } // Sets sid and adds to subs map addSubscription(sub); // Send SUB proto if (!reconnecting()) { sendSubscriptionMessage(sub); } kickFlusher(); return sub; } finally { mu.unlock(); } } @Override public SyncSubscription subscribe(String subject) { return subscribeSync(subject, null); } @Override public SyncSubscription subscribe(String subject, String queue) { return subscribeSync(subject, queue); } @Override public AsyncSubscription subscribe(String subject, MessageHandler cb) { return subscribe(subject, null, cb); } @Override public AsyncSubscription subscribe(String subj, String queue, MessageHandler cb) { return (AsyncSubscriptionImpl) subscribe(subj, queue, cb, null); } @Override @Deprecated public AsyncSubscription subscribeAsync(String subject, String queue, MessageHandler cb) { return (AsyncSubscriptionImpl) subscribe(subject, queue, cb, null); } @Override @Deprecated public AsyncSubscription subscribeAsync(String subj, MessageHandler cb) { return subscribe(subj, null, cb); } private void addSubscription(SubscriptionImpl sub) { sub.setSid(sidCounter.incrementAndGet()); subs.put(sub.getSid(), sub); } @Override public SyncSubscription subscribeSync(String subject, String queue) { return (SyncSubscription) subscribe(subject, queue, null, createMsgChannel()); } @Override public SyncSubscription subscribeSync(String subject) { return (SyncSubscription) subscribe(subject, null, null, createMsgChannel()); } // Use low level primitives to build the protocol for the publish // message. void writePublishProto(ByteBuffer buffer, byte[] subject, byte[] reply, int msgSize) { pubProtoBuf.put(subject, 0, subject.length); if (reply != null) { pubProtoBuf.put((byte) ' '); pubProtoBuf.put(reply, 0, reply.length); } pubProtoBuf.put((byte) ' '); byte[] bytes = new byte[12]; int idx = bytes.length; if (msgSize > 0) { for (int l = msgSize; l > 0; l /= 10) { idx bytes[idx] = digits[l % 10]; } } else { idx -= 1; bytes[idx] = digits[0]; } pubProtoBuf.put(bytes, idx, bytes.length - idx); pubProtoBuf.put(crlfProtoBytes, 0, crlfProtoBytesLen); } // Used for handrolled itoa static final byte[] digits = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'}; // The internal publish operation sends a protocol data message by queueing into the buffered // OutputStream and kicking the flush go routine. These writes should be protected. void publish(byte[] subject, byte[] reply, byte[] data, boolean forceFlush) throws IOException { int msgSize = (data != null) ? data.length : 0; mu.lock(); try { // Proactively reject payloads over the threshold set by server. if (msgSize > info.getMaxPayload()) { throw new IllegalArgumentException(ERR_MAX_PAYLOAD); } // Since we have the lock, examine directly for a tiny performance // boost in fastpath if (closed()) { throw new IllegalStateException(ERR_CONNECTION_CLOSED); } // Check if we are reconnecting, and if so check if // we have exceeded our reconnect outbound buffer limits. if (reconnecting()) { // Flush to underlying buffer try { bw.flush(); } catch (IOException e) { logger.error("I/O exception during flush"); } if (pending.size() >= opts.getReconnectBufSize()) { throw new IOException(ERR_RECONNECT_BUF_EXCEEDED); } } // write our pubProtoBuf buffer to the buffered writer. try { writePublishProto(pubProtoBuf, subject, reply, msgSize); } catch (BufferOverflowException e) { // We can get here if we have very large subjects. // Expand with some room to spare. logger.warn("nats: reallocating publish buffer due to overflow"); int resizeAmount = Parser.MAX_CONTROL_LINE_SIZE + subject.length + (reply != null ? reply.length : 0); buildPublishProtocolBuffer(resizeAmount); writePublishProto(pubProtoBuf, subject, reply, msgSize); } try { bw.write(pubProtoBuf.array(), 0, pubProtoBuf.position()); pubProtoBuf.position(pubPrimBytesLen); if (msgSize > 0) { bw.write(data, 0, msgSize); } bw.write(crlfProtoBytes, 0, crlfProtoBytesLen); } catch (IOException e) { setLastError(e); return; } stats.incrementOutMsgs(); stats.incrementOutBytes(msgSize); if (forceFlush) { bw.flush(); stats.incrementFlushes(); } else { // Opportunistic flush if (fch.isEmpty()) { kickFlusher(); } } } finally { mu.unlock(); } } // publish can throw a few different unchecked exceptions: @Override public void publish(String subject, String reply, byte[] data, boolean flush) throws IOException { if (subject == null) { throw new NullPointerException(ERR_BAD_SUBJECT); } if (subject.isEmpty()) { throw new IllegalArgumentException(ERR_BAD_SUBJECT); } byte[] subjBytes = subject.getBytes(); byte[] replyBytes = null; if (reply != null) { replyBytes = reply.getBytes(); } publish(subjBytes, replyBytes, data, flush); } @Override public void publish(String subject, String reply, byte[] data) throws IOException { publish(subject, reply, data, false); } @Override public void publish(String subject, byte[] data) throws IOException { publish(subject, null, data); } @Override public void publish(Message msg) throws IOException { publish(msg.getSubjectBytes(), msg.getReplyToBytes(), msg.getData(), false); } @Override public Message request(String subject, byte[] data, long timeout, TimeUnit unit) throws IOException, InterruptedException { String inbox = newInbox(); BlockingQueue<Message> ch = createMsgChannel(8); try (SyncSubscription sub = (SyncSubscription) subscribe(inbox, null, null, ch)) { sub.autoUnsubscribe(1); publish(subject, inbox, data); return sub.nextMessage(timeout, unit); } } @Override public Message request(String subject, byte[] data, long timeout) throws IOException, InterruptedException { return request(subject, data, timeout, TimeUnit.MILLISECONDS); } @Override public Message request(String subject, byte[] data) throws IOException, InterruptedException { return request(subject, data, -1, TimeUnit.MILLISECONDS); } @Override public String newInbox() { return String.format("%s%s", INBOX_PREFIX, NUID.nextGlobal()); } @Override public synchronized Statistics getStats() { return new Statistics(stats); } @Override public synchronized void resetStats() { stats.clear(); } @Override public synchronized long getMaxPayload() { return info.getMaxPayload(); } // Assumes already have the lock void sendSubscriptionMessage(SubscriptionImpl sub) { // We will send these for all subs when we reconnect // so that we can suppress here. String queue = sub.getQueue(); String subLine = String.format(SUB_PROTO, sub.getSubject(), (queue != null && !queue.isEmpty()) ? " " + queue : "", sub.getSid()); try { bw.write(subLine.getBytes()); } catch (IOException e) { logger.warn("nats: I/O exception while sending subscription message"); } } @Override public ClosedCallback getClosedCallback() { mu.lock(); try { return opts.getClosedCallback(); } finally { mu.unlock(); } } @Override public void setClosedCallback(ClosedCallback cb) { mu.lock(); try { opts.closedCb = cb; } finally { mu.unlock(); } } @Override public DisconnectedCallback getDisconnectedCallback() { mu.lock(); try { return opts.getDisconnectedCallback(); } finally { mu.unlock(); } } @Override public void setDisconnectedCallback(DisconnectedCallback cb) { mu.lock(); try { opts.disconnectedCb = cb; } finally { mu.unlock(); } } @Override public ReconnectedCallback getReconnectedCallback() { mu.lock(); try { return opts.getReconnectedCallback(); } finally { mu.unlock(); } } @Override public void setReconnectedCallback(ReconnectedCallback cb) { mu.lock(); try { opts.reconnectedCb = cb; } finally { mu.unlock(); } } @Override public ExceptionHandler getExceptionHandler() { mu.lock(); try { return opts.getExceptionHandler(); } finally { mu.unlock(); } } @Override public void setExceptionHandler(ExceptionHandler exceptionHandler) { mu.lock(); try { opts.asyncErrorCb = exceptionHandler; } finally { mu.unlock(); } } @Override public String getConnectedUrl() { mu.lock(); try { if (status != CONNECTED) { return null; } return getUrl().toString(); } finally { mu.unlock(); } } @Override public String getConnectedServerId() { mu.lock(); try { if (status != CONNECTED) { return null; } return info.getId(); } finally { mu.unlock(); } } @Override public ConnState getState() { mu.lock(); try { return this.status; } finally { mu.unlock(); } } @Override public ServerInfo getConnectedServerInfo() { return this.info; } void setConnectedServerInfo(ServerInfo info) { this.info = info; } @Override public Exception getLastException() { return lastEx; } void setLastError(Exception err) { this.lastEx = err; } Options getOptions() { return this.opts; } void setOptions(Options options) { this.opts = options; } void setPending(ByteArrayOutputStream pending) { this.pending = pending; } ByteArrayOutputStream getPending() { return this.pending; } void setOutputStream(OutputStream out) { mu.lock(); try { this.bw = out; } finally { mu.unlock(); } } OutputStream getOutputStream() { return bw; } void setInputStream(InputStream in) { mu.lock(); try { this.br = in; } finally { mu.unlock(); } } InputStream getInputStream() { return br; } List<BlockingQueue<Boolean>> getPongs() { return pongs; } void setPongs(List<BlockingQueue<Boolean>> pongs) { this.pongs = pongs; } Map<Long, SubscriptionImpl> getSubs() { return subs; } void setSubs(Map<Long, SubscriptionImpl> subs) { this.subs = subs; } // for testing purposes List<Srv> getServerPool() { return this.srvPool; } // for testing purposes void setServerPool(List<Srv> pool) { this.srvPool = pool; } @Override public int getPendingByteCount() { int rv = 0; if (getPending() != null) { rv = getPending().size(); } return rv; } protected void setFlushChannel(BlockingQueue<Boolean> fch) { this.fch = fch; } protected BlockingQueue<Boolean> getFlushChannel() { return fch; } void setTcpConnection(TcpConnection conn) { this.conn = conn; } TcpConnection getTcpConnection() { return this.conn; } void setTcpConnectionFactory(TcpConnectionFactory factory) { this.tcf = factory; } TcpConnectionFactory getTcpConnectionFactory() { return this.tcf; } URI getUrl() { return url; } void setUrl(URI url) { this.url = url; } int getActualPingsOutstanding() { return pout; } void setActualPingsOutstanding(int pout) { this.pout = pout; } ScheduledFuture<?> getPingTimer() { return ptmr; } void setPingTimer(ScheduledFuture<?> ptmr) { this.ptmr = ptmr; } void setParser(Parser parser) { this.parser = parser; } Parser getParser() { return parser; } String[] getServers(boolean implicitOnly) { List<String> serversList = new ArrayList<String>(srvPool.size()); for (Srv aSrvPool : srvPool) { if (implicitOnly && !aSrvPool.isImplicit()) { continue; } URI url = aSrvPool.url; String schemeUrl = String.format("%s://%s:%d", url.getScheme(), url.getHost(), url.getPort()); serversList.add(schemeUrl); } String[] servers = new String[serversList.size()]; return serversList.toArray(servers); } @Override public String[] getServers() { mu.lock(); try { return getServers(false); } finally { mu.unlock(); } } @Override public String[] getDiscoveredServers() { mu.lock(); try { return getServers(true); } finally { mu.unlock(); } } @Override public boolean isAuthRequired() { mu.lock(); try { return info.isAuthRequired(); } finally { mu.unlock(); } } @Override public boolean isTlsRequired() { mu.lock(); try { return info.isTlsRequired(); } finally { mu.unlock(); } } static class Control { String op = null; String args = null; Control(String line) { if (line == null) { return; } String[] parts = line.split(" ", 2); switch (parts.length) { case 1: op = parts[0].trim(); break; case 2: op = parts[0].trim(); args = parts[1].trim(); if (args.isEmpty()) { args = null; } break; default: } } public String toString() { return "{op=" + op + ", args=" + args + "}"; } } static class ConnectInfo { @SerializedName("verbose") private final Boolean verbose; @SerializedName("pedantic") private final Boolean pedantic; @SerializedName("user") private final String user; @SerializedName("pass") private final String pass; @SerializedName("auth_token") private final String token; @SerializedName("tls_required") private final Boolean tlsRequired; @SerializedName("name") private final String name; @SerializedName("lang") private String lang = ConnectionImpl.LANG_STRING; @SerializedName("version") private String version; @SerializedName("protocol") private final int protocol; private final transient Gson gson = new GsonBuilder().create(); public ConnectInfo(boolean verbose, boolean pedantic, String username, String password, String token, boolean secure, String connectionName, String lang, String version, ClientProto proto) { this.verbose = verbose; this.pedantic = pedantic; this.user = username; this.pass = password; this.token = token; this.tlsRequired = secure; this.name = connectionName; this.lang = lang; this.version = version; this.protocol = proto.getValue(); } public String toString() { return gson.toJson(this); } } static class Srv { URI url = null; int reconnects = 0; long lastAttemptNanos = 0L; boolean implicit = false; Srv(URI url, boolean implicit) { this.url = url; this.implicit = implicit; } boolean isImplicit() { return implicit; } // Mark the last attempt to connect to this Srv void updateLastAttempt() { lastAttemptNanos = System.nanoTime(); } // Returns time since last attempt, in msec long timeSinceLastAttempt() { return (TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - lastAttemptNanos)); } public String toString() { return String.format( "{url=%s, reconnects=%d, timeSinceLastAttempt=%dms}", url.toString(), reconnects, timeSinceLastAttempt()); } } // This will fire periodically and send a client origin // ping to the server. Will also check that we have received // responses from the server. class PingTimerTask extends TimerTask { public void run() { boolean stale = false; mu.lock(); try { if (!connected()) { return; } // Check for violation setActualPingsOutstanding(getActualPingsOutstanding() + 1); if (getActualPingsOutstanding() > opts.getMaxPingsOut()) { stale = true; return; } sendPing(null); } finally { mu.unlock(); if (stale) { try { processOpError(new IOException(ERR_STALE_CONNECTION)); } catch (InterruptedException e) { logger.warn("Interrupted"); Thread.currentThread().interrupt(); } } } } } }
package be.ibridge.kettle.core.dialog; import org.eclipse.swt.SWT; import org.eclipse.swt.events.ShellAdapter; import org.eclipse.swt.events.ShellEvent; import org.eclipse.swt.layout.FormAttachment; import org.eclipse.swt.layout.FormData; import org.eclipse.swt.layout.FormLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Dialog; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Event; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Listener; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.TableItem; import be.ibridge.kettle.core.ColumnInfo; import be.ibridge.kettle.core.Const; import be.ibridge.kettle.core.Props; import be.ibridge.kettle.core.Row; import be.ibridge.kettle.core.WindowProperty; import be.ibridge.kettle.core.value.Value; import be.ibridge.kettle.core.widget.TableView; import be.ibridge.kettle.trans.step.BaseStepDialog; /** * Shows a dialog that allows you to enter values for a number of strings. * * @author Matt * */ public class EnterStringsDialog extends Dialog { private Label wlFields; private TableView wFields; private FormData fdlFields, fdFields; private Button wOK, wCancel; private Listener lsOK, lsCancel; private Shell shell; private Row strings; private Props props; private boolean readOnly; private String message; private String title; /** * Constructs a new dialog * @param parent The parent shell to link to * @param style The style in which we want to draw this shell. * @param strings The list of rows to change. */ public EnterStringsDialog(Shell parent, int style, Row strings) { super(parent, style); this.strings=strings; props=Props.getInstance(); readOnly=false; title = "Enter string values"; message = "Enter values for the Strings specified below : "; } public Row open() { Shell parent = getParent(); Display display = parent.getDisplay(); shell = new Shell(parent, SWT.DIALOG_TRIM | SWT.RESIZE | SWT.MAX); props.setLook(shell); FormLayout formLayout = new FormLayout (); formLayout.marginWidth = Const.FORM_MARGIN; formLayout.marginHeight = Const.FORM_MARGIN; shell.setLayout(formLayout); shell.setText(title); int margin = Const.MARGIN; // Message line wlFields=new Label(shell, SWT.NONE); wlFields.setText(message); props.setLook(wlFields); fdlFields=new FormData(); fdlFields.left = new FormAttachment(0, 0); fdlFields.top = new FormAttachment(0, margin); wlFields.setLayoutData(fdlFields); int FieldsRows=strings.size(); ColumnInfo[] colinf=new ColumnInfo[] { new ColumnInfo("String name", ColumnInfo.COLUMN_TYPE_TEXT, false, readOnly), new ColumnInfo("String value", ColumnInfo.COLUMN_TYPE_TEXT, false, readOnly) }; wFields=new TableView(shell, SWT.BORDER | SWT.FULL_SELECTION | SWT.MULTI, colinf, FieldsRows, null, props ); wFields.setReadonly(readOnly); fdFields=new FormData(); fdFields.left = new FormAttachment(0, 0); fdFields.top = new FormAttachment(wlFields, 30); fdFields.right = new FormAttachment(100, 0); fdFields.bottom = new FormAttachment(100, -50); wFields.setLayoutData(fdFields); wOK=new Button(shell, SWT.PUSH); wOK.setText(" &OK "); wCancel=new Button(shell, SWT.PUSH); wCancel.setText(" &Cancel "); BaseStepDialog.positionBottomButtons(shell, new Button[] { wOK, wCancel }, margin, wFields); // Add listeners lsOK = new Listener() { public void handleEvent(Event e) { ok(); } }; lsCancel = new Listener() { public void handleEvent(Event e) { cancel(); } }; wOK.addListener (SWT.Selection, lsOK ); wCancel.addListener(SWT.Selection, lsCancel ); // Detect X or ALT-F4 or something that kills this window... shell.addShellListener( new ShellAdapter() { public void shellClosed(ShellEvent e) { cancel(); } } ); getData(); BaseStepDialog.setSize(shell); shell.open(); while (!shell.isDisposed()) { if (!display.readAndDispatch()) display.sleep(); } return strings; } public void dispose() { props.setScreen(new WindowProperty(shell)); shell.dispose(); } /** * Copy information from the meta-data input to the dialog fields. */ public void getData() { if (strings!=null) { for (int i=0;i<strings.size();i++) { Value value = strings.getValue(i); TableItem item = wFields.table.getItem(i); item.setText(1, value.getName()); if (value.getString()!=null && !value.isNull()) item.setText(2, value.getString()); } } wFields.sortTable(1); wFields.setRowNums(); wFields.optWidth(true); } private void cancel() { strings=null; dispose(); } private void ok() { if (readOnly) { // Loop over the input rows and find the new values... for (int i=0;i<wFields.nrNonEmpty();i++) { TableItem item = wFields.getNonEmpty(i); String name = item.getText(1); for (int j=0;j<strings.size();j++) { Value value = strings.getValue(j); if (value.getName().equalsIgnoreCase(name)) { String stringValue = item.getText(2); value.setValue(stringValue); } } } } else // Variable: re-construct the list of strings again... { strings.clear(); for (int i=0;i<wFields.nrNonEmpty();i++) { TableItem item = wFields.getNonEmpty(i); String name = item.getText(1); String value = item.getText(2); strings.addValue( new Value(name, value) ); } } dispose(); } /** * @return Returns the readOnly. */ public boolean isReadOnly() { return readOnly; } /** * @param readOnly The readOnly to set. */ public void setReadOnly(boolean readOnly) { this.readOnly = readOnly; } /** * @return the message */ public String getMessage() { return message; } /** * @param message the message to set */ public void setMessage(String message) { this.message = message; } /** * @return the title */ public String getTitle() { return title; } /** * @param title the title to set */ public void setTitle(String title) { this.title = title; } }
package beast.math.distributions; import java.util.List; import java.util.Random; import org.apache.commons.math.distribution.GammaDistribution; import org.apache.commons.math.distribution.GammaDistributionImpl; import beast.core.Description; import beast.core.Distribution; import beast.core.Input; import beast.core.Input.Validate; import beast.core.State; import beast.core.parameter.RealParameter; import beast.math.distributions.LogNormalDistributionModel.LogNormalImpl; /** * Initial version Ported from Beast 1.7 ExponentialMarkovModel */ @Description("A class that produces a distribution chaining values in a parameter through the Gamma distribution. " + "The value of a parameter is assumed to be Gamma distributed with mean as the previous value in the parameter. " + "If useLogNormal is set, a log normal distribution is used instead of a Gamma. " + "If a Jeffrey's prior is used, the first value is assumed to be distributed as 1/x, otherwise it is assumed to be uniform. " + "Handy for population parameters. ") public class MarkovChainDistribution extends Distribution { final public Input<Boolean> isJeffreysInput = new Input<>("jeffreys", "use Jeffrey's prior (default false)", false); final public Input<Boolean> isReverseInput = new Input<>("reverse", "parameter in reverse (default false)", false); final public Input<Boolean> useLogInput = new Input<>("uselog", "use logarithm of parameter values (default false)", false); final public Input<Double> shapeInput = new Input<>("shape", "shape parameter of the Gamma distribution (default 1.0 = exponential distribution) " + " or precision parameter if the log normal is used.", 1.0); final public Input<RealParameter> parameterInput = new Input<>("parameter", "chain parameter to calculate distribution over", Validate.REQUIRED); final public Input<Boolean> useLogNormalInput = new Input<>("useLogNormal", "use Log Normal distribution instead of Gamma (default false)", false); // Private instance variables private RealParameter chainParameter = null; private boolean jeffreys = false; private boolean reverse = false; private boolean uselog = false; private double shape = 1.0; GammaDistribution gamma; LogNormalImpl logNormal; boolean useLogNormal; @Override public void initAndValidate() { reverse = isReverseInput.get(); jeffreys = isJeffreysInput.get(); uselog = useLogInput.get(); shape = shapeInput.get(); chainParameter = parameterInput.get(); useLogNormal = useLogNormalInput.get(); gamma = new GammaDistributionImpl(shape, 1); logNormal = new LogNormalDistributionModel().new LogNormalImpl(1, 1); } /** * Get the log likelihood. * * @return the log likelihood. */ @SuppressWarnings("deprecation") @Override public double calculateLogP() { logP = 0.0; // jeffreys Prior! if (jeffreys) { logP += -Math.log(getChainValue(0)); } for (int i = 1; i < chainParameter.getDimension(); i++) { final double mean = getChainValue(i - 1); final double x = getChainValue(i); if (useLogNormal) { final double sigma = 1.0 / shape; // shape = precision // convert mean to log space final double M = Math.log(mean) - (0.5 * sigma * sigma); logNormal.setMeanAndStdDev(M, sigma); logP += logNormal.logDensity(x); } else { final double scale = mean / shape; gamma.setBeta(scale); logP += gamma.logDensity(x); } } return logP; } private double getChainValue(int i) { if (uselog) { return Math.log(chainParameter.getValue(index(i))); } else { return chainParameter.getValue(index(i)); } } private int index(int i) { if (reverse) return chainParameter.getDimension() - i - 1; else return i; } @Override public List<String> getArguments() { return null; } @Override public List<String> getConditions() { return null; } @Override public void sample(State state, Random random) { } }
package mil.dds.anet; import org.skife.jdbi.v2.DBI; import io.dropwizard.cli.ConfiguredCommand; import net.sourceforge.argparse4j.inf.Namespace; import mil.dds.anet.config.AnetConfiguration; import io.dropwizard.setup.Bootstrap; import io.dropwizard.jdbi.DBIFactory; import io.dropwizard.setup.Environment; import net.sourceforge.argparse4j.inf.Subparser; public class WaitForDBCommand extends ConfiguredCommand<AnetConfiguration> { public WaitForDBCommand() { super("waitForDB","Waits until DB is ready for connection"); } @Override public void configure(Subparser subparser) { subparser.addArgument("-n", "--nbAttempts") .dest("dbConnectionNbAttempts") .type(Integer.class) .required(false) .setDefault(20) .help("Nb of attempts before giving up. 20 by default"); subparser.addArgument("-d", "--delay") .dest("dbConnectionDelay") .type(Integer.class) .required(false) .setDefault(500) .help("Delay in ms between attempts. 500 by default"); addFileArgument(subparser); } @Override protected void run(Bootstrap<AnetConfiguration> bootstrap, Namespace namespace, AnetConfiguration configuration) throws Exception { final DBIFactory factory = new DBIFactory(); final Environment environment = new Environment(bootstrap.getApplication().getName(), bootstrap.getObjectMapper(), bootstrap.getValidatorFactory().getValidator(), bootstrap.getMetricRegistry(), bootstrap.getClassLoader(), bootstrap.getHealthCheckRegistry()); final DBI jdbi = factory.build(environment, configuration.getDataSourceFactory(), "mssql"); //We want to possibly wait for the database to be ready, and keep trying to connect int remainingTries = namespace.getInt("dbConnectionNbAttempts").intValue(); final int delay = namespace.getInt("dbConnectionDelay").intValue(); while (remainingTries try { jdbi.close(jdbi.open()); break; } catch (Exception exception) { if (remainingTries==0) throw new RuntimeException(exception); } try { Thread.sleep(delay); } catch(InterruptedException exception){ throw new RuntimeException(exception); } } } }
package net.mingsoft.config; import java.io.File; import org.springframework.aop.Advisor; import org.springframework.aop.support.DefaultPointcutAdvisor; import org.springframework.aop.support.JdkRegexpMethodPointcut; import org.springframework.boot.web.servlet.FilterRegistrationBean; import org.springframework.boot.web.servlet.ServletListenerRegistrationBean; import org.springframework.boot.web.servlet.ServletRegistrationBean; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.Ordered; import org.springframework.web.context.request.RequestContextListener; import org.springframework.web.servlet.config.annotation.InterceptorRegistry; import org.springframework.web.servlet.config.annotation.PathMatchConfigurer; import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; import com.alibaba.druid.pool.DruidDataSource; import com.alibaba.druid.support.http.StatViewServlet; import com.alibaba.druid.support.http.WebStatFilter; import com.alibaba.druid.support.spring.stat.BeanTypeAutoProxyCreator; import com.alibaba.druid.support.spring.stat.DruidStatInterceptor; import net.mingsoft.basic.interceptor.ActionInterceptor; import net.mingsoft.basic.util.BasicUtil; @Configuration public class WebConfig implements WebMvcConfigurer { @Bean public ActionInterceptor actionInterceptor() { return new ActionInterceptor(); } @Override public void configurePathMatch(PathMatchConfigurer configurer) { configurer.setUseRegisteredSuffixPatternMatch(true); } /** * rest apispring mvc */ @Override public void addInterceptors(InterceptorRegistry registry) { /** * druidServlet */ @Bean public ServletRegistrationBean druidServletRegistration() { ServletRegistrationBean registration = new ServletRegistrationBean(new StatViewServlet()); /** * druid URI */ @Bean public FilterRegistrationBean druidStatFilter() { FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean(new WebStatFilter()); /** * druid */ @Bean public DruidStatInterceptor druidStatInterceptor() { return new DruidStatInterceptor(); } @Bean public JdkRegexpMethodPointcut druidStatPointcut() { JdkRegexpMethodPointcut druidStatPointcut = new JdkRegexpMethodPointcut(); String patterns = "net.mingsoft.*.biz.*"; // set druidStatPointcut.setPatterns(patterns); return druidStatPointcut; } /** * druid */ @Bean public BeanTypeAutoProxyCreator beanTypeAutoProxyCreator() { BeanTypeAutoProxyCreator beanTypeAutoProxyCreator = new BeanTypeAutoProxyCreator(); beanTypeAutoProxyCreator.setTargetBeanType(DruidDataSource.class); beanTypeAutoProxyCreator.setInterceptorNames("druidStatInterceptor"); return beanTypeAutoProxyCreator; } /** * druid druidStatPointcut * * @return */ @Bean public Advisor druidStatAdvisor() { return new DefaultPointcutAdvisor(druidStatPointcut(), druidStatInterceptor()); } // /** // * xssFilter // */ // @Bean // public FilterRegistrationBean xssFilterRegistration() { // XssFilter xssFilter = new XssFilter(); // xssFilter.setUrlExclusion(Arrays.asList("/static/")); // FilterRegistrationBean registration = new // FilterRegistrationBean(xssFilter); /** * RequestContextListener */ @Bean public ServletListenerRegistrationBean<RequestContextListener> requestContextListenerRegistration() { return new ServletListenerRegistrationBean<>(new RequestContextListener()); } @Override public void addViewControllers(ViewControllerRegistry registry) { registry.addViewController("/").setViewName("forward:/index"); registry.setOrder(Ordered.HIGHEST_PRECEDENCE); WebMvcConfigurer.super.addViewControllers(registry); } }
package org.dynmap.spout; import java.io.File; import java.net.InetSocketAddress; import java.util.Collections; import java.util.HashSet; import java.util.Set; import java.util.concurrent.Callable; import java.util.concurrent.Future; import java.util.concurrent.FutureTask; import org.dynmap.DynmapCommonAPI; import org.dynmap.DynmapCore; import org.dynmap.DynmapLocation; import org.dynmap.DynmapWorld; import org.dynmap.Log; import org.dynmap.common.BiomeMap; import org.dynmap.common.DynmapCommandSender; import org.dynmap.common.DynmapPlayer; import org.dynmap.common.DynmapServerInterface; import org.dynmap.common.DynmapListenerManager.EventType; import org.dynmap.markers.MarkerAPI; import org.dynmap.spout.permissions.PermissionProvider; import org.spout.api.command.Command; import org.spout.api.command.CommandSource; import org.spout.api.command.RawCommandExecutor; import org.spout.api.entity.Entity; import org.spout.api.event.Event; import org.spout.api.event.EventExecutor; import org.spout.api.event.EventHandler; import org.spout.api.event.Listener; import org.spout.api.event.block.BlockChangeEvent; import org.spout.api.event.player.PlayerChatEvent; import org.spout.api.event.player.PlayerJoinEvent; import org.spout.api.event.player.PlayerLeaveEvent; import org.spout.api.exception.CommandException; import org.spout.api.geo.World; import org.spout.api.geo.cuboid.Block; import org.spout.api.geo.discrete.Point; import org.spout.api.geo.discrete.atomic.AtomicPoint; import org.spout.api.geo.discrete.atomic.Transform; import org.spout.api.player.Player; import org.spout.api.plugin.CommonPlugin; import org.spout.api.plugin.PluginDescriptionFile; import org.spout.api.plugin.PluginManager; import org.spout.api.util.Named; import org.spout.api.Game; import org.spout.api.ChatColor; public class DynmapPlugin extends CommonPlugin implements DynmapCommonAPI { private final String prefix = "[Dynmap] "; private DynmapCore core; private PermissionProvider permissions; private String version; private Game game; public SpoutEventProcessor sep; //TODO public SnapshotCache sscache; public static DynmapPlugin plugin; public DynmapPlugin() { plugin = this; } /** * Server access abstraction class */ public class SpoutServer implements DynmapServerInterface { public void scheduleServerTask(Runnable run, long delay) { game.getScheduler().scheduleSyncDelayedTask(DynmapPlugin.this, run, delay); } public DynmapPlayer[] getOnlinePlayers() { Player[] players = game.getOnlinePlayers(); DynmapPlayer[] dplay = new DynmapPlayer[players.length]; for(int i = 0; i < players.length; i++) { dplay[i] = new SpoutPlayer(players[i]); } return dplay; } public void reload() { PluginManager pluginManager = game.getPluginManager(); pluginManager.disablePlugin(DynmapPlugin.this); pluginManager.enablePlugin(DynmapPlugin.this); } public DynmapPlayer getPlayer(String name) { Player p = game.getPlayer(name, true); if(p != null) { return new SpoutPlayer(p); } return null; } public Set<String> getIPBans() { //TODO return getServer().getIPBans(); return Collections.emptySet(); } public <T> Future<T> callSyncMethod(final Callable<T> task) { final FutureTask<T> ft = new FutureTask<T>(task); final Object o = new Object(); synchronized(o) { game.getScheduler().scheduleSyncDelayedTask(DynmapPlugin.this, new Runnable() { public void run() { try { ft.run(); } finally { synchronized(o) { o.notify(); } } } }); try { o.wait(); } catch (InterruptedException ix) {} } return ft; } public String getServerName() { return game.getName(); } public boolean isPlayerBanned(String pid) { //TODO OfflinePlayer p = getServer().getOfflinePlayer(pid); //TODO if((p != null) && p.isBanned()) //TODO return true; return false; } public String stripChatColor(String s) { return ChatColor.strip(s); } private Set<EventType> registered = new HashSet<EventType>(); public boolean requestEventNotification(EventType type) { if(registered.contains(type)) return true; switch(type) { case WORLD_LOAD: case WORLD_UNLOAD: /* Already called for normal world activation/deactivation */ break; case WORLD_SPAWN_CHANGE: //TODO sep.registerEvent(Type.SPAWN_CHANGE, new WorldListener() { //TODO @Override //TODO public void onSpawnChange(SpawnChangeEvent evt) { //TODO DynmapWorld w = new SpoutWorld(evt.getWorld()); //TODO core.listenerManager.processWorldEvent(EventType.WORLD_SPAWN_CHANGE, w); //TODO } //TODO }); break; case PLAYER_JOIN: case PLAYER_QUIT: /* Already handled */ break; case PLAYER_BED_LEAVE: //TODO sep.registerEvent(Type.PLAYER_BED_LEAVE, new PlayerListener() { //TODO @Override //TODO public void onPlayerBedLeave(PlayerBedLeaveEvent evt) { //TODO DynmapPlayer p = new BukkitPlayer(evt.getPlayer()); //TODO core.listenerManager.processPlayerEvent(EventType.PLAYER_BED_LEAVE, p); //TODO } //TODO }); break; case PLAYER_CHAT: sep.registerEvent(PlayerChatEvent.class, new EventExecutor() { public void execute(Event evt) { PlayerChatEvent chatevt = (PlayerChatEvent)evt; DynmapPlayer p = null; if(chatevt.getPlayer() != null) p = new SpoutPlayer(chatevt.getPlayer()); core.listenerManager.processChatEvent(EventType.PLAYER_CHAT, p, chatevt.getMessage()); } }); break; case BLOCK_BREAK: //TODO - doing this for all block changes, not just breaks sep.registerEvent(BlockChangeEvent.class, new EventExecutor() { public void execute(Event evt) { BlockChangeEvent bce = (BlockChangeEvent)evt; Block b = bce.getBlock(); core.listenerManager.processBlockEvent(EventType.BLOCK_BREAK, b.getBlockId(), b.getWorld().getName(), b.getX(), b.getY(), b.getZ()); } }); break; case SIGN_CHANGE: //TODO - no event yet //bep.registerEvent(Type.SIGN_CHANGE, new BlockListener() { // @Override // public void onSignChange(SignChangeEvent evt) { // Block b = evt.getBlock(); // Location l = b.getLocation(); // String[] lines = evt.getLines(); /* Note: changes to this change event - intentional */ // DynmapPlayer dp = null; // Player p = evt.getPlayer(); // if(p != null) dp = new BukkitPlayer(p); // core.listenerManager.processSignChangeEvent(EventType.SIGN_CHANGE, b.getType().getId(), // l.getWorld().getName(), l.getBlockX(), l.getBlockY(), l.getBlockZ(), lines, dp); break; default: Log.severe("Unhandled event type: " + type); return false; } return true; } public boolean sendWebChatEvent(String source, String name, String msg) { DynmapWebChatEvent evt = new DynmapWebChatEvent(source, name, msg); game.getEventManager().callEvent(evt); return (evt.isCancelled() == false); } public void broadcastMessage(String msg) { game.broadcastMessage(msg); } public String[] getBiomeIDs() { BiomeMap[] b = BiomeMap.values(); String[] bname = new String[b.length]; for(int i = 0; i < bname.length; i++) bname[i] = b[i].toString(); return bname; } public double getCacheHitRate() { //TODO return sscache.getHitRate(); return 0.0; } public void resetCacheStats() { //TODO sscache.resetStats(); } public DynmapWorld getWorldByName(String wname) { World w = game.getWorld(wname); if(w != null) { return new SpoutWorld(w); } return null; } public DynmapPlayer getOfflinePlayer(String name) { //TODO return null; } } /** * Player access abstraction class */ public class SpoutPlayer extends SpoutCommandSender implements DynmapPlayer { private Player player; public SpoutPlayer(Player p) { super(p); player = p; } public boolean isConnected() { return player.isOnline(); } public String getName() { return player.getName(); } public String getDisplayName() { return player.getDisplayName(); } public boolean isOnline() { return player.isOnline(); } public DynmapLocation getLocation() { Point p = player.getEntity().getTransform().getPosition(); return toLoc(p); } public String getWorld() { Entity e = player.getEntity(); if(e != null) { World w = e.getWorld(); if(w != null) { return w.getName(); } } return null; } public InetSocketAddress getAddress() { return new InetSocketAddress(player.getAddress(), 0); } public boolean isSneaking() { //TODO return false; } public int getHealth() { //TODO return 0; } public int getArmorPoints() { //TODO return 0; } public DynmapLocation getBedSpawnLocation() { //TODO return null; } public long getLastLoginTime() { // TODO return 0; } public long getFirstLoginTime() { // TODO return 0; } } /* Handler for generic console command sender */ public class SpoutCommandSender implements DynmapCommandSender { private CommandSource sender; public SpoutCommandSender(CommandSource send) { sender = send; } public boolean hasPrivilege(String privid) { return permissions.has(sender, privid); } public void sendMessage(String msg) { sender.sendMessage(msg); } public boolean isConnected() { return true; } public boolean isOp() { //TODO return sender.isInGroup(group) return false; } } @Override public void onEnable() { game = getGame(); PluginDescriptionFile pdfFile = this.getDescription(); version = pdfFile.getVersion(); /* Initialize event processor */ if(sep == null) sep = new SpoutEventProcessor(this); /* Set up player login/quit event handler */ registerPlayerLoginListener(); permissions = new PermissionProvider(); /* Use spout default */ /* Get and initialize data folder */ File dataDirectory = this.getDataFolder(); if(dataDirectory.exists() == false) dataDirectory.mkdirs(); /* Get MC version */ String mcver = game.getVersion(); /* Instantiate core */ if(core == null) core = new DynmapCore(); /* Inject dependencies */ core.setPluginVersion(version); core.setMinecraftVersion(mcver); core.setDataFolder(dataDirectory); core.setServer(new SpoutServer()); /* Enable core */ if(!core.enableCore()) { this.setEnabled(false); return; } //TODO sscache = new SnapshotCache(core.getSnapShotCacheSize()); game.getScheduler().scheduleSyncDelayedTask(this, new Runnable() { public void run() { /* Initialized the currently loaded worlds */ for (World world : game.getWorlds()) { SpoutWorld w = new SpoutWorld(world); if(core.processWorldLoad(w)) /* Have core process load first - fire event listeners if good load after */ core.listenerManager.processWorldEvent(EventType.WORLD_LOAD, w); } } }, 100); /* Register our update trigger events */ registerEvents(); Command cmd = game.getRootCommand().addSubCommand(new Named() { public String getName() { return "dynmap"; } }, "dynmap"); cmd.setRawExecutor(new RawCommandExecutor() { public void execute(CommandSource sender, String[] args, int baseIndex, boolean fuzzyLookup) throws CommandException { DynmapCommandSender dsender; if(sender instanceof Player) { dsender = new SpoutPlayer((Player)sender); } else { dsender = new SpoutCommandSender(sender); } String[] cmdargs = new String[args.length-1]; System.arraycopy(args, 1, cmdargs, 0, cmdargs.length); if(!core.processCommand(dsender, args[0], "dynmap", cmdargs)) throw new CommandException("Bad Command"); } }); } @Override public void onDisable() { /* Reset registered listeners */ sep.cleanup(); /* Disable core */ core.disableCore(); //TODO if(sscache != null) { //TODO sscache.cleanup(); //TODO sscache = null; //TODO } } public String getPrefix() { return prefix; } public final MarkerAPI getMarkerAPI() { return core.getMarkerAPI(); } public final boolean markerAPIInitialized() { return core.markerAPIInitialized(); } public final boolean sendBroadcastToWeb(String sender, String msg) { return core.sendBroadcastToWeb(sender, msg); } public final int triggerRenderOfVolume(String wid, int minx, int miny, int minz, int maxx, int maxy, int maxz) { return core.triggerRenderOfVolume(wid, minx, miny, minz, maxx, maxy, maxz); } public final int triggerRenderOfBlock(String wid, int x, int y, int z) { return core.triggerRenderOfBlock(wid, x, y, z); } public final void setPauseFullRadiusRenders(boolean dopause) { core.setPauseFullRadiusRenders(dopause); } public final boolean getPauseFullRadiusRenders() { return core.getPauseFullRadiusRenders(); } public final void setPauseUpdateRenders(boolean dopause) { core.setPauseUpdateRenders(dopause); } public final boolean getPauseUpdateRenders() { return core.getPauseUpdateRenders(); } public final void setPlayerVisiblity(String player, boolean is_visible) { core.setPlayerVisiblity(player, is_visible); } public final boolean getPlayerVisbility(String player) { return core.getPlayerVisbility(player); } public final void postPlayerMessageToWeb(String playerid, String playerdisplay, String message) { core.postPlayerMessageToWeb(playerid, playerdisplay, message); } public final void postPlayerJoinQuitToWeb(String playerid, String playerdisplay, boolean isjoin) { core.postPlayerJoinQuitToWeb(playerid, playerdisplay, isjoin); } public final String getDynmapCoreVersion() { return core.getDynmapCoreVersion(); } public final void setPlayerVisiblity(Player player, boolean is_visible) { core.setPlayerVisiblity(player.getName(), is_visible); } public final boolean getPlayerVisbility(Player player) { return core.getPlayerVisbility(player.getName()); } public final void postPlayerMessageToWeb(Player player, String message) { core.postPlayerMessageToWeb(player.getName(), player.getDisplayName(), message); } public void postPlayerJoinQuitToWeb(Player player, boolean isjoin) { core.postPlayerJoinQuitToWeb(player.getName(), player.getDisplayName(), isjoin); } public String getDynmapVersion() { return version; } private static DynmapLocation toLoc(Point p) { return new DynmapLocation(p.getWorld().getName(), p.getX(), p.getY(), p.getZ()); } private void registerPlayerLoginListener() { sep.registerEvent(PlayerJoinEvent.class, new EventExecutor() { public void execute(Event evt) { PlayerJoinEvent pje = (PlayerJoinEvent)evt; SpoutPlayer dp = new SpoutPlayer(pje.getPlayer()); core.listenerManager.processPlayerEvent(EventType.PLAYER_JOIN, dp); } }); sep.registerEvent(PlayerLeaveEvent.class, new EventExecutor() { public void execute(Event evt) { PlayerLeaveEvent pje = (PlayerLeaveEvent)evt; SpoutPlayer dp = new SpoutPlayer(pje.getPlayer()); core.listenerManager.processPlayerEvent(EventType.PLAYER_QUIT, dp); } }); } private boolean onplace; private boolean onbreak; private boolean onblockform; private boolean onblockfade; private boolean onblockspread; private boolean onblockfromto; private boolean onblockphysics; private boolean onleaves; private boolean onburn; private boolean onpiston; private boolean onplayerjoin; private boolean onplayermove; private boolean ongeneratechunk; private boolean onloadchunk; private boolean onexplosion; private void registerEvents() { // BlockListener blockTrigger = new BlockListener() { // @Override // public void onBlockPlace(BlockPlaceEvent event) { // if(event.isCancelled()) // return; // Location loc = event.getBlock().getLocation(); // String wn = loc.getWorld().getName(); // sscache.invalidateSnapshot(wn, loc.getBlockX(), loc.getBlockY(), loc.getBlockZ()); // if(onplace) { // mapManager.touch(wn, loc.getBlockX(), loc.getBlockY(), loc.getBlockZ(), "blockplace"); // @Override // public void onBlockBreak(BlockBreakEvent event) { // if(event.isCancelled()) // return; // Location loc = event.getBlock().getLocation(); // String wn = loc.getWorld().getName(); // sscache.invalidateSnapshot(wn, loc.getBlockX(), loc.getBlockY(), loc.getBlockZ()); // if(onbreak) { // mapManager.touch(wn, loc.getBlockX(), loc.getBlockY(), loc.getBlockZ(), "blockbreak"); // @Override // public void onLeavesDecay(LeavesDecayEvent event) { // if(event.isCancelled()) // return; // Location loc = event.getBlock().getLocation(); // String wn = loc.getWorld().getName(); // sscache.invalidateSnapshot(wn, loc.getBlockX(), loc.getBlockY(), loc.getBlockZ()); // if(onleaves) { // mapManager.touch(wn, loc.getBlockX(), loc.getBlockY(), loc.getBlockZ(), "leavesdecay"); // @Override // public void onBlockBurn(BlockBurnEvent event) { // if(event.isCancelled()) // return; // Location loc = event.getBlock().getLocation(); // String wn = loc.getWorld().getName(); // sscache.invalidateSnapshot(wn, loc.getBlockX(), loc.getBlockY(), loc.getBlockZ()); // if(onburn) { // mapManager.touch(wn, loc.getBlockX(), loc.getBlockY(), loc.getBlockZ(), "blockburn"); // @Override // public void onBlockForm(BlockFormEvent event) { // if(event.isCancelled()) // return; // Location loc = event.getBlock().getLocation(); // String wn = loc.getWorld().getName(); // sscache.invalidateSnapshot(wn, loc.getBlockX(), loc.getBlockY(), loc.getBlockZ()); // if(onblockform) { // mapManager.touch(wn, loc.getBlockX(), loc.getBlockY(), loc.getBlockZ(), "blockform"); // @Override // public void onBlockFade(BlockFadeEvent event) { // if(event.isCancelled()) // return; // Location loc = event.getBlock().getLocation(); // String wn = loc.getWorld().getName(); // sscache.invalidateSnapshot(wn, loc.getBlockX(), loc.getBlockY(), loc.getBlockZ()); // if(onblockfade) { // mapManager.touch(wn, loc.getBlockX(), loc.getBlockY(), loc.getBlockZ(), "blockfade"); // @Override // public void onBlockSpread(BlockSpreadEvent event) { // if(event.isCancelled()) // return; // Location loc = event.getBlock().getLocation(); // String wn = loc.getWorld().getName(); // sscache.invalidateSnapshot(wn, loc.getBlockX(), loc.getBlockY(), loc.getBlockZ()); // if(onblockspread) { // mapManager.touch(wn, loc.getBlockX(), loc.getBlockY(), loc.getBlockZ(), "blockspread"); // @Override // public void onBlockFromTo(BlockFromToEvent event) { // if(event.isCancelled()) // return; // Location loc = event.getToBlock().getLocation(); // String wn = loc.getWorld().getName(); // sscache.invalidateSnapshot(wn, loc.getBlockX(), loc.getBlockY(), loc.getBlockZ()); // if(onblockfromto) // mapManager.touch(wn, loc.getBlockX(), loc.getBlockY(), loc.getBlockZ(), "blockfromto"); // loc = event.getBlock().getLocation(); // wn = loc.getWorld().getName(); // sscache.invalidateSnapshot(wn, loc.getBlockX(), loc.getBlockY(), loc.getBlockZ()); // if(onblockfromto) // mapManager.touch(wn, loc.getBlockX(), loc.getBlockY(), loc.getBlockZ(), "blockfromto"); // @Override // public void onBlockPhysics(BlockPhysicsEvent event) { // if(event.isCancelled()) // return; // Location loc = event.getBlock().getLocation(); // String wn = loc.getWorld().getName(); // sscache.invalidateSnapshot(wn, loc.getBlockX(), loc.getBlockY(), loc.getBlockZ()); // if(onblockphysics) { // mapManager.touch(wn, loc.getBlockX(), loc.getBlockY(), loc.getBlockZ(), "blockphysics"); // @Override // public void onBlockPistonRetract(BlockPistonRetractEvent event) { // if(event.isCancelled()) // return; // Block b = event.getBlock(); // Location loc = b.getLocation(); // BlockFace dir; // try { // dir = event.getDirection(); // } catch (ClassCastException ccx) { // dir = BlockFace.NORTH; // String wn = loc.getWorld().getName(); // int x = loc.getBlockX(), y = loc.getBlockY(), z = loc.getBlockZ(); // sscache.invalidateSnapshot(wn, x, y, z); // if(onpiston) // mapManager.touch(wn, x, y, z, "pistonretract"); // for(int i = 0; i < 2; i++) { // x += dir.getModX(); // y += dir.getModY(); // z += dir.getModZ(); // sscache.invalidateSnapshot(wn, x, y, z); // if(onpiston) // mapManager.touch(wn, x, y, z, "pistonretract"); // @Override // public void onBlockPistonExtend(BlockPistonExtendEvent event) { // if(event.isCancelled()) // return; // Block b = event.getBlock(); // Location loc = b.getLocation(); // BlockFace dir; // try { // dir = event.getDirection(); // } catch (ClassCastException ccx) { // dir = BlockFace.NORTH; // String wn = loc.getWorld().getName(); // int x = loc.getBlockX(), y = loc.getBlockY(), z = loc.getBlockZ(); // sscache.invalidateSnapshot(wn, x, y, z); // if(onpiston) // mapManager.touch(wn, x, y, z, "pistonretract"); // for(int i = 0; i < 1+event.getLength(); i++) { // x += dir.getModX(); // y += dir.getModY(); // z += dir.getModZ(); // sscache.invalidateSnapshot(wn, x, y, z); // if(onpiston) // mapManager.touch(wn, x, y, z, "pistonretract"); // // To trigger rendering. // onplace = core.isTrigger("blockplaced"); // bep.registerEvent(Event.Type.BLOCK_PLACE, blockTrigger); // onbreak = core.isTrigger("blockbreak"); // bep.registerEvent(Event.Type.BLOCK_BREAK, blockTrigger); // if(core.isTrigger("snowform")) Log.info("The 'snowform' trigger has been deprecated due to Bukkit changes - use 'blockformed'"); // onleaves = core.isTrigger("leavesdecay"); // bep.registerEvent(Event.Type.LEAVES_DECAY, blockTrigger); // onburn = core.isTrigger("blockburn"); // bep.registerEvent(Event.Type.BLOCK_BURN, blockTrigger); // onblockform = core.isTrigger("blockformed"); // bep.registerEvent(Event.Type.BLOCK_FORM, blockTrigger); // onblockfade = core.isTrigger("blockfaded"); // bep.registerEvent(Event.Type.BLOCK_FADE, blockTrigger); // onblockspread = core.isTrigger("blockspread"); // bep.registerEvent(Event.Type.BLOCK_SPREAD, blockTrigger); // onblockfromto = core.isTrigger("blockfromto"); // bep.registerEvent(Event.Type.BLOCK_FROMTO, blockTrigger); // onblockphysics = core.isTrigger("blockphysics"); // bep.registerEvent(Event.Type.BLOCK_PHYSICS, blockTrigger); // onpiston = core.isTrigger("pistonmoved"); // bep.registerEvent(Event.Type.BLOCK_PISTON_EXTEND, blockTrigger); // bep.registerEvent(Event.Type.BLOCK_PISTON_RETRACT, blockTrigger); // /* Register player event trigger handlers */ Listener playerTrigger = new Listener() { @EventHandler void handlePlayerJoin(PlayerJoinEvent event) { if(onplayerjoin) { AtomicPoint loc = event.getPlayer().getEntity().getTransform().getPosition(); core.mapManager.touch(loc.getWorld().getName(), (int)loc.getX(), (int)loc.getY(), (int)loc.getZ(), "playerjoin"); } core.listenerManager.processPlayerEvent(EventType.PLAYER_JOIN, new SpoutPlayer(event.getPlayer())); } @EventHandler void handlePlayerLeave(PlayerLeaveEvent event) { core.listenerManager.processPlayerEvent(EventType.PLAYER_QUIT, new SpoutPlayer(event.getPlayer())); } }; onplayerjoin = core.isTrigger("playerjoin"); onplayermove = core.isTrigger("playermove"); game.getEventManager().registerEvents(playerTrigger, plugin); // if(onplayermove) // bep.registerEvent(Event.Type.PLAYER_MOVE, playerTrigger); // /* Register entity event triggers */ // EntityListener entityTrigger = new EntityListener() { // @Override // public void onEntityExplode(EntityExplodeEvent event) { // Location loc = event.getLocation(); // String wname = loc.getWorld().getName(); // int minx, maxx, miny, maxy, minz, maxz; // minx = maxx = loc.getBlockX(); // miny = maxy = loc.getBlockY(); // minz = maxz = loc.getBlockZ(); // /* Calculate volume impacted by explosion */ // List<Block> blocks = event.blockList(); // for(Block b: blocks) { // Location l = b.getLocation(); // int x = l.getBlockX(); // if(x < minx) minx = x; // if(x > maxx) maxx = x; // int y = l.getBlockY(); // if(y < miny) miny = y; // if(y > maxy) maxy = y; // int z = l.getBlockZ(); // if(z < minz) minz = z; // if(z > maxz) maxz = z; // sscache.invalidateSnapshot(wname, minx, miny, minz, maxx, maxy, maxz); // if(onexplosion) { // mapManager.touchVolume(wname, minx, miny, minz, maxx, maxy, maxz, "entityexplode"); // onexplosion = core.isTrigger("explosion"); // bep.registerEvent(Event.Type.ENTITY_EXPLODE, entityTrigger); // /* Register world event triggers */ // WorldListener worldTrigger = new WorldListener() { // @Override // public void onChunkLoad(ChunkLoadEvent event) { // if(DynmapCore.ignore_chunk_loads) // return; // Chunk c = event.getChunk(); // /* Touch extreme corners */ // int x = c.getX() << 4; // int z = c.getZ() << 4; // mapManager.touchVolume(event.getWorld().getName(), x, 0, z, x+15, 128, z+16, "chunkload"); // @Override // public void onChunkPopulate(ChunkPopulateEvent event) { // Chunk c = event.getChunk(); // /* Touch extreme corners */ // int x = c.getX() << 4; // int z = c.getZ() << 4; // mapManager.touchVolume(event.getWorld().getName(), x, 0, z, x+15, 128, z+16, "chunkpopulate"); // @Override // public void onWorldLoad(WorldLoadEvent event) { // core.updateConfigHashcode(); // SpoutWorld w = new SpoutWorld(event.getWorld()); // if(core.processWorldLoad(w)) /* Have core process load first - fire event listeners if good load after */ // core.listenerManager.processWorldEvent(EventType.WORLD_LOAD, w); // @Override // public void onWorldUnload(WorldUnloadEvent event) { // core.updateConfigHashcode(); // DynmapWorld w = core.getWorld(event.getWorld().getName()); // if(w != null) // core.listenerManager.processWorldEvent(EventType.WORLD_UNLOAD, w); // ongeneratechunk = core.isTrigger("chunkgenerated"); // if(ongeneratechunk) { // bep.registerEvent(Event.Type.CHUNK_POPULATED, worldTrigger); // onloadchunk = core.isTrigger("chunkloaded"); // if(onloadchunk) { // bep.registerEvent(Event.Type.CHUNK_LOAD, worldTrigger); // // To link configuration to real loaded worlds. // bep.registerEvent(Event.Type.WORLD_LOAD, worldTrigger); // bep.registerEvent(Event.Type.WORLD_UNLOAD, worldTrigger); } public void assertPlayerInvisibility(String player, boolean is_invisible, String plugin_id) { core.assertPlayerInvisibility(player, is_invisible, plugin_id); } public void assertPlayerVisibility(String player, boolean is_visible, String plugin_id) { core.assertPlayerVisibility(player, is_visible, plugin_id); } }
package ch.unizh.ini.jaer.projects.minliu; import java.awt.Dimension; import java.awt.Font; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.awt.font.FontRenderContext; import java.awt.geom.Rectangle2D; import java.beans.PropertyChangeEvent; import java.util.Arrays; import java.util.Observable; import java.util.Observer; import java.util.logging.Level; import javax.swing.BoxLayout; import javax.swing.JFrame; import javax.swing.JPanel; import com.jogamp.opengl.GL; import com.jogamp.opengl.GL2; import com.jogamp.opengl.GL2ES3; import com.jogamp.opengl.GLAutoDrawable; import com.jogamp.opengl.util.awt.TextRenderer; import ch.unizh.ini.jaer.projects.rbodo.opticalflow.AbstractMotionFlow; import com.jogamp.opengl.GLException; import java.util.Iterator; import java.util.StringTokenizer; import java.util.Timer; import java.util.TimerTask; import net.sf.jaer.Description; import net.sf.jaer.DevelopmentStatus; import net.sf.jaer.chip.AEChip; import net.sf.jaer.event.ApsDvsEvent; import net.sf.jaer.event.ApsDvsEventPacket; import net.sf.jaer.event.EventPacket; import net.sf.jaer.event.PolarityEvent; import net.sf.jaer.eventio.AEInputStream; import net.sf.jaer.eventprocessing.TimeLimiter; import net.sf.jaer.graphics.AEViewer; import net.sf.jaer.graphics.FrameAnnotater; import net.sf.jaer.graphics.ImageDisplay; import net.sf.jaer.graphics.ImageDisplay.Legend; import net.sf.jaer.util.DrawGL; import net.sf.jaer.util.EngineeringFormat; import net.sf.jaer.util.TobiLogger; import net.sf.jaer.util.filter.LowpassFilter; /** * Uses patch matching to measureTT local optical flow. <b>Not</b> gradient * based, but rather matches local features backwards in time. * * @author Tobi and Min, Jan 2016 */ @Description("Computes optical flow with vector direction using block matching") @DevelopmentStatus(DevelopmentStatus.Status.Experimental) public class PatchMatchFlow extends AbstractMotionFlow implements Observer, FrameAnnotater { /* LDSP is Large Diamond Search Pattern, and SDSP mens Small Diamond Search Pattern. LDSP has 9 points and SDSP consists of 5 points. */ private static final int LDSP[][] = {{0, -2}, {-1, -1}, {1, -1}, {-2, 0}, {0, 0}, {2, 0}, {-1, 1}, {1, 1}, {0, 2}}; private static final int SDSP[][] = {{0, -1}, {-1, 0}, {0, 0}, {1, 0}, {0, 1}}; // private int[][][] histograms = null; private int numSlices = 3; //getInt("numSlices", 3); // fix to 4 slices to compute error sign from min SAD result from t-2d to t-3d volatile private int numScales = getInt("numScales", 3); //getInt("numSlices", 3); // fix to 4 slices to compute error sign from min SAD result from t-2d to t-3d private String scalesToCompute = getString("scalesToCompute", ""); //getInt("numSlices", 3); // fix to 4 slices to compute error sign from min SAD result from t-2d to t-3d private int[] scalesToComputeArray = null; // holds array of scales to actually compute, for debugging private int[] scaleResultCounts = new int[numScales]; // holds counts at each scale for min SAD results /** * The computed average possible match distance from 0 motion */ protected float avgPossibleMatchDistance; private static final int MIN_SLICE_EVENT_COUNT_FULL_FRAME = 50; private static final int MAX_SLICE_EVENT_COUNT_FULL_FRAME = 100000; // private int sx, sy; private int currentSliceIdx = 0; // the slice we are currently filling with events /** * time slice 2d histograms of (maybe signed) event counts slices = new * byte[numSlices][numScales][subSizeX][subSizeY] [slice][scale][x][y] */ private byte[][][][] slices = null; private float[] sliceSummedSADValues = null; // tracks the total summed SAD differences between reference and past slices, to adjust the slice duration private int[] sliceSummedSADCounts = null; // tracks the total summed SAD differences between reference and past slices, to adjust the slice duration private int[] sliceStartTimeUs; // holds the time interval between reference slice and this slice private int[] sliceEndTimeUs; // holds the time interval between reference slice and this slice private byte[][][] currentSlice; private SADResult lastGoodSadResult = new SADResult(0, 0, 0, 0); // used for consistency check private int blockDimension = getInt("blockDimension", 23); // private float cost = getFloat("cost", 0.001f); private float maxAllowedSadDistance = getFloat("maxAllowedSadDistance", .5f); private float validPixOccupancy = getFloat("validPixOccupancy", 0.01f); // threshold for valid pixel percent for one block private float weightDistance = getFloat("weightDistance", 0.95f); // confidence value consists of the distance and the dispersion, this value set the distance value private static final int MAX_SKIP_COUNT = 1000; private int skipProcessingEventsCount = getInt("skipProcessingEventsCount", 0); // skip this many events for processing (but not for accumulating to bitmaps) private int skipCounter = 0; private boolean adaptiveEventSkipping = getBoolean("adaptiveEventSkipping", true); private float skipChangeFactor = (float) Math.sqrt(2); // by what factor to change the skip count if too slow or too fast private boolean outputSearchErrorInfo = false; // make user choose this slow down every time private boolean adaptiveSliceDuration = getBoolean("adaptiveSliceDuration", true); private boolean adaptiveSliceDurationLogging = false; // for debugging and analyzing control of slice event number/duration private TobiLogger adaptiveSliceDurationLogger = null; private int adaptiveSliceDurationPacketCount = 0; private boolean useSubsampling = getBoolean("useSubsampling", false); private int adaptiveSliceDurationMinVectorsToControl = getInt("adaptiveSliceDurationMinVectorsToControl", 10); private boolean showSliceBitMap = false; // Display the bitmaps private float adapativeSliceDurationProportionalErrorGain = 0.05f; // factor by which an error signal on match distance changes slice duration private int processingTimeLimitMs = getInt("processingTimeLimitMs", 100); // time limit for processing packet in ms to process OF events (events still accumulate). Overrides the system EventPacket timelimiter, which cannot be used here because we still need to accumulate and render the events. private int sliceMaxValue = getInt("sliceMaxValue", 7); private boolean rectifyPolarties = getBoolean("rectifyPolarties", false); private TimeLimiter timeLimiter = new TimeLimiter(); // private instance used to accumulate events to slices even if packet has timed out // results histogram for each packet // private int ANGLE_HISTOGRAM_COUNT = 16; // private int[] resultAngleHistogram = new int[ANGLE_HISTOGRAM_COUNT + 1]; private int[][] resultHistogram = null; // private int resultAngleHistogramCount = 0, resultAngleHistogramMax = 0; private int resultHistogramCount; private volatile float avgMatchDistance = 0; // stores average match distance for rendering it private float histStdDev = 0, lastHistStdDev = 0; private float FSCnt = 0, DSCorrectCnt = 0; float DSAverageNum = 0, DSAveError[] = {0, 0}; // Evaluate DS cost average number and the error. // private float lastErrSign = Math.signum(1); // private final String outputFilename; private int sliceDeltaT; // The time difference between two slices used for velocity caluction. For constantDuration, this one is equal to the duration. For constantEventNumber, this value will change. private int MIN_SLICE_DURATION_US = 100; private int MAX_SLICE_DURATION_US = 300000; private boolean enableImuTimesliceLogging = false; private TobiLogger imuTimesliceLogger = null; private volatile boolean resetOFHistogramFlag; // signals to reset the OF histogram after it is rendered public enum PatchCompareMethod { /*JaccardDistance,*/ /*HammingDistance*/ SAD/*, EventSqeDistance*/ }; private PatchCompareMethod patchCompareMethod = null; public enum SearchMethod { FullSearch, DiamondSearch, CrossDiamondSearch }; private SearchMethod searchMethod = SearchMethod.valueOf(getString("searchMethod", SearchMethod.DiamondSearch.toString())); private int sliceDurationUs = getInt("sliceDurationUs", 20000); private int sliceEventCount = getInt("sliceEventCount", 1000); private boolean rewindFlg = false; // The flag to indicate the rewind event. private boolean displayResultHistogram = getBoolean("displayResultHistogram", true); public enum SliceMethod { ConstantDuration, ConstantEventNumber, AreaEventNumber, ConstantIntegratedFlow }; private SliceMethod sliceMethod = SliceMethod.valueOf(getString("sliceMethod", SliceMethod.AreaEventNumber.toString())); // counting events into subsampled areas, when count exceeds the threshold in any area, the slices are rotated private int areaEventNumberSubsampling = getInt("areaEventNumberSubsampling", 5); private int[][] areaCounts = null; private boolean areaCountExceeded = false; // nongreedy flow evaluation // the entire scene is subdivided into regions, and a bitmap of these regions distributed flow computation more fairly // by only servicing a region when sufficient fraction of other regions have been serviced first private boolean nonGreedyFlowComputingEnabled = getBoolean("nonGreedyFlowComputingEnabled", true); private boolean[][] nonGreedyRegions = null; private int nonGreedyRegionsNumberOfRegions, nonGreedyRegionsCount; /** * This fraction of the regions must be serviced for computing flow before * we reset the nonGreedyRegions map */ private float nonGreedyFractionToBeServiced = getFloat("nonGreedyFractionToBeServiced", .5f); // timers and flags for showing filter properties temporarily private final int SHOW_STUFF_DURATION_MS = 4000; private volatile TimerTask stopShowingStuffTask = null; private boolean showBlockSizeAndSearchAreaTemporarily = false; private volatile boolean showAreaCountAreasTemporarily = false; private int eventCounter = 0; private int sliceLastTs = Integer.MAX_VALUE; private ImageDisplay sliceBitmapImageDisplay; // makde a new ImageDisplay GLCanvas with default OpenGL capabilities private JFrame sliceBitMapFrame = null; private Legend sliceBitmapLegend; /** * A PropertyChangeEvent with this value is fired when the slices has been * rotated. The oldValue is t-2d slice. The newValue is the t-d slice. */ public static final String EVENT_NEW_SLICES = "eventNewSlices"; TobiLogger sadValueLogger = new TobiLogger("sadvalues", "sadvalue,scale"); // TODO debug public PatchMatchFlow(AEChip chip) { super(chip); setSliceDurationUs(getSliceDurationUs()); // 40ms is good for the start of the slice duration adatative since 4ms is too fast and 500ms is too slow. setDefaultScalesToCompute(); // // Save the result to the file // Format formatter = new SimpleDateFormat("YYYY-MM-dd_hh-mm-ss"); // // Instantiate a Date object // Date date = new Date(); // Log file for the OF distribution's statistics // outputFilename = "PMF_HistStdDev" + formatter.format(date) + ".txt"; String patchTT = "0a: Block matching"; // String eventSqeMatching = "Event squence matching"; // String preProcess = "Denoise"; String metricConfid = "Confidence of current metric"; try { patchCompareMethod = PatchCompareMethod.valueOf(getString("patchCompareMethod", PatchCompareMethod.SAD.toString())); } catch (IllegalArgumentException e) { patchCompareMethod = PatchCompareMethod.SAD; } chip.addObserver(this); // to allocate memory once chip size is known setPropertyTooltip(metricConfid, "maxAllowedSadDistance", "<html>SAD distance threshold for rejecting unresonable block matching result; <br> events with SAD distance larger than this value are rejected. <p>Lower value means it is harder to accept the event."); setPropertyTooltip(metricConfid, "validPixOccupancy", "<html>Threshold for valid pixel percent for each block; Range from 0 to 1. <p>If either matching block is less occupied than this fraction, no motion vector will be calculated."); setPropertyTooltip(metricConfid, "weightDistance", "<html>The confidence value consists of the distance and the dispersion; <br>weightDistance sets the weighting of the distance value compared with the dispersion value; Range from 0 to 1. <p>To count only e.g. hamming distance, set weighting to 1. <p> To count only dispersion, set to 0."); setPropertyTooltip(patchTT, "blockDimension", "linear dimenion of patches to match, in pixels"); setPropertyTooltip(patchTT, "searchDistance", "search distance for matching patches, in pixels"); setPropertyTooltip(patchTT, "patchCompareMethod", "method to compare two patches; SAD=sum of absolute differences, HammingDistance is same as SAD for binary bitmaps"); setPropertyTooltip(patchTT, "searchMethod", "method to search patches"); setPropertyTooltip(patchTT, "sliceDurationUs", "duration of bitmaps in us, also called sample interval, when ConstantDuration method is used"); setPropertyTooltip(patchTT, "sliceEventCount", "number of events collected to fill a slice, when ConstantEventNumber method is used"); setPropertyTooltip(patchTT, "sliceMethod", "<html>Method for determining time slice duration for block matching<ul>" + "<li>ConstantDuration: slices are fixed time duration" + "<li>ConstantEventNumber: slices are fixed event number" + "<li>AreaEventNumber: slices are fixed event number in any subsampled area defined by areaEventNumberSubsampling" + "<li>ConstantIntegratedFlow: slices are rotated when average speeds times delta time exceeds half the search distance"); setPropertyTooltip(patchTT, "areaEventNumberSubsampling", "<html>how to subsample total area to count events per unit subsampling blocks for AreaEventNumber method. <p>For example, if areaEventNumberSubsampling=5, <br> then events falling into 32x32 blocks of pixels are counted <br>to determine when they exceed sliceEventCount to make new slice"); setPropertyTooltip(patchTT, "skipProcessingEventsCount", "skip this many events for processing (but not for accumulating to bitmaps)"); setPropertyTooltip(patchTT, "adaptiveEventSkipping", "enables adaptive event skipping depending on free time left in AEViewer animation loop"); setPropertyTooltip(patchTT, "adaptiveSliceDuration", "<html>Enables adaptive slice duration using feedback control, <br> based on average match search distance compared with total search distance. <p>If the match distance is too small, increaes duration or event count, and if too far, decreases duration or event count.<p>If using <i>AreaEventNumber</i> slice rotation method, don't increase count if actual duration is already longer than <i>sliceDurationUs</i>"); setPropertyTooltip(patchTT, "nonGreedyFlowComputingEnabled", "<html>Enables fairer distribution of computing flow by areas; an area is only serviced after " + nonGreedyFractionToBeServiced + " fraction of areas have been serviced. <p> Areas are defined by the the area subsubsampling bit shift.<p>Enabling this option ignores event skipping, so use <i>processingTimeLimitMs</i> to ensure minimum frame rate"); setPropertyTooltip(patchTT, "nonGreedyFractionToBeServiced", "An area is only serviced after " + nonGreedyFractionToBeServiced + " fraction of areas have been serviced. <p> Areas are defined by the the area subsubsampling bit shift.<p>Enabling this option ignores event skipping, so use the timeLimiter to ensure minimum frame rate"); setPropertyTooltip(patchTT, "useSubsampling", "<html>Enables using both full and subsampled block matching; <p>when using adaptiveSliceDuration, enables adaptive slice duration using feedback controlusing difference between full and subsampled resolution slice matching"); setPropertyTooltip(patchTT, "adaptiveSliceDurationMinVectorsToControl", "<html>Min flow vectors computed in packet to control slice duration, increase to reject control during idle periods"); setPropertyTooltip(patchTT, "processingTimeLimitMs", "<html>time limit for processing packet in ms to process OF events (events still accumulate). <br> Set to 0 to disable. <p>Alternative to the system EventPacket timelimiter, which cannot be used here because we still need to accumulate and render the events"); setPropertyTooltip(patchTT, "outputSearchErrorInfo", "enables displaying the search method error information"); setPropertyTooltip(patchTT, "outlierMotionFilteringEnabled", "(Currently has no effect) discards first optical flow event that points in opposite direction as previous one (dot product is negative)"); setPropertyTooltip(patchTT, "numSlices", "<html>Number of bitmaps to use. <p>At least 3: 1 to collect on, and two more to match on. <br>If >3, then best match is found between last slice reference block and all previous slices."); setPropertyTooltip(patchTT, "numScales", "<html>Number of scales to search over for minimum SAD value; 1 for single full resolution scale, 2 for full + 2x2 subsampling, etc."); setPropertyTooltip(patchTT, "sliceMaxValue", "<html> the maximum value used to represent each pixel in the time slice:<br>1 for binary or signed binary slice, (in conjunction with rectifyEventPolarities==true), etc, <br>up to 127 by these byte values"); setPropertyTooltip(patchTT, "rectifyPolarties", "<html> whether to rectify ON and OFF polarities to unsigned counts; true ignores polarity for block matching, false uses polarity with sliceNumBits>1"); setPropertyTooltip(patchTT, "scalesToCompute", "Scales to compute, e.g. 1,2; blank for all scales. 0 is full resolution, 1 is subsampled 2x2, etc"); setPropertyTooltip(patchTT, "showSlice", "Scales to compute, e.g. 1,2; blank for all scales. 0 is full resolution, 1 is subsampled 2x2, etc"); setPropertyTooltip(patchTT, "defaults", "Sets reasonable defaults"); setPropertyTooltip(patchTT, "enableImuTimesliceLogging", "Logs IMU and rate gyro"); String patchDispTT = "0b: Block matching display"; setPropertyTooltip(patchDispTT, "showSliceBitMap", "enables displaying the slices' bitmap"); setPropertyTooltip(patchDispTT, "ppsScale", "scale of pixels per second to draw local motion vectors; global vectors are scaled up by an additional factor of " + GLOBAL_MOTION_DRAWING_SCALE); setPropertyTooltip(patchDispTT, "displayOutputVectors", "display the output motion vectors or not"); setPropertyTooltip(patchDispTT, "displayResultHistogram", "display the output motion vectors histogram to show disribution of results for each packet. Only implemented for HammingDistance"); getSupport().addPropertyChangeListener(AEViewer.EVENT_TIMESTAMPS_RESET, this); getSupport().addPropertyChangeListener(AEViewer.EVENT_FILEOPEN, this); getSupport().addPropertyChangeListener(AEInputStream.EVENT_REWIND, this); getSupport().addPropertyChangeListener(AEInputStream.EVENT_NON_MONOTONIC_TIMESTAMP, this); computeAveragePossibleMatchDistance(); } // TODO debug public void doStartLogSadValues() { sadValueLogger.setEnabled(true); } // TODO debug public void doStopLogSadValues() { sadValueLogger.setEnabled(false); } @Override synchronized public EventPacket filterPacket(EventPacket in) { if (cameraCalibration != null && cameraCalibration.isFilterEnabled()) { in = cameraCalibration.filterPacket(in); } setupFilter(in); checkArrays(); if (processingTimeLimitMs > 0) { timeLimiter.setTimeLimitMs(processingTimeLimitMs); timeLimiter.restart(); } else { timeLimiter.setEnabled(false); } int minDistScale = 0; // following awkward block needed to deal with DVS/DAVIS and IMU/APS events // block STARTS Iterator i = null; if (in instanceof ApsDvsEventPacket) { i = ((ApsDvsEventPacket) in).fullIterator(); } else { i = ((EventPacket) in).inputIterator(); } nSkipped = 0; nProcessed = 0; while (i.hasNext()) { Object o = i.next(); if (o == null) { log.warning("null event passed in, returning input packet"); return in; } if ((o instanceof ApsDvsEvent) && ((ApsDvsEvent) o).isApsData()) { continue; } PolarityEvent ein = (PolarityEvent) o; if (!extractEventInfo(o)) { continue; } if (measureAccuracy || discardOutliersForStatisticalMeasurementEnabled) { if (imuFlowEstimator.calculateImuFlow(o)) { continue; } } // block ENDS if (xyFilter()) { continue; } countIn++; // compute flow SADResult result = null; float[] sadVals = new float[numScales]; // TODO debug switch (patchCompareMethod) { case SAD: boolean rotated = maybeRotateSlices(); if (rotated) { adaptSliceDuration(); setResetOFHistogramFlag(); } // if (ein.x >= subSizeX || ein.y > subSizeY) { // log.warning("event out of range"); // continue; if (!accumulateEvent(ein)) { // maybe skip events here break; } SADResult sliceResult; minDistScale = 0; for (int scale : scalesToComputeArray) { if (scale >= numScales) { log.warning("scale " + scale + " is out of range of " + numScales + "; fix scalesToCompute for example by clearing it"); break; } sliceResult = minSADDistance(ein.x, ein.y, slices[sliceIndex(1)], slices[sliceIndex(2)], scale); // from ref slice to past slice k+1, using scale 0,1,.... // sliceSummedSADValues[sliceIndex(scale + 2)] += sliceResult.sadValue; // accumulate SAD for this past slice // sliceSummedSADCounts[sliceIndex(scale + 2)]++; // accumulate SAD count for this past slice // sliceSummedSADValues should end up filling 2 values for 4 slices if ((result == null) || (sliceResult.sadValue < result.sadValue)) { result = sliceResult; // result holds the overall min sad result minDistScale = scale; } sadVals[scale] = sliceResult.sadValue; // TODO debug } scaleResultCounts[minDistScale]++; float dt = (sliceDeltaTimeUs(2) * 1e-6f); if (result != null) { result.vx = result.dx / dt; // hack, convert to pix/second result.vy = result.dy / dt; // TODO clean up, make time for each slice, since could be different when const num events } break; // case JaccardDistance: // maybeRotateSlices(); // if (!accumulateEvent(in)) { // break; // result = minJaccardDistance(x, y, bitmaps[sliceIndex(2)], bitmaps[sliceIndex(1)]); // float dtj=(sliceDeltaTimeUs(2) * 1e-6f); // result.dx = result.dx / dtj; // result.dy = result.dy / dtj; // break; } if (result == null /*|| result.sadValue == Float.MAX_VALUE*/) { continue; // maybe some property change caused this } // reject values that are unreasonable if (isNotSufficientlyAccurate(result)) { continue; } vx = result.vx; vy = result.vy; v = (float) Math.sqrt((vx * vx) + (vy * vy)); // TODO debug StringBuilder sadValsString = new StringBuilder(); for (int k = 0; k < sadVals.length - 1; k++) { sadValsString.append(String.format("%f,", sadVals[k])); } sadValsString.append(String.format("%f", sadVals[sadVals.length - 1])); // very awkward to prevent trailing , if (sadValueLogger.isEnabled()) { // TODO debug sadValueLogger.log(sadValsString.toString()); } if (showSliceBitMap) { // TODO danger, drawing outside AWT thread drawMatching(result, ein, slices); // ein.x >> result.scale, ein.y >> result.scale, (int) result.dx >> result.scale, (int) result.dy >> result.scale, slices[sliceIndex(1)][result.scale], slices[sliceIndex(2)][result.scale], result.scale); } // if (filterOutInconsistentEvent(result)) { // continue; if (resultHistogram != null) { resultHistogram[result.xidx][result.yidx]++; resultHistogramCount++; } // if (result.dx != 0 || result.dy != 0) { // final int bin = (int) Math.round(ANGLE_HISTOGRAM_COUNT * (Math.atan2(result.dy, result.dx) + Math.PI) / (2 * Math.PI)); // int v = ++resultAngleHistogram[bin]; // resultAngleHistogramCount++; // if (v > resultAngleHistogramMax) { // resultAngleHistogramMax = v; processGoodEvent(); lastGoodSadResult.set(result); } if (rewindFlg) { rewindFlg = false; sliceLastTs = Integer.MAX_VALUE; } motionFlowStatistics.updatePacket(countIn, countOut); adaptEventSkipping(); return isDisplayRawInput() ? in : dirPacket; } public void doDefaults() { setSearchMethod(SearchMethod.DiamondSearch); setBlockDimension(21); setNumScales(2); setSearchDistance(4); setAdaptiveEventSkipping(true); setAdaptiveSliceDuration(true); setMaxAllowedSadDistance(.5f); setDisplayVectorsEnabled(true); setPpsScaleDisplayRelativeOFLength(true); setDisplayGlobalMotion(true); setPpsScale(.1f); setSliceMaxValue(7); setRectifyPolarties(true); // rectify to better handle cases of steadicam where pan/tilt flips event polarities setValidPixOccupancy(.01f); // at least this fraction of pixels from each block must both have nonzero values setSliceMethod(SliceMethod.AreaEventNumber); // compute nearest power of two over block dimension int ss = (int) (Math.log(blockDimension - 1) / Math.log(2)); setAreaEventNumberSubsampling(ss); // set event count so that count=block area * sliceMaxValue/4; // i.e. set count to roll over when slice pixels from most subsampled scale are half full if they are half stimulated final int eventCount = (((blockDimension * blockDimension) * sliceMaxValue) / 2) >> (numScales - 1); setSliceEventCount(eventCount); setSliceDurationUs(50000); // set a bit smaller max duration in us to avoid instability where count gets too high with sparse input } private void adaptSliceDuration() { // measure last hist to get control signal on slice duration // measures avg match distance. weights the average so that long distances with more pixels in hist are not overcounted, simply // by having more pixels. float radiusSum = 0; int countSum = 0; // int maxRadius = (int) Math.ceil(Math.sqrt(2 * searchDistance * searchDistance)); // int countSum = 0; final int totSD = searchDistance << (numScales - 1); for (int xx = -totSD; xx <= totSD; xx++) { for (int yy = -totSD; yy <= totSD; yy++) { int count = resultHistogram[xx + totSD][yy + totSD]; if (count > 0) { final float radius = (float) Math.sqrt((xx * xx) + (yy * yy)); countSum += count; radiusSum += radius * count; } } } if (countSum > 0) { avgMatchDistance = radiusSum / (countSum); // compute average match distance from reference block } if (adaptiveSliceDuration && (countSum > adaptiveSliceDurationMinVectorsToControl)) { // if (resultHistogramCount > 0) { // following stats not currently used // double[] rstHist1D = new double[resultHistogram.length * resultHistogram.length]; // int index = 0; //// int rstHistMax = 0; // for (int[] resultHistogram1 : resultHistogram) { // for (int element : resultHistogram1) { // rstHist1D[index++] = element; // Statistics histStats = new Statistics(rstHist1D); // // double histMax = Collections.max(Arrays.asList(ArrayUtils.toObject(rstHist1D))); // double histMax = histStats.getMax(); // for (int m = 0; m < rstHist1D.length; m++) { // rstHist1D[m] = rstHist1D[m] / histMax; // lastHistStdDev = histStdDev; // histStdDev = (float) histStats.getStdDev(); // try (FileWriter outFile = new FileWriter(outputFilename,true)) { // outFile.write(String.format(in.getFirstEvent().getTimestamp() + " " + histStdDev + "\r\n")); // outFile.close(); // } catch (IOException ex) { // Logger.getLogger(PatchMatchFlow.class.getName()).log(Level.SEVERE, null, ex); // } catch (Exception e) { // log.warning("Caught " + e + ". See following stack trace."); // e.printStackTrace(); // float histMean = (float) histStats.getMean(); // compute error signal. // If err<0 it means the average match distance is larger than target avg match distance, so we need to reduce slice duration // If err>0, it means the avg match distance is too short, so increse time slice final float err = avgPossibleMatchDistance / 2 - avgMatchDistance; // use target that is smaller than average possible to bound excursions to large slices better // final float err = ((searchDistance << (numScales - 1)) / 2) - avgMatchDistance; // final float lastErr = searchDistance / 2 - lastHistStdDev; // final double err = histMean - 1/ (rstHist1D.length * rstHist1D.length); float errSign = Math.signum(err); // float avgSad2 = sliceSummedSADValues[sliceIndex(4)] / sliceSummedSADCounts[sliceIndex(4)]; // float avgSad3 = sliceSummedSADValues[sliceIndex(3)] / sliceSummedSADCounts[sliceIndex(3)]; // float errSign = avgSad2 <= avgSad3 ? 1 : -1; // if(Math.abs(err) > Math.abs(lastErr)) { // errSign = -errSign; // if(histStdDev >= 0.14) { // if(lastHistStdDev > histStdDev) { // errSign = -lastErrSign; // } else { // errSign = lastErrSign; // errSign = 1; // } else { // errSign = (float) Math.signum(err); // lastErrSign = errSign; // problem with following is that if sliceDurationUs gets really big, then of course the avgMatchDistance becomes small because // of the biased-towards-zero search policy that selects the closest match switch (sliceMethod) { case ConstantDuration: int durChange = (int) (errSign * adapativeSliceDurationProportionalErrorGain * sliceDurationUs); setSliceDurationUs(sliceDurationUs + durChange); break; case ConstantEventNumber: case AreaEventNumber: if (errSign > 0 && sliceDeltaTimeUs(2) < getSliceDurationUs()) { // don't increase slice past the sliceDurationUs limit // match too short, increase count setSliceEventCount(Math.round(sliceEventCount * (1 + adapativeSliceDurationProportionalErrorGain))); } else { setSliceEventCount(Math.round(sliceEventCount * (1 - adapativeSliceDurationProportionalErrorGain))); } break; case ConstantIntegratedFlow: setSliceEventCount(eventCounter); } if (adaptiveSliceDurationLogger != null && adaptiveSliceDurationLogger.isEnabled()) { if (!isDisplayGlobalMotion()) { setDisplayGlobalMotion(true); } adaptiveSliceDurationLogger.log(String.format("%d\t%f\t%f\t%f\t%d\t%d", adaptiveSliceDurationPacketCount++, avgMatchDistance, err, motionFlowStatistics.getGlobalMotion().getGlobalSpeed().getMean(), sliceDurationUs, sliceEventCount)); } } } private void setResetOFHistogramFlag() { resetOFHistogramFlag=true; } private void clearResetOFHistogramFlag() { resetOFHistogramFlag=false; } private void resetOFHistogram(){ if(!resetOFHistogramFlag) return; for (int[] h : resultHistogram) { Arrays.fill(h, 0); } resultHistogramCount = 0; // Arrays.fill(resultAngleHistogram, 0); // resultAngleHistogramCount = 0; // resultAngleHistogramMax = Integer.MIN_VALUE; Arrays.fill(scaleResultCounts, 0); clearResetOFHistogramFlag(); } private EngineeringFormat engFmt = new EngineeringFormat(); private TextRenderer textRenderer = null; @Override synchronized public void annotate(GLAutoDrawable drawable) { super.annotate(drawable); GL2 gl = drawable.getGL().getGL2(); try { gl.glEnable(GL.GL_BLEND); gl.glBlendFunc(GL.GL_SRC_ALPHA, GL.GL_ONE_MINUS_SRC_ALPHA); gl.glBlendEquation(GL.GL_FUNC_ADD); } catch (GLException e) { e.printStackTrace(); } if (displayResultHistogram && (resultHistogram != null)) { // draw histogram as shaded in 2d hist above color wheel // normalize hist int rhDim = resultHistogram.length; // 2*(searchDistance<<numScales)+1 gl.glPushMatrix(); final float scale = 30f / rhDim; // size same as the color wheel gl.glTranslatef(-35, .65f * chip.getSizeY(), 0); // center above color wheel gl.glScalef(scale, scale, 1); gl.glColor3f(0, 0, 1); gl.glLineWidth(2f); gl.glBegin(GL.GL_LINE_LOOP); gl.glVertex2f(0, 0); gl.glVertex2f(rhDim, 0); gl.glVertex2f(rhDim, rhDim); gl.glVertex2f(0, rhDim); gl.glEnd(); if (textRenderer == null) { textRenderer = new TextRenderer(new Font("SansSerif", Font.PLAIN, 64)); } int max = 0; for (int[] h : resultHistogram) { for (int vv : h) { if (vv > max) { max = vv; } } } if (max == 0) { gl.glTranslatef(0, rhDim / 2, 0); // translate to UL corner of histogram textRenderer.begin3DRendering(); textRenderer.draw3D("No data", 0, 0, 0, .07f); textRenderer.end3DRendering(); gl.glPopMatrix(); } else { final float maxRecip = 2f / max; gl.glPushMatrix(); // draw hist values for (int xx = 0; xx < rhDim; xx++) { for (int yy = 0; yy < rhDim; yy++) { float g = maxRecip * resultHistogram[xx][yy]; gl.glColor3f(g, g, g); gl.glBegin(GL2ES3.GL_QUADS); gl.glVertex2f(xx, yy); gl.glVertex2f(xx + 1, yy); gl.glVertex2f(xx + 1, yy + 1); gl.glVertex2f(xx, yy + 1); gl.glEnd(); } } final int tsd = searchDistance << (numScales - 1); if (avgMatchDistance > 0) { gl.glPushMatrix(); gl.glColor4f(1f, 0, 0, .5f); gl.glLineWidth(5f); DrawGL.drawCircle(gl, tsd + .5f, tsd + .5f, avgMatchDistance, 16); gl.glPopMatrix(); } if (avgPossibleMatchDistance > 0) { gl.glPushMatrix(); gl.glColor4f(0, 1f, 0, .5f); gl.glLineWidth(5f); DrawGL.drawCircle(gl, tsd + .5f, tsd + .5f, avgPossibleMatchDistance / 2, 16); // draw circle at target match distance gl.glPopMatrix(); } // a bunch of cryptic crap to draw a string the same width as the histogram... gl.glPopMatrix(); gl.glPopMatrix(); // back to original chip coordinates gl.glPushMatrix(); textRenderer.begin3DRendering(); String s = String.format("d=%.1f ms", 1e-3f * sliceDeltaT); // final float sc = TextRendererScale.draw3dScale(textRenderer, s, chip.getCanvas().getScale(), chip.getWidth(), .1f); // determine width of string in pixels and scale accordingly FontRenderContext frc = textRenderer.getFontRenderContext(); Rectangle2D r = textRenderer.getBounds(s); // bounds in java2d coordinates, downwards more positive Rectangle2D rt = frc.getTransform().createTransformedShape(r).getBounds2D(); // get bounds in textrenderer coordinates // float ps = chip.getCanvas().getScale(); float w = (float) rt.getWidth(); // width of text in textrenderer, i.e. histogram cell coordinates (1 unit = 1 histogram cell) float sc = subSizeX / w / 6; // scale to histogram width gl.glTranslatef(0, .65f * subSizeY, 0); // translate to UL corner of histogram textRenderer.draw3D(s, 0, 0, 0, sc); String s2 = String.format("skip: %d", skipProcessingEventsCount); textRenderer.draw3D(s2, 0, (float) (rt.getHeight()) * sc, 0, sc); String s3 = String.format("events: %d", sliceEventCount); textRenderer.draw3D(s3, 0, 2 * (float) (rt.getHeight()) * sc, 0, sc); StringBuilder sb = new StringBuilder("Scale counts: "); for (int c : scaleResultCounts) { sb.append(String.format("%d ", c)); } textRenderer.draw3D(sb.toString(), 0, (float) (3 * rt.getHeight()) * sc, 0, sc); textRenderer.end3DRendering(); gl.glPopMatrix(); // back to original chip coordinates // log.info(String.format("processed %.1f%% (%d/%d)", 100 * (float) nProcessed / (nSkipped + nProcessed), nProcessed, (nProcessed + nSkipped))); // // draw histogram of angles around center of image // if (resultAngleHistogramCount > 0) { // gl.glPushMatrix(); // gl.glTranslatef(subSizeX / 2, subSizeY / 2, 0); // gl.glLineWidth(getMotionVectorLineWidthPixels()); // gl.glColor3f(1, 1, 1); // gl.glBegin(GL.GL_LINES); // for (int i = 0; i < ANGLE_HISTOGRAM_COUNT; i++) { // float l = ((float) resultAngleHistogram[i] / resultAngleHistogramMax) * chip.getMinSize() / 2; // bin 0 is angle -PI // double angle = ((2 * Math.PI * i) / ANGLE_HISTOGRAM_COUNT) - Math.PI; // float dx = (float) Math.cos(angle) * l, dy = (float) Math.sin(angle) * l; // gl.glVertex2f(0, 0); // gl.glVertex2f(dx, dy); // gl.glEnd(); // gl.glPopMatrix(); } resetOFHistogram(); // clears OF histogram if slices have been rotated } if (sliceMethod == SliceMethod.AreaEventNumber && showAreaCountAreasTemporarily) { int d = 1 << areaEventNumberSubsampling; gl.glLineWidth(2f); gl.glColor3f(1, 1, 1); gl.glBegin(GL.GL_LINES); for (int x = 0; x <= subSizeX; x += d) { gl.glVertex2f(x, 0); gl.glVertex2f(x, subSizeY); } for (int y = 0; y <= subSizeY; y += d) { gl.glVertex2f(0, y); gl.glVertex2f(subSizeX, y); } gl.glEnd(); } if (sliceMethod == SliceMethod.ConstantIntegratedFlow && showAreaCountAreasTemporarily) { // TODO fill in what to draw } if (showBlockSizeAndSearchAreaTemporarily) { gl.glLineWidth(2f); gl.glColor3f(1, 0, 0); // show block size final int xx = subSizeX / 2, yy = subSizeY / 2, d = blockDimension / 2; gl.glBegin(GL.GL_LINE_LOOP); gl.glVertex2f(xx - d, yy - d); gl.glVertex2f(xx + d, yy - d); gl.glVertex2f(xx + d, yy + d); gl.glVertex2f(xx - d, yy + d); gl.glEnd(); // show search area gl.glColor3f(0, 1, 0); final int sd = d + (searchDistance << (numScales - 1)); gl.glBegin(GL.GL_LINE_LOOP); gl.glVertex2f(xx - sd, yy - sd); gl.glVertex2f(xx + sd, yy - sd); gl.glVertex2f(xx + sd, yy + sd); gl.glVertex2f(xx - sd, yy + sd); gl.glEnd(); } } @Override public synchronized void resetFilter() { setSubSampleShift(0); // filter breaks with super's bit shift subsampling super.resetFilter(); eventCounter = 0; // lastTs = Integer.MIN_VALUE; checkArrays(); if (slices == null) { return; // on reset maybe chip is not set yet } for (byte[][][] b : slices) { clearSlice(b); } currentSliceIdx = 0; // start by filling slice 0 currentSlice = slices[currentSliceIdx]; sliceLastTs = Integer.MAX_VALUE; rewindFlg = true; if (adaptiveEventSkippingUpdateCounterLPFilter != null) { adaptiveEventSkippingUpdateCounterLPFilter.reset(); } clearAreaCounts(); clearNonGreedyRegions(); } @Override public void update(Observable o, Object arg) { if (!isFilterEnabled()) { return; } super.update(o, arg); if ((o instanceof AEChip) && (chip.getNumPixels() > 0)) { resetFilter(); } } private LowpassFilter speedFilter = new LowpassFilter(); /** * uses the current event to maybe rotate the slices * * @return true if slices were rotated */ private boolean maybeRotateSlices() { int dt = ts - sliceLastTs; if (dt < 0 || rewindFlg) { // handle timestamp wrapping // System.out.println("rotated slices at "); // System.out.println("rotated slices with dt= "+dt); rotateSlices(); eventCounter = 0; sliceDeltaT = dt; sliceLastTs = ts; return true; } switch (sliceMethod) { case ConstantDuration: if ((dt < sliceDurationUs)) { return false; } break; case ConstantEventNumber: if (eventCounter < sliceEventCount) { return false; } break; case AreaEventNumber: if (!areaCountExceeded && dt < MAX_SLICE_DURATION_US) { return false; } break; case ConstantIntegratedFlow: speedFilter.setTauMs(sliceDeltaTimeUs(2) >> 10); final float meanGlobalSpeed = motionFlowStatistics.getGlobalMotion().meanGlobalSpeed; if (!Float.isNaN(meanGlobalSpeed)) { speedFilter.filter(meanGlobalSpeed, ts); } final float filteredMeanGlobalSpeed = speedFilter.getValue(); final float totalMovement = filteredMeanGlobalSpeed * dt * 1e-6f; if (Float.isNaN(meanGlobalSpeed)) { // we need to rotate slices somwhow even if there is no motion computed yet if (eventCounter < sliceEventCount) { return false; } if ((dt < sliceDurationUs)) { return false; } break; } if (totalMovement < searchDistance / 2 && dt < sliceDurationUs) { return false; } break; } rotateSlices(); /* Slices have been rotated */ getSupport().firePropertyChange(PatchMatchFlow.EVENT_NEW_SLICES, slices[sliceIndex(1)], slices[sliceIndex(2)]); return true; } /** * Rotates slices by incrementing the slice pointer with rollover back to * zero, and sets currentSliceIdx and currentBitmap. Clears the new * currentBitmap. Thus the slice pointer increments. 0,1,2,0,1,2 * */ private void rotateSlices() { if (e != null) { sliceEndTimeUs[currentSliceIdx] = e.timestamp; } /*Thus if 0 is current index for current filling slice, then sliceIndex returns 1,2 for pointer =1,2. * Then if NUM_SLICES=3, after rotateSlices(), currentSliceIdx=NUM_SLICES-1=2, and sliceIndex(0)=2, sliceIndex(1)=0, sliceIndex(2)=1. */ sliceSummedSADValues[currentSliceIdx] = 0; // clear out current collecting slice which becomes the oldest slice after rotation sliceSummedSADCounts[currentSliceIdx] = 0; // clear out current collecting slice which becomes the oldest slice after rotation currentSliceIdx if (currentSliceIdx < 0) { currentSliceIdx = numSlices - 1; } currentSlice = slices[currentSliceIdx]; //sliceStartTimeUs[currentSliceIdx] = ts; // current event timestamp; set on first event to slice clearSlice(currentSlice); clearAreaCounts(); eventCounter = 0; sliceDeltaT = ts - sliceLastTs; sliceLastTs = ts; if (imuTimesliceLogger != null && imuTimesliceLogger.isEnabled()) { imuTimesliceLogger.log(String.format("%d %d %.3f", ts, sliceDeltaT, imuFlowEstimator.getPanRateDps())); } } /** * Returns index to slice given pointer, with zero as current filling slice * pointer. * * * @param pointer how many slices in the past to index for. I.e.. 0 for * current slice (one being currently filled), 1 for next oldest, 2 for * oldest (when using NUM_SLICES=3). * @return index into bitmaps[] */ private int sliceIndex(int pointer) { return (currentSliceIdx + pointer) % numSlices; } /** * returns slice delta time in us from reference slice * * @param pointer how many slices in the past to index for. I.e.. 0 for * current slice (one being currently filled), 1 for next oldest, 2 for * oldest (when using NUM_SLICES=3). Only meaningful for pointer>=2, * currently exactly only pointer==2 since we are using only 3 slices. * * Modified to compute the delta time using the average of start and end * timestamps of each slices, i.e. the slice time "midpoint" where midpoint * is defined by average of first and last timestamp. * */ private int sliceDeltaTimeUs(int pointer) { // System.out.println("dt(" + pointer + ")=" + (sliceStartTimeUs[sliceIndex(1)] - sliceStartTimeUs[sliceIndex(pointer)])); int idxOlder = sliceIndex(pointer), idxYounger = sliceIndex(1); int tOlder = (sliceStartTimeUs[idxOlder] + sliceEndTimeUs[idxOlder]) / 2; int tYounger = (sliceStartTimeUs[idxYounger] + sliceEndTimeUs[idxYounger]) / 2; int dt = tYounger - tOlder; return dt; } private int nSkipped = 0, nProcessed = 0; /** * Accumulates the current event to the current slice * * @return true if subsequent processing should done, false if it should be * skipped for efficiency */ synchronized private boolean accumulateEvent(PolarityEvent e) { if (eventCounter++ == 0) { sliceStartTimeUs[currentSliceIdx] = e.timestamp; // current event timestamp } for (int s = 0; s < numScales; s++) { final int xx = e.x >> s; final int yy = e.y >> s; // if (xx >= currentSlice[s].length || yy > currentSlice[s][xx].length) { // log.warning("event out of range"); // return false; int cv = currentSlice[s][xx][yy]; cv += rectifyPolarties ? 1 : (e.polarity == PolarityEvent.Polarity.On ? 1 : -1); if (cv > sliceMaxValue) { cv = sliceMaxValue; } else if (cv < -sliceMaxValue) { cv = -sliceMaxValue; } currentSlice[s][xx][yy] = (byte) cv; } if (sliceMethod == SliceMethod.AreaEventNumber) { if (areaCounts == null) { clearAreaCounts(); } int c = ++areaCounts[e.x >> areaEventNumberSubsampling][e.y >> areaEventNumberSubsampling]; if (c >= sliceEventCount) { areaCountExceeded = true; // int count=0, sum=0, sum2=0; // StringBuilder sb=new StringBuilder("Area counts:\n"); // for(int[] i:areaCounts){ // for(int j:i){ // count++; // sum+=j; // sum2+=j*j; // sb.append(String.format("%6d ",j)); // sb.append("\n"); // float m=(float)sum/count; // float s=(float)Math.sqrt((float)sum2/count-m*m); // sb.append(String.format("mean=%.1f, std=%.1f",m,s)); // log.info("area count stats "+sb.toString()); } } if (timeLimiter.isTimedOut()) { nSkipped++; return false; } if (nonGreedyFlowComputingEnabled) { // only process the event for flow if most of the other regions have already been processed int xx = e.x >> areaEventNumberSubsampling, yy = e.y >> areaEventNumberSubsampling; boolean didArea = nonGreedyRegions[xx][yy]; if (!didArea) { nonGreedyRegions[xx][yy] = true; nonGreedyRegionsCount++; if (nonGreedyRegionsCount >= (int) (nonGreedyFractionToBeServiced * nonGreedyRegionsNumberOfRegions)) { clearNonGreedyRegions(); } nProcessed++; return true; // skip counter is ignored } else { nSkipped++; return false; } } if (skipProcessingEventsCount == 0) { nProcessed++; return true; } if (skipCounter++ < skipProcessingEventsCount) { nSkipped++; return false; } nProcessed++; skipCounter = 0; return true; } // private void clearSlice(int idx) { // for (int[] a : histograms[idx]) { // Arrays.fill(a, 0); private float sumArray[][] = null; /** * Computes block matching image difference best match around point x,y * using blockDimension and searchDistance and scale * * @param x coordinate in subsampled space * @param y * @param prevSlice the slice over which we search for best match * @param curSlice the slice from which we get the reference block * @param subSampleBy the scale to compute this SAD on, 0 for full * resolution, 1 for 2x2 subsampled block bitmap, etc * @return SADResult that provides the shift and SAD value */ // private SADResult minHammingDistance(int x, int y, BitSet prevSlice, BitSet curSlice) { private SADResult minSADDistance(int x, int y, byte[][][] curSlice, byte[][][] prevSlice, int subSampleBy) { SADResult result = new SADResult(); float minSum = Float.MAX_VALUE, sum; float FSDx = 0, FSDy = 0, DSDx = 0, DSDy = 0; // This is for testing the DS search accuracy. final int searchRange = (2 * searchDistance) + 1; // The maximum search distance in this subSampleBy slice if ((sumArray == null) || (sumArray.length != searchRange)) { sumArray = new float[searchRange][searchRange]; } else { for (float[] row : sumArray) { Arrays.fill(row, Float.MAX_VALUE); } } if (outputSearchErrorInfo) { searchMethod = SearchMethod.FullSearch; } else { searchMethod = getSearchMethod(); } switch (searchMethod) { case DiamondSearch: // SD = small diamond, LD=large diamond SP=search process /* The center of the LDSP or SDSP could change in the iteration process, so we need to use a variable to represent it. In the first interation, it's the Zero Motion Potion (ZMP). */ int xCenter = x, yCenter = y; /* x offset of center point relative to ZMP, y offset of center point to ZMP. x offset of center pointin positive number to ZMP, y offset of center point in positive number to ZMP. */ int dx, dy, xidx, yidx; // x and y best match offsets in pixels, indices of these in 2d hist int minPointIdx = 0; // Store the minimum point index. boolean SDSPFlg = false; // If this flag is set true, then it means LDSP search is finished and SDSP search could start. /* If one block has been already calculated, the computedFlg will be set so we don't to do the calculation again. */ boolean computedFlg[][] = new boolean[searchRange][searchRange]; for (boolean[] row : computedFlg) { Arrays.fill(row, false); } if (searchDistance == 1) { // LDSP search can only be applied for search distance >= 2. SDSPFlg = true; } int iterationsLeft = searchRange * searchRange; while (!SDSPFlg) { /* 1. LDSP search */ for (int pointIdx = 0; pointIdx < LDSP.length; pointIdx++) { dx = (LDSP[pointIdx][0] + xCenter) - x; dy = (LDSP[pointIdx][1] + yCenter) - y; xidx = dx + searchDistance; yidx = dy + searchDistance; // Point to be searched is out of search area, skip it. if ((xidx >= searchRange) || (yidx >= searchRange) || (xidx < 0) || (yidx < 0)) { continue; } /* We just calculate the blocks that haven't been calculated before */ if (computedFlg[xidx][yidx] == false) { sumArray[xidx][yidx] = sadDistance(x, y, dx, dy, curSlice, prevSlice, subSampleBy); computedFlg[xidx][yidx] = true; if (outputSearchErrorInfo) { DSAverageNum++; } if (outputSearchErrorInfo) { if (sumArray[xidx][yidx] != sumArray[xidx][yidx]) { // TODO huh? this is never true, compares to itself log.warning("It seems that there're some bugs in the DS algorithm."); } } } if (sumArray[xidx][yidx] <= minSum) { minSum = sumArray[xidx][yidx]; minPointIdx = pointIdx; } } /* 2. Check the minimum value position is in the center or not. */ xCenter = xCenter + LDSP[minPointIdx][0]; yCenter = yCenter + LDSP[minPointIdx][1]; if (minPointIdx == 4) { // It means it's in the center, so we should break the loop and go to SDSP search. SDSPFlg = true; } if (--iterationsLeft < 0) { log.warning("something is wrong with diamond search; did not find min in SDSP search"); SDSPFlg = true; } } /* 3. SDSP Search */ for (int[] element : SDSP) { dx = (element[0] + xCenter) - x; dy = (element[1] + yCenter) - y; xidx = dx + searchDistance; yidx = dy + searchDistance; // Point to be searched is out of search area, skip it. if ((xidx >= searchRange) || (yidx >= searchRange) || (xidx < 0) || (yidx < 0)) { continue; } /* We just calculate the blocks that haven't been calculated before */ if (computedFlg[xidx][yidx] == false) { sumArray[xidx][yidx] = sadDistance(x, y, dx, dy, curSlice, prevSlice, subSampleBy); computedFlg[xidx][yidx] = true; if (outputSearchErrorInfo) { DSAverageNum++; } if (outputSearchErrorInfo) { if (sumArray[xidx][yidx] != sumArray[xidx][yidx]) { log.warning("It seems that there're some bugs in the DS algorithm."); } } } if (sumArray[xidx][yidx] <= minSum) { minSum = sumArray[xidx][yidx]; result.dx = -dx; // minus is because result points to the past slice and motion is in the other direction result.dy = -dy; result.sadValue = minSum; } // // debug // if(result.dx==-searchDistance && result.dy==-searchDistance){ // System.out.println(result); } if (outputSearchErrorInfo) { DSDx = result.dx; DSDy = result.dy; } break; case FullSearch: for (dx = -searchDistance; dx <= searchDistance; dx++) { for (dy = -searchDistance; dy <= searchDistance; dy++) { sum = sadDistance(x, y, dx, dy, curSlice, prevSlice, subSampleBy); sumArray[dx + searchDistance][dy + searchDistance] = sum; if (sum < minSum) { minSum = sum; result.dx = -dx; // minus is because result points to the past slice and motion is in the other direction result.dy = -dy; result.sadValue = minSum; } } } if (outputSearchErrorInfo) { FSCnt += 1; FSDx = result.dx; FSDy = result.dy; } else { break; } case CrossDiamondSearch: break; } // compute the indices into 2d histogram of all motion vector results. // It's a bit complicated because of multiple scales. // Also, we want the indexes to be centered in the histogram array so that searches at full scale appear at the middle // of the array and not at 0,0 corner. // Suppose searchDistance=1 and numScales=2. Then the histogram has size 2*2+1=5. // Therefore the scale 0 results need to have offset added to them to center results in histogram that // shows results over all scales. result.scale = subSampleBy; // convert dx in search steps to dx in pixels including subsampling // compute index assuming no subsampling or centering result.xidx = result.dx + searchDistance; result.yidx = result.dy + searchDistance; // compute final dx and dy including subsampling result.dx = result.dx << subSampleBy; result.dy = result.dy << subSampleBy; // compute final index including subsampling and centering // idxCentering is shift needed to be applyed to store this result finally into the hist, final int idxCentering = (searchDistance << (numScales - 1)) - ((searchDistance) << subSampleBy); // i.e. for subSampleBy=0 and numScales=2, shift=1 so that full scale search is centered in 5x5 hist result.xidx = (result.xidx << subSampleBy) + idxCentering; result.yidx = (result.yidx << subSampleBy) + idxCentering; // if (result.xidx < 0 || result.yidx < 0 || result.xidx > maxIdx || result.yidx > maxIdx) { // log.warning("something wrong with result=" + result); // return null; if (outputSearchErrorInfo) { if ((DSDx == FSDx) && (DSDy == FSDy)) { DSCorrectCnt += 1; } else { DSAveError[0] += Math.abs(DSDx - FSDx); DSAveError[1] += Math.abs(DSDy - FSDy); } if (0 == (FSCnt % 10000)) { log.log(Level.INFO, "Correct Diamond Search times are {0}, Full Search times are {1}, accuracy is {2}, averageNumberPercent is {3}, averageError is ({4}, {5})", new Object[]{DSCorrectCnt, FSCnt, DSCorrectCnt / FSCnt, DSAverageNum / (searchRange * searchRange * FSCnt), DSAveError[0] / FSCnt, DSAveError[1] / (FSCnt - DSCorrectCnt)}); } } // if (tmpSadResult.xidx == searchRange-1 && tmpSadResult.yidx == searchRange-1) { // tmpSadResult.sadValue = 1; // reject results to top right that are likely result of ambiguous search return result; } /** * computes Hamming distance centered on x,y with patch of patchSize for * prevSliceIdx relative to curSliceIdx patch. * * @param xfull coordinate x in full resolution * @param yfull coordinate y in full resolution * @param dx the offset in pixels in the subsampled space of the past slice. * The motion vector is then *from* this position *to* the current slice. * @param dy * @param prevSlice * @param curSlice * @param subsampleBy the scale to search over * @return Distance value, max 1 when all pixels differ, min 0 when all the * same */ private float sadDistance(final int xfull, final int yfull, final int dx, final int dy, final byte[][][] curSlice, final byte[][][] prevSlice, final int subsampleBy) { final int x = xfull >> subsampleBy; final int y = yfull >> subsampleBy; final int r = ((blockDimension) / 2); int w = subSizeX >> subsampleBy, h = subSizeY >> subsampleBy; int adx = dx > 0 ? dx : -dx; // abs val of dx and dy, to compute limits int ady = dy > 0 ? dy : -dy; // Make sure both ref block and past slice block are in bounds on all sides or there'll be arrayIndexOutOfBoundary exception. // Also we don't want to match ref block only on inner sides or there will be a bias towards motion towards middle if (x - r - adx < 0 || x + r + adx >= w || y - r - ady < 0 || y + r + ady >= h) { return 1; // tobi changed to 1 again // Float.MAX_VALUE; // return very large distance for this match so it is not selected } int validPixNumCurSlice = 0, validPixNumPrevSlice = 0; // The valid pixel number in the current block int nonZeroMatchCount = 0; // int saturatedPixNumCurSlice = 0, saturatedPixNumPrevSlice = 0; // The valid pixel number in the current block int sumDist = 0; // try { for (int xx = x - r; xx <= (x + r); xx++) { for (int yy = y - r; yy <= (y + r); yy++) { // if (xx < 0 || yy < 0 || xx >= w || yy >= h // || xx + dx < 0 || yy + dy < 0 || xx + dx >= w || yy + dy >= h) { //// log.warning("out of bounds slice access; something wrong"); // TODO fix this check above // continue; int currSliceVal = curSlice[subsampleBy][xx][yy]; // binary value on (xx, yy) for current slice int prevSliceVal = prevSlice[subsampleBy][xx + dx][yy + dy]; // binary value on (xx, yy) for previous slice at offset dx,dy in (possibly subsampled) slice int dist = (currSliceVal - prevSliceVal); if (dist < 0) { dist = (-dist); } sumDist += dist; // if (currSlicePol != prevSlicePol) { // hd += 1; // if (currSliceVal == sliceMaxValue || currSliceVal == -sliceMaxValue) { // saturatedPixNumCurSlice++; // pixels that are not saturated // if (prevSliceVal == sliceMaxValue || prevSliceVal == -sliceMaxValue) { // saturatedPixNumPrevSlice++; if (currSliceVal != 0) { validPixNumCurSlice++; // pixels that are not saturated } if (prevSliceVal != 0) { validPixNumPrevSlice++; } if (currSliceVal != 0 && prevSliceVal != 0) { nonZeroMatchCount++; // pixels that both have events in them } } } // } catch (ArrayIndexOutOfBoundsException ex) { // log.warning(ex.toString()); // debug // if(dx==-1 && dy==-1) return 0; else return Float.MAX_VALUE; // normalize by dimesion of subsampling, with idea that subsampling increases SAD //by sqrt(area) because of Gaussian distribution of SAD values sumDist = sumDist >> (subsampleBy << 1); final int blockDim = (2 * r) + 1; final int blockArea = (blockDim) * (blockDim); // TODO check math here for fraction correct with subsampling // TODD: NEXT WORK IS TO DO THE RESEARCH ON WEIGHTED HAMMING DISTANCE // Calculate the metric confidence value final int minValidPixNum = (int) (this.validPixOccupancy * blockArea); // final int maxSaturatedPixNum = (int) ((1 - this.validPixOccupancy) * blockArea); final float sadNormalizer = 1f / (blockArea * (rectifyPolarties ? 2 : 1) * sliceMaxValue); // if current or previous block has insufficient pixels with values or if all the pixels are filled up, then reject match if ((validPixNumCurSlice < minValidPixNum) || (validPixNumPrevSlice < minValidPixNum) || (nonZeroMatchCount < minValidPixNum) // || (saturatedPixNumCurSlice >= maxSaturatedPixNum) || (saturatedPixNumPrevSlice >= maxSaturatedPixNum) ) { // If valid pixel number of any slice is 0, then we set the distance to very big value so we can exclude it. return 1; // tobi changed to 1 to represent max distance // Float.MAX_VALUE; } else { /* retVal consists of the distance and the dispersion. dispersion is used to describe the spatial relationship within one block. Here we use the difference between validPixNumCurrSli and validPixNumPrevSli to calculate the dispersion. Inspired by paper "Measuring the spatial dispersion of evolutionist search process: application to Walksat" by Alain Sidaner. */ final float finalDistance = sadNormalizer * ((sumDist * weightDistance) + (Math.abs(validPixNumCurSlice - validPixNumPrevSlice) * (1 - weightDistance))); return finalDistance; } } /** * Computes hamming weight around point x,y using blockDimension and * searchDistance * * @param x coordinate in subsampled space * @param y * @param prevSlice * @param curSlice * @return SADResult that provides the shift and SAD value */ // private SADResult minJaccardDistance(int x, int y, BitSet prevSlice, BitSet curSlice) { // private SADResult minJaccardDistance(int x, int y, byte[][] prevSlice, byte[][] curSlice) { // float minSum = Integer.MAX_VALUE, sum = 0; // SADResult sadResult = new SADResult(0, 0, 0); // for (int dx = -searchDistance; dx <= searchDistance; dx++) { // for (int dy = -searchDistance; dy <= searchDistance; dy++) { // sum = jaccardDistance(x, y, dx, dy, prevSlice, curSlice); // if (sum <= minSum) { // minSum = sum; // sadResult.dx = dx; // sadResult.dy = dy; // sadResult.sadValue = minSum; // return sadResult; /** * computes Hamming distance centered on x,y with patch of patchSize for * prevSliceIdx relative to curSliceIdx patch. * * @param x coordinate in subSampled space * @param y * @param patchSize * @param prevSlice * @param curSlice * @return SAD value */ // private float jaccardDistance(int x, int y, int dx, int dy, BitSet prevSlice, BitSet curSlice) { private float jaccardDistance(int x, int y, int dx, int dy, boolean[][] prevSlice, boolean[][] curSlice) { float M01 = 0, M10 = 0, M11 = 0; int blockRadius = blockDimension / 2; // Make sure 0<=xx+dx<subSizeX, 0<=xx<subSizeX and 0<=yy+dy<subSizeY, 0<=yy<subSizeY, or there'll be arrayIndexOutOfBoundary exception. if ((x < (blockRadius + dx)) || (x >= ((subSizeX - blockRadius) + dx)) || (x < blockRadius) || (x >= (subSizeX - blockRadius)) || (y < (blockRadius + dy)) || (y >= ((subSizeY - blockRadius) + dy)) || (y < blockRadius) || (y >= (subSizeY - blockRadius))) { return 1; // changed back to 1 // Float.MAX_VALUE; } for (int xx = x - blockRadius; xx <= (x + blockRadius); xx++) { for (int yy = y - blockRadius; yy <= (y + blockRadius); yy++) { final boolean c = curSlice[xx][yy], p = prevSlice[xx - dx][yy - dy]; if ((c == true) && (p == true)) { M11 += 1; } if ((c == true) && (p == false)) { M01 += 1; } if ((c == false) && (p == true)) { M10 += 1; } // if ((curSlice.get((xx + 1) + ((yy) * subSizeX)) == true) && (prevSlice.get(((xx + 1) - dx) + ((yy - dy) * subSizeX)) == true)) { // M11 += 1; // if ((curSlice.get((xx + 1) + ((yy) * subSizeX)) == true) && (prevSlice.get(((xx + 1) - dx) + ((yy - dy) * subSizeX)) == false)) { // M01 += 1; // if ((curSlice.get((xx + 1) + ((yy) * subSizeX)) == false) && (prevSlice.get(((xx + 1) - dx) + ((yy - dy) * subSizeX)) == true)) { // M10 += 1; } } float retVal; if (0 == (M01 + M10 + M11)) { retVal = 0; } else { retVal = M11 / (M01 + M10 + M11); } retVal = 1 - retVal; return retVal; } // private SADResult minVicPurDistance(int blockX, int blockY) { // ArrayList<Integer[]> seq1 = new ArrayList(1); // SADResult sadResult = new SADResult(0, 0, 0); // int size = spikeTrains[blockX][blockY].size(); // int lastTs = spikeTrains[blockX][blockY].get(size - forwardEventNum)[0]; // for (int i = size - forwardEventNum; i < size; i++) { // seq1.add(spikeTrains[blockX][blockY].get(i)); //// if(seq1.get(2)[0] - seq1.get(0)[0] > thresholdTime) { //// return sadResult; // double minium = Integer.MAX_VALUE; // for (int i = -1; i < 2; i++) { // for (int j = -1; j < 2; j++) { // // Remove the seq1 itself // if ((0 == i) && (0 == j)) { // continue; // ArrayList<Integer[]> seq2 = new ArrayList(1); // if ((blockX >= 2) && (blockY >= 2)) { // ArrayList<Integer[]> tmpSpikes = spikeTrains[blockX + i][blockY + j]; // if (tmpSpikes != null) { // for (int index = 0; index < tmpSpikes.size(); index++) { // if (tmpSpikes.get(index)[0] >= lastTs) { // seq2.add(tmpSpikes.get(index)); // double dis = vicPurDistance(seq1, seq2); // if (dis < minium) { // minium = dis; // sadResult.dx = -i; // sadResult.dy = -j; // lastFireIndex[blockX][blockY] = spikeTrains[blockX][blockY].size() - 1; // if ((sadResult.dx != 1) || (sadResult.dy != 0)) { // // sadResult = new SADResult(0, 0, 0); // return sadResult; // private double vicPurDistance(ArrayList<Integer[]> seq1, ArrayList<Integer[]> seq2) { // int sum1Plus = 0, sum1Minus = 0, sum2Plus = 0, sum2Minus = 0; // Iterator itr1 = seq1.iterator(); // Iterator itr2 = seq2.iterator(); // int length1 = seq1.size(); // int length2 = seq2.size(); // double[][] distanceMatrix = new double[length1 + 1][length2 + 1]; // for (int h = 0; h <= length1; h++) { // for (int k = 0; k <= length2; k++) { // if (h == 0) { // distanceMatrix[h][k] = k; // continue; // if (k == 0) { // distanceMatrix[h][k] = h; // continue; // double tmpMin = Math.min(distanceMatrix[h][k - 1] + 1, distanceMatrix[h - 1][k] + 1); // double event1 = seq1.get(h - 1)[0] - seq1.get(0)[0]; // double event2 = seq2.get(k - 1)[0] - seq2.get(0)[0]; // distanceMatrix[h][k] = Math.min(tmpMin, distanceMatrix[h - 1][k - 1] + (cost * Math.abs(event1 - event2))); // while (itr1.hasNext()) { // Integer[] ii = (Integer[]) itr1.next(); // if (ii[1] == 1) { // sum1Plus += 1; // } else { // sum1Minus += 1; // while (itr2.hasNext()) { // Integer[] ii = (Integer[]) itr2.next(); // if (ii[1] == 1) { // sum2Plus += 1; // } else { // sum2Minus += 1; // // return Math.abs(sum1Plus - sum2Plus) + Math.abs(sum1Minus - sum2Minus); // return distanceMatrix[length1][length2]; // /** // * Computes min SAD shift around point x,y using blockDimension and // * searchDistance // * // * @param x coordinate in subsampled space // * @param y // * @param prevSlice // * @param curSlice // * @return SADResult that provides the shift and SAD value // */ // private SADResult minSad(int x, int y, BitSet prevSlice, BitSet curSlice) { // // for now just do exhaustive search over all shifts up to +/-searchDistance // SADResult sadResult = new SADResult(0, 0, 0); // float minSad = 1; // for (int dx = -searchDistance; dx <= searchDistance; dx++) { // for (int dy = -searchDistance; dy <= searchDistance; dy++) { // float sad = sad(x, y, dx, dy, prevSlice, curSlice); // if (sad <= minSad) { // minSad = sad; // sadResult.dx = dx; // sadResult.dy = dy; // sadResult.sadValue = minSad; // return sadResult; // /** // * computes SAD centered on x,y with shift of dx,dy for prevSliceIdx // * relative to curSliceIdx patch. // * // * @param x coordinate x in subSampled space // * @param y coordinate y in subSampled space // * @param dx block shift of x // * @param dy block shift of y // * @param prevSliceIdx // * @param curSliceIdx // * @return SAD value // */ // private float sad(int x, int y, int dx, int dy, BitSet prevSlice, BitSet curSlice) { // int blockRadius = blockDimension / 2; // // Make sure 0<=xx+dx<subSizeX, 0<=xx<subSizeX and 0<=yy+dy<subSizeY, 0<=yy<subSizeY, or there'll be arrayIndexOutOfBoundary exception. // if ((x < (blockRadius + dx)) || (x >= ((subSizeX - blockRadius) + dx)) || (x < blockRadius) || (x >= (subSizeX - blockRadius)) // || (y < (blockRadius + dy)) || (y >= ((subSizeY - blockRadius) + dy)) || (y < blockRadius) || (y >= (subSizeY - blockRadius))) { // return Float.MAX_VALUE; // float sad = 0, retVal = 0; // float validPixNumCurrSli = 0, validPixNumPrevSli = 0; // The valid pixel number in the current block // for (int xx = x - blockRadius; xx <= (x + blockRadius); xx++) { // for (int yy = y - blockRadius; yy <= (y + blockRadius); yy++) { // boolean currSlicePol = curSlice.get((xx + 1) + ((yy) * subSizeX)); // binary value on (xx, yy) for current slice // boolean prevSlicePol = prevSlice.get(((xx + 1) - dx) + ((yy - dy) * subSizeX)); // binary value on (xx, yy) for previous slice // int imuWarningDialog = (currSlicePol ? 1 : 0) - (prevSlicePol ? 1 : 0); // if (currSlicePol == true) { // validPixNumCurrSli += 1; // if (prevSlicePol == true) { // validPixNumPrevSli += 1; // if (imuWarningDialog <= 0) { // imuWarningDialog = -imuWarningDialog; // sad += imuWarningDialog; // // Calculate the metric confidence value // float validPixNum = this.validPixOccupancy * (((2 * blockRadius) + 1) * ((2 * blockRadius) + 1)); // if ((validPixNumCurrSli <= validPixNum) || (validPixNumPrevSli <= validPixNum)) { // If valid pixel number of any slice is 0, then we set the distance to very big value so we can exclude it. // retVal = 1; // } else { // /* // retVal is consisted of the distance and the dispersion, dispersion is used to describe the spatial relationship within one block. // Here we use the difference between validPixNumCurrSli and validPixNumPrevSli to calculate the dispersion. // Inspired by paper "Measuring the spatial dispersion of evolutionist search process: application to Walksat" by Alain Sidaner. // */ // retVal = ((sad * weightDistance) + (Math.abs(validPixNumCurrSli - validPixNumPrevSli) * (1 - weightDistance))) / (((2 * blockRadius) + 1) * ((2 * blockRadius) + 1)); // return retVal; private class SADResult { int dx, dy; // best match offset in pixels to reference block from past slice block, i.e. motion vector points in this direction float vx, vy; // optical flow in pixels/second corresponding to this match float sadValue; // sum of absolute differences for this best match normalized by number of pixels in reference area int xidx, yidx; // x and y indices into 2d matrix of result. 0,0 corresponds to motion SW. dx, dy may be negative, like (-1, -1) represents SW. // However, for histgram index, it's not possible to use negative number. That's the reason for intrducing xidx and yidx. // boolean minSearchedFlg = false; // The flag indicates that this minimum have been already searched before. int scale; /** * Allocates new results initialized to zero */ public SADResult() { this(0, 0, 0, 0); } public SADResult(int dx, int dy, float sadValue, int scale) { this.dx = dx; this.dy = dy; this.sadValue = sadValue; } public void set(SADResult s) { this.dx = s.dx; this.dy = s.dy; this.sadValue = s.sadValue; this.xidx = s.xidx; this.yidx = s.yidx; this.scale = s.scale; } @Override public String toString() { return String.format("(dx,dy=%5d,%5d), (vx,vy=%.1f,%.1f pps), SAD=%f, scale=%d", dx, dy, vx, vy, sadValue, scale); } } private class Statistics { double[] data; int size; public Statistics(double[] data) { this.data = data; size = data.length; } double getMean() { double sum = 0.0; for (double a : data) { sum += a; } return sum / size; } double getVariance() { double mean = getMean(); double temp = 0; for (double a : data) { temp += (a - mean) * (a - mean); } return temp / size; } double getStdDev() { return Math.sqrt(getVariance()); } public double median() { Arrays.sort(data); if ((data.length % 2) == 0) { return (data[(data.length / 2) - 1] + data[data.length / 2]) / 2.0; } return data[data.length / 2]; } public double getMin() { Arrays.sort(data); return data[0]; } public double getMax() { Arrays.sort(data); return data[data.length - 1]; } } /** * @return the blockDimension */ public int getBlockDimension() { return blockDimension; } /** * @param blockDimension the blockDimension to set */ synchronized public void setBlockDimension(int blockDimension) { int old = this.blockDimension; // enforce odd value if ((blockDimension & 1) == 0) { // even if (blockDimension > old) { blockDimension++; } else { blockDimension } } // clip final value if (blockDimension < 1) { blockDimension = 1; } else if (blockDimension > 63) { blockDimension = 63; } this.blockDimension = blockDimension; getSupport().firePropertyChange("blockDimension", old, blockDimension); putInt("blockDimension", blockDimension); showBlockSizeAndSearchAreaTemporarily(); } /** * @return the sliceMethod */ public SliceMethod getSliceMethod() { return sliceMethod; } /** * @param sliceMethod the sliceMethod to set */ synchronized public void setSliceMethod(SliceMethod sliceMethod) { SliceMethod old = this.sliceMethod; this.sliceMethod = sliceMethod; putString("sliceMethod", sliceMethod.toString()); if (sliceMethod == SliceMethod.AreaEventNumber || sliceMethod == SliceMethod.ConstantIntegratedFlow) { showAreasForAreaCountsTemporarily(); } // if(sliceMethod==SliceMethod.ConstantIntegratedFlow){ // setDisplayGlobalMotion(true); getSupport().firePropertyChange("sliceMethod", old, this.sliceMethod); } public PatchCompareMethod getPatchCompareMethod() { return patchCompareMethod; } synchronized public void setPatchCompareMethod(PatchCompareMethod patchCompareMethod) { this.patchCompareMethod = patchCompareMethod; putString("patchCompareMethod", patchCompareMethod.toString()); } /** * * @return the search method */ public SearchMethod getSearchMethod() { return searchMethod; } /** * * @param searchMethod the method to be used for searching */ synchronized public void setSearchMethod(SearchMethod searchMethod) { SearchMethod old = this.searchMethod; this.searchMethod = searchMethod; putString("searchMethod", searchMethod.toString()); getSupport().firePropertyChange("searchMethod", old, this.searchMethod); } private void computeAveragePossibleMatchDistance() { int n = 0; double s = 0; for (int xx = -searchDistance; xx <= searchDistance; xx++) { for (int yy = -searchDistance; yy <= searchDistance; yy++) { n++; s += Math.sqrt((xx * xx) + (yy * yy)); } } double d = s / n; // avg for one scale double s2 = 0; for (int i = 0; i < numScales; i++) { s2 += d * (1 << i); } double d2 = s2 / numScales; log.info(String.format("searchDistance=%d numScales=%d: avgPossibleMatchDistance=%.1f", searchDistance, numScales, avgPossibleMatchDistance)); avgPossibleMatchDistance = (float) d2; } @Override synchronized public void setSearchDistance(int searchDistance) { int old = this.searchDistance; if (searchDistance > 12) { searchDistance = 12; } else if (searchDistance < 1) { searchDistance = 1; // limit size } this.searchDistance = searchDistance; putInt("searchDistance", searchDistance); getSupport().firePropertyChange("searchDistance", old, searchDistance); resetFilter(); showBlockSizeAndSearchAreaTemporarily(); computeAveragePossibleMatchDistance(); } /** * @return the sliceDurationUs */ public int getSliceDurationUs() { return sliceDurationUs; } /** * @param sliceDurationUs the sliceDurationUs to set */ public void setSliceDurationUs(int sliceDurationUs) { int old = this.sliceDurationUs; if (sliceDurationUs < MIN_SLICE_DURATION_US) { sliceDurationUs = MIN_SLICE_DURATION_US; } else if (sliceDurationUs > MAX_SLICE_DURATION_US) { sliceDurationUs = MAX_SLICE_DURATION_US; // limit it to one second } this.sliceDurationUs = sliceDurationUs; /* If the slice duration is changed, reset FSCnt and DScorrect so we can get more accurate evaluation result */ FSCnt = 0; DSCorrectCnt = 0; putInt("sliceDurationUs", sliceDurationUs); getSupport().firePropertyChange("sliceDurationUs", old, this.sliceDurationUs); } /** * @return the sliceEventCount */ public int getSliceEventCount() { return sliceEventCount; } /** * @param sliceEventCount the sliceEventCount to set */ public void setSliceEventCount(int sliceEventCount) { int old = this.sliceEventCount; if (sliceEventCount < MIN_SLICE_EVENT_COUNT_FULL_FRAME) { sliceEventCount = MIN_SLICE_EVENT_COUNT_FULL_FRAME; } else if (sliceEventCount > MAX_SLICE_EVENT_COUNT_FULL_FRAME) { sliceEventCount = MAX_SLICE_EVENT_COUNT_FULL_FRAME; } this.sliceEventCount = sliceEventCount; putInt("sliceEventCount", sliceEventCount); getSupport().firePropertyChange("sliceEventCount", old, this.sliceEventCount); } public float getMaxAllowedSadDistance() { return maxAllowedSadDistance; } public void setMaxAllowedSadDistance(float maxAllowedSadDistance) { float old = this.maxAllowedSadDistance; if (maxAllowedSadDistance < 0) { maxAllowedSadDistance = 0; } else if (maxAllowedSadDistance > 1) { maxAllowedSadDistance = 1; } this.maxAllowedSadDistance = maxAllowedSadDistance; putFloat("maxAllowedSadDistance", maxAllowedSadDistance); getSupport().firePropertyChange("maxAllowedSadDistance", old, this.maxAllowedSadDistance); } public float getValidPixOccupancy() { return validPixOccupancy; } public void setValidPixOccupancy(float validPixOccupancy) { float old = this.validPixOccupancy; if (validPixOccupancy < 0) { validPixOccupancy = 0; } else if (validPixOccupancy > 1) { validPixOccupancy = 1; } this.validPixOccupancy = validPixOccupancy; putFloat("validPixOccupancy", validPixOccupancy); getSupport().firePropertyChange("validPixOccupancy", old, this.validPixOccupancy); } public float getWeightDistance() { return weightDistance; } public void setWeightDistance(float weightDistance) { if (weightDistance < 0) { weightDistance = 0; } else if (weightDistance > 1) { weightDistance = 1; } this.weightDistance = weightDistance; putFloat("weightDistance", weightDistance); } // private int totalFlowEvents=0, filteredOutFlowEvents=0; // private boolean filterOutInconsistentEvent(SADResult result) { // if (!isOutlierMotionFilteringEnabled()) { // return false; // totalFlowEvents++; // if (lastGoodSadResult == null) { // return false; // if (result.dx * lastGoodSadResult.dx + result.dy * lastGoodSadResult.dy >= 0) { // return false; // filteredOutFlowEvents++; // return true; synchronized private void checkArrays() { if (subSizeX == 0 || subSizeY == 0) { return; // don't do on init when chip is not known yet } // numSlices = getInt("numSlices", 3); // since resetFilter is called in super before numSlices is even initialized if (slices == null || slices.length != numSlices || slices[0] == null || slices[0].length != numScales) { if (numScales > 0 && numSlices > 0) { // deal with filter reconstruction where these fields are not set slices = new byte[numSlices][numScales][][]; for (int n = 0; n < numSlices; n++) { for (int s = 0; s < numScales; s++) { int nx = (subSizeX >> s) + 1, ny = (subSizeY >> s) + 1; if (slices[n][s] == null || slices[n][s].length != nx || slices[n][s][0] == null || slices[n][s][0].length != ny) { slices[n][s] = new byte[nx][ny]; } } } currentSliceIdx = 0; // start by filling slice 0 currentSlice = slices[currentSliceIdx]; sliceLastTs = Integer.MAX_VALUE; sliceStartTimeUs = new int[numSlices]; sliceEndTimeUs = new int[numSlices]; sliceSummedSADValues = new float[numSlices]; sliceSummedSADCounts = new int[numSlices]; } // log.info("allocated slice memory"); } if (lastTimesMap != null) { lastTimesMap = null; // save memory } int rhDim = (2 * (searchDistance << (numScales - 1))) + 1; // e.g. search distance 1, dim=3, 3x3 possibilties (including zero motion) if ((resultHistogram == null) || (resultHistogram.length != rhDim)) { resultHistogram = new int[rhDim][rhDim]; resultHistogramCount = 0; } checkNonGreedyRegionsAllocated(); } /** * * @param distResult * @return the confidence of the result. True means it's not good and should * be rejected, false means we should accept it. */ private synchronized boolean isNotSufficientlyAccurate(SADResult distResult) { boolean retVal = super.accuracyTests(); // check accuracy in super, if reject returns true // additional test, normalized blaock distance must be small enough // distance has max value 1 if (distResult.sadValue >= maxAllowedSadDistance) { retVal = true; } return retVal; } /** * @return the skipProcessingEventsCount */ public int getSkipProcessingEventsCount() { return skipProcessingEventsCount; } /** * @param skipProcessingEventsCount the skipProcessingEventsCount to set */ public void setSkipProcessingEventsCount(int skipProcessingEventsCount) { int old = this.skipProcessingEventsCount; if (skipProcessingEventsCount < 0) { skipProcessingEventsCount = 0; } if (skipProcessingEventsCount > MAX_SKIP_COUNT) { skipProcessingEventsCount = MAX_SKIP_COUNT; } this.skipProcessingEventsCount = skipProcessingEventsCount; getSupport().firePropertyChange("skipProcessingEventsCount", old, this.skipProcessingEventsCount); putInt("skipProcessingEventsCount", skipProcessingEventsCount); } /** * @return the displayResultHistogram */ public boolean isDisplayResultHistogram() { return displayResultHistogram; } /** * @param displayResultHistogram the displayResultHistogram to set */ public void setDisplayResultHistogram(boolean displayResultHistogram) { this.displayResultHistogram = displayResultHistogram; putBoolean("displayResultHistogram", displayResultHistogram); } /** * @return the adaptiveEventSkipping */ public boolean isAdaptiveEventSkipping() { return adaptiveEventSkipping; } /** * @param adaptiveEventSkipping the adaptiveEventSkipping to set */ synchronized public void setAdaptiveEventSkipping(boolean adaptiveEventSkipping) { boolean old = this.adaptiveEventSkipping; this.adaptiveEventSkipping = adaptiveEventSkipping; putBoolean("adaptiveEventSkipping", adaptiveEventSkipping); if (adaptiveEventSkipping && adaptiveEventSkippingUpdateCounterLPFilter != null) { adaptiveEventSkippingUpdateCounterLPFilter.reset(); } getSupport().firePropertyChange("adaptiveEventSkipping", old, this.adaptiveEventSkipping); } public boolean isOutputSearchErrorInfo() { return outputSearchErrorInfo; } public boolean isShowSliceBitMap() { return showSliceBitMap; } /** * @param showSliceBitMap * @param showSliceBitMap the option of displaying bitmap */ synchronized public void setShowSliceBitMap(boolean showSliceBitMap) { boolean old = this.showSliceBitMap; this.showSliceBitMap = showSliceBitMap; getSupport().firePropertyChange("showSliceBitMap", old, this.showSliceBitMap); } synchronized public void setOutputSearchErrorInfo(boolean outputSearchErrorInfo) { this.outputSearchErrorInfo = outputSearchErrorInfo; if (!outputSearchErrorInfo) { searchMethod = SearchMethod.valueOf(getString("searchMethod", SearchMethod.FullSearch.toString())); // make sure method is reset } } private LowpassFilter adaptiveEventSkippingUpdateCounterLPFilter = null; private int adaptiveEventSkippingUpdateCounter = 0; private void adaptEventSkipping() { if (!adaptiveEventSkipping) { return; } if (chip.getAeViewer() == null) { return; } int old = skipProcessingEventsCount; if (chip.getAeViewer().isPaused() || chip.getAeViewer().isSingleStep()) { skipProcessingEventsCount = 0; getSupport().firePropertyChange("skipProcessingEventsCount", old, this.skipProcessingEventsCount); } if (adaptiveEventSkippingUpdateCounterLPFilter == null) { adaptiveEventSkippingUpdateCounterLPFilter = new LowpassFilter(chip.getAeViewer().getFrameRater().FPS_LOWPASS_FILTER_TIMECONSTANT_MS); } final float averageFPS = chip.getAeViewer().getFrameRater().getAverageFPS(); final int frameRate = chip.getAeViewer().getDesiredFrameRate(); boolean skipMore = averageFPS < (int) (0.75f * frameRate); boolean skipLess = averageFPS > (int) (0.25f * frameRate); float newSkipCount = skipProcessingEventsCount; if (skipMore) { newSkipCount = adaptiveEventSkippingUpdateCounterLPFilter.filter(1 + (skipChangeFactor * skipProcessingEventsCount), 1000 * (int) System.currentTimeMillis()); } else if (skipLess) { newSkipCount = adaptiveEventSkippingUpdateCounterLPFilter.filter((skipProcessingEventsCount / skipChangeFactor) - 1, 1000 * (int) System.currentTimeMillis()); } skipProcessingEventsCount = Math.round(newSkipCount); if (skipProcessingEventsCount > MAX_SKIP_COUNT) { skipProcessingEventsCount = MAX_SKIP_COUNT; } else if (skipProcessingEventsCount < 0) { skipProcessingEventsCount = 0; } getSupport().firePropertyChange("skipProcessingEventsCount", old, this.skipProcessingEventsCount); } /** * @return the adaptiveSliceDuration */ public boolean isAdaptiveSliceDuration() { return adaptiveSliceDuration; } /** * @param adaptiveSliceDuration the adaptiveSliceDuration to set */ synchronized public void setAdaptiveSliceDuration(boolean adaptiveSliceDuration) { boolean old = this.adaptiveSliceDuration; this.adaptiveSliceDuration = adaptiveSliceDuration; putBoolean("adaptiveSliceDuration", adaptiveSliceDuration); if (adaptiveSliceDurationLogging) { if (adaptiveSliceDurationLogger == null) { adaptiveSliceDurationLogger = new TobiLogger("PatchMatchFlow-SliceDurationControl", "slice duration or event count control logging"); adaptiveSliceDurationLogger.setHeaderLine("systemTimeMs\tpacketNumber\tavgMatchDistance\tmatchRadiusError\tglobalTranslationSpeedPPS\tsliceDurationUs\tsliceEventCount"); } adaptiveSliceDurationLogger.setEnabled(adaptiveSliceDuration); } getSupport().firePropertyChange("adaptiveSliceDuration", old, this.adaptiveSliceDuration); } /** * @return the processingTimeLimitMs */ public int getProcessingTimeLimitMs() { return processingTimeLimitMs; } /** * @param processingTimeLimitMs the processingTimeLimitMs to set */ public void setProcessingTimeLimitMs(int processingTimeLimitMs) { this.processingTimeLimitMs = processingTimeLimitMs; putInt("processingTimeLimitMs", processingTimeLimitMs); } /** * clears all scales for a particular time slice * * @param slice [scale][x][y] */ private void clearSlice(byte[][][] slice) { for (byte[][] scale : slice) { // for each scale for (byte[] row : scale) { // for each col Arrays.fill(row, (byte) 0); // fill col } } } private int dim = blockDimension + (2 * searchDistance); protected static final String G_SEARCH_AREA_R_REF_BLOCK_AREA_B_BEST_MATCH = "G: search area\nR: ref block area\nB: best match"; /** * Draws the block matching bitmap * * @param x * @param y * @param dx * @param dy * @param refBlock * @param searchBlock * @param subSampleBy */ synchronized private void drawMatching(SADResult result, PolarityEvent ein, byte[][][][] slices) { // synchronized private void drawMatching(int x, int y, int dx, int dy, byte[][] refBlock, byte[][] searchBlock, int subSampleBy) { int x = ein.x >> result.scale, y = ein.y >> result.scale; int dx = (int) result.dx >> result.scale, dy = (int) result.dy >> result.scale; byte[][] refBlock = slices[sliceIndex(1)][result.scale], searchBlock = slices[sliceIndex(2)][result.scale]; int subSampleBy = result.scale; Legend sadLegend = null; int dimNew = blockDimension + (2 * (searchDistance)); if (sliceBitMapFrame == null) { String windowName = "Slice bitmaps"; sliceBitMapFrame = new JFrame(windowName); sliceBitMapFrame.setLayout(new BoxLayout(sliceBitMapFrame.getContentPane(), BoxLayout.Y_AXIS)); sliceBitMapFrame.setPreferredSize(new Dimension(600, 600)); JPanel panel = new JPanel(); panel.setLayout(new BoxLayout(panel, BoxLayout.X_AXIS)); sliceBitmapImageDisplay = ImageDisplay.createOpenGLCanvas(); sliceBitmapImageDisplay.setBorderSpacePixels(10); sliceBitmapImageDisplay.setImageSize(dimNew, dimNew); sliceBitmapImageDisplay.setSize(200, 200); sliceBitmapImageDisplay.setGrayValue(0); sliceBitmapLegend = sliceBitmapImageDisplay.addLegend(G_SEARCH_AREA_R_REF_BLOCK_AREA_B_BEST_MATCH, 0, dim); panel.add(sliceBitmapImageDisplay); sliceBitMapFrame.getContentPane().add(panel); sliceBitMapFrame.pack(); sliceBitMapFrame.addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { setShowSliceBitMap(false); } }); } if (!sliceBitMapFrame.isVisible()) { sliceBitMapFrame.setVisible(true); } final int radius = (blockDimension / 2) + searchDistance; float scale = 1f / getSliceMaxValue(); try { if ((x >= radius) && ((x + radius) < subSizeX) && (y >= radius) && ((y + radius) < subSizeY)) { if (dimNew != sliceBitmapImageDisplay.getWidth()) { dim = dimNew; sliceBitmapImageDisplay.setImageSize(dimNew, dimNew); sliceBitmapImageDisplay.clearLegends(); sliceBitmapLegend = sliceBitmapImageDisplay.addLegend(G_SEARCH_AREA_R_REF_BLOCK_AREA_B_BEST_MATCH, 0, dim); } // TextRenderer textRenderer = new TextRenderer(new Font("SansSerif", Font.PLAIN, 12)); /* Reset the image first */ sliceBitmapImageDisplay.clearImage(); /* Rendering the reference patch in t-imuWarningDialog slice, it's on the center with color red */ for (int i = searchDistance; i < (blockDimension + searchDistance); i++) { for (int j = searchDistance; j < (blockDimension + searchDistance); j++) { float[] f = sliceBitmapImageDisplay.getPixmapRGB(i, j); f[0] = scale * Math.abs(refBlock[((x - (blockDimension / 2)) + i) - searchDistance][((y - (blockDimension / 2)) + j) - searchDistance]); sliceBitmapImageDisplay.setPixmapRGB(i, j, f); } } /* Rendering the area within search distance in t-2d slice, it's full of the whole search area with color green */ for (int i = 0; i < ((2 * radius) + 1); i++) { for (int j = 0; j < ((2 * radius) + 1); j++) { float[] f = sliceBitmapImageDisplay.getPixmapRGB(i, j); f[1] = scale * Math.abs(searchBlock[(x - radius) + i][(y - radius) + j]); sliceBitmapImageDisplay.setPixmapRGB(i, j, f); } } /* Rendering the best matching patch in t-2d slice, it's on the shifted position related to the center location with color blue */ for (int i = searchDistance + dx; i < (blockDimension + searchDistance + dx); i++) { for (int j = searchDistance + dy; j < (blockDimension + searchDistance + dy); j++) { float[] f = sliceBitmapImageDisplay.getPixmapRGB(i, j); f[2] = scale * Math.abs(searchBlock[((x - (blockDimension / 2)) + i) - searchDistance][((y - (blockDimension / 2)) + j) - searchDistance]); sliceBitmapImageDisplay.setPixmapRGB(i, j, f); } } if (sliceBitmapLegend != null) { sliceBitmapLegend.s = G_SEARCH_AREA_R_REF_BLOCK_AREA_B_BEST_MATCH + "\nScale: " + subSampleBy + "\nSAD: " + engFmt.format(result.sadValue); } } } catch (ArrayIndexOutOfBoundsException e) { } sliceBitmapImageDisplay.repaint(); } // /** // * @return the numSlices // */ // public int getNumSlices() { // return numSlices; // /** // * @param numSlices the numSlices to set // */ // synchronized public void setNumSlices(int numSlices) { // if (numSlices < 3) { // numSlices = 3; // } else if (numSlices > 8) { // numSlices = 8; // this.numSlices = numSlices; // putInt("numSlices", numSlices); /** * @return the sliceNumBits */ public int getSliceMaxValue() { return sliceMaxValue; } /** * @param sliceMaxValue the sliceMaxValue to set */ public void setSliceMaxValue(int sliceMaxValue) { int old = this.sliceMaxValue; if (sliceMaxValue < 1) { sliceMaxValue = 1; } else if (sliceMaxValue > 127) { sliceMaxValue = 127; } this.sliceMaxValue = sliceMaxValue; putInt("sliceMaxValue", sliceMaxValue); getSupport().firePropertyChange("sliceMaxValue", old, this.sliceMaxValue); } /** * @return the rectifyPolarties */ public boolean isRectifyPolarties() { return rectifyPolarties; } /** * @param rectifyPolarties the rectifyPolarties to set */ public void setRectifyPolarties(boolean rectifyPolarties) { boolean old = this.rectifyPolarties; this.rectifyPolarties = rectifyPolarties; putBoolean("rectifyPolarties", rectifyPolarties); getSupport().firePropertyChange("rectifyPolarties", old, this.rectifyPolarties); } /** * @return the useSubsampling */ public boolean isUseSubsampling() { return useSubsampling; } /** * @param useSubsampling the useSubsampling to set */ public void setUseSubsampling(boolean useSubsampling) { this.useSubsampling = useSubsampling; } /** * @return the numScales */ public int getNumScales() { return numScales; } /** * @param numScales the numScales to set */ synchronized public void setNumScales(int numScales) { int old = this.numScales; if (numScales < 1) { numScales = 1; } else if (numScales > 4) { numScales = 4; } this.numScales = numScales; putInt("numScales", numScales); setDefaultScalesToCompute(); scaleResultCounts = new int[numScales]; showBlockSizeAndSearchAreaTemporarily(); computeAveragePossibleMatchDistance(); getSupport().firePropertyChange("numScales", old, this.numScales); } /** * Computes pooled (summed) value of slice at location xx, yy, in subsampled * region around this point * * @param slice * @param x * @param y * @param subsampleBy pool over 1<<subsampleBy by 1<<subsampleBy area to sum * up the slice values @return */ private int pool(byte[][] slice, int x, int y, int subsampleBy) { if (subsampleBy == 0) { return slice[x][y]; } else { int n = 1 << subsampleBy; int sum = 0; for (int xx = x; xx < x + n + n; xx++) { for (int yy = y; yy < y + n + n; yy++) { if (xx >= subSizeX || yy >= subSizeY) { // log.warning("should not happen that xx="+xx+" or yy="+yy); continue; // TODO remove this check when iteration avoids this sum explictly } sum += slice[xx][yy]; } } return sum; } } /** * @return the scalesToCompute */ public String getScalesToCompute() { return scalesToCompute; } /** * @param scalesToCompute the scalesToCompute to set */ synchronized public void setScalesToCompute(String scalesToCompute) { this.scalesToCompute = scalesToCompute; if (scalesToCompute == null || scalesToCompute.isEmpty()) { setDefaultScalesToCompute(); } else { StringTokenizer st = new StringTokenizer(scalesToCompute, ", ", false); int n = st.countTokens(); if (n == 0) { setDefaultScalesToCompute(); } else { scalesToComputeArray = new int[n]; int i = 0; while (st.hasMoreTokens()) { try { int scale = Integer.parseInt(st.nextToken()); scalesToComputeArray[i++] = scale; } catch (NumberFormatException e) { log.warning("bad string in scalesToCompute field, use blank or 0,2 for example"); setDefaultScalesToCompute(); } } } } } private void setDefaultScalesToCompute() { scalesToComputeArray = new int[numScales]; for (int i = 0; i < numScales; i++) { scalesToComputeArray[i] = i; } } /** * @return the areaEventNumberSubsampling */ public int getAreaEventNumberSubsampling() { return areaEventNumberSubsampling; } /** * @param areaEventNumberSubsampling the areaEventNumberSubsampling to set */ synchronized public void setAreaEventNumberSubsampling(int areaEventNumberSubsampling) { int old = this.areaEventNumberSubsampling; if (areaEventNumberSubsampling < 3) { areaEventNumberSubsampling = 3; } else if (areaEventNumberSubsampling > 7) { areaEventNumberSubsampling = 7; } this.areaEventNumberSubsampling = areaEventNumberSubsampling; putInt("areaEventNumberSubsampling", areaEventNumberSubsampling); showAreasForAreaCountsTemporarily(); clearAreaCounts(); if (sliceMethod != SliceMethod.AreaEventNumber) { log.warning("AreaEventNumber method is not currently selected as sliceMethod"); } getSupport().firePropertyChange("areaEventNumberSubsampling", old, this.areaEventNumberSubsampling); } private void showAreasForAreaCountsTemporarily() { if (stopShowingStuffTask != null) { stopShowingStuffTask.cancel(); } stopShowingStuffTask = new TimerTask() { @Override public void run() { showBlockSizeAndSearchAreaTemporarily = false; // in case we are canceling a task that would clear this showAreaCountAreasTemporarily = false; } }; Timer showAreaCountsAreasTimer = new Timer(); showAreaCountAreasTemporarily = true; showAreaCountsAreasTimer.schedule(stopShowingStuffTask, SHOW_STUFF_DURATION_MS); } private void showBlockSizeAndSearchAreaTemporarily() { if (stopShowingStuffTask != null) { stopShowingStuffTask.cancel(); } stopShowingStuffTask = new TimerTask() { @Override public void run() { showAreaCountAreasTemporarily = false; // in case we are canceling a task that would clear this showBlockSizeAndSearchAreaTemporarily = false; } }; Timer showBlockSizeAndSearchAreaTimer = new Timer(); showBlockSizeAndSearchAreaTemporarily = true; showBlockSizeAndSearchAreaTimer.schedule(stopShowingStuffTask, SHOW_STUFF_DURATION_MS); } private void clearAreaCounts() { if (sliceMethod != SliceMethod.AreaEventNumber) { return; } if (areaCounts == null || areaCounts.length != 1 + (subSizeX >> areaEventNumberSubsampling)) { areaCounts = new int[1 + (subSizeX >> areaEventNumberSubsampling)][1 + (subSizeY >> areaEventNumberSubsampling)]; } else { for (int[] i : areaCounts) { Arrays.fill(i, 0); } } areaCountExceeded = false; } private void clearNonGreedyRegions() { if (!nonGreedyFlowComputingEnabled) { return; } checkNonGreedyRegionsAllocated(); nonGreedyRegionsCount = 0; for (boolean[] i : nonGreedyRegions) { Arrays.fill(i, false); } } private void checkNonGreedyRegionsAllocated() { if (nonGreedyRegions == null || nonGreedyRegions.length != 1 + (subSizeX >> areaEventNumberSubsampling)) { nonGreedyRegionsNumberOfRegions = (1 + (subSizeX >> areaEventNumberSubsampling)) * (1 + (subSizeY >> areaEventNumberSubsampling)); nonGreedyRegions = new boolean[1 + (subSizeX >> areaEventNumberSubsampling)][1 + (subSizeY >> areaEventNumberSubsampling)]; nonGreedyRegionsNumberOfRegions = (1 + (subSizeX >> areaEventNumberSubsampling)) * (1 + (subSizeY >> areaEventNumberSubsampling)); } } public int getSliceDeltaT() { return sliceDeltaT; } /** * @return the enableImuTimesliceLogging */ public boolean isEnableImuTimesliceLogging() { return enableImuTimesliceLogging; } /** * @param enableImuTimesliceLogging the enableImuTimesliceLogging to set */ public void setEnableImuTimesliceLogging(boolean enableImuTimesliceLogging) { this.enableImuTimesliceLogging = enableImuTimesliceLogging; if (enableImuTimesliceLogging) { if (imuTimesliceLogger == null) { imuTimesliceLogger = new TobiLogger("imuTimeslice.txt", "IMU rate gyro deg/s and patchmatch timeslice duration in ms"); imuTimesliceLogger.setHeaderLine("systemtime(ms) timestamp(us) timeslice(us) rate(deg/s)"); } } imuTimesliceLogger.setEnabled(enableImuTimesliceLogging); } /** * @return the nonGreedyFlowComputingEnabled */ public boolean isNonGreedyFlowComputingEnabled() { return nonGreedyFlowComputingEnabled; } /** * @param nonGreedyFlowComputingEnabled the nonGreedyFlowComputingEnabled to * set */ synchronized public void setNonGreedyFlowComputingEnabled(boolean nonGreedyFlowComputingEnabled) { boolean old = this.nonGreedyFlowComputingEnabled; this.nonGreedyFlowComputingEnabled = nonGreedyFlowComputingEnabled; putBoolean("nonGreedyFlowComputingEnabled", nonGreedyFlowComputingEnabled); if (nonGreedyFlowComputingEnabled) { clearNonGreedyRegions(); } getSupport().firePropertyChange("nonGreedyFlowComputingEnabled", old, nonGreedyFlowComputingEnabled); } /** * @return the nonGreedyFractionToBeServiced */ public float getNonGreedyFractionToBeServiced() { return nonGreedyFractionToBeServiced; } /** * @param nonGreedyFractionToBeServiced the nonGreedyFractionToBeServiced to * set */ public void setNonGreedyFractionToBeServiced(float nonGreedyFractionToBeServiced) { this.nonGreedyFractionToBeServiced = nonGreedyFractionToBeServiced; putFloat("nonGreedyFractionToBeServiced", nonGreedyFractionToBeServiced); } }
package ch.unizh.ini.jaer.projects.minliu; import ch.unizh.ini.jaer.projects.davis.frames.ApsFrameExtractor; import java.awt.Dimension; import java.awt.Font; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.awt.font.FontRenderContext; import java.awt.geom.Rectangle2D; import java.util.logging.Level; import javax.swing.BoxLayout; import javax.swing.JFrame; import javax.swing.JPanel; import com.jogamp.opengl.GL; import com.jogamp.opengl.GL2; import com.jogamp.opengl.GL2ES3; import com.jogamp.opengl.GLAutoDrawable; import com.jogamp.opengl.util.awt.TextRenderer; import ch.unizh.ini.jaer.projects.rbodo.opticalflow.AbstractMotionFlow; import ch.unizh.ini.jaer.projects.rbodo.opticalflow.MotionFlowStatistics; import ch.unizh.ini.jaer.projects.rbodo.opticalflow.MotionFlowStatistics.GlobalMotion; import com.jogamp.opengl.GLException; import java.awt.image.BufferedImage; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.PrintWriter; import java.nio.file.Paths; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Date; import java.util.Iterator; import java.util.List; import java.util.StringTokenizer; import java.util.Timer; import java.util.TimerTask; import java.util.logging.Logger; import javax.imageio.ImageIO; import javax.swing.JFileChooser; import javax.swing.SwingUtilities; import javax.swing.filechooser.FileFilter; import net.sf.jaer.Description; import net.sf.jaer.DevelopmentStatus; import net.sf.jaer.chip.AEChip; import net.sf.jaer.event.ApsDvsEvent; import net.sf.jaer.event.ApsDvsEventPacket; import net.sf.jaer.event.BasicEvent; import net.sf.jaer.event.EventPacket; import net.sf.jaer.event.PolarityEvent; import net.sf.jaer.eventio.AEInputStream; import net.sf.jaer.eventprocessing.TimeLimiter; import net.sf.jaer.graphics.AEViewer; import net.sf.jaer.graphics.FrameAnnotater; import net.sf.jaer.graphics.ImageDisplay; import net.sf.jaer.graphics.ImageDisplay.Legend; import net.sf.jaer.util.DrawGL; import net.sf.jaer.util.EngineeringFormat; import net.sf.jaer.util.TobiLogger; import net.sf.jaer.util.filter.LowpassFilter; import org.apache.commons.lang3.ArrayUtils; /** * Uses adaptive block matching optical flow (ABMOF) to measureTT local optical * flow. <b>Not</b> gradient based, but rather matches local features backwards * in time. * * @author Tobi and Min, Jan 2016 */ @Description("<html>EDFLOW: Computes optical flow with vector direction using SFAST keypoint/corner detection and adaptive time slice block matching (ABMOF) as published in<br>" + "Liu, M., and Delbruck, T. (2018). <a href=\"http://bmvc2018.org/contents/papers/0280.pdf\">Adaptive Time-Slice Block-Matching Optical Flow Algorithm for Dynamic Vision Sensors</a>.<br> in BMVC 2018 (Nescatle upon Tyne)") @DevelopmentStatus(DevelopmentStatus.Status.Experimental) public class PatchMatchFlow extends AbstractMotionFlow implements FrameAnnotater { /* LDSP is Large Diamond Search Pattern, and SDSP mens Small Diamond Search Pattern. LDSP has 9 points and SDSP consists of 5 points. */ private static final int LDSP[][] = {{0, -2}, {-1, -1}, {1, -1}, {-2, 0}, {0, 0}, {2, 0}, {-1, 1}, {1, 1}, {0, 2}}; private static final int SDSP[][] = {{0, -1}, {-1, 0}, {0, 0}, {1, 0}, {0, 1}}; // private int[][][] histograms = null; private int numSlices = 3; //getInt("numSlices", 3); // fix to 4 slices to compute error sign from min SAD result from t-2d to t-3d volatile private int numScales = getInt("numScales", 3); //getInt("numSlices", 3); // fix to 4 slices to compute error sign from min SAD result from t-2d to t-3d private String scalesToCompute = getString("scalesToCompute", ""); //getInt("numSlices", 3); // fix to 4 slices to compute error sign from min SAD result from t-2d to t-3d private Integer[] scalesToComputeArray = null; // holds array of scales to actually compute, for debugging private int[] scaleResultCounts = new int[numScales]; // holds counts at each scale for min SAD results /** * The computed average possible match distance from 0 motion */ protected float avgPossibleMatchDistance; private static final int MIN_SLICE_EVENT_COUNT_FULL_FRAME = 1000; private static final int MAX_SLICE_EVENT_COUNT_FULL_FRAME = 1000000; // private int sx, sy; private int currentSliceIdx = 0; // the slice we are currently filling with events /** * time slice 2d histograms of (maybe signed) event counts slices = new * byte[numSlices][numScales][subSizeX][subSizeY] [slice][scale][x][y] */ private byte[][][][] slices = null; private float[] sliceSummedSADValues = null; // tracks the total summed SAD differences between reference and past slices, to adjust the slice duration private int[] sliceSummedSADCounts = null; // tracks the total summed SAD differences between reference and past slices, to adjust the slice duration private int[] sliceStartTimeUs; // holds the time interval between reference slice and this slice private int[] sliceEndTimeUs; // holds the time interval between reference slice and this slice private byte[][][] currentSlice; private SADResult lastGoodSadResult = new SADResult(0, 0, 0, 0); // used for consistency check public static final int BLOCK_DIMENSION_DEFAULT = 7; private int blockDimension = getInt("blockDimension", BLOCK_DIMENSION_DEFAULT); // This is the block dimension of the coarse scale. // private float cost = getFloat("cost", 0.001f); public static final float MAX_ALLOWABLE_SAD_DISTANCE_DEFAULT = .5f; private float maxAllowedSadDistance = getFloat("maxAllowedSadDistance", MAX_ALLOWABLE_SAD_DISTANCE_DEFAULT); public static final float VALID_PIXEL_OCCUPANCY_DEFAULT = 0.01f; private float validPixOccupancy = getFloat("validPixOccupancy", VALID_PIXEL_OCCUPANCY_DEFAULT); // threshold for valid pixel percent for one block private float weightDistance = getFloat("weightDistance", 0.95f); // confidence value consists of the distance and the dispersion, this value set the distance value private static final int MAX_SKIP_COUNT = 1000; private int skipProcessingEventsCount = getInt("skipProcessingEventsCount", 0); // skip this many events for processing (but not for accumulating to bitmaps) private int skipCounter = 0; private boolean adaptiveEventSkipping = getBoolean("adaptiveEventSkipping", true); private float skipChangeFactor = (float) Math.sqrt(2); // by what factor to change the skip count if too slow or too fast private boolean outputSearchErrorInfo = false; // make user choose this slow down every time private boolean adaptiveSliceDuration = getBoolean("adaptiveSliceDuration", true); private boolean adaptiveSliceDurationLogging = false; // for debugging and analyzing control of slice event number/duration private TobiLogger adaptiveSliceDurationLogger = null; private int adaptiveSliceDurationPacketCount = 0; private boolean useSubsampling = getBoolean("useSubsampling", false); private int adaptiveSliceDurationMinVectorsToControl = getInt("adaptiveSliceDurationMinVectorsToControl", 10); private boolean showBlockMatches = getBoolean("showBlockMatches", false); // Display the bitmaps private boolean showSlices = false; // Display the bitmaps private int showSlicesScale = 0; // Display the bitmaps private float adapativeSliceDurationProportionalErrorGain = getFloat("adapativeSliceDurationProportionalErrorGain", 0.05f); // factor by which an error signal on match distance changes slice duration private boolean adapativeSliceDurationUseProportionalControl = getBoolean("adapativeSliceDurationUseProportionalControl", false); private int processingTimeLimitMs = getInt("processingTimeLimitMs", 100); // time limit for processing packet in ms to process OF events (events still accumulate). Overrides the system EventPacket timelimiter, which cannot be used here because we still need to accumulate and render the events. public static final int SLICE_MAX_VALUE_DEFAULT = 15; private int sliceMaxValue = getInt("sliceMaxValue", SLICE_MAX_VALUE_DEFAULT); private boolean rectifyPolarties = getBoolean("rectifyPolarties", false); private int sliceDurationMinLimitUS = getInt("sliceDurationMinLimitUS", 100); private int sliceDurationMaxLimitUS = getInt("sliceDurationMaxLimitUS", 300000); private boolean outlierRejectionEnabled = getBoolean("outlierRejectionEnabled", false); private float outlierRejectionThresholdSigma = getFloat("outlierRejectionThresholdSigma", 2f); protected int outlierRejectionWindowSize = getInt("outlierRejectionWindowSize", 300); private MotionFlowStatistics outlierRejectionMotionFlowStatistics; private TimeLimiter timeLimiter = new TimeLimiter(); // private instance used to accumulate events to slices even if packet has timed out // results histogram for each packet // private int ANGLE_HISTOGRAM_COUNT = 16; // private int[] resultAngleHistogram = new int[ANGLE_HISTOGRAM_COUNT + 1]; private int[][] resultHistogram = null; // private int resultAngleHistogramCount = 0, resultAngleHistogramMax = 0; private int resultHistogramCount; private volatile float avgMatchDistance = 0; // stores average match distance for rendering it private float histStdDev = 0, lastHistStdDev = 0; private float FSCnt = 0, DSCorrectCnt = 0; float DSAverageNum = 0, DSAveError[] = {0, 0}; // Evaluate DS cost average number and the error. // private float lastErrSign = Math.signum(1); // private final String outputFilename; private int sliceDeltaT; // The time difference between two slices used for velocity caluction. For constantDuration, this one is equal to the duration. For constantEventNumber, this value will change. private boolean enableImuTimesliceLogging = false; private TobiLogger imuTimesliceLogger = null; private volatile boolean resetOFHistogramFlag; // signals to reset the OF histogram after it is rendered private float cornerThr = getFloat("cornerThr", 0.2f); private boolean saveSliceGrayImage = false; private PrintWriter dvsWriter = null; private EngineeringFormat engFmt; private TextRenderer textRenderer = null; // These variables are only used by HW_ABMOF. // HW_ABMOF send slice rotation flag so we need to indicate the real rotation timestamp // HW_ABMOF is only supported for davis346Zynq private int curretnRotatTs_HW = 0, tMinus1RotateTs_HW = 0, tMinus2RotateTs_HW = 0; private float deltaTsMs_HW = 0; private boolean HWABMOFEnabled = false; public enum CornerCircleSelection { InnerCircle, OuterCircle, OR, AND } private CornerCircleSelection cornerCircleSelection = CornerCircleSelection.valueOf(getString("cornerCircleSelection", CornerCircleSelection.OuterCircle.name())); // Tobi change to Outer which is the condition used for experimental results in paper protected static String DEFAULT_FILENAME = "jAER.txt"; protected String lastFileName = getString("lastFileName", DEFAULT_FILENAME); public enum PatchCompareMethod { /*JaccardDistance,*/ /*HammingDistance*/ SAD/*, EventSqeDistance*/ }; private PatchCompareMethod patchCompareMethod = null; public enum SearchMethod { FullSearch, DiamondSearch, CrossDiamondSearch }; private SearchMethod searchMethod = SearchMethod.valueOf(getString("searchMethod", SearchMethod.DiamondSearch.toString())); private int sliceDurationUs = getInt("sliceDurationUs", 20000); public static final int SLICE_EVENT_COUNT_DEFAULT = 700; private int sliceEventCount = getInt("sliceEventCount", SLICE_EVENT_COUNT_DEFAULT); private boolean rewindFlg = false; // The flag to indicate the rewind event. private boolean displayResultHistogram = getBoolean("displayResultHistogram", true); public enum SliceMethod { ConstantDuration, ConstantEventNumber, AreaEventNumber, ConstantIntegratedFlow }; private SliceMethod sliceMethod = SliceMethod.valueOf(getString("sliceMethod", SliceMethod.AreaEventNumber.toString())); // counting events into subsampled areas, when count exceeds the threshold in any area, the slices are rotated public static final int AREA_EVENT_NUMBER_SUBSAMPLING_DEFAULT = 5; private int areaEventNumberSubsampling = getInt("areaEventNumberSubsampling", AREA_EVENT_NUMBER_SUBSAMPLING_DEFAULT); private int[][] areaCounts = null; private int numAreas = 1; private boolean areaCountExceeded = false; // nongreedy flow evaluation // the entire scene is subdivided into regions, and a bitmap of these regions distributed flow computation more fairly // by only servicing a region when sufficient fraction of other regions have been serviced first private boolean nonGreedyFlowComputingEnabled = getBoolean("nonGreedyFlowComputingEnabled", false); private boolean[][] nonGreedyRegions = null; private int nonGreedyRegionsNumberOfRegions, nonGreedyRegionsCount; /** * This fraction of the regions must be serviced for computing flow before * we reset the nonGreedyRegions map */ private float nonGreedyFractionToBeServiced = getFloat("nonGreedyFractionToBeServiced", .5f); // Print scale count's statics private boolean printScaleCntStatEnabled = getBoolean("printScaleCntStatEnabled", false); // timers and flags for showing filter properties temporarily private final int SHOW_STUFF_DURATION_MS = 4000; private volatile TimerTask stopShowingStuffTask = null; private boolean showBlockSizeAndSearchAreaTemporarily = false; private volatile boolean showAreaCountAreasTemporarily = false; private int eventCounter = 0; private int sliceLastTs = Integer.MAX_VALUE; private JFrame blockMatchingFrame[] = new JFrame[numScales]; private JFrame blockMatchingFrameTarget[] = new JFrame[numScales]; private ImageDisplay blockMatchingImageDisplay[] = new ImageDisplay[numScales]; private ImageDisplay blockMatchingImageDisplayTarget[] = new ImageDisplay[numScales]; // makde a new ImageDisplay GLCanvas with default OpenGL capabilities private Legend blockMatchingDisplayLegend[] = new Legend[numScales]; private Legend blockMatchingDisplayLegendTarget[] = new Legend[numScales]; private static final String LEGEND_G_SEARCH_AREA_R_REF_BLOCK_AREA_B_BEST_MATCH = "G: search area\nR: ref block area\nB: best match"; private JFrame sliceBitMapFrame = null; private ImageDisplay sliceBitmapImageDisplay; // makde a new ImageDisplay GLCanvas with default OpenGL capabilities private Legend sliceBitmapImageDisplayLegend; private static final String LEGEND_SLICES = "R: Slice t-d\nG: Slice t-2d"; private JFrame timeStampBlockFrame = null; private ImageDisplay timeStampBlockImageDisplay; // makde a new ImageDisplay GLCanvas with default OpenGL capabilities private Legend timeStampBlockImageDisplayLegend; private static final String TIME_STAMP_BLOCK_LEGEND_SLICES = "R: Inner Circle\nB: Outer Circle\nG: Current event"; private static final int circle1[][] = {{0, 1}, {1, 1}, {1, 0}, {1, -1}, {0, -1}, {-1, -1}, {-1, 0}, {-1, 1}}; private static final int circle2[][] = {{0, 2}, {1, 2}, {2, 1}, {2, 0}, {2, -1}, {1, -2}, {0, -2}, {-1, -2}, {-2, -1}, {-2, 0}, {-2, 1}, {-1, 2}}; private static final int circle3[][] = {{0, 3}, {1, 3}, {2, 2}, {3, 1}, {3, 0}, {3, -1}, {2, -2}, {1, -3}, {0, -3}, {-1, -3}, {-2, -2}, {-3, -1}, {-3, 0}, {-3, 1}, {-2, 2}, {-1, 3}}; private static final int circle4[][] = {{0, 4}, {1, 4}, {2, 3}, {3, 2}, {4, 1}, {4, 0}, {4, -1}, {3, -2}, {2, -3}, {1, -4}, {0, -4}, {-1, -4}, {-2, -3}, {-3, -2}, {-4, -1}, {-4, 0}, {-4, 1}, {-3, 2}, {-2, 3}, {-1, 4}}; int innerCircle[][] = circle1; int innerCircleSize = innerCircle.length; int xInnerOffset[] = new int[innerCircleSize]; int yInnerOffset[] = new int[innerCircleSize]; int innerTsValue[] = new int[innerCircleSize]; int outerCircle[][] = circle2; int outerCircleSize = outerCircle.length; int yOuterOffset[] = new int[outerCircleSize]; int xOuterOffset[] = new int[outerCircleSize]; int outerTsValue[] = new int[outerCircleSize]; private HWCornerPointRenderer keypointFilter = null; /** * A PropertyChangeEvent with this value is fired when the slices has been * rotated. The oldValue is t-2d slice. The newValue is the t-d slice. */ public static final String EVENT_NEW_SLICES = "eventNewSlices"; TobiLogger sadValueLogger = new TobiLogger("sadvalues", "sadvalue,scale"); // TODO debug private boolean calcOFonCornersEnabled = getBoolean("calcOFonCornersEnabled", true); protected boolean useEFASTnotSFAST = getBoolean("useEFASTnotSFAST", false); private final ApsFrameExtractor apsFrameExtractor; // Corner events array; only used for rendering. private boolean showCorners = getBoolean("showCorners", true); protected int cornerSize = getInt("cornerSize", 2); private ArrayList<BasicEvent> cornerEvents = new ArrayList(1000); public PatchMatchFlow(AEChip chip) { super(chip); this.engFmt = new EngineeringFormat(); getEnclosedFilterChain().clear(); // getEnclosedFilterChain().add(new SpatioTemporalCorrelationFilter(chip)); keypointFilter = new HWCornerPointRenderer(chip); apsFrameExtractor = new ApsFrameExtractor(chip); apsFrameExtractor.setShowAPSFrameDisplay(false); getEnclosedFilterChain().add(apsFrameExtractor); // getEnclosedFilterChain().add(keypointFilter); // use for EFAST setSliceDurationUs(getSliceDurationUs()); // 40ms is good for the start of the slice duration adatative since 4ms is too fast and 500ms is too slow. setDefaultScalesToCompute(); // // Save the result to the file // Format formatter = new SimpleDateFormat("YYYY-MM-dd_hh-mm-ss"); // // Instantiate a Date object // Date date = new Date(); // Log file for the OF distribution's statistics // outputFilename = "PMF_HistStdDev" + formatter.format(date) + ".txt"; // String eventSqeMatching = "Event squence matching"; // String preProcess = "Denoise"; try { patchCompareMethod = PatchCompareMethod.valueOf(getString("patchCompareMethod", PatchCompareMethod.SAD.toString())); } catch (IllegalArgumentException e) { patchCompareMethod = PatchCompareMethod.SAD; } String hwTip = "0b: Hardware EDFLOW"; setPropertyTooltip(hwTip, "HWABMOFEnabled", "Select to show output of hardware EDFLOW camera"); String cornerTip = "0c: Corners/Keypoints"; setPropertyTooltip(cornerTip, "showCorners", "Select to show corners (as red overlay)"); setPropertyTooltip(cornerTip, "cornerThr", "Threshold difference for SFAST detection as fraction of maximum event count value; increase for fewer corners"); setPropertyTooltip(cornerTip, "calcOFonCornersEnabled", "Calculate OF based on corners or not"); setPropertyTooltip(cornerTip, "cornerCircleSelection", "Determines SFAST circles used for detecting the corner/keypoint"); setPropertyTooltip(cornerTip, "useEFASTnotSFAST", "Use EFAST corner detector, not SFAST which is default"); setPropertyTooltip(cornerTip, "cornerSize", "Dimension WxH of the drawn detector corners in chip pixels"); String patchTT = "0a: Block matching"; // move ppsScale to main top GUI since we use it a lot setPropertyTooltip(patchTT, "ppsScale", "<html>When <i>ppsScaleDisplayRelativeOFLength=false</i>, then this is <br>scale of screen pixels per px/s flow to draw local motion vectors; <br>global vectors are scaled up by an additional factor of " + GLOBAL_MOTION_DRAWING_SCALE + "<p>" + "When <i>ppsScaleDisplayRelativeOFLength=true</i>, then local motion vectors are scaled by average speed of flow"); setPropertyTooltip(patchTT, "blockDimension", "Linear dimenion of patches to match on coarse scale, in pixels. Median and fine scale block sizes are scaled up approx by powers of 2."); setPropertyTooltip(patchTT, "searchDistance", "Search distance for matching patches, in pixels"); setPropertyTooltip(patchTT, "patchCompareMethod", "method to compare two patches; SAD=sum of absolute differences, HammingDistance is same as SAD for binary bitmaps"); setPropertyTooltip(patchTT, "searchMethod", "method to search patches"); setPropertyTooltip(patchTT, "sliceDurationUs", "duration of bitmaps in us, also called sample interval, when ConstantDuration method is used"); setPropertyTooltip(patchTT, "sliceEventCount", "number of events collected to fill a slice, when ConstantEventNumber method is used"); setPropertyTooltip(patchTT, "sliceMethod", "<html>Method for determining time slice duration for block matching<ul>" + "<li>ConstantDuration: slices are fixed time duration" + "<li>ConstantEventNumber: slices are fixed event number" + "<li>AreaEventNumber: slices are fixed event number in any subsampled area defined by areaEventNumberSubsampling" + "<li>ConstantIntegratedFlow: slices are rotated when average speeds times delta time exceeds half the search distance"); setPropertyTooltip(patchTT, "areaEventNumberSubsampling", "<html>how to subsample total area to count events per unit subsampling blocks for AreaEventNumber method. <p>For example, if areaEventNumberSubsampling=5, <br> then events falling into 32x32 blocks of pixels are counted <br>to determine when they exceed sliceEventCount to make new slice"); setPropertyTooltip(patchTT, "adapativeSliceDurationProportionalErrorGain", "gain for proporportional change of duration or slice event number. typically 0.05f for bang-bang, and 0.5f for proportional control"); setPropertyTooltip(patchTT, "adapativeSliceDurationUseProportionalControl", "If true, then use proportional error control. If false, use bang-bang control with sign of match distance error"); setPropertyTooltip(patchTT, "skipProcessingEventsCount", "skip this many events for processing (but not for accumulating to bitmaps)"); setPropertyTooltip(patchTT, "adaptiveEventSkipping", "enables adaptive event skipping depending on free time left in AEViewer animation loop"); setPropertyTooltip(patchTT, "adaptiveSliceDuration", "<html>Enables adaptive slice duration using feedback control, <br> based on average match search distance compared with total search distance. <p>If the match distance is too small, increaes duration or event count, and if too far, decreases duration or event count.<p>If using <i>AreaEventNumber</i> slice rotation method, don't increase count if actual duration is already longer than <i>sliceDurationUs</i>"); setPropertyTooltip(patchTT, "nonGreedyFlowComputingEnabled", "<html>Enables fairer distribution of computing flow by areas; an area is only serviced after " + nonGreedyFractionToBeServiced + " fraction of areas have been serviced. <p> Areas are defined by the the area subsubsampling bit shift.<p>Enabling this option ignores event skipping, so use <i>processingTimeLimitMs</i> to ensure minimum frame rate"); setPropertyTooltip(patchTT, "nonGreedyFractionToBeServiced", "An area is only serviced after " + nonGreedyFractionToBeServiced + " fraction of areas have been serviced. <p> Areas are defined by the the area subsubsampling bit shift.<p>Enabling this option ignores event skipping, so use the timeLimiter to ensure minimum frame rate"); setPropertyTooltip(patchTT, "useSubsampling", "<html>Enables using both full and subsampled block matching; <p>when using adaptiveSliceDuration, enables adaptive slice duration using feedback controlusing difference between full and subsampled resolution slice matching"); setPropertyTooltip(patchTT, "adaptiveSliceDurationMinVectorsToControl", "<html>Min flow vectors computed in packet to control slice duration, increase to reject control during idle periods"); setPropertyTooltip(patchTT, "processingTimeLimitMs", "<html>time limit for processing packet in ms to process OF events (events still accumulate). <br> Set to 0 to disable. <p>Alternative to the system EventPacket timelimiter, which cannot be used here because we still need to accumulate and render the events"); setPropertyTooltip(patchTT, "outputSearchErrorInfo", "enables displaying the search method error information"); setPropertyTooltip(patchTT, "outlierMotionFilteringEnabled", "(Currently has no effect) discards first optical flow event that points in opposite direction as previous one (dot product is negative)"); setPropertyTooltip(patchTT, "numSlices", "<html>Number of bitmaps to use. <p>At least 3: 1 to collect on, and two more to match on. <br>If >3, then best match is found between last slice reference block and all previous slices."); setPropertyTooltip(patchTT, "numScales", "<html>Number of scales to search over for minimum SAD value; 1 for single full resolution scale, 2 for full + 2x2 subsampling, etc."); setPropertyTooltip(patchTT, "sliceMaxValue", "<html> the maximum value used to represent each pixel in the time slice:<br>1 for binary or signed binary slice, (in conjunction with rectifyEventPolarities==true), etc, <br>up to 127 by these byte values"); setPropertyTooltip(patchTT, "rectifyPolarties", "<html> whether to rectify ON and OFF polarities to unsigned counts; true ignores polarity for block matching, false uses polarity with sliceNumBits>1"); setPropertyTooltip(patchTT, "scalesToCompute", "Scales to compute, e.g. 1,2; blank for all scales. 0 is full resolution, 1 is subsampled 2x2, etc"); setPropertyTooltip(patchTT, "defaults", "Sets reasonable defaults"); setPropertyTooltip(patchTT, "enableImuTimesliceLogging", "Logs IMU and rate gyro"); setPropertyTooltip(patchTT, "startRecordingForEDFLOW", "Start to record events and its OF result to a file which can be converted to a .bin file for EDFLOW."); setPropertyTooltip(patchTT, "stopRecordingForEDFLOW", "Stop to record events and its OF result to a file which can be converted to a .bin file for EDFLOW."); setPropertyTooltip(patchTT, "sliceDurationMinLimitUS", "The minimum value (us) of slice duration."); setPropertyTooltip(patchTT, "sliceDurationMaxLimitUS", "The maximum value (us) of slice duration."); setPropertyTooltip(patchTT, "outlierRejectionEnabled", "Enable outlier flow vector rejection"); setPropertyTooltip(patchTT, "outlierRejectionThresholdSigma", "Flow vectors that are larger than this many sigma from global flow variation are discarded"); setPropertyTooltip(patchTT, "outlierRejectionWindowSize", "Window in events for measurement of average flow for outlier rejection"); String metricConfid = "0ab: Density checks"; setPropertyTooltip(metricConfid, "maxAllowedSadDistance", "<html>SAD distance threshold for rejecting unresonable block matching result; <br> events with SAD distance larger than this value are rejected. <p>Lower value means it is harder to accept the event. <p> Distance is sum of absolute differences for this best match normalized by number of pixels in reference area."); setPropertyTooltip(metricConfid, "validPixOccupancy", "<html>Threshold for valid pixel percent for each block; Range from 0 to 1. <p>If either matching block is less occupied than this fraction, no motion vector will be calculated."); setPropertyTooltip(metricConfid, "weightDistance", "<html>The confidence value consists of the distance and the dispersion; <br>weightDistance sets the weighting of the distance value compared with the dispersion value; Range from 0 to 1. <p>To count only e.g. hamming distance, set weighting to 1. <p> To count only dispersion, set to 0."); String patchDispTT = "0b: Block matching display"; setPropertyTooltip(patchDispTT, "showSlices", "enables displaying the entire bitmaps slices (the current slices)"); setPropertyTooltip(patchDispTT, "showSlicesScale", "sets which scale of the slices to display"); setPropertyTooltip(patchDispTT, "showBlockMatches", "enables displaying the individual block matches"); setPropertyTooltip(patchDispTT, "displayOutputVectors", "display the output motion vectors or not"); setPropertyTooltip(patchDispTT, "displayResultHistogram", "display the output motion vectors histogram to show disribution of results for each packet. Only implemented for HammingDistance"); setPropertyTooltip(patchDispTT, "printScaleCntStatEnabled", "enables printing the statics of scale counts"); getSupport().addPropertyChangeListener(AEViewer.EVENT_TIMESTAMPS_RESET, this); getSupport().addPropertyChangeListener(AEViewer.EVENT_FILEOPEN, this); getSupport().addPropertyChangeListener(AEInputStream.EVENT_REWOUND, this); getSupport().addPropertyChangeListener(AEInputStream.EVENT_NON_MONOTONIC_TIMESTAMP, this); computeAveragePossibleMatchDistance(); numInputTypes = 2; // allocate timestamp map } // TODO debug public void doStartLogSadValues() { sadValueLogger.setEnabled(true); } // TODO debug public void doStopLogSadValues() { sadValueLogger.setEnabled(false); } @Override synchronized public EventPacket filterPacket(EventPacket in) { setupFilter(in); checkArrays(); if (processingTimeLimitMs > 0) { timeLimiter.setTimeLimitMs(processingTimeLimitMs); timeLimiter.restart(); } else { timeLimiter.setEnabled(false); } int minDistScale = 0; // following awkward block needed to deal with DVS/DAVIS and IMU/APS events // block STARTS Iterator i = null; if (in instanceof ApsDvsEventPacket) { i = ((ApsDvsEventPacket) in).fullIterator(); } else { i = ((EventPacket) in).inputIterator(); } cornerEvents.clear(); nSkipped = 0; nProcessed = 0; while (i.hasNext()) { Object o = i.next(); if (o == null) { log.warning("null event passed in, returning input packet"); return in; } if ((o instanceof ApsDvsEvent) && ((ApsDvsEvent) o).isApsData()) { continue; } PolarityEvent ein = (PolarityEvent) o; if (!extractEventInfo(o)) { continue; } if (measureAccuracy || discardOutliersForStatisticalMeasurementEnabled) { if (imuFlowEstimator.calculateImuFlow(o)) { continue; } } // block ENDS if (xyFilter()) { continue; } if (isInvalidTimestamp()) { continue; } countIn++; // compute flow SADResult result = null; if (HWABMOFEnabled) // Only use it when there is hardware supported. Hardware is davis346Zynq { SADResult sliceResult = new SADResult(); int data = ein.address & 0x7ff; // The OF result from the hardware has following procotol: // If the data is 0x7ff, it indicates that this result is an invalid result // if the data is 0x7fe, then it means slice rotated on this event, // in this case, only rotation information is included. // Other cases are valid OF data. // The valid OF data is represented in a compressed data format. // It is calculated by OF_x * (2 * maxSearchDistanceRadius + 1) + OF_y. // Therefore, simple decompress is required. if ((data & 0x7ff) == 0x7ff) { continue; } else if ((data & 0x7ff) == 0x7fe) { tMinus2RotateTs_HW = tMinus1RotateTs_HW; tMinus1RotateTs_HW = curretnRotatTs_HW; curretnRotatTs_HW = ts; deltaTsMs_HW = (float) (tMinus1RotateTs_HW - tMinus2RotateTs_HW) / (float) 1000.0; continue; } else { final int searchDistanceHW = 3; // hardcoded on hardware. final int maxSearchDistanceRadius = (4 + 2 + 1) * searchDistanceHW; int OF_x = (data / (2 * maxSearchDistanceRadius + 1)) - maxSearchDistanceRadius; int OF_y = (data % (2 * maxSearchDistanceRadius + 1)) - maxSearchDistanceRadius; sliceResult.dx = -OF_x; sliceResult.dy = OF_y; sliceResult.vx = (float) (1e3 * sliceResult.dx / deltaTsMs_HW); sliceResult.vy = (float) (1e3 * sliceResult.dy / deltaTsMs_HW); result = sliceResult; vx = result.vx; vy = result.vy; v = (float) Math.sqrt((vx * vx) + (vy * vy)); cornerEvents.add(e); } } else { float[] sadVals = new float[numScales]; // TODO debug int[] dxInitVals = new int[numScales]; int[] dyInitVals = new int[numScales]; int rotateFlg = 0; switch (patchCompareMethod) { case SAD: boolean rotated = maybeRotateSlices(); if (rotated) { rotateFlg = 1; adaptSliceDuration(); setResetOFHistogramFlag(); resetOFHistogram(); nCountPerSlicePacket = 0; // Reset counter for next slice packet. } nCountPerSlicePacket++; // if (ein.x >= subSizeX || ein.y > subSizeY) { // log.warning("event out of range"); // continue; if (!accumulateEvent(ein)) { // maybe skip events here if (dvsWriter != null) { dvsWriter.println(String.format("%d %d %d %d %d %d %d %d %d", ein.timestamp, ein.x, ein.y, ein.polarity == PolarityEvent.Polarity.Off ? 0 : 1, 0x7, 0x7, 0, rotateFlg, 0)); } break; } SADResult sliceResult = new SADResult(); minDistScale = 0; boolean OFRetValidFlag = true; // Sorts scalesToComputeArray[] in descending order Arrays.sort(scalesToComputeArray, Collections.reverseOrder()); for (int scale : scalesToComputeArray) { if (scale >= numScales) { // log.warning("scale " + scale + " is out of range of " + numScales + "; fix scalesToCompute for example by clearing it"); // break; } int dx_init = ((result != null) && !isNotSufficientlyAccurate(sliceResult)) ? (sliceResult.dx >> scale) : 0; int dy_init = ((result != null) && !isNotSufficientlyAccurate(sliceResult)) ? (sliceResult.dy >> scale) : 0; // dx_init = 0; // dy_init = 0; // The reason why we inverse dx_init, dy_init i is the offset is pointing from previous slice to current slice. // The dx_init, dy_init are from the corse scale's result, and it is used as the finer scale's initial guess. sliceResult = minSADDistance(ein.x, ein.y, -dx_init, -dy_init, slices[sliceIndex(1)], slices[sliceIndex(2)], scale); // from ref slice to past slice k+1, using scale 0,1,.... // sliceSummedSADValues[sliceIndex(scale + 2)] += sliceResult.sadValue; // accumulate SAD for this past slice // sliceSummedSADCounts[sliceIndex(scale + 2)]++; // accumulate SAD count for this past slice // sliceSummedSADValues should end up filling 2 values for 4 slices sadVals[scale] = sliceResult.sadValue; // TODO debug dxInitVals[scale] = dx_init; dyInitVals[scale] = dy_init; if (sliceResult.sadValue >= this.maxAllowedSadDistance) { OFRetValidFlag = false; break; } else { if ((result == null) || (sliceResult.sadValue < result.sadValue)) { result = sliceResult; // result holds the overall min sad result minDistScale = scale; } } // result=sliceResult; // TODO tobi: override the absolute minimum to always use the finest scale result, which has been guided by coarser scales } result = sliceResult; minDistScale = 0; float dt = (sliceDeltaTimeUs(2) * 1e-6f); if (result != null) { result.vx = result.dx / dt; // hack, convert to pix/second result.vy = result.dy / dt; // TODO clean up, make time for each slice, since could be different when const num events } if (dvsWriter != null) { dvsWriter.println(String.format("%d %d %d %d %d %d %d %d %d", ein.timestamp, ein.x, ein.y, ein.polarity == PolarityEvent.Polarity.Off ? 0 : 1, result.dx, result.dy, OFRetValidFlag ? 1 : 0, rotateFlg, 1)); } break; // case JaccardDistance: // maybeRotateSlices(); // if (!accumulateEvent(in)) { // break; // result = minJaccardDistance(x, y, bitmaps[sliceIndex(2)], bitmaps[sliceIndex(1)]); // float dtj=(sliceDeltaTimeUs(2) * 1e-6f); // result.dx = result.dx / dtj; // result.dy = result.dy / dtj; // break; } if (result == null || result.sadValue == Float.MAX_VALUE) { continue; // maybe some property change caused this } // reject values that are unreasonable if (isNotSufficientlyAccurate(result)) { continue; } scaleResultCounts[minDistScale]++; vx = result.vx; vy = result.vy; v = (float) Math.sqrt((vx * vx) + (vy * vy)); // TODO debug StringBuilder sadValsString = new StringBuilder(); for (int k = 0; k < sadVals.length - 1; k++) { sadValsString.append(String.format("%f,", sadVals[k])); } sadValsString.append(String.format("%f", sadVals[sadVals.length - 1])); // very awkward to prevent trailing , if (sadValueLogger.isEnabled()) { // TODO debug sadValueLogger.log(sadValsString.toString()); } if (showBlockMatches) { // TODO danger, drawing outside AWT thread final SADResult thisResult = result; final PolarityEvent thisEvent = ein; final byte[][][][] thisSlices = slices; // SwingUtilities.invokeLater(new Runnable() { // @Override // public void run() { drawMatching(thisResult, thisEvent, thisSlices, sadVals, dxInitVals, dyInitVals); // ein.x >> result.scale, ein.y >> result.scale, (int) result.dx >> result.scale, (int) result.dy >> result.scale, slices[sliceIndex(1)][result.scale], slices[sliceIndex(2)][result.scale], result.scale); drawTimeStampBlock(thisEvent); } } if (isOutlierFlowVector(result)) { countOutliers++; continue; } // if (result.dx != 0 || result.dy != 0) { // final int bin = (int) Math.round(ANGLE_HISTOGRAM_COUNT * (Math.atan2(result.dy, result.dx) + Math.PI) / (2 * Math.PI)); // int v = ++resultAngleHistogram[bin]; // resultAngleHistogramCount++; // if (v > resultAngleHistogramMax) { // resultAngleHistogramMax = v; processGoodEvent(); if (resultHistogram != null) { resultHistogram[result.dx + computeMaxSearchDistance()][result.dy + computeMaxSearchDistance()]++; resultHistogramCount++; } lastGoodSadResult.set(result); } motionFlowStatistics.updatePacket(countIn, countOut, ts); outlierRejectionMotionFlowStatistics.updatePacket(countIn, countOut, ts); // float fracOutliers = (float) countOutliers / countIn; // System.out.println(String.format("Fraction of outliers: %.1f%%", 100 * fracOutliers)); adaptEventSkipping(); if (rewindFlg) { rewindFlg = false; for (byte[][][] b : slices) { clearSlice(b); } currentSliceIdx = 0; // start by filling slice 0 currentSlice = slices[currentSliceIdx]; sliceLastTs = Integer.MAX_VALUE; } return isDisplayRawInput() ? in : dirPacket; } public void doDefaults() { setSearchMethod(SearchMethod.DiamondSearch); setBlockDimension(BLOCK_DIMENSION_DEFAULT); setNumScales(3); setSearchDistance(3); setAdaptiveEventSkipping(false); setSkipProcessingEventsCount(0); setProcessingTimeLimitMs(5000); setDisplayVectorsEnabled(true); setPpsScaleDisplayRelativeOFLength(false); setDisplayGlobalMotion(true); setRectifyPolarties(true); // rectify to better handle cases of steadicam where pan/tilt flips event polarities setPpsScale(.1f); setSliceMaxValue(SLICE_MAX_VALUE_DEFAULT); setValidPixOccupancy(VALID_PIXEL_OCCUPANCY_DEFAULT); // at least this fraction of pixels from each block must both have nonzero values setMaxAllowedSadDistance(MAX_ALLOWABLE_SAD_DISTANCE_DEFAULT); setSliceMethod(SliceMethod.AreaEventNumber); setAdaptiveSliceDuration(true); setSliceEventCount(SLICE_EVENT_COUNT_DEFAULT); // compute nearest power of two over block dimension // int ss = (int) (Math.log(blockDimension - 1) / Math.log(2)) + 1; setAreaEventNumberSubsampling(AREA_EVENT_NUMBER_SUBSAMPLING_DEFAULT); // set to paper value // // set event count so that count=block area * sliceMaxValue/4; // // i.e. set count to roll over when slice pixels from most subsampled scale are half full if they are half stimulated // final int eventCount = (((blockDimension * blockDimension) * sliceMaxValue) / 2) >> (numScales - 1); // setSliceEventCount(eventCount); setSliceDurationMinLimitUS(1000); setSliceDurationMaxLimitUS(300000); setSliceDurationUs(50000); // set a bit smaller max duration in us to avoid instability where count gets too high with sparse input setShowCorners(true); setCalcOFonCornersEnabled(true); // Enable corner detector setCornerCircleSelection(CornerCircleSelection.OuterCircle); setCornerThr(0.2f); } private void adaptSliceDuration() { // measure last hist to get control signal on slice duration // measures avg match distance. weights the average so that long distances with more pixels in hist are not overcounted, simply // by having more pixels. if (rewindFlg) { return; // don't adapt during rewind or delay before playing again } float radiusSum = 0; int countSum = 0; // int maxRadius = (int) Math.ceil(Math.sqrt(2 * searchDistance * searchDistance)); // int countSum = 0; final int totSD = computeMaxSearchDistance(); for (int xx = -totSD; xx <= totSD; xx++) { for (int yy = -totSD; yy <= totSD; yy++) { int count = resultHistogram[xx + totSD][yy + totSD]; if (count > 0) { final float radius = (float) Math.sqrt((xx * xx) + (yy * yy)); countSum += count; radiusSum += radius * count; } } } if (countSum > 0) { avgMatchDistance = radiusSum / (countSum); // compute average match distance from reference block } if (adaptiveSliceDuration && (countSum > adaptiveSliceDurationMinVectorsToControl)) { // if (resultHistogramCount > 0) { // following stats not currently used // double[] rstHist1D = new double[resultHistogram.length * resultHistogram.length]; // int index = 0; //// int rstHistMax = 0; // for (int[] resultHistogram1 : resultHistogram) { // for (int element : resultHistogram1) { // rstHist1D[index++] = element; // Statistics histStats = new Statistics(rstHist1D); // // double histMax = Collections.max(Arrays.asList(ArrayUtils.toObject(rstHist1D))); // double histMax = histStats.getMax(); // for (int m = 0; m < rstHist1D.length; m++) { // rstHist1D[m] = rstHist1D[m] / histMax; // lastHistStdDev = histStdDev; // histStdDev = (float) histStats.getStdDev(); // try (FileWriter outFile = new FileWriter(outputFilename,true)) { // outFile.write(String.format(in.getFirstEvent().getTimestamp() + " " + histStdDev + "\r\n")); // outFile.close(); // } catch (IOException ex) { // Logger.getLogger(PatchMatchFlow.class.getName()).log(Level.SEVERE, null, ex); // } catch (Exception e) { // log.warning("Caught " + e + ". See following stack trace."); // e.printStackTrace(); // float histMean = (float) histStats.getMean(); // compute error signal. // If err<0 it means the average match distance is larger than target avg match distance, so we need to reduce slice duration // If err>0, it means the avg match distance is too short, so increse time slice final float err = avgMatchDistance / (avgPossibleMatchDistance); // use target that is smaller than average possible to bound excursions to large slices better // final float err = avgPossibleMatchDistance / 2 - avgMatchDistance; // use target that is smaller than average possible to bound excursions to large slices better // final float err = ((searchDistance << (numScales - 1)) / 2) - avgMatchDistance; // final float lastErr = searchDistance / 2 - lastHistStdDev; // final double err = histMean - 1/ (rstHist1D.length * rstHist1D.length); float errSign = Math.signum(err - 1); // float avgSad2 = sliceSummedSADValues[sliceIndex(4)] / sliceSummedSADCounts[sliceIndex(4)]; // float avgSad3 = sliceSummedSADValues[sliceIndex(3)] / sliceSummedSADCounts[sliceIndex(3)]; // float errSign = avgSad2 <= avgSad3 ? 1 : -1; // if(Math.abs(err) > Math.abs(lastErr)) { // errSign = -errSign; // if(histStdDev >= 0.14) { // if(lastHistStdDev > histStdDev) { // errSign = -lastErrSign; // } else { // errSign = lastErrSign; // errSign = 1; // } else { // errSign = (float) Math.signum(err); // lastErrSign = errSign; // problem with following is that if sliceDurationUs gets really big, then of course the avgMatchDistance becomes small because // of the biased-towards-zero search policy that selects the closest match switch (sliceMethod) { case ConstantDuration: if (adapativeSliceDurationUseProportionalControl) { // proportional setSliceDurationUs(Math.round((1 / (1 + (err - 1) * adapativeSliceDurationProportionalErrorGain)) * sliceDurationUs)); } else { // bang bang int durChange = (int) (-errSign * adapativeSliceDurationProportionalErrorGain * sliceDurationUs); setSliceDurationUs(sliceDurationUs + durChange); } break; case ConstantEventNumber: case AreaEventNumber: if (adapativeSliceDurationUseProportionalControl) { // proportional setSliceEventCount(Math.round((1 / (1 + (err - 1) * adapativeSliceDurationProportionalErrorGain)) * sliceEventCount)); } else { if (errSign < 0) { // match distance too short, increase duration // match too short, increase count setSliceEventCount(Math.round(sliceEventCount * (1 + adapativeSliceDurationProportionalErrorGain))); } else if (errSign > 0) { // match too long, decrease duration setSliceEventCount(Math.round(sliceEventCount * (1 - adapativeSliceDurationProportionalErrorGain))); } } break; case ConstantIntegratedFlow: setSliceEventCount(eventCounter); } if (adaptiveSliceDurationLogger != null && adaptiveSliceDurationLogger.isEnabled()) { if (!isDisplayGlobalMotion()) { setDisplayGlobalMotion(true); } adaptiveSliceDurationLogger.log(String.format("%f\t%d\t%d\t%f\t%f\t%f\t%d\t%d", e.timestamp * 1e-6f, adaptiveSliceDurationPacketCount++, nCountPerSlicePacket, avgMatchDistance, err, motionFlowStatistics.getGlobalMotion().getGlobalSpeed().getMean(), sliceDeltaT, sliceEventCount)); } } } private void setResetOFHistogramFlag() { resetOFHistogramFlag = true; } private void clearResetOFHistogramFlag() { resetOFHistogramFlag = false; } private void resetOFHistogram() { if (!resetOFHistogramFlag || resultHistogram == null) { return; } for (int[] h : resultHistogram) { Arrays.fill(h, 0); } resultHistogramCount = 0; // Arrays.fill(resultAngleHistogram, 0); // resultAngleHistogramCount = 0; // resultAngleHistogramMax = Integer.MIN_VALUE; // Print statics of scale count, only for debuuging. if (printScaleCntStatEnabled) { float sumScaleCounts = 0; for (int scale : scalesToComputeArray) { sumScaleCounts += scaleResultCounts[scale]; } for (int scale : scalesToComputeArray) { System.out.println("Scale " + scale + " count percentage is: " + scaleResultCounts[scale] / sumScaleCounts); } } Arrays.fill(scaleResultCounts, 0); clearResetOFHistogramFlag(); } @Override synchronized public void annotate(GLAutoDrawable drawable) { super.annotate(drawable); GL2 gl = drawable.getGL().getGL2(); try { gl.glEnable(GL.GL_BLEND); gl.glBlendFunc(GL.GL_SRC_ALPHA, GL.GL_ONE_MINUS_SRC_ALPHA); gl.glBlendEquation(GL.GL_FUNC_ADD); } catch (GLException e) { e.printStackTrace(); } if (displayResultHistogram && (resultHistogram != null)) { // draw histogram as shaded in 2d hist above color wheel // normalize hist int rhDim = resultHistogram.length; // this.computeMaxSearchDistance(); gl.glPushMatrix(); final float scale = 30f / rhDim; // size same as the color wheel gl.glTranslatef(-35, .65f * chip.getSizeY(), 0); // center above color wheel gl.glScalef(scale, scale, 1); gl.glColor3f(0, 0, 1); gl.glLineWidth(2f); gl.glBegin(GL.GL_LINE_LOOP); gl.glVertex2f(0, 0); gl.glVertex2f(rhDim, 0); gl.glVertex2f(rhDim, rhDim); gl.glVertex2f(0, rhDim); gl.glEnd(); if (textRenderer == null) { textRenderer = new TextRenderer(new Font("SansSerif", Font.PLAIN, 64)); } int max = 0; for (int[] h : resultHistogram) { for (int vv : h) { if (vv > max) { max = vv; } } } if (max == 0) { gl.glTranslatef(0, rhDim / 2, 0); // translate to UL corner of histogram textRenderer.begin3DRendering(); textRenderer.draw3D("No data", 0, 0, 0, .07f); textRenderer.end3DRendering(); gl.glPopMatrix(); } else { final float maxRecip = 2f / max; gl.glPushMatrix(); // draw hist values for (int xx = 0; xx < rhDim; xx++) { for (int yy = 0; yy < rhDim; yy++) { float g = maxRecip * resultHistogram[xx][yy]; gl.glColor3f(g, g, g); gl.glBegin(GL2ES3.GL_QUADS); gl.glVertex2f(xx, yy); gl.glVertex2f(xx + 1, yy); gl.glVertex2f(xx + 1, yy + 1); gl.glVertex2f(xx, yy + 1); gl.glEnd(); } } final int tsd = computeMaxSearchDistance(); if (avgMatchDistance > 0) { gl.glPushMatrix(); gl.glColor4f(1f, 0, 0, .5f); gl.glLineWidth(5f); DrawGL.drawCircle(gl, tsd + .5f, tsd + .5f, avgMatchDistance, 16); gl.glPopMatrix(); } if (avgPossibleMatchDistance > 0) { gl.glPushMatrix(); gl.glColor4f(0, 1f, 0, .5f); gl.glLineWidth(5f); DrawGL.drawCircle(gl, tsd + .5f, tsd + .5f, avgPossibleMatchDistance, 16); // draw circle at target match distance gl.glPopMatrix(); } // a bunch of cryptic crap to draw a string the same width as the histogram... gl.glPopMatrix(); gl.glPopMatrix(); // back to original chip coordinates gl.glPushMatrix(); textRenderer.begin3DRendering(); String s = String.format("dt=%.1f ms", 1e-3f * sliceDeltaT); // final float sc = TextRendererScale.draw3dScale(textRenderer, s, chip.getCanvas().getScale(), chip.getWidth(), .1f); // determine width of string in pixels and scale accordingly FontRenderContext frc = textRenderer.getFontRenderContext(); Rectangle2D r = textRenderer.getBounds(s); // bounds in java2d coordinates, downwards more positive Rectangle2D rt = frc.getTransform().createTransformedShape(r).getBounds2D(); // get bounds in textrenderer coordinates // float ps = chip.getCanvas().getScale(); float w = (float) rt.getWidth(); // width of text in textrenderer, i.e. histogram cell coordinates (1 unit = 1 histogram cell) float sc = subSizeX / w / 6; // scale to histogram width gl.glTranslatef(0, .65f * subSizeY, 0); // translate to UL corner of histogram textRenderer.draw3D(s, 0, 0, 0, sc); String s2 = String.format("Skip: %d", skipProcessingEventsCount); textRenderer.draw3D(s2, 0, (float) (rt.getHeight()) * sc, 0, sc); String s3 = String.format("Slice events: %d", sliceEventCount); textRenderer.draw3D(s3, 0, 2 * (float) (rt.getHeight()) * sc, 0, sc); StringBuilder sb = new StringBuilder("Scale counts: "); for (int c : scaleResultCounts) { sb.append(String.format("%d ", c)); } textRenderer.draw3D(sb.toString(), 0, (float) (3 * rt.getHeight()) * sc, 0, sc); if (timeLimiter.isTimedOut()) { String s4 = String.format("Timed out: skipped %,d events", nSkipped); textRenderer.draw3D(s4, 0, 4 * (float) (rt.getHeight()) * sc, 0, sc); } if (outlierRejectionEnabled) { String s5 = String.format("Outliers: %%%.0f", 100 * (float) countOutliers / countIn); textRenderer.draw3D(s5, 0, 5 * (float) (rt.getHeight()) * sc, 0, sc); } textRenderer.end3DRendering(); gl.glPopMatrix(); // back to original chip coordinates // log.info(String.format("processed %.1f%% (%d/%d)", 100 * (float) nProcessed / (nSkipped + nProcessed), nProcessed, (nProcessed + nSkipped))); // // draw histogram of angles around center of image // if (resultAngleHistogramCount > 0) { // gl.glPushMatrix(); // gl.glTranslatef(subSizeX / 2, subSizeY / 2, 0); // gl.glLineWidth(getMotionVectorLineWidthPixels()); // gl.glColor3f(1, 1, 1); // gl.glBegin(GL.GL_LINES); // for (int i = 0; i < ANGLE_HISTOGRAM_COUNT; i++) { // float l = ((float) resultAngleHistogram[i] / resultAngleHistogramMax) * chip.getMinSize() / 2; // bin 0 is angle -PI // double angle = ((2 * Math.PI * i) / ANGLE_HISTOGRAM_COUNT) - Math.PI; // float dx = (float) Math.cos(angle) * l, dy = (float) Math.sin(angle) * l; // gl.glVertex2f(0, 0); // gl.glVertex2f(dx, dy); // gl.glEnd(); // gl.glPopMatrix(); } } if (sliceMethod == SliceMethod.AreaEventNumber && showAreaCountAreasTemporarily) { int d = 1 << areaEventNumberSubsampling; gl.glLineWidth(2f); gl.glColor3f(1, 1, 1); gl.glBegin(GL.GL_LINES); for (int x = 0; x <= subSizeX; x += d) { gl.glVertex2f(x, 0); gl.glVertex2f(x, subSizeY); } for (int y = 0; y <= subSizeY; y += d) { gl.glVertex2f(0, y); gl.glVertex2f(subSizeX, y); } gl.glEnd(); } if (sliceMethod == SliceMethod.ConstantIntegratedFlow && showAreaCountAreasTemporarily) { // TODO fill in what to draw } if (showBlockSizeAndSearchAreaTemporarily) { gl.glLineWidth(2f); gl.glColor3f(1, 0, 0); // show block size final int xx = subSizeX / 2, yy = subSizeY / 2, d = blockDimension / 2; gl.glBegin(GL.GL_LINE_LOOP); gl.glVertex2f(xx - d, yy - d); gl.glVertex2f(xx + d, yy - d); gl.glVertex2f(xx + d, yy + d); gl.glVertex2f(xx - d, yy + d); gl.glEnd(); // show search area gl.glColor3f(0, 1, 0); final int sd = d + (searchDistance << (numScales - 1)); gl.glBegin(GL.GL_LINE_LOOP); gl.glVertex2f(xx - sd, yy - sd); gl.glVertex2f(xx + sd, yy - sd); gl.glVertex2f(xx + sd, yy + sd); gl.glVertex2f(xx - sd, yy + sd); gl.glEnd(); } if (showCorners) { gl.glColor4f(1f, 0, 0, 0.1f); for (BasicEvent e : cornerEvents) { gl.glPushMatrix(); DrawGL.drawBox(gl, e.x, e.y, getCornerSize(), getCornerSize(), 0); gl.glPopMatrix(); } } } @Override public void initFilter() { super.initFilter(); checkForEASTCornerDetectorEnclosedFilter(); outlierRejectionMotionFlowStatistics = new MotionFlowStatistics(this.getClass().getSimpleName(), subSizeX, subSizeY, outlierRejectionWindowSize); outlierRejectionMotionFlowStatistics.setMeasureGlobalMotion(true); } @Override public synchronized void resetFilter() { setSubSampleShift(0); // filter breaks with super's bit shift subsampling super.resetFilter(); eventCounter = 0; // lastTs = Integer.MIN_VALUE; checkArrays(); if (slices == null) { return; // on reset maybe chip is not set yet } for (byte[][][] b : slices) { clearSlice(b); } // currentSliceIdx = 0; // start by filling slice 0 // currentSlice = slices[currentSliceIdx]; // sliceLastTs = Integer.MAX_VALUE; rewindFlg = true; if (adaptiveEventSkippingUpdateCounterLPFilter != null) { adaptiveEventSkippingUpdateCounterLPFilter.reset(); } clearAreaCounts(); clearNonGreedyRegions(); setSliceEventCount(getInt("sliceEventCount", SLICE_EVENT_COUNT_DEFAULT)); } private LowpassFilter speedFilter = new LowpassFilter(); /** * uses the current event to maybe rotate the slices * * @return true if slices were rotated */ private boolean maybeRotateSlices() { int dt = ts - sliceLastTs; if (dt < 0) { // handle timestamp wrapping // System.out.println("rotated slices at "); // System.out.println("rotated slices with dt= "+dt); rotateSlices(); eventCounter = 0; sliceDeltaT = dt; sliceLastTs = ts; return true; } switch (sliceMethod) { case ConstantDuration: if ((dt < sliceDurationUs)) { return false; } break; case ConstantEventNumber: if (eventCounter < sliceEventCount) { return false; } break; case AreaEventNumber: // If dt is too small, we should rotate it later until it has enough accumulation time. if (!areaCountExceeded && dt < getSliceDurationMaxLimitUS() || (dt < getSliceDurationMinLimitUS())) { return false; } break; case ConstantIntegratedFlow: speedFilter.setTauMs(sliceDeltaTimeUs(2) >> 10); final float meanGlobalSpeed = motionFlowStatistics.getGlobalMotion().meanGlobalSpeed; if (!Float.isNaN(meanGlobalSpeed)) { speedFilter.filter(meanGlobalSpeed, ts); } final float filteredMeanGlobalSpeed = speedFilter.getValue(); final float totalMovement = filteredMeanGlobalSpeed * dt * 1e-6f; if (Float.isNaN(meanGlobalSpeed)) { // we need to rotate slices somwhow even if there is no motion computed yet if (eventCounter < sliceEventCount) { return false; } if ((dt < sliceDurationUs)) { return false; } break; } if (totalMovement < searchDistance / 2 && dt < sliceDurationUs) { return false; } break; } rotateSlices(); /* Slices have been rotated */ getSupport().firePropertyChange(PatchMatchFlow.EVENT_NEW_SLICES, slices[sliceIndex(1)], slices[sliceIndex(2)]); return true; } void saveAPSImage() { byte[] grayImageBuffer = new byte[sizex * sizey]; for (int y = 0; y < sizey; y++) { for (int x = 0; x < sizex; x++) { final int idx = x + (sizey - y - 1) * chip.getSizeX(); float bufferValue = apsFrameExtractor.getRawFrame()[idx]; grayImageBuffer[x + y * chip.getSizeX()] = (byte) (int) (bufferValue * 0.5f); } } final BufferedImage theImage = new BufferedImage(chip.getSizeX(), chip.getSizeY(), BufferedImage.TYPE_BYTE_GRAY); theImage.getRaster().setDataElements(0, 0, sizex, sizey, grayImageBuffer); final Date d = new Date(); final String PNG = "png"; final String fn = "ApsFrame-" + sliceEndTimeUs[sliceIndex(1)] + "." + PNG; // if user is playing a file, use folder that file lives in String userDir = Paths.get(".").toAbsolutePath().normalize().toString(); File APSFrmaeDir = new File(userDir + File.separator + "APSFrames" + File.separator + getChip().getAeInputStream().getFile().getName()); if (!APSFrmaeDir.exists()) { APSFrmaeDir.mkdirs(); } File outputfile = new File(APSFrmaeDir + File.separator + fn); try { ImageIO.write(theImage, "png", outputfile); } catch (IOException ex) { Logger.getLogger(PatchMatchFlow.class.getName()).log(Level.SEVERE, null, ex); } } /** * Rotates slices by incrementing the slice pointer with rollover back to * zero, and sets currentSliceIdx and currentBitmap. Clears the new * currentBitmap. Thus the slice pointer increments. 0,1,2,0,1,2 * */ private void rotateSlices() { if (e != null) { sliceEndTimeUs[currentSliceIdx] = e.timestamp; } /*Thus if 0 is current index for current filling slice, then sliceIndex returns 1,2 for pointer =1,2. * Then if NUM_SLICES=3, after rotateSlices(), currentSliceIdx=NUM_SLICES-1=2, and sliceIndex(0)=2, sliceIndex(1)=0, sliceIndex(2)=1. */ sliceSummedSADValues[currentSliceIdx] = 0; // clear out current collecting slice which becomes the oldest slice after rotation sliceSummedSADCounts[currentSliceIdx] = 0; // clear out current collecting slice which becomes the oldest slice after rotation currentSliceIdx if (currentSliceIdx < 0) { currentSliceIdx = numSlices - 1; } currentSlice = slices[currentSliceIdx]; //sliceStartTimeUs[currentSliceIdx] = ts; // current event timestamp; set on first event to slice clearSlice(currentSlice); clearAreaCounts(); eventCounter = 0; sliceDeltaT = ts - sliceLastTs; sliceLastTs = ts; if (imuTimesliceLogger != null && imuTimesliceLogger.isEnabled()) { imuTimesliceLogger.log(String.format("%d %d %.3f", ts, sliceDeltaT, imuFlowEstimator.getPanRateDps())); } saveSliceGrayImage = true; // if(e.timestamp == 213686212) // saveAPSImage(); // saveSliceGrayImage = true; if (isShowSlices() && !rewindFlg) { // TODO danger, drawing outside AWT thread final byte[][][][] thisSlices = slices; // log.info("making runnable to draw slices in EDT"); SwingUtilities.invokeLater(new Runnable() { @Override public void run() { // will grab this instance. if called from AWT via e.g. slider, then can deadlock if we also invokeAndWait to draw something in ViewLoop drawSlices(thisSlices); } }); } } /** * Returns index to slice given pointer, with zero as current filling slice * pointer. * * * @param pointer how many slices in the past to index for. I.e.. 0 for * current slice (one being currently filled), 1 for next oldest, 2 for * oldest (when using NUM_SLICES=3). * @return index into bitmaps[] */ private int sliceIndex(int pointer) { return (currentSliceIdx + pointer) % numSlices; } /** * returns slice delta time in us from reference slice * * @param pointer how many slices in the past to index for. I.e.. 0 for * current slice (one being currently filled), 1 for next oldest, 2 for * oldest (when using NUM_SLICES=3). Only meaningful for pointer>=2, * currently exactly only pointer==2 since we are using only 3 slices. * * Modified to compute the delta time using the average of start and end * timestamps of each slices, i.e. the slice time "midpoint" where midpoint * is defined by average of first and last timestamp. * */ protected int sliceDeltaTimeUs(int pointer) { // System.out.println("dt(" + pointer + ")=" + (sliceStartTimeUs[sliceIndex(1)] - sliceStartTimeUs[sliceIndex(pointer)])); int idxOlder = sliceIndex(pointer), idxYounger = sliceIndex(1); int tOlder = (sliceStartTimeUs[idxOlder] + sliceEndTimeUs[idxOlder]) / 2; int tYounger = (sliceStartTimeUs[idxYounger] + sliceEndTimeUs[idxYounger]) / 2; int dt = tYounger - tOlder; return dt; } private int nSkipped = 0, nProcessed = 0, nCountPerSlicePacket = 0; /** * Accumulates the current event to the current slice * * @return true if subsequent processing should done, false if it should be * skipped for efficiency */ synchronized private boolean accumulateEvent(PolarityEvent e) { if (eventCounter++ == 0) { sliceStartTimeUs[currentSliceIdx] = e.timestamp; // current event timestamp } for (int s = 0; s < numScales; s++) { final int xx = e.x >> s; final int yy = e.y >> s; // if (xx >= currentSlice[legendString].length || yy > currentSlice[legendString][xx].length) { // log.warning("event out of range"); // return false; int cv = currentSlice[s][xx][yy]; cv += rectifyPolarties ? 1 : (e.polarity == PolarityEvent.Polarity.On ? 1 : -1); // cv = cv << (numScales - 1 - legendString); if (cv > sliceMaxValue) { cv = sliceMaxValue; } else if (cv < -sliceMaxValue) { cv = -sliceMaxValue; } currentSlice[s][xx][yy] = (byte) cv; } if (sliceMethod == SliceMethod.AreaEventNumber) { if (areaCounts == null) { clearAreaCounts(); } int c = ++areaCounts[e.x >> areaEventNumberSubsampling][e.y >> areaEventNumberSubsampling]; if (c >= sliceEventCount) { areaCountExceeded = true; // int count=0, sum=0, sum2=0; // StringBuilder sb=new StringBuilder("Area counts:\n"); // for(int[] i:areaCounts){ // for(int j:i){ // count++; // sum+=j; // sum2+=j*j; // sb.append(String.format("%6d ",j)); // sb.append("\n"); // float m=(float)sum/count; // float legendString=(float)Math.sqrt((float)sum2/count-m*m); // sb.append(String.format("mean=%.1f, std=%.1f",m,legendString)); // log.info("area count stats "+sb.toString()); } } // detect if keypoint here boolean isEASTCorner = (useEFASTnotSFAST && ((e.getAddress() & 1) == 1)); // supported only HWCornerPointRender or HW EFAST is used boolean isBFASTCorner = PatchFastDetectorisFeature(e); boolean isCorner = (useEFASTnotSFAST && isEASTCorner) || (!useEFASTnotSFAST && isBFASTCorner); if (calcOFonCornersEnabled && !isCorner) { return false; } else { cornerEvents.add(e); } // now finally compute flow if (timeLimiter.isTimedOut()) { nSkipped++; return false; } if (nonGreedyFlowComputingEnabled) { // only process the event for flow if most of the other regions have already been processed int xx = e.x >> areaEventNumberSubsampling, yy = e.y >> areaEventNumberSubsampling; boolean didArea = nonGreedyRegions[xx][yy]; if (!didArea) { nonGreedyRegions[xx][yy] = true; nonGreedyRegionsCount++; if (nonGreedyRegionsCount >= (int) (nonGreedyFractionToBeServiced * nonGreedyRegionsNumberOfRegions)) { clearNonGreedyRegions(); } nProcessed++; return true; // skip counter is ignored } else { nSkipped++; return false; } } if (skipProcessingEventsCount == 0) { nProcessed++; return true; } if (skipCounter++ < skipProcessingEventsCount) { nSkipped++; return false; } nProcessed++; skipCounter = 0; return true; } // private void clearSlice(int idx) { // for (int[] a : histograms[idx]) { // Arrays.fill(a, 0); private float sumArray[][] = null; /** * Computes block matching image difference best match around point x,y * using blockDimension and searchDistance and scale * * @param x coordinate in subsampled space * @param y * @param dx_init initial offset * @param dy_init * @param prevSlice the slice over which we search for best match * @param curSlice the slice from which we get the reference block * @param subSampleBy the scale to compute this SAD on, 0 for full * resolution, 1 for 2x2 subsampled block bitmap, etc * @return SADResult that provides the shift and SAD value */ // private SADResult minHammingDistance(int x, int y, BitSet prevSlice, BitSet curSlice) { private SADResult minSADDistance(int x, int y, int dx_init, int dy_init, byte[][][] curSlice, byte[][][] prevSlice, int subSampleBy) { SADResult result = new SADResult(); float minSum = Float.MAX_VALUE, sum; float FSDx = 0, FSDy = 0, DSDx = 0, DSDy = 0; // This is for testing the DS search accuracy. final int searchRange = (2 * searchDistance) + 1; // The maximum search distance in this subSampleBy slice if ((sumArray == null) || (sumArray.length != searchRange)) { sumArray = new float[searchRange][searchRange]; } else { for (float[] row : sumArray) { Arrays.fill(row, Float.MAX_VALUE); } } if (outputSearchErrorInfo) { searchMethod = SearchMethod.FullSearch; } else { searchMethod = getSearchMethod(); } final int xsub = (x >> subSampleBy) + dx_init; final int ysub = (y >> subSampleBy) + dy_init; final int r = ((blockDimension) / 2) << (numScales - 1 - subSampleBy); int w = subSizeX >> subSampleBy, h = subSizeY >> subSampleBy; // Make sure both ref block and past slice block are in bounds on all sides or there'll be arrayIndexOutOfBoundary exception. // Also we don't want to match ref block only on inner sides or there will be a bias towards motion towards middle if (xsub - r - searchDistance < 0 || xsub + r + searchDistance >= 1 * w || ysub - r - searchDistance < 0 || ysub + r + searchDistance >= 1 * h) { result.sadValue = Float.MAX_VALUE; // return very large distance for this match so it is not selected result.scale = subSampleBy; return result; } switch (searchMethod) { case DiamondSearch: // SD = small diamond, LD=large diamond SP=search process /* The center of the LDSP or SDSP could change in the iteration process, so we need to use a variable to represent it. In the first interation, it's the Zero Motion Potion (ZMP). */ int xCenter = x, yCenter = y; /* x offset of center point relative to ZMP, y offset of center point to ZMP. x offset of center pointin positive number to ZMP, y offset of center point in positive number to ZMP. */ int dx, dy, xidx, yidx; // x and y best match offsets in pixels, indices of these in 2d hist int minPointIdx = 0; // Store the minimum point index. boolean SDSPFlg = false; // If this flag is set true, then it means LDSP search is finished and SDSP search could start. /* If one block has been already calculated, the computedFlg will be set so we don't to do the calculation again. */ boolean computedFlg[][] = new boolean[searchRange][searchRange]; for (boolean[] row : computedFlg) { Arrays.fill(row, false); } if (searchDistance == 1) { // LDSP search can only be applied for search distance >= 2. SDSPFlg = true; } int iterationsLeft = searchRange * searchRange; while (!SDSPFlg) { /* 1. LDSP search */ for (int pointIdx = 0; pointIdx < LDSP.length; pointIdx++) { dx = (LDSP[pointIdx][0] + xCenter) - x; dy = (LDSP[pointIdx][1] + yCenter) - y; xidx = dx + searchDistance; yidx = dy + searchDistance; // Point to be searched is out of search area, skip it. if ((xidx >= searchRange) || (yidx >= searchRange) || (xidx < 0) || (yidx < 0)) { continue; } /* We just calculate the blocks that haven't been calculated before */ if (computedFlg[xidx][yidx] == false) { sumArray[xidx][yidx] = sadDistance(x, y, dx_init + dx, dy_init + dy, curSlice, prevSlice, subSampleBy); computedFlg[xidx][yidx] = true; if (outputSearchErrorInfo) { DSAverageNum++; } if (outputSearchErrorInfo) { if (sumArray[xidx][yidx] != sumArray[xidx][yidx]) { // TODO huh? this is never true, compares to itself log.warning("It seems that there're some bugs in the DS algorithm."); } } } if (sumArray[xidx][yidx] <= minSum) { minSum = sumArray[xidx][yidx]; minPointIdx = pointIdx; } } /* 2. Check the minimum value position is in the center or not. */ xCenter = xCenter + LDSP[minPointIdx][0]; yCenter = yCenter + LDSP[minPointIdx][1]; if (minPointIdx == 4) { // It means it's in the center, so we should break the loop and go to SDSP search. SDSPFlg = true; } if (--iterationsLeft < 0) { log.warning("something is wrong with diamond search; did not find min in SDSP search"); SDSPFlg = true; } } /* 3. SDSP Search */ for (int[] element : SDSP) { dx = (element[0] + xCenter) - x; dy = (element[1] + yCenter) - y; xidx = dx + searchDistance; yidx = dy + searchDistance; // Point to be searched is out of search area, skip it. if ((xidx >= searchRange) || (yidx >= searchRange) || (xidx < 0) || (yidx < 0)) { continue; } /* We just calculate the blocks that haven't been calculated before */ if (computedFlg[xidx][yidx] == false) { sumArray[xidx][yidx] = sadDistance(x, y, dx_init + dx, dy_init + dy, curSlice, prevSlice, subSampleBy); computedFlg[xidx][yidx] = true; if (outputSearchErrorInfo) { DSAverageNum++; } if (outputSearchErrorInfo) { if (sumArray[xidx][yidx] != sumArray[xidx][yidx]) { log.warning("It seems that there're some bugs in the DS algorithm."); } } } if (sumArray[xidx][yidx] <= minSum) { minSum = sumArray[xidx][yidx]; result.dx = -dx - dx_init; // minus is because result points to the past slice and motion is in the other direction result.dy = -dy - dy_init; result.sadValue = minSum; } // // debug // if(result.dx==-searchDistance && result.dy==-searchDistance){ // System.out.println(result); } if (outputSearchErrorInfo) { DSDx = result.dx; DSDy = result.dy; } break; case FullSearch: if ((e.timestamp) == 81160149) { System.out.printf("Scale %d with Refblock is: \n", subSampleBy); int xscale = (x >> subSampleBy); int yscale = (y >> subSampleBy); for (int xx = xscale - r; xx <= (xscale + r); xx++) { for (int yy = yscale - r; yy <= (yscale + r); yy++) { System.out.printf("%d\t", curSlice[subSampleBy][xx][yy]); } System.out.printf("\n"); } System.out.printf("\n"); System.out.printf("Tagblock is: \n"); for (int xx = xscale + dx_init - r - searchDistance; xx <= (xscale + dx_init + r + searchDistance); xx++) { for (int yy = yscale + dy_init - r - searchDistance; yy <= (yscale + dy_init + r + searchDistance); yy++) { System.out.printf("%d\t", prevSlice[subSampleBy][xx][yy]); } System.out.printf("\n"); } } for (dx = -searchDistance; dx <= searchDistance; dx++) { for (dy = -searchDistance; dy <= searchDistance; dy++) { sum = sadDistance(x, y, dx_init + dx, dy_init + dy, curSlice, prevSlice, subSampleBy); sumArray[dx + searchDistance][dy + searchDistance] = sum; if (sum < minSum) { minSum = sum; result.dx = -dx - dx_init; // minus is because result points to the past slice and motion is in the other direction result.dy = -dy - dy_init; result.sadValue = minSum; } } } // System.out.printf("result is %s: \n", result.toString()); if (outputSearchErrorInfo) { FSCnt += 1; FSDx = result.dx; FSDy = result.dy; } else { break; } case CrossDiamondSearch: break; } // compute the indices into 2d histogram of all motion vector results. // It's a bit complicated because of multiple scales. // Also, we want the indexes to be centered in the histogram array so that searches at full scale appear at the middle // of the array and not at 0,0 corner. // Suppose searchDistance=1 and numScales=2. Then the histogram has size 2*2+1=5. // Therefore the scale 0 results need to have offset added to them to center results in histogram that // shows results over all scales. result.scale = subSampleBy; // convert dx in search steps to dx in pixels including subsampling // compute index assuming no subsampling or centering result.xidx = (result.dx + dx_init) + searchDistance; result.yidx = (result.dy + dy_init) + searchDistance; // compute final dx and dy including subsampling result.dx = (result.dx) << subSampleBy; result.dy = (result.dy) << subSampleBy; // compute final index including subsampling and centering // idxCentering is shift needed to be applyed to store this result finally into the hist, final int idxCentering = (searchDistance << (numScales - 1)) - ((searchDistance) << subSampleBy); // i.e. for subSampleBy=0 and numScales=2, shift=1 so that full scale search is centered in 5x5 hist result.xidx = (result.xidx << subSampleBy) + idxCentering; result.yidx = (result.yidx << subSampleBy) + idxCentering; // if (result.xidx < 0 || result.yidx < 0 || result.xidx > maxIdx || result.yidx > maxIdx) { // log.warning("something wrong with result=" + result); // return null; if (outputSearchErrorInfo) { if ((DSDx == FSDx) && (DSDy == FSDy)) { DSCorrectCnt += 1; } else { DSAveError[0] += Math.abs(DSDx - FSDx); DSAveError[1] += Math.abs(DSDy - FSDy); } if (0 == (FSCnt % 10000)) { log.log(Level.INFO, "Correct Diamond Search times are {0}, Full Search times are {1}, accuracy is {2}, averageNumberPercent is {3}, averageError is ({4}, {5})", new Object[]{DSCorrectCnt, FSCnt, DSCorrectCnt / FSCnt, DSAverageNum / (searchRange * searchRange * FSCnt), DSAveError[0] / FSCnt, DSAveError[1] / (FSCnt - DSCorrectCnt)}); } } // if (tmpSadResult.xidx == searchRange-1 && tmpSadResult.yidx == searchRange-1) { // tmpSadResult.sadValue = 1; // reject results to top right that are likely result of ambiguous search return result; } /** * computes Hamming distance centered on x,y with patch of patchSize for * prevSliceIdx relative to curSliceIdx patch. * * @param xfull coordinate x in full resolution * @param yfull coordinate y in full resolution * @param dx the offset in pixels in the subsampled space of the past slice. * The motion vector is then *from* this position *to* the current slice. * @param dy * @param prevSlice * @param curSlice * @param subsampleBy the scale to search over * @return Distance value, max 1 when all pixels differ, min 0 when all the * same */ private float sadDistance(final int xfull, final int yfull, final int dx, final int dy, final byte[][][] curSlice, final byte[][][] prevSlice, final int subsampleBy) { final int x = xfull >> subsampleBy; final int y = yfull >> subsampleBy; final int r = ((blockDimension) / 2) << (numScales - 1 - subsampleBy); // int w = subSizeX >> subsampleBy, h = subSizeY >> subsampleBy; // int adx = dx > 0 ? dx : -dx; // abs val of dx and dy, to compute limits // int ady = dy > 0 ? dy : -dy; // // Make sure both ref block and past slice block are in bounds on all sides or there'll be arrayIndexOutOfBoundary exception. // // Also we don't want to match ref block only on inner sides or there will be a bias towards motion towards middle // if (x - r - adx < 0 || x + r + adx >= w // || y - r - ady < 0 || y + r + ady >= h) { // return 1; // tobi changed to 1 again // Float.MAX_VALUE; // return very large distance for this match so it is not selected int validPixNumCurSlice = 0, validPixNumPrevSlice = 0; // The valid pixel number in the current block int nonZeroMatchCount = 0; // int saturatedPixNumCurSlice = 0, saturatedPixNumPrevSlice = 0; // The valid pixel number in the current block int sumDist = 0; // try { for (int xx = x - r; xx <= (x + r); xx++) { for (int yy = y - r; yy <= (y + r); yy++) { // if (xx < 0 || yy < 0 || xx >= w || yy >= h // || xx + dx < 0 || yy + dy < 0 || xx + dx >= w || yy + dy >= h) { //// log.warning("out of bounds slice access; something wrong"); // TODO fix this check above // continue; int currSliceVal = curSlice[subsampleBy][xx][yy]; // binary value on (xx, yy) for current slice int prevSliceVal = prevSlice[subsampleBy][xx + dx][yy + dy]; // binary value on (xx, yy) for previous slice at offset dx,dy in (possibly subsampled) slice int dist = (currSliceVal - prevSliceVal); if (dist < 0) { dist = (-dist); } sumDist += dist; // if (currSlicePol != prevSlicePol) { // hd += 1; // if (currSliceVal == sliceMaxValue || currSliceVal == -sliceMaxValue) { // saturatedPixNumCurSlice++; // pixels that are not saturated // if (prevSliceVal == sliceMaxValue || prevSliceVal == -sliceMaxValue) { // saturatedPixNumPrevSlice++; if (currSliceVal != 0) { validPixNumCurSlice++; // pixels that are not saturated } if (prevSliceVal != 0) { validPixNumPrevSlice++; } if (currSliceVal != 0 && prevSliceVal != 0) { nonZeroMatchCount++; // pixels that both have events in them } } } // } catch (ArrayIndexOutOfBoundsException ex) { // log.warning(ex.toString()); // debug // if(dx==-1 && dy==-1) return 0; else return Float.MAX_VALUE; sumDist = sumDist; final int blockDim = (2 * r) + 1; final int blockArea = (blockDim) * (blockDim); // TODO check math here for fraction correct with subsampling // TODD: NEXT WORK IS TO DO THE RESEARCH ON WEIGHTED HAMMING DISTANCE // Calculate the metric confidence value final int minValidPixNum = (int) (this.validPixOccupancy * blockArea); // final int maxSaturatedPixNum = (int) ((1 - this.validPixOccupancy) * blockArea); final float sadNormalizer = 1f / (blockArea * (rectifyPolarties ? 2 : 1) * sliceMaxValue); // if current or previous block has insufficient pixels with values or if all the pixels are filled up, then reject match if ((validPixNumCurSlice < minValidPixNum) || (validPixNumPrevSlice < minValidPixNum) || (nonZeroMatchCount < minValidPixNum) // || (saturatedPixNumCurSlice >= maxSaturatedPixNum) || (saturatedPixNumPrevSlice >= maxSaturatedPixNum) ) { // If valid pixel number of any slice is 0, then we set the distance to very big value so we can exclude it. return 1; // tobi changed to 1 to represent max distance // Float.MAX_VALUE; } else { /* retVal consists of the distance and the dispersion. dispersion is used to describe the spatial relationship within one block. Here we use the difference between validPixNumCurrSli and validPixNumPrevSli to calculate the dispersion. Inspired by paper "Measuring the spatial dispersion of evolutionist search process: application to Walksat" by Alain Sidaner. */ final float finalDistance = sadNormalizer * ((sumDist * weightDistance) + (Math.abs(validPixNumCurSlice - validPixNumPrevSlice) * (1 - weightDistance))); return finalDistance; } } /** * Computes hamming weight around point x,y using blockDimension and * searchDistance * * @param x coordinate in subsampled space * @param y * @param prevSlice * @param curSlice * @return SADResult that provides the shift and SAD value */ // private SADResult minJaccardDistance(int x, int y, BitSet prevSlice, BitSet curSlice) { // private SADResult minJaccardDistance(int x, int y, byte[][] prevSlice, byte[][] curSlice) { // float minSum = Integer.MAX_VALUE, sum = 0; // SADResult sadResult = new SADResult(0, 0, 0); // for (int dx = -searchDistance; dx <= searchDistance; dx++) { // for (int dy = -searchDistance; dy <= searchDistance; dy++) { // sum = jaccardDistance(x, y, dx, dy, prevSlice, curSlice); // if (sum <= minSum) { // minSum = sum; // sadResult.dx = dx; // sadResult.dy = dy; // sadResult.sadValue = minSum; // return sadResult; /** * computes Hamming distance centered on x,y with patch of patchSize for * prevSliceIdx relative to curSliceIdx patch. * * @param x coordinate in subSampled space * @param y * @param patchSize * @param prevSlice * @param curSlice * @return SAD value */ // private float jaccardDistance(int x, int y, int dx, int dy, BitSet prevSlice, BitSet curSlice) { private float jaccardDistance(int x, int y, int dx, int dy, boolean[][] prevSlice, boolean[][] curSlice) { float M01 = 0, M10 = 0, M11 = 0; int blockRadius = blockDimension / 2; // Make sure 0<=xx+dx<subSizeX, 0<=xx<subSizeX and 0<=yy+dy<subSizeY, 0<=yy<subSizeY, or there'll be arrayIndexOutOfBoundary exception. if ((x < (blockRadius + dx)) || (x >= ((subSizeX - blockRadius) + dx)) || (x < blockRadius) || (x >= (subSizeX - blockRadius)) || (y < (blockRadius + dy)) || (y >= ((subSizeY - blockRadius) + dy)) || (y < blockRadius) || (y >= (subSizeY - blockRadius))) { return 1; // changed back to 1 // Float.MAX_VALUE; } for (int xx = x - blockRadius; xx <= (x + blockRadius); xx++) { for (int yy = y - blockRadius; yy <= (y + blockRadius); yy++) { final boolean c = curSlice[xx][yy], p = prevSlice[xx - dx][yy - dy]; if ((c == true) && (p == true)) { M11 += 1; } if ((c == true) && (p == false)) { M01 += 1; } if ((c == false) && (p == true)) { M10 += 1; } // if ((curSlice.get((xx + 1) + ((yy) * subSizeX)) == true) && (prevSlice.get(((xx + 1) - dx) + ((yy - dy) * subSizeX)) == true)) { // M11 += 1; // if ((curSlice.get((xx + 1) + ((yy) * subSizeX)) == true) && (prevSlice.get(((xx + 1) - dx) + ((yy - dy) * subSizeX)) == false)) { // M01 += 1; // if ((curSlice.get((xx + 1) + ((yy) * subSizeX)) == false) && (prevSlice.get(((xx + 1) - dx) + ((yy - dy) * subSizeX)) == true)) { // M10 += 1; } } float retVal; if (0 == (M01 + M10 + M11)) { retVal = 0; } else { retVal = M11 / (M01 + M10 + M11); } retVal = 1 - retVal; return retVal; } // private SADResult minVicPurDistance(int blockX, int blockY) { // ArrayList<Integer[]> seq1 = new ArrayList(1); // SADResult sadResult = new SADResult(0, 0, 0); // int size = spikeTrains[blockX][blockY].size(); // int lastTs = spikeTrains[blockX][blockY].get(size - forwardEventNum)[0]; // for (int i = size - forwardEventNum; i < size; i++) { // seq1.appendCopy(spikeTrains[blockX][blockY].get(i)); //// if(seq1.get(2)[0] - seq1.get(0)[0] > thresholdTime) { //// return sadResult; // double minium = Integer.MAX_VALUE; // for (int i = -1; i < 2; i++) { // for (int j = -1; j < 2; j++) { // // Remove the seq1 itself // if ((0 == i) && (0 == j)) { // continue; // ArrayList<Integer[]> seq2 = new ArrayList(1); // if ((blockX >= 2) && (blockY >= 2)) { // ArrayList<Integer[]> tmpSpikes = spikeTrains[blockX + i][blockY + j]; // if (tmpSpikes != null) { // for (int index = 0; index < tmpSpikes.size(); index++) { // if (tmpSpikes.get(index)[0] >= lastTs) { // seq2.appendCopy(tmpSpikes.get(index)); // double dis = vicPurDistance(seq1, seq2); // if (dis < minium) { // minium = dis; // sadResult.dx = -i; // sadResult.dy = -j; // lastFireIndex[blockX][blockY] = spikeTrains[blockX][blockY].size() - 1; // if ((sadResult.dx != 1) || (sadResult.dy != 0)) { // // sadResult = new SADResult(0, 0, 0); // return sadResult; // private double vicPurDistance(ArrayList<Integer[]> seq1, ArrayList<Integer[]> seq2) { // int sum1Plus = 0, sum1Minus = 0, sum2Plus = 0, sum2Minus = 0; // Iterator itr1 = seq1.iterator(); // Iterator itr2 = seq2.iterator(); // int length1 = seq1.size(); // int length2 = seq2.size(); // double[][] distanceMatrix = new double[length1 + 1][length2 + 1]; // for (int h = 0; h <= length1; h++) { // for (int k = 0; k <= length2; k++) { // if (h == 0) { // distanceMatrix[h][k] = k; // continue; // if (k == 0) { // distanceMatrix[h][k] = h; // continue; // double tmpMin = Math.min(distanceMatrix[h][k - 1] + 1, distanceMatrix[h - 1][k] + 1); // double event1 = seq1.get(h - 1)[0] - seq1.get(0)[0]; // double event2 = seq2.get(k - 1)[0] - seq2.get(0)[0]; // distanceMatrix[h][k] = Math.min(tmpMin, distanceMatrix[h - 1][k - 1] + (cost * Math.abs(event1 - event2))); // while (itr1.hasNext()) { // Integer[] ii = (Integer[]) itr1.next(); // if (ii[1] == 1) { // sum1Plus += 1; // } else { // sum1Minus += 1; // while (itr2.hasNext()) { // Integer[] ii = (Integer[]) itr2.next(); // if (ii[1] == 1) { // sum2Plus += 1; // } else { // sum2Minus += 1; // // return Math.abs(sum1Plus - sum2Plus) + Math.abs(sum1Minus - sum2Minus); // return distanceMatrix[length1][length2]; // /** // * Computes min SAD shift around point x,y using blockDimension and // * searchDistance // * // * @param x coordinate in subsampled space // * @param y // * @param prevSlice // * @param curSlice // * @return SADResult that provides the shift and SAD value // */ // private SADResult minSad(int x, int y, BitSet prevSlice, BitSet curSlice) { // // for now just do exhaustive search over all shifts up to +/-searchDistance // SADResult sadResult = new SADResult(0, 0, 0); // float minSad = 1; // for (int dx = -searchDistance; dx <= searchDistance; dx++) { // for (int dy = -searchDistance; dy <= searchDistance; dy++) { // float sad = sad(x, y, dx, dy, prevSlice, curSlice); // if (sad <= minSad) { // minSad = sad; // sadResult.dx = dx; // sadResult.dy = dy; // sadResult.sadValue = minSad; // return sadResult; // /** // * computes SAD centered on x,y with shift of dx,dy for prevSliceIdx // * relative to curSliceIdx patch. // * // * @param x coordinate x in subSampled space // * @param y coordinate y in subSampled space // * @param dx block shift of x // * @param dy block shift of y // * @param prevSliceIdx // * @param curSliceIdx // * @return SAD value // */ // private float sad(int x, int y, int dx, int dy, BitSet prevSlice, BitSet curSlice) { // int blockRadius = blockDimension / 2; // // Make sure 0<=xx+dx<subSizeX, 0<=xx<subSizeX and 0<=yy+dy<subSizeY, 0<=yy<subSizeY, or there'll be arrayIndexOutOfBoundary exception. // if ((x < (blockRadius + dx)) || (x >= ((subSizeX - blockRadius) + dx)) || (x < blockRadius) || (x >= (subSizeX - blockRadius)) // || (y < (blockRadius + dy)) || (y >= ((subSizeY - blockRadius) + dy)) || (y < blockRadius) || (y >= (subSizeY - blockRadius))) { // return Float.MAX_VALUE; // float sad = 0, retVal = 0; // float validPixNumCurrSli = 0, validPixNumPrevSli = 0; // The valid pixel number in the current block // for (int xx = x - blockRadius; xx <= (x + blockRadius); xx++) { // for (int yy = y - blockRadius; yy <= (y + blockRadius); yy++) { // boolean currSlicePol = curSlice.get((xx + 1) + ((yy) * subSizeX)); // binary value on (xx, yy) for current slice // boolean prevSlicePol = prevSlice.get(((xx + 1) - dx) + ((yy - dy) * subSizeX)); // binary value on (xx, yy) for previous slice // int imuWarningDialog = (currSlicePol ? 1 : 0) - (prevSlicePol ? 1 : 0); // if (currSlicePol == true) { // validPixNumCurrSli += 1; // if (prevSlicePol == true) { // validPixNumPrevSli += 1; // if (imuWarningDialog <= 0) { // imuWarningDialog = -imuWarningDialog; // sad += imuWarningDialog; // // Calculate the metric confidence value // float validPixNum = this.validPixOccupancy * (((2 * blockRadius) + 1) * ((2 * blockRadius) + 1)); // if ((validPixNumCurrSli <= validPixNum) || (validPixNumPrevSli <= validPixNum)) { // If valid pixel number of any slice is 0, then we set the distance to very big value so we can exclude it. // retVal = 1; // } else { // /* // retVal is consisted of the distance and the dispersion, dispersion is used to describe the spatial relationship within one block. // Here we use the difference between validPixNumCurrSli and validPixNumPrevSli to calculate the dispersion. // Inspired by paper "Measuring the spatial dispersion of evolutionist search process: application to Walksat" by Alain Sidaner. // */ // retVal = ((sad * weightDistance) + (Math.abs(validPixNumCurrSli - validPixNumPrevSli) * (1 - weightDistance))) / (((2 * blockRadius) + 1) * ((2 * blockRadius) + 1)); // return retVal; private class SADResult { int dx, dy; // best match offset in pixels to reference block from past slice block, i.e. motion vector points in this direction float vx, vy; // optical flow in pixels/second corresponding to this match float sadValue; // sum of absolute differences for this best match normalized by number of pixels in reference area int xidx, yidx; // x and y indices into 2d matrix of result. 0,0 corresponds to motion SW. dx, dy may be negative, like (-1, -1) represents SW. // However, for histgram index, it's not possible to use negative number. That's the reason for intrducing xidx and yidx. // boolean minSearchedFlg = false; // The flag indicates that this minimum have been already searched before. int scale; /** * Allocates new results initialized to zero */ public SADResult() { this(0, 0, 0, 0); } public SADResult(int dx, int dy, float sadValue, int scale) { this.dx = dx; this.dy = dy; this.sadValue = sadValue; } public void set(SADResult s) { this.dx = s.dx; this.dy = s.dy; this.sadValue = s.sadValue; this.xidx = s.xidx; this.yidx = s.yidx; this.scale = s.scale; } @Override public String toString() { return String.format("(dx,dy=%5d,%5d), (vx,vy=%.1f,%.1f px/s), SAD=%f, scale=%d", dx, dy, vx, vy, sadValue, scale); } } private class Statistics { double[] data; int size; public Statistics(double[] data) { this.data = data; size = data.length; } double getMean() { double sum = 0.0; for (double a : data) { sum += a; } return sum / size; } double getVariance() { double mean = getMean(); double temp = 0; for (double a : data) { temp += (a - mean) * (a - mean); } return temp / size; } double getStdDev() { return Math.sqrt(getVariance()); } public double median() { Arrays.sort(data); if ((data.length % 2) == 0) { return (data[(data.length / 2) - 1] + data[data.length / 2]) / 2.0; } return data[data.length / 2]; } public double getMin() { Arrays.sort(data); return data[0]; } public double getMax() { Arrays.sort(data); return data[data.length - 1]; } } /** * @return the blockDimension */ public int getBlockDimension() { return blockDimension; } /** * @param blockDimension the blockDimension to set */ synchronized public void setBlockDimension(int blockDimension) { int old = this.blockDimension; // enforce odd value if ((blockDimension & 1) == 0) { // even if (blockDimension > old) { blockDimension++; } else { blockDimension } } // clip final value if (blockDimension < 1) { blockDimension = 1; } else if (blockDimension > 63) { blockDimension = 63; } this.blockDimension = blockDimension; getSupport().firePropertyChange("blockDimension", old, blockDimension); putInt("blockDimension", blockDimension); showBlockSizeAndSearchAreaTemporarily(); } /** * @return the sliceMethod */ public SliceMethod getSliceMethod() { return sliceMethod; } /** * @param sliceMethod the sliceMethod to set */ synchronized public void setSliceMethod(SliceMethod sliceMethod) { SliceMethod old = this.sliceMethod; this.sliceMethod = sliceMethod; putString("sliceMethod", sliceMethod.toString()); if (sliceMethod == SliceMethod.AreaEventNumber || sliceMethod == SliceMethod.ConstantIntegratedFlow) { showAreasForAreaCountsTemporarily(); } // if(sliceMethod==SliceMethod.ConstantIntegratedFlow){ // setDisplayGlobalMotion(true); getSupport().firePropertyChange("sliceMethod", old, this.sliceMethod); } public PatchCompareMethod getPatchCompareMethod() { return patchCompareMethod; } synchronized public void setPatchCompareMethod(PatchCompareMethod patchCompareMethod) { this.patchCompareMethod = patchCompareMethod; putString("patchCompareMethod", patchCompareMethod.toString()); } /** * * @return the search method */ public SearchMethod getSearchMethod() { return searchMethod; } /** * * @param searchMethod the method to be used for searching */ synchronized public void setSearchMethod(SearchMethod searchMethod) { SearchMethod old = this.searchMethod; this.searchMethod = searchMethod; putString("searchMethod", searchMethod.toString()); getSupport().firePropertyChange("searchMethod", old, this.searchMethod); } private int computeMaxSearchDistance() { int sumScales = 0; for (int i = 0; i < numScales; i++) { sumScales += (1 << i); } return searchDistance * sumScales; } private void computeAveragePossibleMatchDistance() { int n = 0; double s = 0; for (int xx = -searchDistance; xx <= searchDistance; xx++) { for (int yy = -searchDistance; yy <= searchDistance; yy++) { n++; s += Math.sqrt((xx * xx) + (yy * yy)); } } double d = s / n; // avg for one scale double s2 = 0; for (int i = 0; i < numScales; i++) { s2 += d * (1 << i); } double d2 = s2 / numScales; avgPossibleMatchDistance = (float) d2; log.info(String.format("searchDistance=%d numScales=%d: avgPossibleMatchDistance=%.1f", searchDistance, numScales, avgPossibleMatchDistance)); } @Override synchronized public void setSearchDistance(int searchDistance) { int old = this.searchDistance; if (searchDistance > 12) { searchDistance = 12; } else if (searchDistance < 1) { searchDistance = 1; // limit size } this.searchDistance = searchDistance; putInt("searchDistance", searchDistance); getSupport().firePropertyChange("searchDistance", old, searchDistance); resetFilter(); showBlockSizeAndSearchAreaTemporarily(); computeAveragePossibleMatchDistance(); } /** * @return the sliceDurationUs */ public int getSliceDurationUs() { return sliceDurationUs; } /** * @param sliceDurationUs the sliceDurationUs to set */ public void setSliceDurationUs(int sliceDurationUs) { int old = this.sliceDurationUs; if (sliceDurationUs < getSliceDurationMinLimitUS()) { sliceDurationUs = getSliceDurationMinLimitUS(); } else if (sliceDurationUs > getSliceDurationMaxLimitUS()) { sliceDurationUs = getSliceDurationMaxLimitUS(); // limit it to one second } this.sliceDurationUs = sliceDurationUs; /* If the slice duration is changed, reset FSCnt and DScorrect so we can get more accurate evaluation result */ FSCnt = 0; DSCorrectCnt = 0; putInt("sliceDurationUs", sliceDurationUs); getSupport().firePropertyChange("sliceDurationUs", old, this.sliceDurationUs); } /** * @return the sliceEventCount */ public int getSliceEventCount() { return sliceEventCount; } /** * @param sliceEventCount the sliceEventCount to set */ public void setSliceEventCount(int sliceEventCount) { final int div = sliceMethod == SliceMethod.AreaEventNumber ? numAreas : 1; final int old = this.sliceEventCount; if (sliceEventCount < MIN_SLICE_EVENT_COUNT_FULL_FRAME / div) { sliceEventCount = MIN_SLICE_EVENT_COUNT_FULL_FRAME / div; } else if (sliceEventCount > MAX_SLICE_EVENT_COUNT_FULL_FRAME / div) { sliceEventCount = MAX_SLICE_EVENT_COUNT_FULL_FRAME / div; } this.sliceEventCount = sliceEventCount; putInt("sliceEventCount", sliceEventCount); getSupport().firePropertyChange("sliceEventCount", old, this.sliceEventCount); } public float getMaxAllowedSadDistance() { return maxAllowedSadDistance; } public void setMaxAllowedSadDistance(float maxAllowedSadDistance) { float old = this.maxAllowedSadDistance; if (maxAllowedSadDistance < 0) { maxAllowedSadDistance = 0; } else if (maxAllowedSadDistance > 1) { maxAllowedSadDistance = 1; } this.maxAllowedSadDistance = maxAllowedSadDistance; putFloat("maxAllowedSadDistance", maxAllowedSadDistance); getSupport().firePropertyChange("maxAllowedSadDistance", old, this.maxAllowedSadDistance); } public float getValidPixOccupancy() { return validPixOccupancy; } public void setValidPixOccupancy(float validPixOccupancy) { float old = this.validPixOccupancy; if (validPixOccupancy < 0) { validPixOccupancy = 0; } else if (validPixOccupancy > 1) { validPixOccupancy = 1; } this.validPixOccupancy = validPixOccupancy; putFloat("validPixOccupancy", validPixOccupancy); getSupport().firePropertyChange("validPixOccupancy", old, this.validPixOccupancy); } public float getWeightDistance() { return weightDistance; } public void setWeightDistance(float weightDistance) { if (weightDistance < 0) { weightDistance = 0; } else if (weightDistance > 1) { weightDistance = 1; } this.weightDistance = weightDistance; putFloat("weightDistance", weightDistance); } // private int totalFlowEvents=0, filteredOutFlowEvents=0; // private boolean filterOutInconsistentEvent(SADResult result) { // if (!isOutlierMotionFilteringEnabled()) { // return false; // totalFlowEvents++; // if (lastGoodSadResult == null) { // return false; // if (result.dx * lastGoodSadResult.dx + result.dy * lastGoodSadResult.dy >= 0) { // return false; // filteredOutFlowEvents++; // return true; synchronized private void checkArrays() { if (subSizeX == 0 || subSizeY == 0) { return; // don't do on init when chip is not known yet } // numSlices = getInt("numSlices", 3); // since resetFilter is called in super before numSlices is even initialized if (slices == null || slices.length != numSlices || slices[0] == null || slices[0].length != numScales) { if (numScales > 0 && numSlices > 0) { // deal with filter reconstruction where these fields are not set slices = new byte[numSlices][numScales][][]; for (int n = 0; n < numSlices; n++) { for (int s = 0; s < numScales; s++) { int nx = (subSizeX >> s) + 1 + blockDimension, ny = (subSizeY >> s) + 1 + blockDimension; if (slices[n][s] == null || slices[n][s].length != nx || slices[n][s][0] == null || slices[n][s][0].length != ny) { slices[n][s] = new byte[nx][ny]; } } } currentSliceIdx = 0; // start by filling slice 0 currentSlice = slices[currentSliceIdx]; sliceLastTs = Integer.MAX_VALUE; sliceStartTimeUs = new int[numSlices]; sliceEndTimeUs = new int[numSlices]; sliceSummedSADValues = new float[numSlices]; sliceSummedSADCounts = new int[numSlices]; } // log.info("allocated slice memory"); } // if (lastTimesMap != null) { // lastTimesMap = null; // save memory int rhDim = 2 * computeMaxSearchDistance() + 1; // e.g. coarse to fine search strategy if ((resultHistogram == null) || (resultHistogram.length != rhDim)) { resultHistogram = new int[rhDim][rhDim]; resultHistogramCount = 0; } checkNonGreedyRegionsAllocated(); } /** * * @param distResult * @return the confidence of the result. True means it's not good and should * be rejected, false means we should accept it. */ private synchronized boolean isNotSufficientlyAccurate(SADResult distResult) { boolean retVal = super.accuracyTests(); // check accuracy in super, if reject returns true // additional test, normalized blaock distance must be small enough // distance has max value 1 if (distResult.sadValue >= maxAllowedSadDistance) { retVal = true; } return retVal; } /** * @return the skipProcessingEventsCount */ public int getSkipProcessingEventsCount() { return skipProcessingEventsCount; } /** * @param skipProcessingEventsCount the skipProcessingEventsCount to set */ public void setSkipProcessingEventsCount(int skipProcessingEventsCount) { int old = this.skipProcessingEventsCount; if (skipProcessingEventsCount < 0) { skipProcessingEventsCount = 0; } if (skipProcessingEventsCount > MAX_SKIP_COUNT) { skipProcessingEventsCount = MAX_SKIP_COUNT; } this.skipProcessingEventsCount = skipProcessingEventsCount; getSupport().firePropertyChange("skipProcessingEventsCount", old, this.skipProcessingEventsCount); putInt("skipProcessingEventsCount", skipProcessingEventsCount); } /** * @return the displayResultHistogram */ public boolean isDisplayResultHistogram() { return displayResultHistogram; } /** * @param displayResultHistogram the displayResultHistogram to set */ public void setDisplayResultHistogram(boolean displayResultHistogram) { this.displayResultHistogram = displayResultHistogram; putBoolean("displayResultHistogram", displayResultHistogram); } /** * @return the adaptiveEventSkipping */ public boolean isAdaptiveEventSkipping() { return adaptiveEventSkipping; } /** * @param adaptiveEventSkipping the adaptiveEventSkipping to set */ synchronized public void setAdaptiveEventSkipping(boolean adaptiveEventSkipping) { boolean old = this.adaptiveEventSkipping; this.adaptiveEventSkipping = adaptiveEventSkipping; putBoolean("adaptiveEventSkipping", adaptiveEventSkipping); if (adaptiveEventSkipping && adaptiveEventSkippingUpdateCounterLPFilter != null) { adaptiveEventSkippingUpdateCounterLPFilter.reset(); } getSupport().firePropertyChange("adaptiveEventSkipping", old, this.adaptiveEventSkipping); } public boolean isOutputSearchErrorInfo() { return outputSearchErrorInfo; } public boolean isShowBlockMatches() { return showBlockMatches; } /** * @param showBlockMatches * @param showBlockMatches the option of displaying bitmap */ synchronized public void setShowBlockMatches(boolean showBlockMatches) { boolean old = this.showBlockMatches; this.showBlockMatches = showBlockMatches; putBoolean("showBlockMatches", showBlockMatches); getSupport().firePropertyChange("showBlockMatches", old, this.showBlockMatches); } public boolean isShowSlices() { return showSlices; } /** * @param showSlices * @param showSlices the option of displaying bitmap */ synchronized public void setShowSlices(boolean showSlices) { boolean old = this.showSlices; this.showSlices = showSlices; getSupport().firePropertyChange("showSlices", old, this.showSlices); putBoolean("showSlices", showSlices); } synchronized public void setOutputSearchErrorInfo(boolean outputSearchErrorInfo) { this.outputSearchErrorInfo = outputSearchErrorInfo; if (!outputSearchErrorInfo) { searchMethod = SearchMethod.valueOf(getString("searchMethod", SearchMethod.FullSearch.toString())); // make sure method is reset } } private LowpassFilter adaptiveEventSkippingUpdateCounterLPFilter = null; private int adaptiveEventSkippingUpdateCounter = 0; private void adaptEventSkipping() { if (!adaptiveEventSkipping) { return; } if (chip.getAeViewer() == null) { return; } int old = skipProcessingEventsCount; if (chip.getAeViewer().isPaused() || chip.getAeViewer().isSingleStep()) { skipProcessingEventsCount = 0; getSupport().firePropertyChange("skipProcessingEventsCount", old, this.skipProcessingEventsCount); } if (adaptiveEventSkippingUpdateCounterLPFilter == null) { adaptiveEventSkippingUpdateCounterLPFilter = new LowpassFilter(chip.getAeViewer().getFrameRater().FPS_LOWPASS_FILTER_TIMECONSTANT_MS); } final float averageFPS = chip.getAeViewer().getFrameRater().getAverageFPS(); final int frameRate = chip.getAeViewer().getDesiredFrameRate(); boolean skipMore = averageFPS < (int) (0.75f * frameRate); boolean skipLess = averageFPS > (int) (0.25f * frameRate); float newSkipCount = skipProcessingEventsCount; if (skipMore) { newSkipCount = adaptiveEventSkippingUpdateCounterLPFilter.filter(1 + (skipChangeFactor * skipProcessingEventsCount), 1000 * (int) System.currentTimeMillis()); } else if (skipLess) { newSkipCount = adaptiveEventSkippingUpdateCounterLPFilter.filter((skipProcessingEventsCount / skipChangeFactor) - 1, 1000 * (int) System.currentTimeMillis()); } skipProcessingEventsCount = Math.round(newSkipCount); if (skipProcessingEventsCount > MAX_SKIP_COUNT) { skipProcessingEventsCount = MAX_SKIP_COUNT; } else if (skipProcessingEventsCount < 0) { skipProcessingEventsCount = 0; } getSupport().firePropertyChange("skipProcessingEventsCount", old, this.skipProcessingEventsCount); } /** * @return the adaptiveSliceDuration */ public boolean isAdaptiveSliceDuration() { return adaptiveSliceDuration; } /** * @param adaptiveSliceDuration the adaptiveSliceDuration to set */ synchronized public void setAdaptiveSliceDuration(boolean adaptiveSliceDuration) { boolean old = this.adaptiveSliceDuration; this.adaptiveSliceDuration = adaptiveSliceDuration; putBoolean("adaptiveSliceDuration", adaptiveSliceDuration); if (adaptiveSliceDurationLogging) { if (adaptiveSliceDurationLogger == null) { adaptiveSliceDurationLogger = new TobiLogger("PatchMatchFlow-SliceDurationControl", "slice duration or event count control logging"); adaptiveSliceDurationLogger.setColumnHeaderLine("eventTsSec\tpacketNumber\tpacketEvenNumber\tavgMatchDistance\tmatchRadiusError\tglobalTranslationSpeedPPS\tsliceDurationUs\tsliceEventCount"); adaptiveSliceDurationLogger.setSeparator("\t"); } adaptiveSliceDurationLogger.setEnabled(adaptiveSliceDuration); } getSupport().firePropertyChange("adaptiveSliceDuration", old, this.adaptiveSliceDuration); } /** * @return the processingTimeLimitMs */ public int getProcessingTimeLimitMs() { return processingTimeLimitMs; } /** * @param processingTimeLimitMs the processingTimeLimitMs to set */ public void setProcessingTimeLimitMs(int processingTimeLimitMs) { this.processingTimeLimitMs = processingTimeLimitMs; putInt("processingTimeLimitMs", processingTimeLimitMs); } /** * clears all scales for a particular time slice * * @param slice [scale][x][y] */ private void clearSlice(byte[][][] slice) { for (byte[][] scale : slice) { // for each scale for (byte[] row : scale) { // for each col Arrays.fill(row, (byte) 0); // fill col } } } private int dim = blockDimension + (2 * searchDistance); /** * Draws the block matching bitmap * * @param x * @param y * @param dx * @param dy * @param refBlock * @param searchBlock * @param subSampleBy */ synchronized private void drawMatching(SADResult result, PolarityEvent ein, byte[][][][] slices, float[] sadVals, int[] dxInitVals, int[] dyInitVals) { // synchronized private void drawMatching(int x, int y, int dx, int dy, byte[][] refBlock, byte[][] searchBlock, int subSampleBy) { for (int dispIdx = 0; dispIdx < numScales; dispIdx++) { int x = ein.x >> dispIdx, y = ein.y >> dispIdx; int dx = (int) result.dx >> dispIdx, dy = (int) result.dy >> dispIdx; byte[][] refBlock = slices[sliceIndex(1)][dispIdx], searchBlock = slices[sliceIndex(2)][dispIdx]; int subSampleBy = dispIdx; Legend sadLegend = null; final int refRadius = (blockDimension / 2) << (numScales - 1 - dispIdx); int dimNew = refRadius * 2 + 1 + (2 * (searchDistance)); if (blockMatchingFrame[dispIdx] == null) { String windowName = "Ref Block " + dispIdx; blockMatchingFrame[dispIdx] = new JFrame(windowName); blockMatchingFrame[dispIdx].setLayout(new BoxLayout(blockMatchingFrame[dispIdx].getContentPane(), BoxLayout.Y_AXIS)); blockMatchingFrame[dispIdx].setPreferredSize(new Dimension(600, 600)); JPanel panel = new JPanel(); panel.setLayout(new BoxLayout(panel, BoxLayout.X_AXIS)); blockMatchingImageDisplay[dispIdx] = ImageDisplay.createOpenGLCanvas(); blockMatchingImageDisplay[dispIdx].setBorderSpacePixels(10); blockMatchingImageDisplay[dispIdx].setImageSize(dimNew, dimNew); blockMatchingImageDisplay[dispIdx].setSize(200, 200); blockMatchingImageDisplay[dispIdx].setGrayValue(0); blockMatchingDisplayLegend[dispIdx] = blockMatchingImageDisplay[dispIdx].addLegend(LEGEND_G_SEARCH_AREA_R_REF_BLOCK_AREA_B_BEST_MATCH, 0, dim); panel.add(blockMatchingImageDisplay[dispIdx]); blockMatchingFrame[dispIdx].getContentPane().add(panel); blockMatchingFrame[dispIdx].pack(); blockMatchingFrame[dispIdx].addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { setShowBlockMatches(false); } }); } if (!blockMatchingFrame[dispIdx].isVisible()) { blockMatchingFrame[dispIdx].setVisible(true); } if (blockMatchingFrameTarget[dispIdx] == null) { String windowName = "Target Block " + dispIdx; blockMatchingFrameTarget[dispIdx] = new JFrame(windowName); blockMatchingFrameTarget[dispIdx].setLayout(new BoxLayout(blockMatchingFrameTarget[dispIdx].getContentPane(), BoxLayout.Y_AXIS)); blockMatchingFrameTarget[dispIdx].setPreferredSize(new Dimension(600, 600)); JPanel panel = new JPanel(); panel.setLayout(new BoxLayout(panel, BoxLayout.X_AXIS)); blockMatchingImageDisplayTarget[dispIdx] = ImageDisplay.createOpenGLCanvas(); blockMatchingImageDisplayTarget[dispIdx].setBorderSpacePixels(10); blockMatchingImageDisplayTarget[dispIdx].setImageSize(dimNew, dimNew); blockMatchingImageDisplayTarget[dispIdx].setSize(200, 200); blockMatchingImageDisplayTarget[dispIdx].setGrayValue(0); blockMatchingDisplayLegendTarget[dispIdx] = blockMatchingImageDisplayTarget[dispIdx].addLegend(LEGEND_G_SEARCH_AREA_R_REF_BLOCK_AREA_B_BEST_MATCH, 0, dim); panel.add(blockMatchingImageDisplayTarget[dispIdx]); blockMatchingFrameTarget[dispIdx].getContentPane().add(panel); blockMatchingFrameTarget[dispIdx].pack(); blockMatchingFrameTarget[dispIdx].addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { setShowBlockMatches(false); } }); } if (!blockMatchingFrameTarget[dispIdx].isVisible()) { blockMatchingFrameTarget[dispIdx].setVisible(true); } final int radius = (refRadius) + searchDistance; float scale = 1f / getSliceMaxValue(); try { // if ((x >= radius) && ((x + radius) < subSizeX) // && (y >= radius) && ((y + radius) < subSizeY)) { if (dimNew != blockMatchingImageDisplay[dispIdx].getWidth()) { dim = dimNew; blockMatchingImageDisplay[dispIdx].setImageSize(dimNew, dimNew); blockMatchingImageDisplay[dispIdx].clearLegends(); blockMatchingDisplayLegend[dispIdx] = blockMatchingImageDisplay[dispIdx].addLegend(LEGEND_G_SEARCH_AREA_R_REF_BLOCK_AREA_B_BEST_MATCH, 0, dim); } if (dimNew != blockMatchingImageDisplayTarget[dispIdx].getWidth()) { dim = dimNew; blockMatchingImageDisplayTarget[dispIdx].setImageSize(dimNew, dimNew); blockMatchingImageDisplayTarget[dispIdx].clearLegends(); blockMatchingDisplayLegendTarget[dispIdx] = blockMatchingImageDisplayTarget[dispIdx].addLegend(LEGEND_G_SEARCH_AREA_R_REF_BLOCK_AREA_B_BEST_MATCH, 0, dim); } // TextRenderer textRenderer = new TextRenderer(new Font("SansSerif", Font.PLAIN, 12)); if (blockMatchingDisplayLegend[dispIdx] != null) { blockMatchingDisplayLegend[dispIdx].setLegendString("R: ref block area" + "\nScale: " + subSampleBy + "\nSAD: " + engFmt.format(sadVals[dispIdx]) + "\nTimestamp: " + ein.timestamp); } if (blockMatchingDisplayLegendTarget[dispIdx] != null) { blockMatchingDisplayLegendTarget[dispIdx].setLegendString("G: search area" + "\nx: " + ein.x + "\ny: " + ein.y + "\ndx_init: " + dxInitVals[dispIdx] + "\ndy_init: " + dyInitVals[dispIdx]); } /* Reset the image first */ blockMatchingImageDisplay[dispIdx].clearImage(); blockMatchingImageDisplayTarget[dispIdx].clearImage(); /* Rendering the reference patch in t-imuWarningDialog slice, it's on the center with color red */ for (int i = searchDistance; i < (refRadius * 2 + 1 + searchDistance); i++) { for (int j = searchDistance; j < (refRadius * 2 + 1 + searchDistance); j++) { float[] f = blockMatchingImageDisplay[dispIdx].getPixmapRGB(i, j); // Scale the pixel value to make it brighter for finer scale slice. f[0] = (1 << (numScales - 1 - dispIdx)) * scale * Math.abs(refBlock[((x - (refRadius)) + i) - searchDistance][((y - (refRadius)) + j) - searchDistance]); blockMatchingImageDisplay[dispIdx].setPixmapRGB(i, j, f); } } /* Rendering the area within search distance in t-2d slice, it's full of the whole search area with color green */ for (int i = 0; i < ((2 * radius) + 1); i++) { for (int j = 0; j < ((2 * radius) + 1); j++) { float[] f = blockMatchingImageDisplayTarget[dispIdx].getPixmapRGB(i, j); f[1] = scale * Math.abs(searchBlock[(x - dxInitVals[dispIdx] - radius) + i][(y - dyInitVals[dispIdx] - radius) + j]); blockMatchingImageDisplayTarget[dispIdx].setPixmapRGB(i, j, f); } } /* Rendering the best matching patch in t-2d slice, it's on the shifted position related to the center location with color blue */ // for (int i = searchDistance + dx; i < (blockDimension + searchDistance + dx); i++) { // for (int j = searchDistance + dy; j < (blockDimension + searchDistance + dy); j++) { // float[] f = blockMatchingImageDisplayTarget[dispIdx].getPixmapRGB(i, j); // f[2] = scale * Math.abs(searchBlock[((x - (blockDimension / 2)) + i) - searchDistance][((y - (blockDimension / 2)) + j) - searchDistance]); // blockMatchingImageDisplayTarget[dispIdx].setPixmapRGB(i, j, f); } } catch (ArrayIndexOutOfBoundsException e) { } blockMatchingImageDisplay[dispIdx].repaint(); blockMatchingImageDisplayTarget[dispIdx].repaint(); } } synchronized private void drawTimeStampBlock(PolarityEvent ein) { int dim = 11; int sliceScale = 2; int eX = ein.x >> sliceScale, eY = ein.y >> sliceScale, eType = ein.type; if (timeStampBlockFrame == null) { String windowName = "FASTCornerBlock"; timeStampBlockFrame = new JFrame(windowName); timeStampBlockFrame.setLayout(new BoxLayout(timeStampBlockFrame.getContentPane(), BoxLayout.Y_AXIS)); timeStampBlockFrame.setPreferredSize(new Dimension(600, 600)); JPanel panel = new JPanel(); panel.setLayout(new BoxLayout(panel, BoxLayout.X_AXIS)); timeStampBlockImageDisplay = ImageDisplay.createOpenGLCanvas(); timeStampBlockImageDisplay.setBorderSpacePixels(10); timeStampBlockImageDisplay.setImageSize(dim, dim); timeStampBlockImageDisplay.setSize(200, 200); timeStampBlockImageDisplay.setGrayValue(0); timeStampBlockImageDisplayLegend = timeStampBlockImageDisplay.addLegend(LEGEND_G_SEARCH_AREA_R_REF_BLOCK_AREA_B_BEST_MATCH, 0, dim); panel.add(timeStampBlockImageDisplay); timeStampBlockFrame.getContentPane().add(panel); timeStampBlockFrame.pack(); timeStampBlockFrame.addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { setShowSlices(false); } }); } if (!timeStampBlockFrame.isVisible()) { timeStampBlockFrame.setVisible(true); } timeStampBlockImageDisplay.clearImage(); for (int i = 0; i < innerCircleSize; i++) { xInnerOffset[i] = innerCircle[i][0]; yInnerOffset[i] = innerCircle[i][1]; innerTsValue[i] = lastTimesMap[eX + xInnerOffset[i]][eY + yInnerOffset[i]][type]; innerTsValue[i] = slices[sliceIndex(1)][sliceScale][eX + xInnerOffset[i]][eY + yInnerOffset[i]]; if (innerTsValue[i] == 0x80000000) { innerTsValue[i] = 0; } } for (int i = 0; i < outerCircleSize; i++) { xOuterOffset[i] = outerCircle[i][0]; yOuterOffset[i] = outerCircle[i][1]; outerTsValue[i] = lastTimesMap[eX + xOuterOffset[i]][eY + yOuterOffset[i]][type]; outerTsValue[i] = slices[sliceIndex(1)][sliceScale][eX + xOuterOffset[i]][eY + yOuterOffset[i]]; if (outerTsValue[i] == 0x80000000) { outerTsValue[i] = 0; } } List innerList = Arrays.asList(ArrayUtils.toObject(innerTsValue)); int innerMax = (int) Collections.max(innerList); int innerMin = (int) Collections.min(innerList); float innerScale = 1f / (innerMax - innerMin); List outerList = Arrays.asList(ArrayUtils.toObject(outerTsValue)); int outerMax = (int) Collections.max(outerList); int outerMin = (int) Collections.min(outerList); float outerScale = 1f / (outerMax - outerMin); float scale = 1f / getSliceMaxValue(); timeStampBlockImageDisplay.setPixmapRGB(dim / 2, dim / 2, 0, lastTimesMap[eX][eY][type] * scale, 0); timeStampBlockImageDisplay.setPixmapRGB(dim / 2, dim / 2, 0, slices[sliceIndex(1)][sliceScale][eX][eY] * scale, 0); for (int i = 0; i < innerCircleSize; i++) { timeStampBlockImageDisplay.setPixmapRGB(xInnerOffset[i] + dim / 2, yInnerOffset[i] + dim / 2, innerScale * (innerTsValue[i] - innerMin), 0, 0); timeStampBlockImageDisplay.setPixmapRGB(xInnerOffset[i] + dim / 2, yInnerOffset[i] + dim / 2, scale * (innerTsValue[i]), 0, 0); } for (int i = 0; i < outerCircleSize; i++) { timeStampBlockImageDisplay.setPixmapRGB(xOuterOffset[i] + dim / 2, yOuterOffset[i] + dim / 2, 0, 0, outerScale * (outerTsValue[i] - outerMin)); timeStampBlockImageDisplay.setPixmapRGB(xOuterOffset[i] + dim / 2, yOuterOffset[i] + dim / 2, 0, 0, scale * (outerTsValue[i])); } if (timeStampBlockImageDisplayLegend != null) { timeStampBlockImageDisplayLegend.setLegendString(TIME_STAMP_BLOCK_LEGEND_SLICES); } timeStampBlockImageDisplay.repaint(); } private void drawSlices(byte[][][][] slices) { // log.info("drawing slices"); if (sliceBitMapFrame == null) { String windowName = "Slices"; sliceBitMapFrame = new JFrame(windowName); sliceBitMapFrame.setLayout(new BoxLayout(sliceBitMapFrame.getContentPane(), BoxLayout.Y_AXIS)); sliceBitMapFrame.setPreferredSize(new Dimension(600, 600)); JPanel panel = new JPanel(); panel.setLayout(new BoxLayout(panel, BoxLayout.X_AXIS)); sliceBitmapImageDisplay = ImageDisplay.createOpenGLCanvas(); sliceBitmapImageDisplay.setBorderSpacePixels(10); sliceBitmapImageDisplay.setImageSize(sizex >> showSlicesScale, sizey >> showSlicesScale); sliceBitmapImageDisplay.setSize(200, 200); sliceBitmapImageDisplay.setGrayValue(0); sliceBitmapImageDisplayLegend = sliceBitmapImageDisplay.addLegend(LEGEND_G_SEARCH_AREA_R_REF_BLOCK_AREA_B_BEST_MATCH, 0, dim); panel.add(sliceBitmapImageDisplay); sliceBitMapFrame.getContentPane().add(panel); sliceBitMapFrame.pack(); sliceBitMapFrame.addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { setShowSlices(false); } }); } if (!sliceBitMapFrame.isVisible()) { sliceBitMapFrame.setVisible(true); } int dimNewX = sizex >> showSlicesScale; int dimNewY = sizey >> showSlicesScale; if (dimNewX != sliceBitmapImageDisplay.getWidth() || dimNewY != sliceBitmapImageDisplay.getHeight()) { sliceBitmapImageDisplay.setImageSize(dimNewX, dimNewY); sliceBitmapImageDisplay.clearLegends(); sliceBitmapImageDisplayLegend = sliceBitmapImageDisplay.addLegend(LEGEND_G_SEARCH_AREA_R_REF_BLOCK_AREA_B_BEST_MATCH, 0, dim); } float scale = 1f / getSliceMaxValue(); sliceBitmapImageDisplay.clearImage(); int d1 = sliceIndex(1), d2 = sliceIndex(2); if (showSlicesScale >= numScales) { showSlicesScale = numScales - 1; } int imageSizeX = sizex >> showSlicesScale; int imageSizeY = sizey >> showSlicesScale; byte[] grayImageBuffer = new byte[imageSizeX * imageSizeY]; for (int slice = 1; slice <= 2; slice++) { for (int x = 0; x < imageSizeX; x++) { for (int y = 0; y < imageSizeY; y++) { int pixelValue1 = slices[d1][showSlicesScale][x][y]; int pixelValue2 = slices[d2][showSlicesScale][x][y]; sliceBitmapImageDisplay.setPixmapRGB(x, y, scale * pixelValue1, scale * pixelValue2, 0); // The minimum of byte is ox0(0), the maximum is 0xFF(-1); // It is from 0 to 127 and then -128 to -1; int imagePixelVal = (int) (pixelValue1 * 255.0f / getSliceMaxValue() + 128) + (int) (pixelValue2 * 255.0f / getSliceMaxValue()); if (imagePixelVal == 0) { imagePixelVal = 0; // Background } grayImageBuffer[(imageSizeY - 1 - y) * imageSizeX + x] = (byte) imagePixelVal; } } } final BufferedImage theImage = new BufferedImage(imageSizeX, imageSizeY, BufferedImage.TYPE_BYTE_GRAY); theImage.getRaster().setDataElements(0, 0, imageSizeX, imageSizeY, grayImageBuffer); if (saveSliceGrayImage) { final Date d = new Date(); final String PNG = "png"; // final String fn = "EventSlice-" + AEDataFile.DATE_FORMAT.format(d) + "." + PNG; final String fn = "EventSlice-" + sliceEndTimeUs[d1] + "." + PNG; // if user is playing a file, use folder that file lives in String userDir = Paths.get(".").toAbsolutePath().normalize().toString(); File eventSliceDir = new File(userDir + File.separator + "EventSlices" + File.separator + getChip().getAeInputStream().getFile().getName()); if (!eventSliceDir.exists()) { eventSliceDir.mkdirs(); } File outputfile = new File(eventSliceDir + File.separator + fn); try { ImageIO.write(theImage, "png", outputfile); } catch (IOException ex) { Logger.getLogger(PatchMatchFlow.class.getName()).log(Level.SEVERE, null, ex); } saveSliceGrayImage = false; } if (sliceBitmapImageDisplayLegend != null) { sliceBitmapImageDisplayLegend.setLegendString(LEGEND_SLICES); } sliceBitmapImageDisplay.repaint(); } // /** // * @return the numSlices // */ // public int getNumSlices() { // return numSlices; // /** // * @param numSlices the numSlices to set // */ // synchronized public void setNumSlices(int numSlices) { // if (numSlices < 3) { // numSlices = 3; // } else if (numSlices > 8) { // numSlices = 8; // this.numSlices = numSlices; // putInt("numSlices", numSlices); /** * @return the sliceNumBits */ public int getSliceMaxValue() { return sliceMaxValue; } /** * @param sliceMaxValue the sliceMaxValue to set */ public void setSliceMaxValue(int sliceMaxValue) { int old = this.sliceMaxValue; if (sliceMaxValue < 1) { sliceMaxValue = 1; } else if (sliceMaxValue > 127) { sliceMaxValue = 127; } this.sliceMaxValue = sliceMaxValue; putInt("sliceMaxValue", sliceMaxValue); getSupport().firePropertyChange("sliceMaxValue", old, this.sliceMaxValue); } /** * @return the rectifyPolarties */ public boolean isRectifyPolarties() { return rectifyPolarties; } /** * @param rectifyPolarties the rectifyPolarties to set */ public void setRectifyPolarties(boolean rectifyPolarties) { boolean old = this.rectifyPolarties; this.rectifyPolarties = rectifyPolarties; putBoolean("rectifyPolarties", rectifyPolarties); getSupport().firePropertyChange("rectifyPolarties", old, this.rectifyPolarties); } /** * @return the useSubsampling */ public boolean isUseSubsampling() { return useSubsampling; } /** * @param useSubsampling the useSubsampling to set */ public void setUseSubsampling(boolean useSubsampling) { this.useSubsampling = useSubsampling; } /** * @return the numScales */ public int getNumScales() { return numScales; } /** * @param numScales the numScales to set */ synchronized public void setNumScales(int numScales) { int old = this.numScales; if (numScales < 1) { numScales = 1; } else if (numScales > 4) { numScales = 4; } this.numScales = numScales; putInt("numScales", numScales); setDefaultScalesToCompute(); scaleResultCounts = new int[numScales]; showBlockSizeAndSearchAreaTemporarily(); computeAveragePossibleMatchDistance(); getSupport().firePropertyChange("numScales", old, this.numScales); } /** * Computes pooled (summed) value of slice at location xx, yy, in subsampled * region around this point * * @param slice * @param x * @param y * @param subsampleBy pool over 1<<subsampleBy by 1<<subsampleBy area to sum * up the slice values @return */ private int pool(byte[][] slice, int x, int y, int subsampleBy) { if (subsampleBy == 0) { return slice[x][y]; } else { int n = 1 << subsampleBy; int sum = 0; for (int xx = x; xx < x + n + n; xx++) { for (int yy = y; yy < y + n + n; yy++) { if (xx >= subSizeX || yy >= subSizeY) { // log.warning("should not happen that xx="+xx+" or yy="+yy); continue; // TODO remove this check when iteration avoids this sum explictly } sum += slice[xx][yy]; } } return sum; } } /** * @return the scalesToCompute */ public String getScalesToCompute() { return scalesToCompute; } /** * @param scalesToCompute the scalesToCompute to set */ synchronized public void setScalesToCompute(String scalesToCompute) { this.scalesToCompute = scalesToCompute; if (scalesToCompute == null || scalesToCompute.isEmpty()) { setDefaultScalesToCompute(); } else { StringTokenizer st = new StringTokenizer(scalesToCompute, ", ", false); int n = st.countTokens(); if (n == 0) { setDefaultScalesToCompute(); } else { scalesToComputeArray = new Integer[n]; int i = 0; while (st.hasMoreTokens()) { try { int scale = Integer.parseInt(st.nextToken()); scalesToComputeArray[i++] = scale; } catch (NumberFormatException e) { log.warning("bad string in scalesToCompute field, use blank or 0,2 for example"); setDefaultScalesToCompute(); } } } } } private void setDefaultScalesToCompute() { scalesToComputeArray = new Integer[numScales]; for (int i = 0; i < numScales; i++) { scalesToComputeArray[i] = i; } } /** * @return the areaEventNumberSubsampling */ public int getAreaEventNumberSubsampling() { return areaEventNumberSubsampling; } /** * @param areaEventNumberSubsampling the areaEventNumberSubsampling to set */ synchronized public void setAreaEventNumberSubsampling(int areaEventNumberSubsampling) { int old = this.areaEventNumberSubsampling; if (areaEventNumberSubsampling < 3) { areaEventNumberSubsampling = 3; } else if (areaEventNumberSubsampling > 7) { areaEventNumberSubsampling = 7; } this.areaEventNumberSubsampling = areaEventNumberSubsampling; putInt("areaEventNumberSubsampling", areaEventNumberSubsampling); showAreasForAreaCountsTemporarily(); clearAreaCounts(); if (sliceMethod != SliceMethod.AreaEventNumber) { log.warning("AreaEventNumber method is not currently selected as sliceMethod"); } getSupport().firePropertyChange("areaEventNumberSubsampling", old, this.areaEventNumberSubsampling); } private void showAreasForAreaCountsTemporarily() { if (stopShowingStuffTask != null) { stopShowingStuffTask.cancel(); } stopShowingStuffTask = new TimerTask() { @Override public void run() { showBlockSizeAndSearchAreaTemporarily = false; // in case we are canceling a task that would clear this showAreaCountAreasTemporarily = false; } }; Timer showAreaCountsAreasTimer = new Timer(); showAreaCountAreasTemporarily = true; showAreaCountsAreasTimer.schedule(stopShowingStuffTask, SHOW_STUFF_DURATION_MS); } private void showBlockSizeAndSearchAreaTemporarily() { if (stopShowingStuffTask != null) { stopShowingStuffTask.cancel(); } stopShowingStuffTask = new TimerTask() { @Override public void run() { showAreaCountAreasTemporarily = false; // in case we are canceling a task that would clear this showBlockSizeAndSearchAreaTemporarily = false; } }; Timer showBlockSizeAndSearchAreaTimer = new Timer(); showBlockSizeAndSearchAreaTemporarily = true; showBlockSizeAndSearchAreaTimer.schedule(stopShowingStuffTask, SHOW_STUFF_DURATION_MS); } private void clearAreaCounts() { if (sliceMethod != SliceMethod.AreaEventNumber) { return; } if (areaCounts == null || areaCounts.length != 1 + (subSizeX >> areaEventNumberSubsampling)) { int nax = 1 + (subSizeX >> areaEventNumberSubsampling), nay = 1 + (subSizeY >> areaEventNumberSubsampling); numAreas = nax * nay; areaCounts = new int[nax][nay]; } else { for (int[] i : areaCounts) { Arrays.fill(i, 0); } } areaCountExceeded = false; } private void clearNonGreedyRegions() { if (!nonGreedyFlowComputingEnabled) { return; } checkNonGreedyRegionsAllocated(); nonGreedyRegionsCount = 0; for (boolean[] i : nonGreedyRegions) { Arrays.fill(i, false); } } private void checkNonGreedyRegionsAllocated() { if (nonGreedyRegions == null || nonGreedyRegions.length != 1 + (subSizeX >> areaEventNumberSubsampling)) { nonGreedyRegionsNumberOfRegions = (1 + (subSizeX >> areaEventNumberSubsampling)) * (1 + (subSizeY >> areaEventNumberSubsampling)); nonGreedyRegions = new boolean[1 + (subSizeX >> areaEventNumberSubsampling)][1 + (subSizeY >> areaEventNumberSubsampling)]; nonGreedyRegionsNumberOfRegions = (1 + (subSizeX >> areaEventNumberSubsampling)) * (1 + (subSizeY >> areaEventNumberSubsampling)); } } public int getSliceDeltaT() { return sliceDeltaT; } /** * @return the enableImuTimesliceLogging */ public boolean isEnableImuTimesliceLogging() { return enableImuTimesliceLogging; } /** * @param enableImuTimesliceLogging the enableImuTimesliceLogging to set */ public void setEnableImuTimesliceLogging(boolean enableImuTimesliceLogging) { this.enableImuTimesliceLogging = enableImuTimesliceLogging; if (enableImuTimesliceLogging) { if (imuTimesliceLogger == null) { imuTimesliceLogger = new TobiLogger("imuTimeslice.txt", "IMU rate gyro deg/s and patchmatch timeslice duration in ms"); imuTimesliceLogger.setColumnHeaderLine("systemtime(ms) timestamp(us) timeslice(us) rate(deg/s)"); imuTimesliceLogger.setSeparator(" "); } } imuTimesliceLogger.setEnabled(enableImuTimesliceLogging); } /** * @return the nonGreedyFlowComputingEnabled */ public boolean isNonGreedyFlowComputingEnabled() { return nonGreedyFlowComputingEnabled; } /** * @param nonGreedyFlowComputingEnabled the nonGreedyFlowComputingEnabled to * set */ synchronized public void setNonGreedyFlowComputingEnabled(boolean nonGreedyFlowComputingEnabled) { boolean old = this.nonGreedyFlowComputingEnabled; this.nonGreedyFlowComputingEnabled = nonGreedyFlowComputingEnabled; putBoolean("nonGreedyFlowComputingEnabled", nonGreedyFlowComputingEnabled); if (nonGreedyFlowComputingEnabled) { clearNonGreedyRegions(); } getSupport().firePropertyChange("nonGreedyFlowComputingEnabled", old, nonGreedyFlowComputingEnabled); } /** * @return the nonGreedyFractionToBeServiced */ public float getNonGreedyFractionToBeServiced() { return nonGreedyFractionToBeServiced; } /** * @param nonGreedyFractionToBeServiced the nonGreedyFractionToBeServiced to * set */ public void setNonGreedyFractionToBeServiced(float nonGreedyFractionToBeServiced) { this.nonGreedyFractionToBeServiced = nonGreedyFractionToBeServiced; putFloat("nonGreedyFractionToBeServiced", nonGreedyFractionToBeServiced); } /** * @return the adapativeSliceDurationProportionalErrorGain */ public float getAdapativeSliceDurationProportionalErrorGain() { return adapativeSliceDurationProportionalErrorGain; } /** * @param adapativeSliceDurationProportionalErrorGain the * adapativeSliceDurationProportionalErrorGain to set */ public void setAdapativeSliceDurationProportionalErrorGain(float adapativeSliceDurationProportionalErrorGain) { this.adapativeSliceDurationProportionalErrorGain = adapativeSliceDurationProportionalErrorGain; putFloat("adapativeSliceDurationProportionalErrorGain", adapativeSliceDurationProportionalErrorGain); } /** * @return the adapativeSliceDurationUseProportionalControl */ public boolean isAdapativeSliceDurationUseProportionalControl() { return adapativeSliceDurationUseProportionalControl; } /** * @param adapativeSliceDurationUseProportionalControl the * adapativeSliceDurationUseProportionalControl to set */ public void setAdapativeSliceDurationUseProportionalControl(boolean adapativeSliceDurationUseProportionalControl) { this.adapativeSliceDurationUseProportionalControl = adapativeSliceDurationUseProportionalControl; putBoolean("adapativeSliceDurationUseProportionalControl", adapativeSliceDurationUseProportionalControl); } public boolean isPrintScaleCntStatEnabled() { return printScaleCntStatEnabled; } public void setPrintScaleCntStatEnabled(boolean printScaleCntStatEnabled) { this.printScaleCntStatEnabled = printScaleCntStatEnabled; putBoolean("printScaleCntStatEnabled", printScaleCntStatEnabled); } /** * @return the showSlicesScale */ public int getShowSlicesScale() { return showSlicesScale; } /** * @param showSlicesScale the showSlicesScale to set */ public void setShowSlicesScale(int showSlicesScale) { if (showSlicesScale < 0) { showSlicesScale = 0; } else if (showSlicesScale > numScales - 1) { showSlicesScale = numScales - 1; } this.showSlicesScale = showSlicesScale; } public int getSliceDurationMinLimitUS() { return sliceDurationMinLimitUS; } public void setSliceDurationMinLimitUS(int sliceDurationMinLimitUS) { this.sliceDurationMinLimitUS = sliceDurationMinLimitUS; putInt("sliceDurationMinLimitUS", sliceDurationMinLimitUS); } public int getSliceDurationMaxLimitUS() { return sliceDurationMaxLimitUS; } public void setSliceDurationMaxLimitUS(int sliceDurationMaxLimitUS) { this.sliceDurationMaxLimitUS = sliceDurationMaxLimitUS; putInt("sliceDurationMaxLimitUS", sliceDurationMaxLimitUS); } public boolean isShowCorners() { return showCorners; } public void setShowCorners(boolean showCorners) { this.showCorners = showCorners; putBoolean("showCorners", showCorners); } public boolean isHWABMOFEnabled() { return HWABMOFEnabled; } public void setHWABMOFEnabled(boolean HWABMOFEnabled) { this.HWABMOFEnabled = HWABMOFEnabled; } public boolean isCalcOFonCornersEnabled() { return calcOFonCornersEnabled; } public void setCalcOFonCornersEnabled(boolean calcOFonCornersEnabled) { this.calcOFonCornersEnabled = calcOFonCornersEnabled; putBoolean("calcOFonCornersEnabled", calcOFonCornersEnabled); } public float getCornerThr() { return cornerThr; } public void setCornerThr(float cornerThr) { this.cornerThr = cornerThr; if (this.cornerThr > 1) { this.cornerThr = 1; } putFloat("cornerThr", cornerThr); } public CornerCircleSelection getCornerCircleSelection() { return cornerCircleSelection; } public void setCornerCircleSelection(CornerCircleSelection cornerCircleSelection) { CornerCircleSelection old = this.cornerCircleSelection; this.cornerCircleSelection = cornerCircleSelection; putString("cornerCircleSelection", cornerCircleSelection.toString()); getSupport().firePropertyChange("cornerCircleSelection", old, this.cornerCircleSelection); } synchronized public void doStartRecordingForEDFLOW() { JFileChooser c = new JFileChooser(lastFileName); c.setFileFilter(new FileFilter() { public boolean accept(File f) { return f.isDirectory() || f.getName().toLowerCase().endsWith(".txt"); } public String getDescription() { return "text file"; } }); c.setSelectedFile(new File(lastFileName)); int ret = c.showSaveDialog(null); if (ret != JFileChooser.APPROVE_OPTION) { return; } String basename = c.getSelectedFile().toString(); if (basename.toLowerCase().endsWith(".txt")) { basename = basename.substring(0, basename.length() - 4); } lastFileName = basename; putString("lastFileName", lastFileName); String fn = basename + "-OFResult.txt"; try { dvsWriter = new PrintWriter(new File(fn)); } catch (FileNotFoundException ex) { Logger.getLogger(PatchMatchFlow.class.getName()).log(Level.SEVERE, null, ex); } dvsWriter.println("# created " + new Date().toString()); dvsWriter.println("# source-file: " + (chip.getAeInputStream() != null ? chip.getAeInputStream().getFile().toString() : "(live input)")); dvsWriter.println("# dvs-events: One event per line: timestamp(us) x y polarity(0=off,1=on) dx dy OFRetValid rotateFlg SFAST"); } synchronized public void doStopRecordingForEDFLOW() { dvsWriter.close(); dvsWriter = null; } // This is the BFAST (or SFAST in paper) corner dector. EFAST refer to HWCornerPointRender boolean PatchFastDetectorisFeature(PolarityEvent ein) { boolean found_streak = false; boolean found_streak_inner = false, found_streak_outer = false; int innerI = 0, outerI = 0, innerStreakSize = 0, outerStreakSize = 0; int scale = numScales - 1; int pix_x = ein.x >> scale; int pix_y = ein.y >> scale; byte featureSlice[][] = slices[sliceIndex(1)][scale]; int circle3_[][] = innerCircle; int circle4_[][] = outerCircle; final int innerSize = circle3_.length; final int outerSize = circle4_.length; int innerStartX = 0, innerEndX = 0, innerStartY = 0, innerEndY = 0; int outerStartX, outerEndX, outerStartY, outerEndY; // only check if not too close to border if (pix_x < 4 || pix_x >= (getChip().getSizeX() >> scale) - 4 || pix_y < 4 || pix_y >= (getChip().getSizeY() >> scale) - 4) { found_streak = false; return found_streak; } found_streak_inner = false; boolean exit_inner_loop = false; int centerValue = 0; int xInnerOffset[] = new int[innerCircleSize]; int yInnerOffset[] = new int[innerCircleSize]; // int innerTsValue[] = new int[innerCircleSize]; for (int i = 0; i < innerCircleSize; i++) { xInnerOffset[i] = innerCircle[i][0]; yInnerOffset[i] = innerCircle[i][1]; innerTsValue[i] = featureSlice[pix_x + xInnerOffset[i]][pix_y + yInnerOffset[i]]; } int xOuterOffset[] = new int[outerCircleSize]; int yOuterOffset[] = new int[outerCircleSize]; // int outerTsValue[] = new int[outerCircleSize]; for (int i = 0; i < outerCircleSize; i++) { xOuterOffset[i] = outerCircle[i][0]; yOuterOffset[i] = outerCircle[i][1]; outerTsValue[i] = featureSlice[pix_x + xOuterOffset[i]][pix_y + yOuterOffset[i]]; } isFeatureOutterLoop: for (int i = 0; i < innerSize; i++) { FastDetectorisFeature_label2: for (int streak_size = innerCircleSize - 1; streak_size >= 2; streak_size = streak_size - 1) { // check that streak event is larger than neighbor if (Math.abs(featureSlice[pix_x + circle3_[i][0]][pix_y + circle3_[i][1]] - centerValue) < Math.abs(featureSlice[pix_x + circle3_[(i - 1 + innerSize) % innerSize][0]][pix_y + circle3_[(i - 1 + innerSize) % innerSize][1]] - centerValue)) { continue; } // check that streak event is larger than neighbor if (Math.abs(featureSlice[pix_x + circle3_[(i + streak_size - 1) % innerSize][0]][pix_y + circle3_[(i + streak_size - 1) % innerSize][1]] - centerValue) < Math.abs(featureSlice[pix_x + circle3_[(i + streak_size) % innerSize][0]][pix_y + circle3_[(i + streak_size) % innerSize][1]] - centerValue)) { continue; } // find the smallest timestamp in corner min_t double min_t = Math.abs(featureSlice[pix_x + circle3_[i][0]][pix_y + circle3_[i][1]] - centerValue); FastDetectorisFeature_label1: for (int j = 1; j < streak_size; j++) { final double tj = Math.abs(featureSlice[pix_x + circle3_[(i + j) % innerSize][0]][pix_y + circle3_[(i + j) % innerSize][1]] - centerValue); if (tj < min_t) { min_t = tj; } } //check if corner timestamp is higher than corner boolean did_break = false; double max_t = featureSlice[pix_x + circle3_[(i + streak_size) % innerSize][0]][pix_y + circle3_[(i + streak_size) % innerSize][1]]; FastDetectorisFeature_label0: for (int j = streak_size; j < innerSize; j++) { final double tj = Math.abs(featureSlice[pix_x + circle3_[(i + j) % innerSize][0]][pix_y + circle3_[(i + j) % innerSize][1]] - centerValue); if (tj > max_t) { max_t = tj; } if (tj >= min_t - cornerThr * getSliceMaxValue()) { did_break = true; break; } } // The maximum value of the non-streak is on the border, remove it. if (!did_break) { if ((max_t >= 7) && (max_t == featureSlice[pix_x + circle3_[(i + streak_size) % innerSize][0]][pix_y + circle3_[(i + streak_size) % innerSize][1]] || max_t == featureSlice[pix_x + circle3_[(i + innerSize - 1) % innerSize][0]][pix_y + circle3_[(i + innerSize - 1) % innerSize][1]])) { // did_break = true; } } if (!did_break) { innerI = i; innerStreakSize = streak_size; innerStartX = innerCircle[innerI % innerSize][0]; innerEndX = innerCircle[(innerI + innerStreakSize - 1) % innerSize][0]; innerStartY = innerCircle[innerI % innerSize][1]; innerEndY = innerCircle[(innerI + innerStreakSize - 1) % innerSize][1]; int condDiff = (streak_size % 2 == 1) ? 0 : 1; // If streak_size is even, then set it to 1. Otherwise 0. if ((streak_size == innerCircleSize - 1) || Math.abs(innerStartX - innerEndX) <= condDiff || Math.abs(innerStartY - innerEndY) <= condDiff // || featureSlice[pix_x + innerStartX][pix_y + innerEndX] < 12 // || featureSlice[pix_x + innerEndX][pix_y + innerEndY] < 12 ) { found_streak_inner = false; } else { found_streak_inner = true; } exit_inner_loop = true; break; } } if (found_streak_inner || exit_inner_loop) { break; } } found_streak_outer = false; // if (found_streak) { found_streak_outer = false; boolean exit_outer_loop = false; FastDetectorisFeature_label6: for (int streak_size = outerCircleSize - 1; streak_size >= 3; streak_size FastDetectorisFeature_label5: for (int i = 0; i < outerSize; i++) { // check that first event is larger than neighbor if (Math.abs(featureSlice[pix_x + circle4_[i][0]][pix_y + circle4_[i][1]] - centerValue) < Math.abs(featureSlice[pix_x + circle4_[(i - 1 + outerSize) % outerSize][0]][pix_y + circle4_[(i - 1 + outerSize) % outerSize][1]] - centerValue)) { continue; } // check that streak event is larger than neighbor if (Math.abs(featureSlice[pix_x + circle4_[(i + streak_size - 1) % outerSize][0]][pix_y + circle4_[(i + streak_size - 1) % outerSize][1]] - centerValue) < Math.abs(featureSlice[pix_x + circle4_[(i + streak_size) % outerSize][0]][pix_y + circle4_[(i + streak_size) % outerSize][1]] - centerValue)) { continue; } double min_t = Math.abs(featureSlice[pix_x + circle4_[i][0]][pix_y + circle4_[i][1]] - centerValue); FastDetectorisFeature_label4: for (int j = 1; j < streak_size; j++) { final double tj = Math.abs(featureSlice[pix_x + circle4_[(i + j) % outerSize][0]][pix_y + circle4_[(i + j) % outerSize][1]] - centerValue); if (tj < min_t) { min_t = tj; } } boolean did_break = false; double max_t = featureSlice[pix_x + circle4_[(i + streak_size) % outerSize][0]][pix_y + circle4_[(i + streak_size) % outerSize][1]]; float thr = cornerThr * getSliceMaxValue(); if (streak_size >= 9) { thr += 1; } FastDetectorisFeature_label3: for (int j = streak_size; j < outerSize; j++) { final double tj = Math.abs(featureSlice[pix_x + circle4_[(i + j) % outerSize][0]][pix_y + circle4_[(i + j) % outerSize][1]] - centerValue); if (tj > max_t) { max_t = tj; } if (tj >= min_t - thr) { did_break = true; break; } } if (!did_break) { if (streak_size == 9 && (max_t >= 7)) { int tmp = 0; } } if (!did_break) { outerI = i; outerStreakSize = streak_size; outerStartX = outerCircle[outerI % outerSize][0]; outerEndX = outerCircle[(outerI + outerStreakSize - 1) % outerSize][0]; outerStartY = outerCircle[outerI % outerSize][1]; outerEndY = outerCircle[(outerI + outerStreakSize - 1) % outerSize][1]; int condDiff = (streak_size % 2 == 1) ? 0 : 1; // If streak_size is even, then set it to 1. Otherwise 0. if ((streak_size == outerCircleSize - 1) || Math.abs(outerStartX - outerEndX) <= condDiff || Math.abs(outerStartY - outerEndY) <= condDiff // || featureSlice[pix_x + outerStartX][pix_y + outerStartY] < 12 // || featureSlice[pix_x + outerEndX][pix_y + outerEndX] < 12 ) { found_streak_outer = false; } else { found_streak_outer = true; } if (min_t - max_t != 15 || streak_size != 10) { // found_streak_outer = false; } exit_outer_loop = true; break; } } if (found_streak_outer || exit_outer_loop) { break; } } } switch (cornerCircleSelection) { case InnerCircle: found_streak = found_streak_inner; break; case OuterCircle: found_streak = found_streak_outer; break; case OR: found_streak = found_streak_inner || found_streak_outer; break; case AND: found_streak = found_streak_inner && found_streak_outer; break; default: found_streak = found_streak_inner && found_streak_outer; break; } return found_streak; } /** * @return the outlierRejectionEnabled */ public boolean isOutlierRejectionEnabled() { return outlierRejectionEnabled; } /** * @param outlierRejectionEnabled the outlierRejectionEnabled to set */ public void setOutlierRejectionEnabled(boolean outlierRejectionEnabled) { this.outlierRejectionEnabled = outlierRejectionEnabled; putBoolean("outlierRejectionEnabled", outlierRejectionEnabled); } /** * @return the outlierRejectionThresholdSigma */ public float getOutlierRejectionThresholdSigma() { return outlierRejectionThresholdSigma; } /** * @param outlierRejectionThresholdSigma the outlierRejectionThresholdSigma * to set */ public void setOutlierRejectionThresholdSigma(float outlierRejectionThresholdSigma) { this.outlierRejectionThresholdSigma = outlierRejectionThresholdSigma; putFloat("outlierRejectionThresholdSigma", outlierRejectionThresholdSigma); } private boolean isOutlierFlowVector(PatchMatchFlow.SADResult result) { if (!outlierRejectionEnabled) { return false; } GlobalMotion gm = outlierRejectionMotionFlowStatistics.getGlobalMotion(); // update global flow here before outlier rejection, otherwise stats are not updated and std shrinks to zero gm.update(vx, vy, v, (x << getSubSampleShift()), (y << getSubSampleShift())); float speed = (float) Math.sqrt(result.vx * result.vx + result.vy * result.vy); // if the current vector speed is too many stds outside the mean speed then it is an outlier if (Math.abs(speed - gm.meanGlobalSpeed) > outlierRejectionThresholdSigma * gm.sdGlobalSpeed) { return true; } // if((Math.abs(result.vx-gm.meanGlobalVx)>outlierRejectionThresholdSigma*gm.sdGlobalVx) // || (Math.abs(result.vy-gm.meanGlobalVy)>outlierRejectionThresholdSigma*gm.sdGlobalVy)) // return true; return false; } /** * @return the useEFASTnotSFAST */ public boolean isUseEFASTnotSFAST() { return useEFASTnotSFAST; } /** * @param useEFASTnotSFAST the useEFASTnotSFAST to set */ public void setUseEFASTnotSFAST(boolean useEFASTnotSFAST) { this.useEFASTnotSFAST = useEFASTnotSFAST; putBoolean("useEFASTnotSFAST", useEFASTnotSFAST); checkForEASTCornerDetectorEnclosedFilter(); } private void checkForEASTCornerDetectorEnclosedFilter() { if (useEFASTnotSFAST) { // add enclosed filter if not there if (keypointFilter == null) { keypointFilter = new HWCornerPointRenderer(chip); } if (!getEnclosedFilterChain().contains(keypointFilter)) { getEnclosedFilterChain().add(keypointFilter); // use for EFAST } keypointFilter.setFilterEnabled(isFilterEnabled()); if (getChip().getAeViewer().getFilterFrame() != null) { getChip().getAeViewer().getFilterFrame().rebuildContents(); } } else { if (keypointFilter != null && getEnclosedFilterChain().contains(keypointFilter)) { getEnclosedFilterChain().remove(keypointFilter); if (getChip().getAeViewer().getFilterFrame() != null) { getChip().getAeViewer().getFilterFrame().rebuildContents(); } } } } /** * @return the outlierRejectionWindowSize */ public int getOutlierRejectionWindowSize() { return outlierRejectionWindowSize; } /** * @param outlierRejectionWindowSize the outlierRejectionWindowSize to set */ public void setOutlierRejectionWindowSize(int outlierRejectionWindowSize) { this.outlierRejectionWindowSize = outlierRejectionWindowSize; putInt("outlierRejectionWindowSize", outlierRejectionWindowSize); outlierRejectionMotionFlowStatistics.setWindowSize(outlierRejectionWindowSize); } /** * @return the cornerSize */ public int getCornerSize() { return cornerSize; } /** * @param cornerSize the cornerSize to set */ public void setCornerSize(int cornerSize) { this.cornerSize = cornerSize; } }
package org.lightmare.rest; import java.io.IOException; import java.util.Collection; import java.util.HashSet; import java.util.Map; import java.util.Set; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import org.glassfish.jersey.server.ResourceConfig; import org.glassfish.jersey.server.model.Resource; import org.lightmare.cache.RestContainer; import org.lightmare.rest.providers.JacksonFXmlFeature; import org.lightmare.rest.providers.ObjectMapperProvider; import org.lightmare.rest.providers.RestReloader; import org.lightmare.rest.utils.ResourceBuilder; import org.lightmare.utils.ObjectUtils; /** * Dynamically manage REST resources, implementation of {@link ResourceConfig} * class to add and remove {@link Resource}'s and reload at runtime * * @author levan * */ public class RestConfig extends ResourceConfig { // Collection of resources before registration private Set<Resource> preResources; // Reloader instance (implementation of ContainerLifecycleListener class) private RestReloader reloader = RestReloader.get(); private static final Lock LOCK = new ReentrantLock(); public RestConfig(boolean changeCache) { super(); RestConfig config = RestContainer.getRestConfig(); register(ObjectMapperProvider.class); register(JacksonFXmlFeature.class); LOCK.lock(); try { if (reloader == null) { reloader = new RestReloader(); } this.registerInstances(reloader); if (ObjectUtils.notNull(config)) { // Adds resources to pre-resources from existing cached // configuration this.addPreResources(config); Map<String, Object> properties = config.getProperties(); if (ObjectUtils.available(properties)) { addProperties(properties); } } if (changeCache) { RestContainer.setRestConfig(this); } } finally { LOCK.unlock(); } } public RestConfig() { this(Boolean.TRUE); } public void cache() { RestConfig config = RestContainer.getRestConfig(); if (ObjectUtils.notTrue(this.equals(config))) { RestContainer.setRestConfig(this); } } private void clearResources() { Set<Resource> resources = getResources(); if (ObjectUtils.available(resources)) { getResources().clear(); } } /** * Registers {@link Resource}s from passed {@link RestConfig} as * {@link RestConfig#preResources} cache * * @param oldConfig */ public void registerAll(RestConfig oldConfig) { clearResources(); Set<Resource> newResources; newResources = new HashSet<Resource>(); if (ObjectUtils.notNull(oldConfig)) { Set<Resource> olds = oldConfig.getResources(); if (ObjectUtils.available(olds)) { newResources.addAll(olds); } } registerResources(newResources); } public void addPreResource(Resource resource) { if (this.preResources == null || this.preResources.isEmpty()) { this.preResources = new HashSet<Resource>(); } this.preResources.add(resource); } public void addPreResources(Collection<Resource> preResources) { if (ObjectUtils.available(preResources)) { if (this.preResources == null || this.preResources.isEmpty()) { this.preResources = new HashSet<Resource>(); } this.preResources.addAll(preResources); } } public void addPreResources(RestConfig oldConfig) { if (ObjectUtils.notNull(oldConfig)) { addPreResources(oldConfig.getResources()); addPreResources(oldConfig.preResources); } } private void removePreResource(Resource resource) { if (ObjectUtils.available(this.preResources)) { this.preResources.remove(resource); } } /** * Caches {@link Resource} created from passed {@link Class} for further * registration * * @param resourceClass * @param oldConfig * @throws IOException */ public void registerClass(Class<?> resourceClass, RestConfig oldConfig) throws IOException { Resource.Builder builder = Resource.builder(resourceClass); Resource preResource = builder.build(); Resource resource = ResourceBuilder.rebuildResource(preResource); addPreResource(resource); } /** * Removes {@link Resource} created from passed {@link Class} from * pre-resources cache * * @param resourceClass */ public void unregister(Class<?> resourceClass) { Resource resource = RestContainer.getResource(resourceClass); removePreResource(resource); } public void registerPreResources() { if (ObjectUtils.available(preResources)) { RestContainer.putResources(preResources); registerResources(preResources); } } }
package org.thepholio.desktop; import javafx.application.Application; import javafx.embed.swing.SwingNode; import javafx.geometry.HPos; import javafx.geometry.Insets; import javafx.geometry.Pos; import javafx.geometry.Rectangle2D; import javafx.scene.Scene; import javafx.scene.control.ComboBox; import javafx.scene.control.ScrollPane; import javafx.scene.control.SelectionModel; import javafx.scene.layout.GridPane; import javafx.scene.layout.StackPane; import javafx.scene.text.Text; import javafx.stage.Screen; import javafx.stage.Stage; import javax.imageio.ImageIO; import javax.swing.*; import java.awt.*; import java.awt.image.BufferedImage; import java.io.File; import static java.lang.Double.MAX_VALUE; import static javafx.scene.layout.Priority.ALWAYS; import static org.thepholio.desktop.Config.SAMPLES; public class Desktop extends Application { public static class SwingImageNode extends SwingNode { private BufferedImage image; private final JComponent iv = new JPanel() { @Override protected void paintComponent(Graphics g) { //super.paintComponent(g); if (image != null) { g.drawImage(image, 0, 0, null); } } }; public SwingImageNode() { setContent(iv); } public void setImage(BufferedImage image) { this.image = image; SwingUtilities.invokeLater(() -> { iv.repaint();}); } @Override public double minWidth(double height) { return image != null ? image.getWidth() : 0; } @Override public double maxWidth(double height) { return image != null ? image.getWidth() : 0; } @Override public double prefWidth(double height) { return image != null ? image.getWidth() : 0; } @Override public double minHeight(double width) { return image != null ? image.getHeight() : 0; } @Override public double maxHeight(double width) { return image != null ? image.getHeight() : 0; } @Override public double prefHeight(double width) { return image != null ? image.getHeight() : 0; } } private SwingImageNode imageNode = new SwingImageNode(); private ComboBox samplesCB = new ComboBox(); private Text statusBar = new Text(); private static final BufferedImage EMPTY_IMAGE = new BufferedImage(1, 1, BufferedImage.TYPE_INT_ARGB); @SuppressWarnings("unchecked") public Desktop() { // imageNode.setPreserveRatio(true); // imageNode.setSmooth(true); imageNode.setCache(true); samplesCB.setItems(SAMPLES); samplesCB.setMaxWidth(MAX_VALUE); samplesCB.setOnAction(event -> displaySelectedImage()); statusBar.setId("status"); } private void displaySelectedImage() { @SuppressWarnings("unchecked") SelectionModel<File> selection = samplesCB.getSelectionModel(); if (!selection.isEmpty()) { imageNode.setImage(loadSelectedImage(selection)); } } private BufferedImage loadSelectedImage(SelectionModel<File> selection) { try { return ImageIO.read((selection.getSelectedItem()).toURI().toURL()); } catch (Exception e) { statusBar.setText(e.getMessage()); return EMPTY_IMAGE; } } @Override public void start(Stage primaryStage) throws Exception { ScrollPane scroll = new ScrollPane() { public void requestFocus() {} }; scroll.setPannable(true); scroll.setFitToWidth(true); scroll.setFitToHeight(true); scroll.setContent(new StackPane(imageNode)); // allows content aligning and also centers it by default! statusBar.setText("Found " + SAMPLES.size() + " samples."); GridPane root = new GridPane(); root.setPadding(new Insets(4)); root.setHgap(4); root.setVgap(4); root.setAlignment(Pos.CENTER); root.setMaxWidth(MAX_VALUE); root.add(samplesCB, 0, 0); GridPane.setHgrow(samplesCB, ALWAYS); root.add(scroll, 0, 1); GridPane.setHgrow(scroll, ALWAYS); GridPane.setVgrow(scroll, ALWAYS); root.add(statusBar, 0, 2); GridPane.setHgrow(statusBar, ALWAYS); GridPane.setHalignment(statusBar, HPos.RIGHT); Rectangle2D screenBounds = Screen.getPrimary().getVisualBounds(); Scene scene = new Scene(root, screenBounds.getWidth() * 3 / 4, screenBounds.getHeight() * 3 / 4); scene.getStylesheets().add(getClass().getResource("/themes/default/main.css").toExternalForm()); primaryStage.setTitle("ThePholio Desktop"); primaryStage.setScene(scene); primaryStage.show(); samplesCB.getSelectionModel().select(0); } public static void main(String[] args) { launch(args); } }
package org.thymeleaf.dom; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.thymeleaf.exceptions.TemplateProcessingException; import org.thymeleaf.util.Validate; public final class DOMSelector { private static final String selectorPatternStr = "(/{1,2})([^/\\s]*?)(?:\\[(.*?)\\](?:\\[(.*?)\\])?)?"; private static final Pattern selectorPattern = Pattern.compile(selectorPatternStr); private final String selectorSpec; private final boolean descendMoreThanOneLevel; private final String selectorName; private final boolean text; private Map<String,String> attributes = null; private Integer index = null; // will be -1 if last() private final DOMSelector next; public DOMSelector(final String selectorSpec) { super(); this.selectorSpec = selectorSpec; String selectorSpecStr = (selectorSpec.trim().startsWith("/")? selectorSpec.trim() : "/" + selectorSpec.trim()); final int selectorSpecStrLen = selectorSpecStr.length(); int firstNonSlash = 0; while (firstNonSlash < selectorSpecStrLen && selectorSpecStr.charAt(firstNonSlash) == '/') { firstNonSlash++; } if (firstNonSlash >= selectorSpecStrLen) { throw new TemplateProcessingException( "Invalid syntax in DOM selector \"" + selectorSpec + "\": '/' should be followed by a selector name"); } final int selEnd = selectorSpecStr.substring(firstNonSlash).indexOf('/'); if (selEnd != -1) { final String tail = selectorSpecStr.substring(firstNonSlash).substring(selEnd); selectorSpecStr = selectorSpecStr.substring(0, firstNonSlash + selEnd); this.next = new DOMSelector(tail); } else { this.next = null; } final Matcher matcher = selectorPattern.matcher(selectorSpecStr); if (!matcher.matches()) { throw new TemplateProcessingException( "Invalid syntax in DOM selector \"" + selectorSpec + "\": selector does not match selector syntax: " + "(/|//)(selector)([@attrib=\"value\" (and @attrib2=\"value\")?])?([index])?"); } final String rootGroup = matcher.group(1); final String selectorNameGroup = matcher.group(2); final String index1Group = matcher.group(3); final String index2Group = matcher.group(4); if (rootGroup == null) { throw new TemplateProcessingException( "Invalid syntax in DOM selector \"" + selectorSpec + "\": selector does not match selector syntax: " + "(/|//)(selector)([@attrib=\"value\" (and @attrib2=\"value\")?])?([index])?"); } if ("//".equals(rootGroup)) { this.descendMoreThanOneLevel = true; } else if ("/".equals(rootGroup)) { this.descendMoreThanOneLevel = false; } else { throw new TemplateProcessingException( "Invalid syntax in DOM selector \"" + selectorSpec + "\": selector does not match selector syntax: " + "(/|//)(selector)([@attrib=\"value\" (and @attrib2=\"value\")?])?([index])?"); } if (selectorNameGroup == null) { throw new TemplateProcessingException( "Invalid syntax in DOM selector \"" + selectorSpec + "\": selector does not match selector syntax: " + "(/|//)(selector)([@attrib=\"value\" (and @attrib2=\"value\")?])?([index])?"); } this.selectorName = Node.normalizeName(selectorNameGroup); this.text = this.selectorName.equals("text()"); if (index1Group != null) { Integer ind = parseIndex(index1Group); if (ind == null) { Map<String,String> attribs = parseAttributes(selectorSpec, index1Group); if (attribs == null) { throw new TemplateProcessingException( "Invalid syntax in DOM selector \"" + selectorSpec + "\": selector does not match selector syntax: " + "(/|//)(selector)([@attrib=\"value\" (and @attrib2=\"value\")?])?([index])?"); } this.attributes = attribs; } else { this.index = ind; } if (index2Group != null) { if (this.index != null) { throw new TemplateProcessingException( "Invalid syntax in DOM selector \"" + selectorSpec + "\": selector does not match selector syntax: " + "(/|//)(selector)([@attrib=\"value\" (and @attrib2=\"value\")?])?([index])?"); } ind = parseIndex(index1Group); if (ind == null) { throw new TemplateProcessingException( "Invalid syntax in DOM selector \"" + selectorSpec + "\": selector does not match selector syntax: " + "(/|//)(selector)([@attrib=\"value\" (and @attrib2=\"value\")?])?([index])?"); } this.index = ind; } if (this.descendMoreThanOneLevel && this.index != null) { throw new TemplateProcessingException( "Invalid syntax in DOM selector \"" + selectorSpec + "\": index cannot be specified on a \"descend any levels\" selector ( } } } private static Integer parseIndex(final String indexGroup) { if ("last()".equals(indexGroup.toLowerCase())) { return Integer.valueOf(-1); } try { return Integer.valueOf(indexGroup); } catch (final Exception e) { return null; } } private static Map<String,String> parseAttributes(final String selectorSpec, final String indexGroup) { final Map<String,String> attributes = new HashMap<String, String>(); parseAttributes(selectorSpec, attributes, indexGroup); return attributes; } private static void parseAttributes(final String selectorSpec, final Map<String,String> attributes, final String indexGroup) { String att = null; final int andPos = indexGroup.indexOf(" and "); if (andPos != -1) { att = indexGroup.substring(0,andPos); final String tail = indexGroup.substring(andPos + 5); parseAttributes(selectorSpec, attributes, tail); } else { att = indexGroup; } parseAttribute(selectorSpec, attributes, att); } private static void parseAttribute(final String selectorSpec, final Map<String,String> attributes, final String attributeSpec) { final int eqPos = attributeSpec.indexOf("="); if (eqPos != -1) { final String attName = attributeSpec.substring(0, eqPos).trim(); final String attValue = attributeSpec.substring(eqPos + 1).trim(); if (!attName.startsWith("@")) { throw new TemplateProcessingException( "Invalid syntax in DOM selector: \"" + selectorSpec + "\""); } if (!(attValue.startsWith("\"") && attValue.endsWith("\"")) && !(attValue.startsWith("'") && attValue.endsWith("'"))) { throw new TemplateProcessingException( "Invalid syntax in DOM selector: \"" + selectorSpec + "\""); } attributes.put(Node.normalizeName(attName.substring(1)), attValue.substring(1, attValue.length() - 1)); } else { final String attName = attributeSpec.trim(); if (!attName.startsWith("@")) { throw new TemplateProcessingException( "Invalid syntax in DOM selector: \"" + selectorSpec + "\""); } attributes.put(Node.normalizeName(attName.substring(1)), null); } } public List<Node> select(final List<Node> nodes) { Validate.notEmpty(nodes, "Nodes to be searched cannot be null or empty"); final List<Node> selected = new ArrayList<Node>(); for (final Node node : nodes) { doCheckNodeSelection(selected, node); } return selected; } private final boolean checkChildrenSelection(final List<Node> selectedNodes, final Node node) { // will return true if any nodes are added to selectedNodes if (node instanceof NestableNode) { final List<List<Node>> selectedNodesForChildren = new ArrayList<List<Node>>(); final NestableNode nestableNode = (NestableNode) node; if (nestableNode.hasChildren()) { for (final Node child : nestableNode.getChildren()) { final List<Node> childSelectedNodes = new ArrayList<Node>(); if (doCheckNodeSelection(childSelectedNodes, child)) { selectedNodesForChildren.add(childSelectedNodes); } } } if (selectedNodesForChildren.size() == 0) { return false; } if (this.index == null) { for (final List<Node> selectedNodesForChild : selectedNodesForChildren) { selectedNodes.addAll(selectedNodesForChild); } return true; } // There is an index if (this.index.intValue() == -1) { selectedNodes.addAll(selectedNodesForChildren.get(selectedNodesForChildren.size() - 1)); return true; } if (this.index.intValue() >= selectedNodesForChildren.size()) { return false; } selectedNodes.addAll(selectedNodesForChildren.get(this.index.intValue())); return true; } return false; } private final boolean doCheckNodeSelection(final List<Node> selectedNodes, final Node node) { if (!doCheckSpecificNodeSelection(node)) { if (this.descendMoreThanOneLevel) { // This level doesn't match, but maybe next levels do... if (node instanceof NestableNode) { final NestableNode nestableNode = (NestableNode) node; if (nestableNode.hasChildren()) { return checkChildrenSelection(selectedNodes, node); } } } return false; } if (this.next == null) { selectedNodes.add(node); return true; } if (node instanceof NestableNode) { final NestableNode nestableNode = (NestableNode) node; if (nestableNode.hasChildren()) { return this.next.checkChildrenSelection(selectedNodes, node); } } return false; } private final boolean doCheckSpecificNodeSelection(final Node node) { // This method checks all aspects except index (index can only // be applied from the superior level) if (this.text) { return node instanceof AbstractTextNode; } if (node instanceof Tag) { final Tag tag = (Tag)node; final String normalizedName = tag.getNormalizedName(); if (!normalizedName.equals(this.selectorName)) { return false; } if (this.attributes == null || this.attributes.size() == 0) { return true; } for (final Map.Entry<String,String> attributeEntry : this.attributes.entrySet()) { final String selectedAttributeName = attributeEntry.getKey(); final String selectedAttributeValue = attributeEntry.getValue(); if (selectedAttributeValue == null) { if (!tag.hasAttribute(selectedAttributeName)) { return false; } } else { final String attributeValue = tag.getAttributeValueFromNormalizedName(selectedAttributeName); if (attributeValue == null || !attributeValue.equals(selectedAttributeValue)) { return false; } } } return true; } return false; } @Override public final String toString() { return this.selectorSpec; } }
package scrum.server; import ilarkesto.auth.Auth; import ilarkesto.base.PermissionDeniedException; import ilarkesto.base.Utl; import ilarkesto.base.time.Date; import ilarkesto.logging.Logger; import ilarkesto.persistence.ADao; import ilarkesto.persistence.AEntity; import ilarkesto.webapp.AWebApplication; import ilarkesto.webapp.AWebSession; import java.util.Collection; import java.util.Map; import java.util.UUID; import scrum.server.admin.User; import scrum.server.admin.UserDao; import scrum.server.common.Numbered; import scrum.server.common.Transient; import scrum.server.project.Project; import scrum.server.project.ProjectDao; import scrum.server.project.Requirement; import scrum.server.project.RequirementDao; import scrum.server.sprint.Task; public class ScrumServiceImpl extends GScrumServiceImpl { private static final Logger LOG = Logger.get(ScrumServiceImpl.class); private ProjectDao projectDao; private UserDao userDao; private RequirementDao requirementDao; private ScrumWebApplication webApplication; public void setWebApplication(ScrumWebApplication webApplication) { this.webApplication = webApplication; } public void setRequirementDao(RequirementDao requirementDao) { this.requirementDao = requirementDao; } public void setProjectDao(ProjectDao projectDao) { this.projectDao = projectDao; } public void setUserDao(UserDao userDao) { this.userDao = userDao; } @Override protected void onLogout(WebSession session) { session.invalidate(); webApplication.destroyWebSession(session, getThreadLocalRequest().getSession()); } @Override protected void onResetPassword(WebSession session, String userId) { User user = userDao.getById(userId); user.setPassword("geheim"); } @Override protected void onChangePassword(WebSession session, String oldPassword, String newPassword) { if (session.getUser().matchesPassword(oldPassword) == false) { throw new RuntimeException("bad password"); } session.getUser().setPassword(newPassword); LOG.info("password changed by user"); } @Override public void onCreateEntity(WebSession session, String type, Map properties) { String id = (String) properties.get("id"); if (id == null) throw new NullPointerException("id == null"); ADao dao = getDaoService().getDaoByName(type); AEntity entity = dao.newEntityInstance(id); entity.updateProperties(properties); if (entity instanceof Numbered) { ((Numbered) entity).updateNumber(); } if (!(entity instanceof Transient)) dao.saveEntity(entity); session.sendToClient(entity); for (WebSession s : webApplication.getOtherSessionsByProject(session)) { // TODO do this only if client is tracking this entity s.sendToClient(entity); } } @Override public void onDeleteEntity(WebSession session, String entityId) { AEntity entity = getDaoService().getEntityById(entityId); if (!Auth.isDeletable(entity, session.getUser())) throw new PermissionDeniedException(); ADao dao = getDaoService().getDao(entity); dao.deleteEntity(entity); for (WebSession s : webApplication.getOtherSessionsByProject(session)) { // TODO do this only if client is tracking this entity s.getNextData().addDeletedEntity(entityId); } } @Override public void onChangeProperties(WebSession session, String entityId, Map properties) { AEntity entity = getDaoService().getEntityById(entityId); if (!Auth.isEditable(entity, session.getUser())) throw new PermissionDeniedException(); if (entity instanceof Task) { // update sprint day snapshot before change Task task = (Task) entity; task.getRequirement().getSprint().getDaySnapshot(Date.today()).update(); } entity.updateProperties(properties); if (entity instanceof Task) { // update sprint day snapshot after change Task task = (Task) entity; task.getRequirement().getSprint().getDaySnapshot(Date.today()).update(); } if (entity instanceof Requirement) { Requirement requirement = (Requirement) entity; if (properties.containsKey("description") || properties.containsKey("testDescription") || properties.containsKey("estimatedWork") || properties.containsKey("qualitysIds")) { requirement.setDirty(true); } requirement.getProject().getCurrentSprintSnapshot().update(); } if (entity instanceof Project) { Project project = (Project) entity; } for (AWebSession s : webApplication.getWebSessions()) { s.sendToClient(entity); } } @Override public void onLogin(WebSession session, String username, String password) { session.reinitialize(); User user = userDao.getUserByName(username); if (user == null || user.matchesPassword(password) == false) { session.getNextData().errors.add("Login failed."); return; } session.setUser(user); session.getNextData().entityIdBase = UUID.randomUUID().toString(); session.getNextData().setUserId(user.getId()); session.sendToClient(user); session.sendToClient(projectDao.getEntitiesVisibleForUser(user)); session.sendToClient(userDao.getEntitiesVisibleForUser(user)); } @Override public void onSelectProject(WebSession session, String projectId) { Project project = projectDao.getById(projectId); if (!project.isVisibleFor(session.getUser())) throw new RuntimeException("Project '" + project + "' is not visible for user '" + session.getUser() + "'"); session.setProject(project); session.getUser().setCurrentProject(project); // prepare data for client session.sendToClient(project); session.sendToClient(project.getCurrentSprint()); session.sendToClient(project.getNextSprint()); session.sendToClient(project.getParticipants()); session.sendToClient(project.getRequirements()); session.sendToClient(project.getTasks()); } @Override protected void onCloseProject(WebSession session) { session.setProject(null); } @Override protected void onSwitchToNextSprint(WebSession session) { assertProjectSelected(session); Project project = session.getProject(); project.switchToNextSprint(); session.sendToClient(project); session.sendToClient(project.getCurrentSprint()); session.sendToClient(project.getNextSprint()); } @Override public void onRequestImpediments(WebSession session) { assertProjectSelected(session); Project project = session.getProject(); session.sendToClient(project.getImpediments()); } @Override protected void onRequestRisks(WebSession session) { assertProjectSelected(session); Project project = session.getProject(); session.sendToClient(project.getRisks()); } @Override public void onRequestRequirements(WebSession session) { assertProjectSelected(session); Project project = session.getProject(); Collection<Requirement> requirements = project.getRequirements(); for (Requirement requirement : requirements) { if (requirement.isSprintSet()) session.sendToClient(requirement.getSprint()); session.sendToClient(requirement.getTasks()); session.sendToClient(requirement.getQualitys()); } session.sendToClient(requirements); session.sendToClient(project.getQualitys()); session.sendToClient(project); } @Override protected void onRequestQualitys(WebSession session) { assertProjectSelected(session); Project project = session.getProject(); session.sendToClient(project.getQualitys()); } @Override protected void onRequestEntityByReference(WebSession session, String reference) { assertProjectSelected(session); Project project = session.getProject(); int number = Integer.parseInt(reference.substring(1)); if (reference.startsWith("r")) { Requirement requirement = project.getRequirementByNumber(number); if (requirement != null) session.sendToClient(requirement); return; } else if (reference.startsWith("t")) { Task task = project.getTaskByNumber(number); if (task != null) session.sendToClient(task); return; } LOG.info("Requested entity not found:", reference); } @Override public void onPing(WebSession session) { // nop } @Override public void onSleep(WebSession session, long millis) { Utl.sleep(millis); } private void assertProjectSelected(WebSession session) { if (session.getProject() == null) throw new RuntimeException("No project selected."); } @Override protected Class<? extends AWebApplication> getWebApplicationClass() { return ScrumWebApplication.class; } }
package skyhussars.engine.plane; import skyhussars.engine.mission.PlaneMissionDescriptor; import skyhussars.engine.physics.Aileron; import skyhussars.engine.physics.Aileron.ControlDir; import skyhussars.engine.physics.PlanePhysicsImpl; import skyhussars.engine.physics.Airfoil; import skyhussars.engine.physics.Engine; import skyhussars.engine.physics.environment.Environment; import skyhussars.engine.plane.instruments.Instruments; import skyhussars.engine.sound.AudioHandler; import skyhussars.engine.weapons.ProjectileManager; import com.jme3.bounding.BoundingVolume; import com.jme3.effect.ParticleEmitter; import com.jme3.math.FastMath; import com.jme3.math.Quaternion; import com.jme3.math.Vector2f; import com.jme3.math.Vector3f; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; public class Plane { private final static Logger logger = LoggerFactory.getLogger(Plane.class); private PlaneMissionDescriptor planeMissionDescriptor; private String name; private final PlanePhysicsImpl physics; private final AudioHandler engineSound; private final AudioHandler gunSound; private List<GunGroup> gunGroups; private final List<Engine> engines = new ArrayList<>(); private boolean firing = false; private final ProjectileManager projectileManager; private boolean crashed = false; private boolean shotdown = false; private ParticleEmitter fireEffect; private final PlaneGeometry geom; public void updatePlanePhysics(float tpf, Environment environment) { physics.update(tpf, environment); logger.debug(getInfo()); } public void planeMissinDescriptor(PlaneMissionDescriptor planeMissionDescriptor) { this.planeMissionDescriptor = planeMissionDescriptor; } public PlaneMissionDescriptor planeMissionDescriptor() { return planeMissionDescriptor; } private final List<Aileron> horizontalStabilizers = new ArrayList<>(); private final List<Aileron> verticalStabilizers = new ArrayList<>(); private final List<Airfoil> airfoils = new ArrayList<>(); private final List<Aileron> ailerons = new ArrayList<>();; public Plane(List<Airfoil> airfoils, AudioHandler engineSound, AudioHandler gunSound, ProjectileManager projectileManager, PlaneGeometry planeGeometry, Instruments instruments, List<Engine> engines, List<GunGroup> gunGroups, float grossMass) { this.engineSound = engineSound; engineSound.audioNode().setLocalTranslation(0, 0, - 5); this.gunSound = gunSound; geom = planeGeometry; geom.attachSpatialToRootNode(engineSound.audioNode()); geom.attachSpatialToRootNode(gunSound.audioNode()); this.projectileManager = projectileManager; this.gunGroups = gunGroups; sortoutAirfoils(airfoils); Quaternion rotation = Quaternion.IDENTITY.clone();//geom.root() .getLocalRotation(); Vector3f translation = geom.root().getLocalTranslation(); this.physics = new PlanePhysicsImpl(rotation, translation,grossMass, engines, airfoils); this.physics.speedForward(geom.root().getLocalRotation(), 300f); } private Plane sortoutAirfoils(List<Airfoil> airfoils){ ailerons.addAll(airfoils.stream() .filter(af -> af.direction().equals(ControlDir.LEFT) || af.direction().equals(ControlDir.RIGHT)) .map(af -> (Aileron) af).collect(Collectors.toList())); horizontalStabilizers.addAll(airfoils.stream() .filter(af -> af.direction().equals(ControlDir.HORIZONTAL_STABILIZER)) .map(af -> (Aileron) af) .collect(Collectors.toList())); verticalStabilizers.addAll(airfoils.stream() .filter(af -> af.direction().equals(ControlDir.VERTICAL_STABILIZER)) .map(af -> (Aileron) af) .collect(Collectors.toList())); this.airfoils.addAll(airfoils); return this; } public float aoa(){ return physics.aoa(); } public BoundingVolume getHitBox() { return geom.root().getWorldBound(); } public void hit() { if (!shotdown) { geom.attachSpatialToRootNode(fireEffect); fireEffect.emitAllParticles(); for (Engine engine : engines) { engine.damage(1.0f); } } shotdown = true; } public void update(float tpf) { physics.updateScene(geom.root()); float ratio = FastMath.PI * 2 * (physics.speedKmH() / 900); geom.airspeedInd().setLocalRotation(new Quaternion().fromAngles(0, 0, ratio)); if (!crashed) { gunGroups.parallelStream().forEach(gunGroup -> { gunGroup.firing(firing, geom.root().getLocalTranslation(), physics.getVVelovity(), geom.root().getWorldRotation()); }); } } public void updateSound() { if (!crashed) { engineSound.play(); if (firing) { gunSound.play(); } else { gunSound.stop(); } } else { engineSound.pause(); gunSound.stop(); } } /** * This method provides throttle controls for the airplane * * @param throttle - Amount of throttle applied, should be between 0.0f and * 1.0f */ public void setThrottle(float throttle) { /* maybe it would be better to normalize instead of throwing an exception*/ if (throttle < 0.0f || throttle > 1.0f) { throw new IllegalArgumentException(); } for (Engine engine : engines) { engine.setThrottle(throttle); } engineSound.setPitch(0.5f + throttle); } public void setAileron(float aileron) { ailerons.forEach(w -> w.controlAileron(maxAileron * aileron)); } float maxElevator = 10f; float maxAileron = 2f; /** * Sets the status of the elevator. If the elevator is negative, it pushes * the nose down. If the elevator is positive, it pulls the nose up. * * @param elevator must be between -1.0 and 1.0 */ public void setElevator(float elevator) { horizontalStabilizers.forEach(s -> s.controlAileron(maxElevator * elevator)); } public void setRudder(float rudder) { verticalStabilizers.forEach(s -> s.controlAileron(rudder)); } public void setHeight(int height) { Vector3f translation = geom.root().getLocalTranslation(); setLocation((int) translation.getX(), height, (int) translation.getZ()); } public void setLocation(int x, int z) { setLocation(x, (int) geom.root().getLocalTranslation().y, z); } public void setLocation(int x, int y, int z) { setLocation(new Vector3f(x, y, z)); } public void setLocation(Vector3f location) { geom.root().setLocalTranslation(location); physics.translation(location); } public float getHeight() {return geom.root().getLocalTranslation().y;} public Vector3f getLocation() { return geom.root().getLocalTranslation();} public Vector3f forward() {return geom.root().getLocalRotation().mult(Vector3f.UNIT_Z).normalize();} public Vector3f up() {return geom.root().getLocalRotation().mult(Vector3f.UNIT_Y).normalize();} public float roll() { int i = forward().cross(Vector3f.UNIT_Y).dot(up()) > 0 ? 1 : -1; return i * geom.root().getLocalRotation().mult(Vector3f.UNIT_Y).angleBetween(Vector3f.UNIT_Y) * FastMath.RAD_TO_DEG; } public Vector2f getLocation2D() { return new Vector2f(geom.root().getLocalTranslation().x, geom.root().getLocalTranslation().z); } public String velocityKmh() { return physics.getSpeedKmH(); } public void firing(boolean trigger) { firing = trigger; } public void crashed(boolean crashed) { this.crashed = crashed; } public boolean crashed() { return crashed; } public String getInfo() { return physics.getInfo(); } public PlaneGeometry planeGeometry() { return geom; } public void fireEffect(ParticleEmitter fireEffect) { this.fireEffect = fireEffect; } }
package com.eatthepath.jeospatial; /** * <p>A caching geospatial point is an extension of a simple geospatial point * that trades memory efficiency for processing time in calculating distance to * other points. From an external perspective, caching geospatial points behave * identically to simple geospatial points. Internally, caching geospatial * points pre-calculate parts of the spherical distance calculation. This uses * more memory, but reduces the number of trigonometric calculations that need * to be made in repeated calls to the @{code getDistanceTo} method.</p> * * <p>Caching geospatial points are a good choice in cases where one point will * be the origin in distance calculations to lots of other points. Caching * points take up an additional 24 bytes of memory, and testing shows that * distance calculations with caching points take 15%-20% less computation time * than with non-caching points.</p> * * @author <a href="mailto:jon.chambers@gmail.com">Jon Chambers</a> */ public class CachingGeospatialPoint extends SimpleGeospatialPoint { private double lon1; private double sinLat1; private double cosLat1; /** * Constructs a new caching geospatial point at the given coordinates. * * @param latitude the latitude of the new point in degrees * @param longitude the longitude of the new point in degrees */ public CachingGeospatialPoint(double latitude, double longitude) { super(latitude, longitude); this.setLatitude(latitude); this.setLongitude(longitude); } /** * Constructs a new caching geospatial point at the location of the given * point. * * @param p * the point at which the new point should be created */ public CachingGeospatialPoint(GeospatialPoint p) { this(p.getLatitude(), p.getLongitude()); } /** * Sets the latitude of this point. * * @param latitude the latitude of this point in degrees */ @Override public void setLatitude(double latitude) { super.setLatitude(latitude); double lat1 = Math.toRadians(latitude); this.sinLat1 = Math.sin(lat1); this.cosLat1 = Math.cos(lat1); } /** * Sets the longitude of this point. * * @param longitude the longitude of this point in degrees */ @Override public void setLongitude(double longitude) { super.setLongitude(longitude); this.lon1 = Math.toRadians(longitude); } /** * Returns the "great circle" distance to another geospatial point. * * @param otherPoint the other point to which to calculate distance * * @return the great circle distance, in meters, between the two points */ @Override public double getDistanceTo(GeospatialPoint otherPoint) { double lat2 = Math.toRadians(otherPoint.getLatitude()); double lon2 = Math.toRadians(otherPoint.getLongitude()); double angle = Math.acos((this.sinLat1 * Math.sin(lat2)) + (this.cosLat1 * Math.cos(lat2) * Math.cos(lon2 - this.lon1))); return Double.isNaN(angle) ? 0 : GeospatialPoint.EARTH_RADIUS * angle; } /* * (non-Javadoc) * @see com.eatthepath.jeospatial.SimpleGeospatialPoint#equals(java.lang.Object) */ @Override public boolean equals(Object other) { return super.equals(other); } }
package com.example.weathertest.activity; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Locale; import com.example.weathertest.R; import com.example.weathertest.utils.HttpUtil; import com.example.weathertest.utils.HttpUtil.HttpCallbackListener; import com.example.weathertest.utils.Utility; import android.app.Activity; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.preference.PreferenceManager; import android.text.TextUtils; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.view.Window; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.Button; import android.widget.LinearLayout; import android.widget.TextView; public class WeatherActivity extends Activity implements OnClickListener{ private LinearLayout weatherInfoLayout; private TextView cityNameText; private TextView publishText; private TextView weatherDespText; private TextView temp1Text; private TextView temp2Text; private TextView currentDateText; private Button switchCity; private Button refreshWeather; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.weather_layout); weatherInfoLayout=(LinearLayout)findViewById(R.id.weather_info_layout); cityNameText=(TextView)findViewById(R.id.city_name); publishText=(TextView)findViewById(R.id.publish_text); weatherDespText=(TextView)findViewById(R.id.weather_desp); temp1Text=(TextView)findViewById(R.id.temp1); temp2Text=(TextView)findViewById(R.id.temp2); currentDateText=(TextView)findViewById(R.id.current_date); switchCity=(Button)findViewById(R.id.switch_city); refreshWeather=(Button)findViewById(R.id.refresh_weather); String countyCode=getIntent().getStringExtra("county_code"); if (!TextUtils.isEmpty(countyCode)) { publishText.setText("..."); weatherInfoLayout.setVisibility(View.INVISIBLE); cityNameText.setVisibility(View.INVISIBLE); queryWeatherCode(countyCode); }else { showWeather(); } switchCity.setOnClickListener(this); refreshWeather.setOnClickListener(this); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.switch_city: Intent intent=new Intent(this, ChooseAreaActivity.class); intent.putExtra("from_weather_activity", true); startActivity(intent); finish(); break; case R.id.refresh_weather: publishText.setText("..."); SharedPreferences prefs=PreferenceManager.getDefaultSharedPreferences(this); String weatherCode = prefs.getString("weather_code", ""); if (!TextUtils.isEmpty(weatherCode)) { queryWeatherInfo(weatherCode); } break; default: break; } } private void queryWeatherCode(String countyCode) { String address="http: queryFromServer(address,"countyCode"); } private void queryWeatherInfo(String weatherCode) { // API // yyyyMMddHHmm SimpleDateFormat sdf=new SimpleDateFormat("yyyyMMddHHmm", Locale.CHINA); String currentDate=sdf.format(new Date()); String whiteUrlS="http://open.weather.com.cn/data/?areaid="+weatherCode+"&type=forecast_v&date="+currentDate+"&appid=bcbccb513492a6c5"; //appid String whiteUrl="http://open.weather.com.cn/data/?areaid="+weatherCode+"&type=forecast_v&date="+currentDate+"&appid=bcbccb"; String finalUrl=Utility.getSecretiveUrl(whiteUrlS, whiteUrl); if (finalUrl != null) { queryFromServer(finalUrl, "weatherCode"); }else { Log.d("Error", "fail to get finalUrl"); } } private void queryFromServer(final String address,final String type) { HttpUtil.sendHttpRequest(address, new HttpCallbackListener() { @Override public void onFinish(String response) { if ("countyCode".equals(type)) { if (!TextUtils.isEmpty(response)) { String[] array=response.split("\\|"); if (array!=null&&array.length==2) { String weatherCode=array[1]; queryWeatherInfo(weatherCode); } } }else if ("weatherCode".equals(type)) { Utility.handleWeatherResponse(WeatherActivity.this, response); runOnUiThread(new Runnable() { @Override public void run() { showWeather(); } }); } } @Override public void onError(Exception e) { // UIUI runOnUiThread(new Runnable() { @Override public void run() { publishText.setText(""); } }); } }); } //sharedPrefrences public void showWeather() { SharedPreferences prefs=PreferenceManager.getDefaultSharedPreferences(this); cityNameText.setText( prefs.getString("city_name", "")); temp1Text.setText(prefs.getString("temp1", "")); temp2Text.setText(prefs.getString("temp2", "")); weatherDespText.setText(prefs.getString("weather_desp", "")); publishText.setText("" + prefs.getString("publish_time", "") + ""); currentDateText.setText(prefs.getString("current_date", "")); weatherInfoLayout.setVisibility(View.VISIBLE); cityNameText.setVisibility(View.VISIBLE); } }
package com.perpetumobile.bit.config; import java.io.BufferedOutputStream; import java.io.IOException; import java.util.ArrayList; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import com.perpetumobile.bit.android.BitBroadcastReceiver; import com.perpetumobile.bit.http.HttpManager; import com.perpetumobile.bit.http.HttpRequest; import com.perpetumobile.bit.http.HttpResponseDocument; import com.perpetumobile.bit.util.Logger; import com.perpetumobile.bit.util.Util; public class ConfigServerManager { static private ConfigServerManager instance = new ConfigServerManager(); static public ConfigServerManager getInstance() { return instance; } static private Logger logger = new Logger(ConfigServerManager.class); final static public String CONFIG_SERVER_MANAGER_THREAD_POOL_NAME = "ConfigService"; final static public String CONFIG_SERVER_MANAGER_ENABLE_KEY = "ConfigServerManager.Enable"; final static public String CONFIG_SERVER_MANAGER_URLS_KEY = "ConfigServerManager.URLs"; final static public String CONFIG_SERVER_MANAGER_HTTP_REQUEST_CLASS_KEY = "ConfigServerManager.HttpRequest.Class"; final static public String CONFIG_SERVER_MANAGER_INTENT_ACTION_SUFFIX = "ConfigServerManager.INTENT_ACTION_SUFFIX"; final static public String CONFIG_SERVER_MANAGER_TIMER_CANCEL_KEY = "ConfigServerManager.Timer.Cancel"; private String[] requestList = null; private ArrayList<HttpResponseDocument> docList = null; private boolean isRequestPending = false; private Object lock = new Object(); private ConfigServerManager() { HttpManager.getInstance().registerReceiver(broadcastReceiver, CONFIG_SERVER_MANAGER_INTENT_ACTION_SUFFIX); } @SuppressWarnings("unchecked") protected void requestServerConfig() { boolean doRequest = false; synchronized(lock) { // don't request config from server if previous request pending // don't hold the lock to queue up the requests // if request is already pending release the lock and skip the request if(!isRequestPending && Config.getInstance().getBooleanProperty(CONFIG_SERVER_MANAGER_ENABLE_KEY, false)) { String urls = Config.getInstance().getProperty(CONFIG_SERVER_MANAGER_URLS_KEY, null); if(!Util.nullOrEmptyString(urls)) { // member variables are managed in synchronized section docList = new ArrayList<HttpResponseDocument>(); requestList = urls.split(","); isRequestPending = true; doRequest = true; } } } if(doRequest) { String httpRequestClassName = Config.getInstance().getProperty(CONFIG_SERVER_MANAGER_HTTP_REQUEST_CLASS_KEY, null); for(String url : requestList) { HttpRequest httpRequest = null; if(!Util.nullOrEmptyString(httpRequestClassName)) { try { Class<? extends HttpRequest> httpRequestClass = (Class<? extends HttpRequest>)Class.forName(httpRequestClassName); httpRequest = httpRequestClass.newInstance(); } catch (Exception e) { logger.error("ConfigServerManager.requestServerConfig cannot instantiate " + httpRequestClassName); httpRequest = new HttpRequest(); } } else { httpRequest = new HttpRequest(); } httpRequest.setUrl(url); HttpManager.getInstance().execute(httpRequest, CONFIG_SERVER_MANAGER_INTENT_ACTION_SUFFIX, CONFIG_SERVER_MANAGER_THREAD_POOL_NAME); } } } private BroadcastReceiver broadcastReceiver = new BitBroadcastReceiver() { @Override public void onHttpManagerBroadcastReceive(Context context, Intent intent, String intentActionSuffix, HttpResponseDocument result) { if(intentActionSuffix != null && intentActionSuffix.equals(CONFIG_SERVER_MANAGER_INTENT_ACTION_SUFFIX)) { synchronized(lock) { if(isRequestPending) { docList.add(result); if(docList.size() == requestList.length) { if(writeConfig(context)) { Config.getInstance().reset(Config.getInstance().getBooleanProperty(CONFIG_SERVER_MANAGER_TIMER_CANCEL_KEY, false)); } isRequestPending = false; } } } } } }; private boolean writeConfig(Context context) { if(Util.nullOrEmptyList(docList)) { return false; } // all documents need to be valid for(HttpResponseDocument doc : docList) { if(!(doc != null && doc.getStatusCode() == 200 && !Util.nullOrEmptyString(doc.getPageSource()))) { return false; } } // clean previous config files String[] fileList = context.fileList(); for(String file : fileList) { if(file.endsWith(".config.txt") && !file.equals(Config.CONFIG_LOCAL_FILE)) { context.deleteFile(file); } } for(HttpResponseDocument doc : docList) { String url = doc.getSourceUrl(); int index = url.lastIndexOf("/"); if(index != -1) { String fileName = url.substring(index+1); try { BufferedOutputStream out = new BufferedOutputStream(context.openFileOutput(fileName, Context.MODE_PRIVATE)); out.write(doc.getPageSource().getBytes()); out.close(); } catch (IOException e) { logger.error("ConfigServerManager.writeConfig exception.", e); } } } return true; } }
package com.redhat.ceylon.compiler.typechecker.tree; import java.io.StringWriter; import java.util.ArrayList; import java.util.List; import org.antlr.runtime.Token; import org.antlr.runtime.tree.CommonTree; import com.redhat.ceylon.compiler.typechecker.analyzer.AnalysisError; import com.redhat.ceylon.compiler.typechecker.model.Scope; import com.redhat.ceylon.compiler.typechecker.model.Unit; import com.redhat.ceylon.compiler.typechecker.util.PrintVisitor; public abstract class Node { private String text; private final CommonTree antlrTreeNode; private Scope scope; private Unit unit; private List<AnalysisError> errors = new ArrayList<AnalysisError>(); protected Node(CommonTree antlrTreeNode) { this.antlrTreeNode = antlrTreeNode; text = antlrTreeNode.getText(); correctLineNumber(antlrTreeNode); } /** * The scope within which the node occurs. */ public Scope getScope() { return scope; } public void setScope(Scope scope) { this.scope = scope; } /** * The compilation unit in which the node * occurs. */ public Unit getUnit() { return unit; } public void setUnit(Unit unit) { this.unit = unit; } /** * The text of the corresponding ANTLR node. */ public String getText() { return text; } public void setText(String text) { this.text = text; } /** * The text of the corresponding ANTLR tree node. Never null, * since the two trees are isomorphic. */ public CommonTree getAntlrTreeNode() { return antlrTreeNode; } /** * The compilation errors belonging to this node. */ public List<AnalysisError> getErrors() { return errors; } public void addError(String message) { errors.add( new AnalysisError(this, message) ); } public abstract void visitChildren(Visitor visitor); @Override public String toString() { StringWriter w = new StringWriter(); PrintVisitor pv = new PrintVisitor(w); pv.visitAny(this); return w.toString(); //return getClass().getSimpleName() + "(" + text + ")"; } public String getNodeType() { return getClass().getSimpleName(); } public static void correctLineNumber(CommonTree node) { Token token = node.getToken(); if (token!=null && !hasLocation(token)) { Token t = getFirstChildToken(node); if (t==null) { t = getParentToken(node); } if (t!=null) { copyLocation(t, token); } } } private static Token getFirstChildToken(CommonTree node) { @SuppressWarnings("rawtypes") List children = node.getChildren(); if (children!=null) { for (Object child: children) { if (child instanceof CommonTree) { Token ct = ((CommonTree) child).getToken(); if (ct!=null && hasLocation(ct)) { return ct; } else { Token st = getFirstChildToken((CommonTree) child); if (st!=null) return st; } } } } return null; } private static Token getParentToken(CommonTree node) { org.antlr.runtime.tree.Tree parent = node.getParent(); if (parent!=null && parent instanceof CommonTree) { Token pt = ((CommonTree) parent).getToken(); if (pt!=null && hasLocation(pt)) { return pt; } } return null; } private static void copyLocation(Token from, Token to) { to.setLine(from.getLine()); to.setCharPositionInLine(from.getCharPositionInLine()); } private static boolean hasLocation(Token token) { return token.getLine()!=0 || token.getCharPositionInLine()!=-1; } }
package com.syncleus.tests.dann.genetics; import com.syncleus.dann.genetics.*; import java.util.*; import org.junit.*; public class TestGeneticCube { private class VolumeAreaCubeFitness extends GeneticAlgorithmFitnessFunction { private double IDEAL_AREA = 2200d; private double IDEAL_VOLUME = 6000d; public VolumeAreaCubeFitness(GeneticAlgorithmChromosome chromosome) { super(chromosome); if(chromosome.getGenes().size() < 3) throw new IllegalArgumentException("Chromosome must have atleast 3 genes"); } public double getError() { List<ValueGene> genes = this.getChromosome().getGenes(); double side1 = genes.get(0).expressionActivity(); double side2 = genes.get(1).expressionActivity(); double side3 = genes.get(2).expressionActivity(); double volume = side1 * side2 * side3; double area = (side1*side2*2d)+(side1*side3*2d)+(side2*side3*2d); double volumeError = Math.abs(IDEAL_VOLUME - volume); double areaError = Math.abs(IDEAL_AREA - area); return volumeError + areaError; } public int compareTo(GeneticAlgorithmFitnessFunction baseCompareWith) { if(!(baseCompareWith instanceof VolumeAreaCubeFitness)) throw new ClassCastException("Can only compare with VolumeAreaCubeFitness"); VolumeAreaCubeFitness compareWith = (VolumeAreaCubeFitness) baseCompareWith; if(this.getError() < compareWith.getError()) return 1; else if(this.getError() == compareWith.getError()) return 0; else return -1; } } private class VolumeAreaCubePopulation extends GeneticAlgorithmPopulation { public VolumeAreaCubePopulation(Set<GeneticAlgorithmChromosome> initialChromosomes) { super(initialChromosomes, 0.25d, 0.75d, 0.95d); } protected GeneticAlgorithmFitnessFunction packageChromosome(GeneticAlgorithmChromosome chromosome) { return new VolumeAreaCubeFitness(chromosome); } } @Test public void testVolumeArea() { HashSet<GeneticAlgorithmChromosome> cubeChromosomes = new HashSet<GeneticAlgorithmChromosome>(); while(cubeChromosomes.size() < 100) { cubeChromosomes.add(new GeneticAlgorithmChromosome(3, 10d)); } VolumeAreaCubePopulation population = new VolumeAreaCubePopulation(cubeChromosomes); VolumeAreaCubeFitness fitness = new VolumeAreaCubeFitness(population.getWinner()); while((population.getGenerations() < 10000)&&(fitness.getError() > 0.1d)) { population.nextGeneration(); fitness = new VolumeAreaCubeFitness(population.getWinner()); } Assert.assertTrue("Volume/Area Cube failed (error was too great)" + fitness.getError(), fitness.getError() < 0.1d); } }
package com.tactfactory.harmony.template; import java.util.Collection; import java.util.List; import com.tactfactory.harmony.meta.EntityMetadata; import com.tactfactory.harmony.plateforme.IAdapter; import com.tactfactory.harmony.updater.IUpdater; import com.tactfactory.harmony.utils.ConsoleUtils; /** * SQLite Generator. */ public class SQLiteGenerator extends BaseGenerator<IAdapter> { /** * Constructor. * @param adapter The adapter to use * @throws Exception if adapter is null */ public SQLiteGenerator(final IAdapter adapter) throws Exception { super(adapter); this.setDatamodel(this.getAppMetas().toMap(this.getAdapter())); } /** * Generate the adapters and the criterias. */ public final void generateAll() { ConsoleUtils.display(">> Generate Adapter..."); this.getDatamodel().put("dataLoader", this.getAdapter().getAdapterProject() .isDataLoaderAlreadyGenerated()); this.generateDatabase(); Collection<EntityMetadata> metas = this.getAppMetas().getEntities().values(); for (final EntityMetadata classMeta : metas) { if (classMeta.hasFields()) { this.getDatamodel().put( TagConstant.CURRENT_ENTITY, classMeta.getName()); this.generateAdapters(classMeta); } } ConsoleUtils.display(">> Generate CriteriaBase..."); List<IUpdater> files = this.getAdapter().getAdapterProject().getCriteriasFiles(); this.processUpdater(files); } /** * Generate Database Interface Source Code. */ public final void generateDatabase() { // Info ConsoleUtils.display(">> Generate Database"); try { List<IUpdater> files = this.getAdapter().getAdapterProject().getDatabaseFiles(); this.processUpdater(files); } catch (final Exception e) { ConsoleUtils.displayError(e); } } /** * Generate the current entity's adapters. */ private void generateAdapters(EntityMetadata entity) { // Info ConsoleUtils.display(">>> Generate Adapter for " + this.getDatamodel().get(TagConstant.CURRENT_ENTITY)); try { List<IUpdater> files = this.getAdapter().getAdapterProject() .getSqlAdapterEntityFiles(entity); this.processUpdater(files); } catch (final Exception e) { ConsoleUtils.displayError(e); } } }
package com.tilioteo.hypothesis.dao; import java.io.Serializable; import java.lang.reflect.ParameterizedType; import java.util.List; import org.hibernate.Criteria; import org.hibernate.LockOptions; import org.hibernate.Session; import org.hibernate.criterion.Criterion; import com.tilioteo.hypothesis.servlet.HibernateUtil; /** * @author Kamil Morong - Hypothesis * */ public abstract class AbstractHibernateDao<T, ID extends Serializable> implements GenericDao<T, ID> { private Class<T> persistentClass; /** * Class constructor */ @SuppressWarnings("unchecked") public AbstractHibernateDao() { this.persistentClass = (Class<T>) ((ParameterizedType) getClass() .getGenericSuperclass()).getActualTypeArguments()[0]; } /** * Sets the hibernate session for making transactions with the db * * @param s * the session to be set */ /* * public void setSession(Session s) { this.session = s; } */ @Override public void beginTransaction() { HibernateUtil.beginTransaction(); } /** * Clears completely the session */ public void clear() { getSession().clear(); } @Override public void commit() { flush(); HibernateUtil.commitTransaction(); } @Override public List<T> findAll() { return findByCriteria(); } public Criteria createCriteria() { return getSession().createCriteria(getPersistentClass()); } /** * Not used. But, it can be used inside subclasses as a convenience method * * @param criterion * @return */ @SuppressWarnings("unchecked") public List<T> findByCriteria(Criterion... criterion) { Criteria crit = getSession().createCriteria(getPersistentClass()); for (Criterion c : criterion) { crit.add(c); } return crit.list(); } @SuppressWarnings("unchecked") @Override public T findById(ID id, boolean lock) { T entity; if (lock) entity = (T) getSession().load(getPersistentClass(), id, LockOptions.UPGRADE); else entity = (T) getSession().load(getPersistentClass(), id); return entity; } /** * Forces the session to flush */ public void flush() { getSession().flush(); } /** * Returns the class of the entity * * @return the entity class */ public Class<T> getPersistentClass() { return persistentClass; } /** * Retrieves the session used for making transactions with the db * * @return the session retrieved */ public Session getSession() { return HibernateUtil.getSession(); } @Override public T makePersistent(T entity) { getSession().saveOrUpdate(entity); return entity; } /* * public T makePersistent(T entity) { if ((entity instanceof * SerializableIdObject && ((SerializableIdObject)entity).getId() == null) || * (entity instanceof SerializableUidObject && * ((SerializableUidObject)entity).getUid() == null)) { * getSession().save(entity); } else { getSession().merge(entity); } return * entity; } */ @Override public void makeTransient(T entity) { getSession().delete(entity); } @Override public void rollback() { HibernateUtil.rollbackTransaction(); } }
package com.tuinsomniacorp.eulerproject; /** * @author angel_banuelos * */ public class SmallestMultiple { /** * @param args */ public static void main(String[] args) { } }
package com.wb.nextgenlibrary.activity; import android.app.ActivityManager; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.pm.ActivityInfo; import android.content.res.Configuration; import android.graphics.drawable.ColorDrawable; import android.media.MediaPlayer; import android.net.Uri; import android.os.Bundle; import android.os.Handler; import android.os.HandlerThread; import android.support.v4.app.Fragment; import android.support.v7.widget.ListPopupWindow; import android.view.LayoutInflater; import android.view.Menu; import android.view.View; import android.view.ViewGroup; import android.view.Window; import android.view.animation.Animation; import android.view.animation.Transformation; import android.widget.AdapterView; import android.widget.BaseAdapter; import android.widget.FrameLayout; import android.widget.ImageView; import android.widget.ListAdapter; import android.widget.ProgressBar; import android.widget.RelativeLayout; import android.widget.TextView; import android.widget.Toast; import com.google.android.gms.cast.framework.CastButtonFactory; import com.google.android.gms.cast.framework.CastState; import com.wb.nextgenlibrary.NextGenExperience; import com.wb.nextgenlibrary.R; import com.wb.nextgenlibrary.analytic.NGEAnalyticData; import com.wb.nextgenlibrary.fragment.AbstractCastMainMovieFragment; import com.wb.nextgenlibrary.fragment.AbstractNGEMainMovieFragment; import com.wb.nextgenlibrary.fragment.IMEBottomFragment; import com.wb.nextgenlibrary.interfaces.NGEFragmentTransactionInterface; import com.wb.nextgenlibrary.interfaces.NGEPlaybackStatusListener.NextGenPlaybackStatus; import com.wb.nextgenlibrary.util.concurrent.ResultListener; import com.wb.nextgenlibrary.util.utils.F; import com.wb.nextgenlibrary.util.utils.NGEFragmentTransactionEngine; import com.wb.nextgenlibrary.util.utils.NextGenGlide; import com.wb.nextgenlibrary.util.utils.NextGenLogger; import com.wb.nextgenlibrary.util.utils.StringHelper; import com.wb.nextgenlibrary.videoview.IVideoViewActionListener; import com.wb.nextgenlibrary.videoview.ObservableVideoView; import com.wb.nextgenlibrary.widget.CustomMediaController; import com.wb.nextgenlibrary.widget.FontFitTextView; import com.wb.nextgenlibrary.widget.MainFeatureMediaController; import java.util.ArrayList; import java.util.List; import java.util.Timer; import java.util.TimerTask; public class InMovieExperience extends AbstractNGEActivity implements NGEFragmentTransactionInterface, DialogInterface.OnCancelListener { private final static String IS_PLAYER_PLAYING = "IS PLAYING"; private final static String RESUME_PLAYBACK_TIME = "RESUME_PLAYBACK_TIME"; protected ObservableVideoView interstitialVideoView; protected RelativeLayout containerView; protected View skipThisView; protected ProgressBar skipThisCounter; private View actionbarPlaceHolder; private TimerTask imeUpdateTask; private Timer imeUpdateTimer; private MainFeatureMediaController mediaController; //private ProgressDialog mDialog; private ProgressBar loadingView; NGEFragmentTransactionEngine fragmentTransactionEngine; IMEBottomFragment imeBottomFragment; private Uri INTERSTITIAL_VIDEO_URI = null; private Uri currentUri = null; private DRMStatus drmStatus = DRMStatus.NOT_INITIATED; private boolean bInterstitialVideoComplete = false; //TextView imeText; //IMEElementsGridFragment imeGridFragment; private long lastTimeCode = -1; private NextGenPlaybackStatus lastPlaybackStatus = null; AbstractNGEMainMovieFragment mainMovieFragment; int ecFragmentsCounter = 0; MediaPlayer commentaryAudioPlayer; CommentaryOnOffAdapter commentaryOnOffAdapter; ListPopupWindow commentaryPopupWindow; Menu mOptionsMenu; static enum DRMStatus{ SUCCESS, FAILED, IN_PROGRESS, NOT_INITIATED } @Override public void onCastStateChanged(int i) { switch (i){ case CastState.CONNECTED: setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT); resetMainMovieFragment(); startStreamPreparations(); if (isCommentaryAvailable()) actionBarRightTextView.setVisibility(View.GONE); break; case CastState.CONNECTING: break; case CastState.NO_DEVICES_AVAILABLE: break; case CastState.NOT_CONNECTED: setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_FULL_SENSOR); resetMainMovieFragment(); startStreamPreparations(); if (isCommentaryAvailable()) actionBarRightTextView.setVisibility(View.VISIBLE); break; } } @Override public void onCreate(Bundle savedInstanceState) { supportRequestWindowFeature(Window.FEATURE_ACTION_BAR_OVERLAY); super.onCreate(savedInstanceState); detectScreenShotService(); if (NextGenExperience.getMovieMetaData() == null) finish(); INTERSTITIAL_VIDEO_URI = Uri.parse(NextGenExperience.getMovieMetaData().getInterstitialVideoURL()); fragmentTransactionEngine = new NGEFragmentTransactionEngine(this); setContentView(R.layout.next_gen_videoview); loadingView = (ProgressBar)findViewById(R.id.next_gen_loading_progress_bar); if (loadingView != null){ loadingView.setBackgroundColor(getResources().getColor(android.R.color.transparent)); } actionbarPlaceHolder = findViewById(R.id.next_gen_ime_actionbar_placeholder); backgroundImageView = (ImageView)findViewById(R.id.ime_background_image_view); if (backgroundImageView != null){ if (NextGenExperience.getMovieMetaData().getExtraExperience().style != null) { String bgImgUrl = NextGenExperience.getMovieMetaData().getExtraExperience().style.getBackground().getImage().url; NextGenGlide.load(this, bgImgUrl).into(backgroundImageView); } } containerView = (RelativeLayout)findViewById(R.id.interstitial_container); skipThisView = findViewById(R.id.skip_this_layout); skipThisCounter = (ProgressBar) findViewById(R.id.skip_this_countdown); interstitialVideoView = (ObservableVideoView) findViewById(R.id.interstitial_video_view); interstitialVideoView.setOnErrorListener(getOnErrorListener()); interstitialVideoView.setOnPreparedListener(getOnPreparedListener()); interstitialVideoView.setOnCompletionListener(new MediaPlayer.OnCompletionListener() { @Override public void onCompletion(MediaPlayer mp) { updateImeFragment(NextGenPlaybackStatus.STOP, -1L); NextGenExperience.getNextGenEventHandler().setInterstitialWatchedForContent(NextGenExperience.getNextgenPlaybackObject()); bInterstitialVideoComplete = true; playMainMovie(); } }); interstitialVideoView.requestFocus(); imeBottomFragment = new IMEBottomFragment(); transitMainFragment(imeBottomFragment); resetMainMovieFragment(); if (isCommentaryAvailable()) { actionBarRightTextView.setText(getResources().getString(R.string.nge_commentary)); actionBarRightTextView.setCompoundDrawablesWithIntrinsicBounds(null, null, getResources().getDrawable(R.drawable.nge_commentary), null); actionBarRightTextView.setTextColor( getResources().getColor(R.color.gray)); commentaryOnOffAdapter = new CommentaryOnOffAdapter(); commentaryPopupWindow = new ListPopupWindow(this); commentaryPopupWindow.setModal(false); commentaryPopupWindow.setAdapter(commentaryOnOffAdapter); commentaryPopupWindow.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { commentaryOnOffAdapter.setSelection(position); if (position == 0){ // OFF switchCommentary(false); } else { switchCommentary(true); } commentaryPopupWindow.dismiss(); } }); actionBarRightTextView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //toggleCommentary(); if (commentaryPopupWindow.isShowing()) commentaryPopupWindow.dismiss(); else { commentaryPopupWindow.setAnchorView(actionBarRightTextView); commentaryPopupWindow.setContentWidth(measureContentWidth(commentaryOnOffAdapter)); commentaryPopupWindow.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.black))); commentaryPopupWindow.show(); } } }); } //resetActivePlaybackFragment(); } private void resetMainMovieFragment(){ try { int resumeTime = -1; if (mainMovieFragment != null) resumeTime = mainMovieFragment.getCurrentPosition(); if (isCasting()){ setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT); mainMovieFragment = NextGenExperience.getCastMovieFragmentClass().newInstance(); ((AbstractCastMainMovieFragment)mainMovieFragment).setCastControllers(mCastSession, remoteMediaClient, mSessionManager); }else mainMovieFragment = NextGenExperience.getMainMovieFragmentClass().newInstance(); mainMovieFragment.setResumeTime(resumeTime); mainMovieFragment.setLoadingView(loadingView); mainMovieFragment.setOnCompletionLister(new MediaPlayer.OnCompletionListener() { @Override public void onCompletion(MediaPlayer mp) { //launch extra Intent intent = new Intent(InMovieExperience.this, OutOfMovieActivity.class); startActivity(intent); finish(); } }); mediaController = new MainFeatureMediaController(this, mainMovieFragment); mediaController.setVisibilityChangeListener(new CustomMediaController.MediaControllerVisibilityChangeListener(){ public void onVisibilityChange(boolean bShow){ if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) { if (bShow) getSupportActionBar().show(); else getSupportActionBar().hide(); } } }); mainMovieFragment.setCustomMediaController(mediaController); mainMovieFragment.setPlaybackObject(NextGenExperience.getNextgenPlaybackObject()); //mainMovieFragment.setOnCompletionListener mainMovieFragment.setNextGenVideoViewListener(new IVideoViewActionListener() { @Override public void onTimeBarSeekChanged(int currentTime) { updateImeFragment(NextGenPlaybackStatus.SEEK, currentTime); } @Override public void onVideoResume() { updateImeFragment(NextGenPlaybackStatus.RESUME, mainMovieFragment.getCurrentPosition()); } @Override public void onVideoStart() { updateImeFragment(NextGenPlaybackStatus.RESUME, mainMovieFragment.getCurrentPosition()); } @Override public void onVideoPause() { updateImeFragment(NextGenPlaybackStatus.PAUSE, mainMovieFragment.getCurrentPosition()); } @Override public void onVideoComplete(){} }); }catch (InstantiationException ex){ }catch (IllegalAccessException iex){ } prepareCommentaryTrack(); playMainMovie(); } @Override public boolean onPrepareOptionsMenu(final Menu menu) { if (mOptionsMenu == null) { getMenuInflater().inflate(R.menu.next_gen_cast_option_menu, menu); mOptionsMenu = menu; return super.onCreateOptionsMenu(menu); } //resetMenuItems(); return true; } /** * Set up action bar items */ @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); getMenuInflater().inflate(R.menu.next_gen_cast_option_menu, menu); mOptionsMenu = menu; try { CastButtonFactory.setUpMediaRouteButton(getApplicationContext(), menu, R.id.menuChromecast); }catch (Exception ex){} if (actionBarRightTextView != null && actionBarRightTextView instanceof FontFitTextView) ((FontFitTextView)actionBarRightTextView).setNumberOfLinesAllowed(1); return true; } private int measureContentWidth(ListAdapter listAdapter) { ViewGroup mMeasureParent = null; int maxWidth = 0; View itemView = null; int itemType = 0; final ListAdapter adapter = listAdapter; final int widthMeasureSpec = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED); final int heightMeasureSpec = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED); final int count = adapter.getCount(); for (int i = 0; i < count; i++) { final int positionType = adapter.getItemViewType(i); if (positionType != itemType) { itemType = positionType; itemView = null; } if (mMeasureParent == null) { mMeasureParent = new FrameLayout(this); } itemView = adapter.getView(i, itemView, mMeasureParent); itemView.measure(widthMeasureSpec, heightMeasureSpec); final int itemWidth = itemView.getMeasuredWidth(); if (itemWidth > maxWidth) { maxWidth = itemWidth; } } return maxWidth; } class CommentaryOnOffAdapter extends BaseAdapter { private final String[] items = new String[]{getResources().getString(R.string.off_text), getResources().getString(R.string.director_commentary)}; int selectedIndex = 0; CommentaryOnOffAdapter() { } public void setSelection(int index){ selectedIndex = index; notifyDataSetChanged(); } @Override public int getCount() { return 2; } @Override public String getItem(int index) { return items[index]; } @Override public long getItemId(int position) { return position; } @Override public View getView(final int index, View view, ViewGroup arg2) { View target = null; if (view != null){ target = view; }else{ LayoutInflater inflate = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE); target = inflate.inflate(R.layout.nge_commentary_onoff, arg2, false); } TextView tView = (TextView)target.findViewById(R.id.commentary_text_button); tView.setText(getItem(index)); TextView description = (TextView) target.findViewById(R.id.commentary_description); ImageView iView = (ImageView)target.findViewById(R.id.commentary_radio_image); /* if (index > 0){ description.setText("Hear from the director in his own words about the decision he made"); description.setVisibility(View.VISIBLE); }else { description.setVisibility(View.GONE); }*/ if (index == selectedIndex){ tView.setTextColor(getResources().getColor(R.color.drawer_yellow)); iView.setImageDrawable(getResources().getDrawable(R.drawable.commentary_radio_button_selected)); }else { tView.setTextColor(getResources().getColor(R.color.white)); iView.setImageDrawable(getResources().getDrawable(R.drawable.commentary_radio_button)); } return target; } } @Override protected void onStart() { super.onStart(); hideShowNextGenView(); } @Override public void onBackPressed(){ if (ecFragmentsCounter == 1) finish(); else { getSupportFragmentManager().popBackStackImmediate(); ecFragmentsCounter = ecFragmentsCounter - 1; if (isPausedByIME){ isPausedByIME = false; if (mediaController.isShowing()){ mediaController.hide(); } //tr 9/28 } } } @Override protected boolean shouldUseActionBarSpacer(){ return false; } @Override String getTitleImageUrl(){ return NextGenExperience.getMovieMetaData().getTitletreatmentImageUrl(); } @Override public void onCancel(DialogInterface dialog) { dialog.cancel(); //this.finish(); } protected void updateImeFragment(final NextGenPlaybackStatus playbackStatus, final long timecode){ if (INTERSTITIAL_VIDEO_URI.equals(currentUri)) return; if (lastTimeCode == timecode - mainMovieFragment.getMovieOffsetMilliSecond() && lastPlaybackStatus == playbackStatus) return; lastPlaybackStatus = playbackStatus; lastTimeCode = timecode - mainMovieFragment.getMovieOffsetMilliSecond(); if (lastTimeCode < 0) lastTimeCode = 0; runOnUiThread(new Runnable() { @Override public void run() { if (InMovieExperience.this == null || InMovieExperience.this.isDestroyed() || InMovieExperience.this.isFinishing() ) return; if (imeBottomFragment != null) imeBottomFragment.playbackStatusUpdate(playbackStatus, lastTimeCode); } }); switch (playbackStatus){ case PREPARED: break; case STARTED: break; case STOP: break; case TIMESTAMP_UPDATE: break; } if (isCommentaryOn && isCommentaryAvailable()){ resyncCommentary(); /* TODO: should handle commentary here. resync if the timediference is more than 1/2 second and keep track of the player state with it's paused or playing */ } } @Override public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); hideShowNextGenView(); } public int getLayoutViewId(){ return R.layout.next_gen_videoview; } private void hideShowNextGenView(){ View nextGenView = findViewById(R.id.next_gen_ime_bottom_view); if (nextGenView == null) return; String label = "interstitial"; if (bInterstitialVideoComplete){ double percentageDbl = (double)mainMovieFragment.getCurrentPosition()/ (double)mainMovieFragment.getDuration() * 100.0; int percentage = ((int)((percentageDbl + 2.5) / 5) * 5); label = Integer.toString(percentage); } switch (this.getResources().getConfiguration().orientation) { case Configuration.ORIENTATION_PORTRAIT: nextGenView.setVisibility(View.VISIBLE); actionbarPlaceHolder.setVisibility(View.VISIBLE); if (mediaController != null) mediaController.hideShowControls(true); NGEAnalyticData.reportEvent(InMovieExperience.this, null, NGEAnalyticData.AnalyticAction.ACTION_ROTATE_SCREEN_SHOW_EXTRAS, label, null); break; case Configuration.ORIENTATION_LANDSCAPE: try { Fragment fragment = getSupportFragmentManager().findFragmentById(getMainFrameId()); if (!(fragment instanceof IMEBottomFragment) ){ onBackPressed(); } }catch (Exception ex){} nextGenView.setVisibility(View.GONE); actionbarPlaceHolder.setVisibility(View.GONE); getSupportActionBar().hide(); if (mediaController != null) mediaController.hideShowControls(false); NGEAnalyticData.reportEvent(InMovieExperience.this, null, NGEAnalyticData.AnalyticAction.ACTION_ROTATE_SCREEN_HIDE_EXTRAS, label, null); imeBottomFragment.onOrientationChange(this.getResources().getConfiguration().orientation); } } @Override boolean shouldHideActionBar(){ return (this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE); } private class ErrorListener implements MediaPlayer.OnErrorListener { @Override public boolean onError(MediaPlayer mp, int what, int extra) { return true; } } protected MediaPlayer.OnErrorListener getOnErrorListener(){ return new ErrorListener(); } private class ProgressBarAnimation extends Animation{ private ProgressBar progressBar; public ProgressBarAnimation(ProgressBar progressBar) { super(); this.progressBar = progressBar; } @Override protected void applyTransformation(float interpolatedTime, Transformation t) { super.applyTransformation(interpolatedTime, t); float value = 0 + (100) * interpolatedTime; progressBar.setProgress((int) value); } } private class PreparedListener implements MediaPlayer.OnPreparedListener { @Override public void onPrepared(MediaPlayer mp) { interstitialVideoView.start(); skipThisView.setVisibility(View.VISIBLE); skipThisView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { runOnUiThread(new Runnable() { @Override public void run() { bInterstitialVideoComplete = true; NextGenExperience.getNextGenEventHandler().setInterstitialSkippedForContent(NextGenExperience.getNextgenPlaybackObject()); playMainMovie(); NGEAnalyticData.reportEvent(InMovieExperience.this, null, NGEAnalyticData.AnalyticAction.ACTION_SKIP_INTERSTITIAL, null, null); } }); } }); skipThisCounter.setProgress(0); skipThisCounter.setProgress(100); ProgressBarAnimation skipProgressBarAnim = new ProgressBarAnimation(skipThisCounter); skipProgressBarAnim.setDuration(mp.getDuration()); skipThisCounter.startAnimation(skipProgressBarAnim); return; } } protected MediaPlayer.OnPreparedListener getOnPreparedListener(){ return new PreparedListener(); } private synchronized void playMainMovie(){ currentUri = Uri.parse(""); if (drmStatus == DRMStatus.IN_PROGRESS){ // show loading mainMovieFragment.showLoadingView(); /*mDialog.setCanceledOnTouchOutside(false); mDialog.setMessage(getResources().getString(R.string.loading)); mDialog.show();*/ return; }else if (drmStatus == DRMStatus.FAILED){ //Show error Message and exit finish(); return; } else if (!bInterstitialVideoComplete){ // wait for interstitial video to be finished return; } if (skipThisView != null) { skipThisView.setVisibility(View.GONE); skipThisView.setOnClickListener(null); } interstitialVideoView.stopPlayback(); interstitialVideoView.setVisibility(View.GONE); mainMovieFragment.hideLoadingView(); //mDialog.hide(); fragmentTransactionEngine.replaceFragment(getSupportFragmentManager(), R.id.video_view_frame, mainMovieFragment); if (imeUpdateTimer == null){ imeUpdateTimer = new Timer(); } if (imeUpdateTask == null){ imeUpdateTask = new TimerTask() { @Override public void run() { if (InMovieExperience.this != null && !InMovieExperience.this.isFinishing() && !InMovieExperience.this.isDestroyed()) updateImeFragment(NextGenPlaybackStatus.TIMESTAMP_UPDATE, mainMovieFragment.getCurrentPosition()); } }; imeUpdateTimer.scheduleAtFixedRate(imeUpdateTask, 0, 1000); } updateImeFragment(NextGenPlaybackStatus.PREPARED, -1L); } int resumePlayTime = -1; boolean shouldStartAfterResume = true; @Override public void onPause() { shouldStartAfterResume = mainMovieFragment.isPlaying(); resumePlayTime = mainMovieFragment.getCurrentPosition(); if (isCommentaryOn && commentaryAudioPlayer != null){ commentaryAudioPlayer.pause(); } if (!bInterstitialVideoComplete && interstitialVideoView.isPlaying()){ interstitialVideoView.pause(); } super.onPause(); } public void onResume() { if (resumePlayTime != -1){ mainMovieFragment.setResumeTime(resumePlayTime); if (!shouldStartAfterResume && !isCasting()) mainMovieFragment.pause(); } super.onResume(); if (currentUri == null || StringHelper.isEmpty(currentUri.toString())) { currentUri = INTERSTITIAL_VIDEO_URI; drmStatus = DRMStatus.IN_PROGRESS; if (NextGenExperience.getNextGenEventHandler().shouldShowInterstitialForContent(NextGenExperience.getNextgenPlaybackObject())) { interstitialVideoView.setVisibility(View.VISIBLE); interstitialVideoView.setVideoURI(currentUri); } else { bInterstitialVideoComplete = true; playMainMovie(); } startStreamPreparations(); } else{ skipThisView.setVisibility(View.GONE); skipThisView.setOnClickListener(null); currentUri = Uri.parse(""); } if (!bInterstitialVideoComplete && interstitialVideoView.getVisibility() == View.VISIBLE){ interstitialVideoView.resume(); } hideShowNextGenView(); } private void startStreamPreparations(){ mainMovieFragment.streamStartPreparations(new ResultListener<Boolean>() { @Override public void onResult(Boolean result) { drmStatus = DRMStatus.SUCCESS; runOnUiThread(new Runnable() { @Override public void run() { if (!InMovieExperience.this.isDestroyed() && !InMovieExperience.this.isFinishing()) playMainMovie(); } }); } @Override public <E extends Exception> void onException(E e) { drmStatus = DRMStatus.FAILED; } }); } @Override public void onDestroy() { super.onDestroy(); if (mediaController != null){ mediaController.onPlayerDestroy(); } if (imeUpdateTask != null) { imeUpdateTask.cancel(); imeUpdateTask = null; } if (imeUpdateTimer != null){ imeUpdateTimer.cancel(); imeUpdateTimer = null; } if (fragmentTransactionEngine != null) fragmentTransactionEngine.onDestroy(); if (commentaryAudioPlayer != null){ if (isCommentaryOn) commentaryAudioPlayer.stop(); commentaryAudioPlayer.release(); } } @Override public void resetUI(boolean isRoot){ } public int getMainFrameId(){ return R.id.next_gen_ime_bottom_view; } public int getLeftFrameId(){ return R.id.next_gen_ime_bottom_view; } public int getRightFrameId(){ return R.id.next_gen_ime_bottom_view; } boolean isPausedByIME = false; public void pauseMovieForImeECPiece(){ if (mediaController.isShowing()){ mediaController.hide(); } mainMovieFragment.pauseForIME(); isPausedByIME = true; } //tr 9/28 public void resumeMovideForImeECPiece(){ if (mediaController.isShowing()){ mediaController.hide(); } mainMovieFragment.resumePlaybackFromIME(); isPausedByIME = true; } @Override public void transitLeftFragment(Fragment nextFragment){ fragmentTransactionEngine.transitFragment(getSupportFragmentManager(), getLeftFrameId(), nextFragment); } @Override public void transitRightFragment(Fragment nextFragment){ fragmentTransactionEngine.transitFragment(getSupportFragmentManager(), getRightFrameId(), nextFragment); } @Override public void transitMainFragment(Fragment nextFragment){ ecFragmentsCounter = ecFragmentsCounter + 1; fragmentTransactionEngine.transitFragment(getSupportFragmentManager(), getMainFrameId(), nextFragment); } @Override public int getLeftButtonLogoId(){ return R.drawable.home_logo; } @Override public String getBackgroundImgUri(){ return ""; } @Override public String getLeftButtonText(){ return getResources().getString(R.string.home_button_text); } public String getRightTitleImageUri(){ return ""; } @Override protected void onLeftTopActionBarButtonPressed(){ finish(); } @Override public String getRightTitleText(){ return ""; } private boolean isCommentaryAvailable(){ return !StringHelper.isEmpty(NextGenExperience.getMovieMetaData().getCommentaryTrackURL()); } private boolean isCommentaryOn = false; private NGECommentaryPlayersStatusListener commentaryPlayersStatusListener = null; private void prepareCommentaryTrack(){ if (isCommentaryAvailable()) { if (mainMovieFragment.canHandleCommentaryAudioTrackSwitching()){ List<String> commentaries = new ArrayList<>(); commentaries.add(NextGenExperience.getMovieMetaData().getCommentaryTrackURL()); mainMovieFragment.setCommentaryTrackUrls(commentaries); }else { try { commentaryAudioPlayer = MediaPlayer.create(this, Uri.parse(NextGenExperience.getMovieMetaData().getCommentaryTrackURL())); commentaryAudioPlayer.setLooping(false); commentaryPlayersStatusListener = new NGECommentaryPlayersStatusListener(); commentaryAudioPlayer.setOnPreparedListener(commentaryPlayersStatusListener); commentaryAudioPlayer.setOnInfoListener(commentaryPlayersStatusListener); } catch (Exception ex) { NextGenLogger.e(F.TAG, ex.getMessage()); } } } } private class NGECommentaryPlayersStatusListener implements MediaPlayer.OnPreparedListener, MediaPlayer.OnCompletionListener, MediaPlayer.OnInfoListener { private NextGenPlaybackStatus playerStatus = NextGenPlaybackStatus.BUFFERING; public NextGenPlaybackStatus getPlayerStatus(){ return playerStatus; } @Override public void onPrepared(MediaPlayer mp) { playerStatus = NextGenPlaybackStatus.READY; resyncCommentary(); } @Override public void onCompletion(MediaPlayer mp) { playerStatus = NextGenPlaybackStatus.COMPLETED; } @Override public boolean onInfo(MediaPlayer mp, int what, int extra) { NextGenLogger.d(F.TAG_COMMENTARY, "CommentaryPlayer " + InMovieExperience.this.getClass().getSimpleName() + ".onInfo: " + what); switch (what) { case MediaPlayer.MEDIA_INFO_BUFFERING_START: // @since API Level 9 NextGenLogger.d(F.TAG_COMMENTARY, "CommentaryPlayer.onInfo: MEDIA_INFO_BUFFERING_START"); playerStatus = NextGenPlaybackStatus.BUFFERING; resyncCommentary(); break; case MediaPlayer.MEDIA_INFO_BUFFERING_END: // @since API Level 9 NextGenLogger.d(F.TAG_COMMENTARY, "CommentaryPlayer.onInfo: MEDIA_INFO_BUFFERING_END"); playerStatus = NextGenPlaybackStatus.READY; resyncCommentary(); //mDialog.hide(); break; case MediaPlayer.MEDIA_INFO_VIDEO_RENDERING_START: playerStatus = NextGenPlaybackStatus.READY; resyncCommentary(); //mDialog.hide(); break; default: //mDialog.hide(); break; } return true; } } /* private void toggleCommentary(){ if (isCommentaryAvailable() && commentaryAudioPlayer != null){ if (isCommentaryOn) { // turning commentary off isCommentaryOn = false; resyncCommentary(); }else { // turning commentary on isCommentaryOn = true; resyncCommentary(); commentaryAudioPlayer.start(); commentaryAudioPlayer.seekTo(mainMovieFragment.getCurrentPosition() - mainMovieFragment.getMovieOffsetMilliSecond()); } } actionBarRightTextView.setTextColor(isCommentaryOn? getResources().getColor(R.color.drawer_yellow) : getResources().getColor(R.color.gray)); }*/ private void switchCommentary(boolean bOnOff){ isCommentaryOn = bOnOff; if (isCommentaryAvailable()){ if (mainMovieFragment.canHandleCommentaryAudioTrackSwitching()){ mainMovieFragment.setActiveCommentaryTrack(bOnOff ? 0 : -1); }else if (commentaryAudioPlayer != null) { if (!bOnOff) { // turning commentary off resyncCommentary(); } else { // turning commentary on resyncCommentary(); commentaryAudioPlayer.start(); commentaryAudioPlayer.seekTo(mainMovieFragment.getCurrentPosition() - mainMovieFragment.getMovieOffsetMilliSecond()); } } } if (isCommentaryOn) { actionBarRightTextView.setTextColor(getResources().getColor(R.color.drawer_yellow)); actionBarRightTextView.setText(getResources().getString(R.string.nge_commentary_on)); actionBarRightTextView.setCompoundDrawablesWithIntrinsicBounds(null, null, getResources().getDrawable(R.drawable.nge_commentary_on), null); } else { actionBarRightTextView.setTextColor(getResources().getColor(R.color.white)); actionBarRightTextView.setText(getResources().getString(R.string.nge_commentary)); actionBarRightTextView.setCompoundDrawablesWithIntrinsicBounds(null, null, getResources().getDrawable(R.drawable.nge_commentary), null); } } private boolean bPausedForCommentaryBuffering = false; private void resyncCommentary(){ if (isCommentaryAvailable() && !mainMovieFragment.canHandleCommentaryAudioTrackSwitching()){ if (isCommentaryOn){ if (commentaryPlayersStatusListener.getPlayerStatus() == NextGenPlaybackStatus.READY && mainMovieFragment.getPlaybackStatus() == NextGenPlaybackStatus.READY){ // both ready int mainMovieTime = mainMovieFragment.getCurrentPosition() - mainMovieFragment.getMovieOffsetMilliSecond(); if (mainMovieTime < 0) mainMovieTime = 0; int commentaryTime = commentaryAudioPlayer.getCurrentPosition(); int timeDifference = Math.abs(mainMovieTime - commentaryTime); if (timeDifference > 150) { // when they are out of sync i.e. more than 150 mini seconds apart. commentaryAudioPlayer.start(); commentaryAudioPlayer.seekTo(mainMovieTime); final boolean bWasPlaying ; if (mainMovieFragment.isPlaying()) { mainMovieFragment.pause(); bWasPlaying = true; }else bWasPlaying = false; commentaryAudioPlayer.setOnSeekCompleteListener(new MediaPlayer.OnSeekCompleteListener() { @Override public void onSeekComplete(MediaPlayer mp) { if (bWasPlaying){ try{ mainMovieFragment.resumePlayback(); }catch (Exception ex){} } } }); } if (mainMovieFragment.isPlaying()) { // if it's playing, check to see if recy commentaryAudioPlayer.start(); }else if (bPausedForCommentaryBuffering){ // if it's paused for commentary buffering bPausedForCommentaryBuffering = false; mainMovieFragment.resumePlayback(); commentaryAudioPlayer.start(); } else if (commentaryAudioPlayer.isPlaying()){ // if main movie is paused. commentaryAudioPlayer.pause(); } } else if (commentaryPlayersStatusListener.getPlayerStatus() == NextGenPlaybackStatus.BUFFERING || mainMovieFragment.getPlaybackStatus() == NextGenPlaybackStatus.BUFFERING){ // show loading progress bar and pause and wait for buffering completion if (commentaryPlayersStatusListener.getPlayerStatus() == NextGenPlaybackStatus.READY && commentaryAudioPlayer.isPlaying()) commentaryAudioPlayer.pause(); if (mainMovieFragment.getPlaybackStatus() == NextGenPlaybackStatus.READY){ bPausedForCommentaryBuffering = true; mainMovieFragment.pause(); } } mainMovieFragment.switchMainFeatureAudio(false); // turn off movie audio track } else{ // switch off commentary mainMovieFragment.switchMainFeatureAudio(true); // turn on movie audio track if (commentaryPlayersStatusListener.getPlayerStatus() == NextGenPlaybackStatus.READY && commentaryAudioPlayer.isPlaying()) commentaryAudioPlayer.pause(); } } } private android.os.Handler mHandler = null; private HandlerThread mHandlerThread = null; public void startHandlerThread(){ mHandlerThread = new HandlerThread("HandlerThread"); mHandlerThread.start(); mHandler = new Handler(mHandlerThread.getLooper()); } public void detectScreenShotService() { mHandlerThread = new HandlerThread("HandlerThread"); mHandlerThread.start(); mHandler = new Handler(mHandlerThread.getLooper()); final int delay = 3000; //milliseconds final ActivityManager am = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE); mHandler.postDelayed(new Runnable() { public void run() { List<ActivityManager.RunningServiceInfo> rs = am.getRunningServices(200); for (ActivityManager.RunningServiceInfo ar : rs) { if (ar.process.equals("com.android.systemui:screenshot")) { Toast.makeText(InMovieExperience.this, "Screenshot captured!!", Toast.LENGTH_LONG).show(); } } mHandler.postDelayed(this, delay); } }, delay); } }
package com.hearthsim.test; import com.hearthsim.Game; import com.hearthsim.card.Card; import com.hearthsim.card.Deck; import com.hearthsim.card.minion.Hero; import com.hearthsim.card.minion.Minion; import com.hearthsim.card.minion.heroes.Mage; import com.hearthsim.card.minion.heroes.Paladin; import com.hearthsim.exception.HSException; import com.hearthsim.model.PlayerModel; import com.hearthsim.player.playercontroller.ArtificialPlayer; import com.hearthsim.results.GameResult; import org.junit.Test; import static org.junit.Assert.assertTrue; public class testGame { private final org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(this.getClass()); @Test public void testGame0() { int numCardsInDeck_ = 30; byte minionAttack = 5; byte minionHealth = 4; byte minionMana = 4; int numTaunts_ = 30; Card[] cards1_ = new Card[numCardsInDeck_]; Card[] cards2_ = new Card[numCardsInDeck_]; for (int i = 0; i < numCardsInDeck_; ++i) { byte attack = minionAttack; byte health = minionHealth; byte mana = minionMana; cards1_[i] = new Minion("" + i, mana, attack, health, attack, health, health); cards2_[i] = new Minion("" + i, mana, attack, health, attack, health, health); } int nt = 0; while (nt < numTaunts_) { int irand = (int)(Math.random() * numCardsInDeck_); if (!((Minion)cards1_[irand]).getTaunt()) { ((Minion)cards1_[irand]).setTaunt(true); ++nt; } } Hero hero1 = new Paladin(); Hero hero2 = new Mage(); Deck deck1 = new Deck(cards1_); Deck deck2 = new Deck(cards2_); deck1.shuffle(); deck2.shuffle(); PlayerModel playerModel1 = new PlayerModel("player0", hero1, deck1); PlayerModel playerModel2 = new PlayerModel("player1", hero2, deck2); ArtificialPlayer ai0 = ArtificialPlayer.buildStandardAI1(); ArtificialPlayer ai1 = ArtificialPlayer.buildStandardAI1(); long t1 = System.nanoTime(); Game game = new Game(playerModel1, playerModel2, ai0, ai1, false); GameResult w = null; try { w = game.runGame(); } catch (HSException e) { w = new GameResult(0, -1, 0, null); } long t2 = System.nanoTime(); log.info("f = " + w.firstPlayerIndex_ + ", w = " + w.winnerPlayerIndex_ + ", time taken = " + (t2 - t1) / 1000000.0 + " ms"); assertTrue("testGame0", w.winnerPlayerIndex_ == 0); } @Test public void testGame1() { int numCardsInDeck_ = 30; byte minionAttack = 5; byte minionHealth = 4; byte minionMana = 4; Card[] cards1_ = new Card[numCardsInDeck_]; Card[] cards2_ = new Card[numCardsInDeck_]; for (int i = 0; i < numCardsInDeck_; ++i) { byte attack = minionAttack; byte health = minionHealth; byte mana = minionMana; cards1_[i] = new Minion("" + i, mana, attack, health, attack, health, health); cards2_[i] = new Minion("" + i, (byte)9, (byte)1, (byte)1, (byte)1, (byte)1, (byte)1); } Hero hero1 = new Hero(); Hero hero2 = new Hero(); Deck deck1 = new Deck(cards1_); Deck deck2 = new Deck(cards2_); deck1.shuffle(); deck2.shuffle(); PlayerModel playerModel1 = new PlayerModel("player0", hero1, deck1); PlayerModel playerModel2 = new PlayerModel("player1", hero2, deck2); ArtificialPlayer ai0 = ArtificialPlayer.buildStandardAI1(); ArtificialPlayer ai1 = ArtificialPlayer.buildStandardAI1(); for (int iter = 0; iter < 10; ++iter) { long t1 = System.nanoTime(); Game game = new Game(playerModel1, playerModel2, ai0, ai1, true); GameResult w = null; try { w = game.runGame(); } catch (HSException e) { w = new GameResult(0, -1, 0, null); } long t2 = System.nanoTime(); log.info("f = " + w.firstPlayerIndex_ + ", w = " + w.winnerPlayerIndex_ + ", time taken = " + (t2 - t1) / 1000000.0 + " ms"); assertTrue("testGame0", w.winnerPlayerIndex_ == 0); } } }
package com.zenplanner.sql; import com.sun.org.apache.xerces.internal.impl.dv.util.HexBin; import junit.framework.Assert; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import java.nio.ByteBuffer; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.Statement; import java.util.*; import java.util.stream.Collectors; public class UuidTest extends TestCase { private static final int count = 100; public UuidTest(String testName) { super(testName); } public static Test suite() { return new TestSuite(UuidTest.class); } public void testApp() throws Exception { // Get 100 random UUIDs sorted by SQL List<Comparable<?>> sqlList = new ArrayList<>(); Class.forName("net.sourceforge.jtds.jdbc.Driver"); String conStr = "jdbc:jtds:sqlserver://localhost:1433/ZenPlanner-Development;user=zenwebdev;password=Enterprise!"; try (Connection con = DriverManager.getConnection(conStr)) { try(Statement stmt = con.createStatement()) { String sql = String.format("select top %s NEWID() as UUID from sys.sysobjects order by UUID;", count); try(ResultSet rs = stmt.executeQuery(sql)) { String type = rs.getMetaData().getColumnTypeName(1); while(rs.next()) { String str = rs.getString(1); byte[] bytes = rs.getBytes(1); String text = HexBin.encode(bytes); UUID byteUuid = UUID.nameUUIDFromBytes(bytes); UUID strUuid = UUID.fromString(str); ByteBuffer bb = ByteBuffer.wrap(bytes); long firstLong = bb.getLong(); long secondLong = bb.getLong(); UUID bbUuid = new UUID(firstLong, secondLong); byte[] buff = ByteBuffer.allocate(16) .putLong(strUuid.getMostSignificantBits()) .putLong(strUuid.getLeastSignificantBits()) .array(); String hexStr = addDashes(HexBin.encode(buff)); Assert.assertEquals(byteUuid, strUuid); sqlList.add(byteUuid); } } } } // Clone the list and sort with Java List<Comparable<?>> javaList = sqlList.stream().sorted().collect(Collectors.toList()); // Test for correct order boolean eq = true; for(int i = 0; i < javaList.size(); i++) { Comparable sqlId = sqlList.get(i); Comparable javaId = javaList.get(i); if(sqlId.compareTo(javaId) != 0) { eq = false; } } Assert.assertTrue(eq); } private String addDashes(String hex) { return String.format("%s-%s-%s-%s-%s", hex.substring(0,8), hex.substring(8,12), hex.substring(12,16), hex.substring(16,20), hex.substring(20,32)); } }
package diffbot.test; import static junit.framework.Assert.*; import static com.google.common.base.Strings.*; import java.io.IOException; import org.junit.Before; import org.junit.Test; import diffboat.api.DiffbotAPI; import diffboat.model.Article; public class ArticleAPITest { private String token; @Before public void setup() { token = System.getProperty("token"); if (isNullOrEmpty(token)) { token = System.getenv("token"); } } @Test public void must_extract_article_text() throws IOException { String uri = "http: Article article = new DiffbotAPI(this.token) .article() .extractFrom(uri) .withTags() .withComments() .withSummary() .analyze(); assertNotNull(article); assertNotNull(article.getText()); } }
package io.redlink.sdk; import com.google.common.collect.Iterables; import com.google.common.collect.Multimap; import io.redlink.sdk.analysis.AnalysisRequest; import io.redlink.sdk.analysis.AnalysisRequest.AnalysisRequestBuilder; import io.redlink.sdk.analysis.AnalysisRequest.OutputFormat; import io.redlink.sdk.impl.analysis.model.*; import org.apache.commons.io.IOUtils; import org.codehaus.jettison.json.JSONException; import org.codehaus.jettison.json.JSONObject; import org.junit.*; import org.openrdf.model.vocabulary.DCTERMS; import org.openrdf.model.vocabulary.RDF; import org.openrdf.model.vocabulary.RDFS; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.xml.sax.InputSource; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import java.io.IOException; import java.io.InputStream; import java.io.StringReader; import java.util.Collection; import java.util.Map; public class AnalysisTest extends GenericTest { private static Logger log = LoggerFactory.getLogger(AnalysisTest.class); private static RedLink.Analysis redlink; private static final String TEST_FILE = "/willsmith.txt"; private static final String TEST_ANALYSIS = "test"; private static final String STANBOL_TEXT_TO_ENHANCE = "The Open Source Project Apache Stanbol provides different " + "features that facilitate working with linked data, in the netlabs.org early adopter proposal VIE " + "I wanted to try features which were not much used before, like the Ontology Manager and the Rules component. " + "The News of the project can be found on the website! Rupert Westenthaler, living in Austria, " + "is the main developer of Stanbol. The System is well integrated with many CMS like Drupal and Alfresco."; private static String PARIS_TEXT_TO_ENHANCE = "Paris is the capital of France"; private static final String DEREFERENCING_TEXT = "Roberto Baggio is a retired Italian football forward and attacking midfielder/playmaker" + " who was the former President of the Technical Sector of the FIGC. Widely regarded as one of the greatest footballers of all time, " + "he came fourth in the FIFA Player of the Century Internet poll, and was chosen as a member of the FIFA World Cup Dream Team"; @BeforeClass public static void setUpBeforeClass() throws Exception { Credentials credentials = buildCredentials(AnalysisTest.class); Assume.assumeNotNull(credentials); Assume.assumeNotNull(credentials.getVersion()); Assume.assumeTrue(credentials.verify()); redlink = RedLinkFactory.createAnalysisClient(credentials); } @AfterClass public static void tearDownAfterClass() throws Exception { redlink = null; } /** * <p>Tests the empty enhancements when an empty string is sent to the API</p> */ @Test public void testEmptyEnhancement() { AnalysisRequest request = AnalysisRequest.builder() .setAnalysis(TEST_ANALYSIS) .setContent(" ") .setOutputFormat(OutputFormat.TURTLE).build(); Enhancements enhancements = redlink.enhance(request); Assert.assertNotNull(enhancements); //Assert.assertEquals(0, enhancements.getModel().size()); Assert.assertEquals(0, enhancements.getEnhancements().size()); Assert.assertEquals(0, enhancements.getTextAnnotations().size()); Assert.assertEquals(0, enhancements.getEntityAnnotations().size()); } @Test public void testFile() { InputStream in = this.getClass().getResourceAsStream(TEST_FILE); AnalysisRequest request = AnalysisRequest.builder() .setAnalysis(TEST_ANALYSIS) .setContent(in) .setOutputFormat(OutputFormat.TURTLE).build(); Enhancements enhancements = redlink.enhance(request); Assert.assertNotNull(enhancements); Assert.assertFalse(enhancements.getEnhancements().isEmpty()); } /** * <p>Tests the size of the obtained enhancements</p> */ @Test public void testDemoEnhancement() { AnalysisRequest request = AnalysisRequest.builder() .setAnalysis(TEST_ANALYSIS) .setContent(PARIS_TEXT_TO_ENHANCE) .setOutputFormat(OutputFormat.RDFXML).build(); Enhancements enhancements = redlink.enhance(request); Assert.assertNotNull(enhancements); // Assert.assertNotEquals(0, enhancements.getModel().size()); int sizeE = enhancements.getEnhancements().size(); Assert.assertNotEquals(0, sizeE); int sizeTA = enhancements.getTextAnnotations().size(); Assert.assertNotEquals(0, sizeTA); int sizeEA = enhancements.getEntityAnnotations().size(); Assert.assertNotEquals(0, sizeEA); Assert.assertEquals(sizeE, sizeTA + sizeEA); //Best Annotation testEnhancementBestAnnotations(enhancements); // Filter By Confidence testGetEntityAnnotationByConfidenceValue(enhancements); // Entity Properties testEntityProperties(enhancements); } /** * <p>Tests the properties of the enhancements</p> */ @Test public void testEnhancementProperties() { AnalysisRequest request = AnalysisRequest.builder() .setAnalysis(TEST_ANALYSIS) .setContent(STANBOL_TEXT_TO_ENHANCE) .setOutputFormat(OutputFormat.RDFXML).build(); Enhancements enhancements = redlink.enhance(request); Assert.assertFalse(enhancements.getLanguages().isEmpty()); Assert.assertFalse(enhancements.getTextAnnotations().isEmpty()); Assert.assertFalse(enhancements.getEntityAnnotations().isEmpty()); Assert.assertFalse(enhancements.getEntities().isEmpty()); for (Enhancement en : enhancements.getEnhancements()) { Assert.assertNotEquals(0, en.getConfidence()); Assert.assertNotNull(en.getConfidence()); if (en instanceof TextAnnotation) { testTextAnnotationProperties((TextAnnotation) en); } else if (en instanceof EntityAnnotation) { testEntityAnnotationProperties((EntityAnnotation) en); } } } /** * <p>Tests the {@code TextAnnotation} properties</p> * * @param ta the TextAnnotation object */ private void testTextAnnotationProperties(TextAnnotation ta) { Assert.assertEquals("en", ta.getLanguage()); Assert.assertNotEquals("", ta.getSelectionContext()); Assert.assertNotNull(ta.getSelectionContext()); Assert.assertNotEquals("", ta.getSelectedText()); Assert.assertNotNull(ta.getSelectedText()); Assert.assertNotEquals(0, ta.getEnds()); Assert.assertNotEquals(-1, ta.getStarts()); } /** * <p>Tests the {@code EntityAnnotation} properties</p> * * @param ea */ private void testEntityAnnotationProperties(EntityAnnotation ea) { Assert.assertNotEquals(ea.getEntityLabel(), ""); Assert.assertNotNull(ea.getEntityLabel()); Assert.assertNotNull(ea.getEntityReference()); Assert.assertNotNull(ea.getEntityTypes()); Assert.assertNotEquals(ea.getDataset(), ""); //Assert.assertNotNull(ea.getDataset()); } /** * <p>Tests the best annotations method</p> */ private void testEnhancementBestAnnotations(Enhancements enhancements) { Multimap<TextAnnotation, EntityAnnotation> bestAnnotations = enhancements.getBestAnnotations(); Assert.assertNotEquals(0, bestAnnotations.keySet().size()); Assert.assertEquals(bestAnnotations.keySet().size(), enhancements.getTextAnnotations().size()); for (TextAnnotation ta : bestAnnotations.keySet()) { //check all best have the same Collection<EntityAnnotation> eas = bestAnnotations.get(ta); Double confidence = Iterables.get(eas, 0).getConfidence(); for (EntityAnnotation ea : eas) { Assert.assertEquals(confidence, ea.getConfidence()); } //check the confidence is actually the highest for (EntityAnnotation ea : enhancements.getEntityAnnotations(ta)) { Assert.assertTrue(confidence >= ea.getConfidence()); } } } /** * <p>Tests the getTextAnnotationByConfidenceValue method</p> */ private void testGetEntityAnnotationByConfidenceValue(Enhancements enhancements) { Collection<EntityAnnotation> eas = enhancements.getEntityAnnotationsByConfidenceValue((0.5)); Assert.assertTrue(eas.size() > 0); } /** * <p>Tests the getTextAnnotationByConfidenceValue method</p> */ @Test public void testFilterEntitiesByConfidenceValue() { AnalysisRequest request = AnalysisRequest.builder() .setAnalysis(TEST_ANALYSIS) .setContent(STANBOL_TEXT_TO_ENHANCE) .setOutputFormat(OutputFormat.RDFXML).build(); Enhancements enhancements = redlink.enhance(request); Collection<EntityAnnotation> eas = enhancements.getEntityAnnotationsByConfidenceValue((0.9)); Assert.assertTrue(eas.size() > 0); } @Test public void testFormatResponses() { AnalysisRequestBuilder builder = AnalysisRequest.builder() .setAnalysis(TEST_ANALYSIS) .setContent(PARIS_TEXT_TO_ENHANCE); AnalysisRequest request = builder.setOutputFormat(OutputFormat.JSON).build(); String jsonResponse = redlink.enhance(request, String.class); try { new JSONObject(jsonResponse); } catch (JSONException e) { Assert.fail(e.getMessage()); } request = builder.setOutputFormat(OutputFormat.XML).build(); String xmlResponse = redlink.enhance(request, String.class); DocumentBuilderFactory domParserFac = DocumentBuilderFactory.newInstance(); try { DocumentBuilder db = domParserFac.newDocumentBuilder(); db.parse(new InputSource(new StringReader(xmlResponse))); } catch (Exception e) { Assert.fail(e.getMessage()); } Enhancements rdfResponse = redlink.enhance(builder.build(), Enhancements.class); Assert.assertFalse(rdfResponse.getEnhancements().isEmpty()); testEntityProperties(rdfResponse); } @Test public void testDereferencing() { // Dereferencing Fields AnalysisRequest request = AnalysisRequest.builder() .setAnalysis(TEST_ANALYSIS) .setContent(DEREFERENCING_TEXT) .addDereferencingField("fb:people.person.height_meters") .addDereferencingField("fb:people.person.date_of_birth") .addDereferencingField("dct:subject") .addDereferencingField("dbp:totalgoals") .setOutputFormat(OutputFormat.RDFXML).build(); Enhancements enhancements = redlink.enhance(request); Entity baggio = enhancements.getEntity("http://rdf.freebase.com/ns/m.06d6f"); Assert.assertEquals(baggio.getFirstPropertyValue( "http://rdf.freebase.com/ns/people.person.height_meters"), "1.74" ); Assert.assertEquals(baggio.getFirstPropertyValue( "http://rdf.freebase.com/ns/people.person.date_of_birth"), "1967-02-18" ); Entity baggioDBP = enhancements.getEntity("http://dbpedia.org/resource/Roberto_Baggio"); Assert.assertEquals(baggioDBP.getFirstPropertyValue( "http://purl.org/dc/terms/subject"), "http://dbpedia.org/resource/Category:Men" ); Assert.assertEquals(baggioDBP.getFirstPropertyValue( "http://dbpedia.org/property/totalgoals"), "221" ); //LdPath String date = "@prefix fb: <http://rdf.freebase.com/ns/>;" + "@prefix custom :<http://io.redlink/custom/freebase/>" + "custom:date = fb:people.person.date_of_birth :: xsd:string;" + "custom:nationality = fb:people.person.nationality/fb:location.location.adjectival_form :: xsd:string;"; request = AnalysisRequest.builder() .setAnalysis(TEST_ANALYSIS) .setContent(DEREFERENCING_TEXT) .setLDpathProgram(date) .setOutputFormat(OutputFormat.RDFXML).build(); enhancements = redlink.enhance(request); baggio = enhancements.getEntity("http://rdf.freebase.com/ns/m.06d6f"); String dateV = baggio.getFirstPropertyValue( "http://rdf.freebase.com/ns/people.person.date_of_birth"); String dateCustomV = baggio.getFirstPropertyValue( "http://io.redlink/custom/freebase/date"); Assert.assertEquals(dateV, dateCustomV); Assert.assertTrue(baggio.getValues( "http://io.redlink/custom/freebase/nationality") .contains("Italian")); } /** * Test for checking a non-deterministic behaviour (SDK-4) * */ @Test public void testSDK4() throws IOException { String content = IOUtils.toString(AnalysisTest.class.getResourceAsStream("/SDK-4.txt"), "utf8"); AnalysisRequest request = AnalysisRequest.builder() .setAnalysis(TEST_ANALYSIS) .setContent(content) .setOutputFormat(OutputFormat.TURTLE).build(); Enhancements enhancements = redlink.enhance(request); Multimap<TextAnnotation, EntityAnnotation> bestAnnotations = enhancements.getBestAnnotations(); for (TextAnnotation ta : bestAnnotations.keySet()) { Collection<EntityAnnotation> eas = bestAnnotations.get(ta); if (ta.getSelectedText().contains("Lopez")) { log.debug("Found target text annotation \"{}\" with {} entity annotation:", ta.getSelectedText(), eas.size()); for (EntityAnnotation ea : eas) { log.debug(" - {}", ea.getEntityReference().getUri()); } log.trace("selection content: {}", ta.getSelectionContext()); } } } /** * Test for checking an issue with some of the NLP engines * */ @Test public void testSDK5() throws IOException { String content = IOUtils.toString(AnalysisTest.class.getResourceAsStream("/SDK-5.txt"), "utf8"); AnalysisRequest request = AnalysisRequest.builder() .setAnalysis(TEST_ANALYSIS) .setContent(content) .setOutputFormat(OutputFormat.TURTLE).build(); Enhancements enhancements = redlink.enhance(request); Assert.assertEquals(11, enhancements.getTextAnnotations().size()); Assert.assertEquals(7, enhancements.getBestAnnotations().size()); } /** * Test Entities Parsing and Properties */ private void testEntityProperties(Enhancements enhancements) { Assert.assertFalse(enhancements.getEntities().isEmpty()); Entity paris = enhancements.getEntity("http://dbpedia.org/resource/Paris"); Assert.assertNotNull(paris); Assert.assertFalse(paris.getProperties().isEmpty()); //entity has been added to the analysis result Assert.assertFalse(paris.getProperties().isEmpty()); Assert.assertFalse(paris.getValues(RDFS.LABEL.toString()).isEmpty()); Assert.assertEquals("Paris", paris.getValue(RDFS.LABEL.toString(), "en")); Assert.assertTrue(paris.getValues(RDF.TYPE.toString()).contains("http://dbpedia.org/ontology/Place")); // Assert.assertTrue(Float.parseFloat(paris.getFirstPropertyValue("http://stanbol.apache.org/ontology/entityhub/entityhub#entityRank")) > 0.5f); Assert.assertTrue(paris.getValues(DCTERMS.SUBJECT.toString()).contains("http://dbpedia.org/resource/Category:Capitals_in_Europe")); EntityAnnotation parisEa = enhancements.getEntityAnnotation(paris.getUri()); Assert.assertTrue(parisEa.getEntityTypes().contains("http://dbpedia.org/ontology/Place")); Assert.assertEquals("Paris", parisEa.getEntityLabel()); // Assert.assertEquals("dbpedia", parisEa.getDataset()); Assert.assertEquals("en", parisEa.getLanguage()); } }
package com.sometrik.framework; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.List; import com.android.trivialdrivesample.util.IabHelper; import com.android.trivialdrivesample.util.IabHelper.IabAsyncInProgressException; import com.android.trivialdrivesample.util.IabResult; import com.android.trivialdrivesample.util.Inventory; import com.android.trivialdrivesample.util.Purchase; import android.app.AlertDialog; import android.content.DialogInterface; import android.content.DialogInterface.OnCancelListener; import android.content.res.AssetManager; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.text.Editable; import android.text.Html; import android.text.InputType; import android.text.TextWatcher; import android.text.method.LinkMovementMethod; import android.view.Gravity; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.Button; import android.widget.CheckBox; import android.widget.CompoundButton; import android.widget.EditText; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.PopupMenu; import android.widget.PopupMenu.OnMenuItemClickListener; import android.widget.ScrollView; import android.widget.Switch; import android.widget.TableLayout; import android.widget.TextView; public class NativeCommand { private int internalId = 0; private int childInternalId = 0; private int value = 0; private int flags = 0; private String textValue = ""; private String textValue2 = ""; private CommandType command; private String key; private FrameWork frame; private ArrayList<PopupMenu> menuList = new ArrayList<PopupMenu>(); private final int FLAG_PADDING_LEFT = 1; private final int FLAG_PADDING_RIGHT = 2; private final int FLAG_PADDING_TOP = 4; private final int FLAG_PADDING_BOTTOM = 8; private final int FLAG_PASSWORD = 16; private final int FLAG_NUMERIC = 32; private final int FLAG_HYPERLINK = 64; private final int FLAG_USE_PURCHASES_API = 128; public enum CommandType { CREATE_PLATFORM, CREATE_APPLICATION, CREATE_BASICVIEW, CREATE_FORMVIEW, CREATE_OPENGL_VIEW, CREATE_TEXTFIELD, // For viewing single value CREATE_LISTVIEW, // For viewing lists CREATE_GRIDVIEW, // For viewing tables CREATE_BUTTON, CREATE_SWITCH, CREATE_PICKER, // called Spinner in Android CREATE_LINEAR_LAYOUT, CREATE_TABLE_LAYOUT, CREATE_AUTO_COLUMN_LAYOUT, CREATE_HEADING_TEXT, CREATE_TEXT, CREATE_DIALOG, // For future CREATE_IMAGEVIEW, CREATE_ACTION_SHEET, CREATE_CHECKBOX, CREATE_RADIO_GROUP, CREATE_SEPARATOR, CREATE_SLIDER, CREATE_ACTIONBAR, DELETE_ELEMENT, SHOW_MESSAGE_DIALOG, SHOW_INPUT_DIALOG, SHOW_ACTION_SHEET, LAUNCH_BROWSER, POST_NOTIFICATION, HISTORY_GO_BACK, SET_INT_VALUE, // Sets value of radio groups, checkboxes and pickers SET_TEXT_VALUE, // Sets value of textfields, labels and images SET_LABEL, // Sets label for buttons and checkboxes SET_ENABLED, UPDATE_PREFERENCE, ADD_OPTION, QUIT_APP, // Timers CREATE_TIMER, // In-app purchases LIST_PRODUCTS, BUY_PRODUCT, LIST_PURCHASES, CONSUME_PURCHASE } public NativeCommand(FrameWork frame, int messageTypeId, int internalId, int childInternalId, int value, byte[] textValue, byte[] textValue2, int flags){ this.frame = frame; command = CommandType.values()[messageTypeId]; this.internalId = internalId; this.childInternalId = childInternalId; this.value = value; this.flags = flags; if (textValue != null) { this.textValue = new String(textValue, Charset.forName("UTF-8")); } if (textValue2 != null) { this.textValue2 = new String(textValue2, Charset.forName("UTF-8")); } } public void apply(NativeCommandHandler view) { System.out.println("Processing message " + command + " id: " + internalId + " Child id: " + getChildInternalId()); switch (command) { case CREATE_FORMVIEW: FWScrollView scrollView = new FWScrollView(frame); scrollView.setId(getChildInternalId()); FrameWork.addToViewList(scrollView); view.addChild(scrollView); break; case CREATE_BASICVIEW: case CREATE_LINEAR_LAYOUT: FWLayout layout = createLinearLayout(); view.addChild(layout); break; case CREATE_AUTO_COLUMN_LAYOUT: AutoColumnLayout autoLayout = new AutoColumnLayout(frame); autoLayout.setId(getChildInternalId()); FrameWork.addToViewList(autoLayout); view.addChild(autoLayout); break; case CREATE_TABLE_LAYOUT: FWTable table = createTableLayout(); view.addChild(table); break; case CREATE_BUTTON: FWButton button = createButton(); view.addChild(button); break; case CREATE_PICKER: FWPicker picker = createSpinner(); view.addChild(picker); break; case CREATE_SWITCH: Switch click = new Switch(frame); click.setId(childInternalId); if (textValue != "") { click.setTextOn(textValue); if (textValue2 == "") click.setTextOff(textValue); } if (textValue2 != "") click.setTextOff(textValue2); // TODO: add listener view.addChild(click); break; case CREATE_CHECKBOX: FWCheckBox checkBox = new FWCheckBox(frame); checkBox.setId(childInternalId); if (textValue != "") { checkBox.setText(textValue); } checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton box, boolean isChecked) { frame.intChangedEvent(System.currentTimeMillis() / 1000.0, childInternalId, isChecked ? 1 : 0); } }); FrameWork.addToViewList(checkBox); view.addChild(checkBox); break; case CREATE_OPENGL_VIEW: NativeSurface surface = frame.createNativeOpenGLView(childInternalId); surface.showView(); break; case CREATE_TEXTFIELD: FWEditText editText = createEditText(); view.addChild(editText); break; case CREATE_RADIO_GROUP: FWRadioGroup radioGroup = new FWRadioGroup(frame); radioGroup.setId(childInternalId); break; case CREATE_HEADING_TEXT: case CREATE_TEXT: TextView textView = createTextView(); view.addChild(textView); break; case CREATE_IMAGEVIEW: ImageView imageView = createImageView(); view.addChild(imageView); break; // case SHOW_VIEW: // frame.disableDraw(); // view.showView(); // break; case ADD_OPTION: // Forward Command to FWPicker view.addOption(getValue(), getTextValue()); break; case POST_NOTIFICATION: frame.createNotification(getTextValue(), getTextValue2()); break; case CREATE_APPLICATION: frame.setAppId(getInternalId()); frame.setSharedPreferences(textValue); if (isSet(FLAG_USE_PURCHASES_API)) { System.out.println("Initializing purchaseHelper"); frame.initializePurchaseHelper(textValue2, new IabHelper.OnIabSetupFinishedListener() { @Override public void onIabSetupFinished(IabResult result) { if (result.isSuccess()) { System.out.println("PurchaseHelper successfully setup"); sendInventory(frame.getPurchaseHelperInventory()); } else { System.out.println("PurchaseHelper failed to setup"); } } }); } break; case SET_INT_VALUE: view.setValue(getValue()); break; case SET_TEXT_VALUE: view.setValue(getTextValue()); break; case SET_ENABLED: view.setEnabled(value != 0); break; case LAUNCH_BROWSER: frame.launchBrowser(getTextValue()); break; case SHOW_MESSAGE_DIALOG: showMessageDialog(textValue, textValue2); break; case SHOW_INPUT_DIALOG: showInputDialog(textValue, textValue2); break; case CREATE_ACTION_SHEET: createActionSheet(); break; case QUIT_APP: // TODO frame.finish(); break; case UPDATE_PREFERENCE: //Now stores String value to string key. frame.getPreferencesEditor().putString(textValue, textValue2); frame.getPreferencesEditor().apply(); break; case DELETE_ELEMENT: view.removeChild(childInternalId); break; case BUY_PRODUCT: try { launchPurchase("com.sometrik.formtest.coin"); } catch (IabAsyncInProgressException e) { e.printStackTrace(); System.out.println("Error on launchPurchase with message: " + e.getMessage()); } default: System.out.println("Message couldn't be handled"); break; } } private void createActionSheet(){ PopupMenu menu = new PopupMenu(frame, null); menu.setOnMenuItemClickListener(new OnMenuItemClickListener(){ @Override public boolean onMenuItemClick(MenuItem item) { return false; } }); menuList.add(menu); } private FWTable createTableLayout(){ FWTable table = new FWTable(frame); table.setId(getChildInternalId()); table.setColumnCount(value); FrameWork.addToViewList(table); return table; } private ImageView createImageView() { ImageView imageView = new ImageView(frame); imageView.setId(childInternalId); try { InputStream is = frame.getAssets().open(textValue); Bitmap bitmap = BitmapFactory.decodeStream(is); imageView.setImageBitmap(bitmap); return imageView; } catch (IOException e) { e.printStackTrace(); System.out.println("error loading asset file to imageView"); System.exit(1); } return null; } private FWLayout createLinearLayout() { FWLayout layout = new FWLayout(frame); LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT); params.weight = 1.0f; params.gravity = Gravity.FILL; layout.setBaselineAligned(false); layout.setLayoutParams(params); layout.setId(getChildInternalId()); FrameWork.addToViewList(layout); if (getValue() == 2) { layout.setOrientation(LinearLayout.HORIZONTAL); } else { layout.setOrientation(LinearLayout.VERTICAL); } return layout; } private FWButton createButton() { FWButton button = new FWButton(frame); button.setId(getInternalId()); button.setText(getTextValue()); button.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { System.out.println("Java: my button was clicked with id " + getChildInternalId()); frame.intChangedEvent(System.currentTimeMillis() / 1000.0, getChildInternalId(), 1); } }); return button; } private FWEditText createEditText(){ final FWEditText editText = new FWEditText(frame); editText.setId(getChildInternalId()); editText.setText(getTextValue()); TableLayout.LayoutParams params = new TableLayout.LayoutParams(TableLayout.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.MATCH_PARENT); params.weight = 1.0f; params.gravity = Gravity.FILL; editText.setLayoutParams(params); editText.setMinimumWidth(120000 / (int) frame.getScreenWidth()); if (isSet(FLAG_PASSWORD) && isSet(FLAG_NUMERIC)){ editText.setInputType(InputType.TYPE_NUMBER_VARIATION_PASSWORD); } else if (isSet(FLAG_PASSWORD)) { editText.setInputType(InputType.TYPE_TEXT_VARIATION_PASSWORD); } else if (isSet(FLAG_NUMERIC)){ editText.setInputType(InputType.TYPE_CLASS_NUMBER); } editText.addTextChangedListener(new TextWatcher() { public void afterTextChanged(Editable editable) { frame.textChangedEvent(System.currentTimeMillis() / 1000.0, getChildInternalId(), editable.toString()); } public void beforeTextChanged(CharSequence s, int start, int count, int after) {} public void onTextChanged(CharSequence s, int start, int before, int count) {} }); FrameWork.addToViewList(editText); return editText; } private FWPicker createSpinner(){ FWPicker picker = new FWPicker(frame); picker.setId(getChildInternalId()); FrameWork.views.put(getChildInternalId(), picker); return picker; } private TextView createTextView() { TextView textView = new TextView(frame); textView.setId(getChildInternalId()); TableLayout.LayoutParams params = new TableLayout.LayoutParams(TableLayout.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.MATCH_PARENT); params.weight = 1.0f; params.gravity = Gravity.FILL; textView.setLayoutParams(params); if (isSet(FLAG_HYPERLINK)) { textView.setMovementMethod(LinkMovementMethod.getInstance()); String text = "<a href='" + textValue2 + "'>" + textValue + "</a>"; textView.setText(Html.fromHtml(text)); } else { textView.setText(textValue); } return textView; } // Create dialog with user text input private void showInputDialog(String title, String message) { System.out.println("Creating input dialog"); AlertDialog.Builder builder; builder = new AlertDialog.Builder(frame); // Building an alert builder.setTitle(title); builder.setMessage(message); builder.setCancelable(true); final EditText input = new EditText(frame); input.setInputType(InputType.TYPE_CLASS_TEXT); builder.setView(input); builder.setOnCancelListener(new OnCancelListener(){ @Override public void onCancel(DialogInterface arg0) { frame.endModal(System.currentTimeMillis() / 1000.0, 0, null); } }); // Negative button listener builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { frame.endModal(System.currentTimeMillis() / 1000.0, 0, null); dialog.cancel(); } }); // Positive button listener builder.setPositiveButton("OK", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { String inputText = String.valueOf(input.getText()); byte[] b = inputText.getBytes(Charset.forName("UTF-8")); frame.endModal(System.currentTimeMillis() / 1000.0, 1, b); dialog.cancel(); } }); // Create and show the alert AlertDialog alert = builder.create(); alert.show(); } // create Message dialog private void showMessageDialog(String title, String message) { System.out.println("creating message dialog"); AlertDialog.Builder builder; builder = new AlertDialog.Builder(frame); // Building an alert builder.setTitle(title); builder.setMessage(message); builder.setCancelable(true); builder.setOnCancelListener(new OnCancelListener(){ @Override public void onCancel(DialogInterface arg0) { frame.endModal(System.currentTimeMillis() / 1000.0, 0, null); } }); // Positive button listener builder.setPositiveButton("OK", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { frame.endModal(System.currentTimeMillis() / 1000.0, 1, null); dialog.dismiss(); } }); // Create and show the alert AlertDialog alert = builder.create(); alert.show(); System.out.println("message dialog created"); } private void launchPurchase(final String productId) throws IabAsyncInProgressException { // Sku = product id from google account frame.getPurchaseHelper().launchPurchaseFlow(frame, productId, IabHelper.ITEM_TYPE_INAPP, null, 1, new IabHelper.OnIabPurchaseFinishedListener() { @Override public void onIabPurchaseFinished(IabResult result, Purchase info) { if (result.isSuccess()) { System.out.println("Purchase of product id " + productId + " completed"); FrameWork.onPurchaseEvent(info.getPurchaseTime() / 1000.0, info.getSku(), true); // TODO } else { System.out.println("Purchase of product id " + productId + " failed"); // TODO } } }, ""); } private void sendInventory(Inventory inventory){ List <Purchase> purchaseList = inventory.getAllPurchases(); System.out.println("getting purchase history. Purchase list size: " + purchaseList.size()); for (Purchase purchase : inventory.getAllPurchases()){ FrameWork.onPurchaseEvent(purchase.getPurchaseTime() / 1000.0, purchase.getSku(), false); } } private Boolean isSet(int flag) { return (flags & flag) != 0; } public String getKey() { return key; } public void setKey(String key) { this.key = key; } public int getInternalId() { return internalId; } public int getChildInternalId() { return childInternalId; } public String getTextValue() { return textValue; } public String getTextValue2() { return textValue2; } public CommandType getCommand() { return command; } public int getValue() { return value; } }
package me.pagarme; import java.util.Collection; import java.util.Iterator; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import me.pagar.SubscriptionStatus; import me.pagar.model.Card; import me.pagar.model.Customer; import me.pagar.model.PagarMeException; import me.pagar.model.Plan; import me.pagar.model.SplitRule; import me.pagar.model.Subscription; import me.pagar.model.Transaction; import me.pagar.model.Transaction.PaymentMethod; import me.pagarme.factory.CardFactory; import me.pagarme.factory.CustomerFactory; import me.pagarme.factory.PlanFactory; import me.pagarme.factory.SplitRulesFactory; import me.pagarme.factory.SubscriptionFactory; import static org.hamcrest.CoreMatchers.instanceOf; import org.joda.time.DateTime; public class SubscriptionTest extends BaseTest { private PlanFactory planFactory = new PlanFactory(); private SubscriptionFactory subscriptionFactory = new SubscriptionFactory(); private CustomerFactory customerFactory = new CustomerFactory(); private CardFactory cardFactory = new CardFactory(); private SplitRulesFactory splitRulesFactory = new SplitRulesFactory(); private Plan defaultPlanWithTrialDays; private Plan defaultPlanWithoutTrialDays; private Customer defaultCustomer; private Card defaultCard; @Before public void beforeEach() throws PagarMeException { super.setUp(); defaultCustomer = customerFactory.create(); defaultCustomer.save(); defaultPlanWithTrialDays = planFactory.create(); defaultPlanWithTrialDays.save(); defaultPlanWithoutTrialDays = planFactory.createPlanWithoutTrialDays(); defaultPlanWithoutTrialDays.save(); defaultCard = cardFactory.create(); defaultCard.save(); } @Test public void testCreateSubscription() throws Throwable { Subscription subscription = subscriptionFactory.createCreditCardSubscription(defaultPlanWithTrialDays.getId(), defaultCard.getId(), defaultCustomer); subscription.save(); Assert.assertEquals(SubscriptionStatus.TRIALING, subscription.getStatus()); Assert.assertNotNull(subscription.getId()); } @Test public void testUpdateSubscriptionPlan() throws Throwable { Subscription subscription = subscriptionFactory.createCreditCardSubscription(defaultPlanWithTrialDays.getId(), defaultCard.getId(), defaultCustomer); subscription.save(); Plan newPlan = planFactory.create(); newPlan.save(); String newPlanId = newPlan.getId(); Subscription edittedSubscription = new Subscription(); edittedSubscription.setId(subscription.getId()); edittedSubscription.setUpdatableParameters(null, null, newPlanId); edittedSubscription.save(); Assert.assertEquals(newPlanId, edittedSubscription.getPlan().getId()); } @Test public void testFindSubscription() throws Throwable { Subscription subscription = subscriptionFactory.createCreditCardSubscription(defaultPlanWithTrialDays.getId(), defaultCard.getId(), defaultCustomer); subscription.save(); Subscription foundSubscription = new Subscription().find(subscription.getId()); Assert.assertEquals(subscription.getId(), foundSubscription.getId()); Assert.assertEquals(subscription.getPostbackUrl(), foundSubscription.getPostbackUrl()); Assert.assertEquals(subscription.getCharges(), foundSubscription.getCharges()); Assert.assertEquals(subscription.getCreatedAt(), foundSubscription.getCreatedAt()); Assert.assertEquals(subscription.getCurrentPeriodEnd(), foundSubscription.getCurrentPeriodEnd()); Assert.assertEquals(subscription.getCurrentPeriodStart(), foundSubscription.getCurrentPeriodStart()); Assert.assertEquals(subscription.getCurrentTransaction(), foundSubscription.getCurrentTransaction()); Assert.assertEquals(subscription.getCustomer().getId(), foundSubscription.getCustomer().getId()); Assert.assertEquals(PaymentMethod.CREDIT_CARD, foundSubscription.getPaymentMethod()); Assert.assertEquals(subscription.getPlan().getId(), foundSubscription.getPlan().getId()); Assert.assertEquals(subscription.getStatus(), foundSubscription.getStatus()); Assert.assertEquals("some_metadata", foundSubscription.getMetadata().keySet().iterator().next()); Assert.assertEquals("123456", foundSubscription.getMetadata().values().iterator().next()); Assert.assertEquals("soft_test", foundSubscription.getSoftDescriptor()); } /* @Test public void testListSubscription() throws Throwable { Subscription subscription1 = subscriptionFactory.createCreditCardSubscription(defaultPlan.getId(), defaultCard.getId(), defaultCustomer); subscription1.save(); Customer otherCustomer = customerFactory.create(); otherCustomer.setEmail("other@email.com"); otherCustomer.setDocumentNumber("31102987166"); Subscription subscription2 = subscriptionFactory.createBoletoSubscription(defaultPlan.getId(), otherCustomer); subscription2.save(); Collection<Subscription> subscriptions = new Subscription().findCollection(10, 1); Assert.assertEquals(2, subscriptions.size()); } */ @Test public void testTransactionsCollectionInSubscription() throws PagarMeException { Subscription subscription = subscriptionFactory.createCreditCardSubscription(defaultPlanWithoutTrialDays.getId(), defaultCard.getId(), defaultCustomer); subscription.save(); Iterator t = subscription.transactions().iterator(); while (t.hasNext()) { Assert.assertThat(t.next(), instanceOf(Transaction.class)); } } @Test public void testCancelSubscription() throws Throwable { Subscription subscription = subscriptionFactory.createCreditCardSubscription(defaultPlanWithTrialDays.getId(), defaultCard.getId(), defaultCustomer); subscription.save(); subscription.cancel(); Assert.assertEquals(subscription.getStatus(), SubscriptionStatus.CANCELED); } @Test public void testSavePostbackUrl() throws PagarMeException { Subscription subscription = subscriptionFactory.createCreditCardSubscription(defaultPlanWithTrialDays.getId(), defaultCard.getId(), defaultCustomer); subscription.setPostbackUrl("http://requestb.in/t5mzh9t5"); subscription = subscription.save(); Assert.assertEquals("http://requestb.in/t5mzh9t5", subscription.getPostbackUrl()); } @Test public void testSplitSubscriptionPercentage() throws Throwable { Subscription subscription = subscriptionFactory.createCreditCardSubscription(defaultPlanWithoutTrialDays.getId(), defaultCard.getId(), defaultCustomer); Collection<SplitRule> splitRules = splitRulesFactory.createSplitRuleWithPercentage(); subscription.setSplitRules(splitRules); subscription.save(); Transaction foundTransaction = new Transaction().find(subscription.getCurrentTransaction().getId()); Collection<SplitRule> foundSplitRules = foundTransaction.getSplitRules(); Assert.assertEquals(splitRules.size(), foundSplitRules.size()); } @Test public void testSplitSubscriptionAmount() throws Throwable { Subscription subscription = subscriptionFactory.createCreditCardSubscription(defaultPlanWithoutTrialDays.getId(), defaultCard.getId(), defaultCustomer); Collection<SplitRule> splitRules = splitRulesFactory.createSplitRuleWithAmount(defaultPlanWithoutTrialDays); subscription.setSplitRules(splitRules); subscription.save(); Transaction foundTransaction = new Transaction().find(subscription.getCurrentTransaction().getId()); Collection<SplitRule> foundSplitRules = foundTransaction.getSplitRules(); Assert.assertEquals(splitRules.size(), foundSplitRules.size()); } @Test public void testDefaultSettleCharges() throws Throwable { Subscription subscription = subscriptionFactory.createBoletoSubscription(defaultPlanWithoutTrialDays.getId(), defaultCustomer); subscription.save(); subscription = subscription.settleCharges(); Subscription foundSubscription = new Subscription(); foundSubscription.find(subscription.getId()); DateTime expectedCurrentPeriodEnd = DateTime.now().plusDays( foundSubscription.getPlan().getDays() ); Assert.assertEquals( foundSubscription.getCurrentPeriodEnd().toLocalDate(), expectedCurrentPeriodEnd.toLocalDate() ); } @Test public void testSettleChargesWithParameter() throws Throwable { Subscription subscription = subscriptionFactory.createBoletoSubscription(defaultPlanWithoutTrialDays.getId(), defaultCustomer); subscription.save(); int chargesToSettle = 2; subscription = subscription.settleCharges(chargesToSettle); Subscription foundSubscription = new Subscription(); foundSubscription.find(subscription.getId()); Assert.assertEquals(chargesToSettle, foundSubscription.getSettledCharges().size()); } }
package wepa.wepa.selenium; import java.util.Arrays; import java.util.UUID; import org.fluentlenium.adapter.FluentTest; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; import org.junit.runner.RunWith; import org.openqa.selenium.WebDriver; import org.openqa.selenium.htmlunit.HtmlUnitDriver; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.context.embedded.LocalServerPort; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.context.annotation.Bean; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.test.context.junit4.SpringRunner; import wepa.wepa.domain.Person; import wepa.wepa.repository.PersonRepository; @RunWith(SpringRunner.class) @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) public class wepaTest extends FluentTest { public WebDriver webDriver = new HtmlUnitDriver(); public WebDriver getDefaultDriver() { return webDriver; } @Bean public PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); } @LocalServerPort private Integer port; @Autowired private PersonRepository personRepository; private String personname; @Before public void setUp() { Person testperson = new Person(); personname = UUID.randomUUID().toString(); testperson.setName(personname); testperson.setPassword(passwordEncoder().encode(personname)); testperson.setStudentNumber("987654321"); testperson.setAuthorities(Arrays.asList("TEACHER")); personRepository.save(testperson); } @Test public void loginTest() { goTo("http://localhost:" + port + "/login"); fill(find("input")).with(personname); fill(find("input")).with(personname); submit(find("form").first()); goTo("http://localhost:" + port + "/persons/" + personRepository.findByName(personname).getId()); assertFalse(pageSource().contains("555555555")); assertFalse(pageSource().contains("Maija")); assertTrue(pageSource().contains(personname)); } // fill(find("#studentNumber")).with("555555555"); // fill(find("#name")).with("Maija"); // fill(find("#exercises")).with("4"); // submit(find("form").first()); // assertTrue(pageSource().contains("555555555")); // assertTrue(pageSource().contains("Maija")); }
package net.asfun.jangod.lib.tag; import java.util.HashMap; import java.util.Map; import net.asfun.jangod.base.Context; import net.asfun.jangod.interpret.InterpretException; import net.asfun.jangod.interpret.JangodInterpreter; import net.asfun.jangod.lib.TagLibrary; import net.asfun.jangod.parse.TokenParser; import android.app.Instrumentation; import android.test.InstrumentationTestCase; import android.util.Log; public class TagTest extends InstrumentationTestCase { static final String TAG = "TagTest"; Instrumentation mInstru; JangodInterpreter interpreter; @Override protected void setUp() throws Exception { mInstru = getInstrumentation(); Map<String, Object> data = new HashMap<String, Object>(); data.put("var1", "app_name"); data.put("var2", "result_view"); Context context = new Context(); context.initBindings(data, Context.SCOPE_GLOBAL); interpreter = new JangodInterpreter(context); } public void testResStrTag() throws Exception { Log.e(TAG, "testResStrTag"); mInstru.runOnMainSync(new Runnable() { @Override public void run() { TagLibrary.addTag(new ResStrTag()); String script = "{% rstr var1 %} is {% rstr 'app_name' %}"; try { assertEquals("WebServ is WebServ", eval(script)); } catch (InterpretException e) { } } }); } public void testResColorTag() throws Exception { Log.e(TAG, "testResColorTag"); mInstru.runOnMainSync(new Runnable() { @Override public void run() { TagLibrary.addTag(new ResColorTag()); String script = "{% rcolor var2 %} or {% rcolor 'result_view' %}"; try { Log.e(TAG, eval(script)); assertEquals("#b0000000 or #b0000000", eval(script)); } catch (InterpretException e) { } } }); } public void testUUIDTag() throws Exception { Log.e(TAG, "testUUIDTag"); TagLibrary.addTag(new UUIDTag()); String script = "{% uuid %} or {% uuid %}"; Log.e(TAG, eval(script)); } private String eval(String script) throws InterpretException { TokenParser parser = new TokenParser(script); try { return interpreter.render(parser); } catch (InterpretException e) { throw e; } } @Override protected void tearDown() throws Exception { interpreter = null; } }
// arch-tag: AAE1AD0E-CDD6-4143-B607-C79DFEF7BCA2 package net.spy.memcached.ops; import java.nio.ByteBuffer; import java.util.Arrays; import java.util.LinkedList; import java.util.List; import net.spy.test.BaseMockCase; /** * Test the basic operation buffer handling stuff. */ public class BaseOpTest extends BaseMockCase { public void testAssertions() { try { assert false; fail("Assertions are not enabled."); } catch(AssertionError e) { } } public void testDataReadType() throws Exception { SimpleOp op=new SimpleOp(Operation.ReadType.DATA); assertSame(Operation.ReadType.DATA, op.getReadType()); // Make sure lines aren't handled try { op.handleLine("x"); fail("Handled a line in data mode"); } catch(AssertionError e) { } op.setBytesToRead(2); op.handleRead(ByteBuffer.wrap("hi".getBytes())); } public void testLineReadType() throws Exception { SimpleOp op=new SimpleOp(Operation.ReadType.LINE); assertSame(Operation.ReadType.LINE, op.getReadType()); // Make sure lines aren't handled try { op.handleRead(ByteBuffer.allocate(3)); fail("Handled data in line mode"); } catch(AssertionError e) { } op.handleLine("x"); } public void testLineParser() throws Exception { String input="This is a multiline string\r\nhere is line two\r\n"; ByteBuffer b=ByteBuffer.wrap(input.getBytes()); SimpleOp op=new SimpleOp(Operation.ReadType.LINE); op.linesToRead=2; op.readFromBuffer(b); assertEquals("This is a multiline string", op.getLines().get(0)); assertEquals("here is line two", op.getLines().get(1)); op.setBytesToRead(2); op.readFromBuffer(ByteBuffer.wrap("xy".getBytes())); byte[] expected={'x', 'y'}; assertTrue("Expected " + Arrays.toString(expected) + " but got " + Arrays.toString(op.getCurentBytes()), Arrays.equals(expected, op.getCurentBytes())); } public void testPartialLine() throws Exception { String input1="this is a "; String input2="test\r\n"; ByteBuffer b=ByteBuffer.allocate(20); SimpleOp op=new SimpleOp(Operation.ReadType.LINE); b.put(input1.getBytes()); b.flip(); op.readFromBuffer(b); assertNull(op.getCurrentLine()); b.clear(); b.put(input2.getBytes()); b.flip(); op.readFromBuffer(b); assertEquals("this is a test", op.getCurrentLine()); } private static class SimpleOp extends Operation { private LinkedList<String> lines=new LinkedList<String>(); private byte[] currentBytes=null; private int bytesToRead=0; public int linesToRead=1; public SimpleOp(ReadType t) { setReadType(t); } public void setBytesToRead(int to) { bytesToRead=to; } public String getCurrentLine() { return lines.isEmpty()?null:lines.getLast(); } public List<String> getLines() { return lines; } public byte[] getCurentBytes() { return currentBytes; } @Override public void handleLine(String line) { assert getReadType() == Operation.ReadType.LINE; lines.add(line); if(--linesToRead == 0) { setReadType(Operation.ReadType.DATA); } } @Override public void handleRead(ByteBuffer data) { assert getReadType() == Operation.ReadType.DATA; assert bytesToRead > 0; if(bytesToRead > 0) { currentBytes=new byte[bytesToRead]; data.get(currentBytes); } } @Override public void initialize() { setBuffer(ByteBuffer.allocate(0)); } @Override protected void wasCancelled() { // nothing } } }
package sys; import java.awt.Desktop; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.FileWriter; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.BufferedWriter; import java.net.URL; import java.net.URLConnection; import java.net.HttpURLConnection; import java.net.URI; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Properties; import org.jsoup.Jsoup; import org.jsoup.select.Elements; import org.jsoup.nodes.Document; import common.ErrorHandling; /** * <p> * <p>, static * <p>Instantiation (private ) * @author occidere */ @SuppressWarnings("unused") public class SystemInfo { private SystemInfo(){} static final String fileSeparator = File.separator; static final String lineSeparator = System.getProperty("line.separator"); // \r\n, \n, \r //OS ex) Windows 10, Linux .. static transient final String OS_NAME = System.getProperty("os.name"); // ex) C:\Users\occid\Marumaru home/occidere/marumaru public static transient final String DEFAULT_PATH = System.getProperty("user.home")+ fileSeparator + "Marumaru"; public static transient String PATH = DEFAULT_PATH; public static final String ERROR_LOG_PATH = DEFAULT_PATH + fileSeparator + "log"; public static final String MARU_ADDR = "http://marumaru.in/"; private transient static final String LATEST_VERSION_URL = "https://github.com/occidere/MMDownloader/blob/master/VERSION_INFO"; private static final String VERSION = "0.5.0.0"; private static final String UPDATED_DATE = "2017.12.17"; private static final String DEVELOPER = ": occidere"; private static final String VERSION_INFO = String.format(": %s (%s)", VERSION, UPDATED_DATE); /* . null */ private static String LATEST_VERSION = null; private static String LATEST_UPDATED_DATE = null; private static String LATEST_VERSION_INFO = null; private static String LATEST_WINDOWS = null; private static String LATEST_OTHERS = null; /** * <p> , . * <p> . */ public static void printProgramInfo(){ try { Configuration.refresh(); } catch (Exception e) {} System.out.print(DEVELOPER+"\t"); System.out.println(VERSION_INFO); System.out.println(": "+Configuration.getString("PATH", DEFAULT_PATH)); System.out.printf("( : %s, : %s, : %s)\n", Configuration.getBoolean("MERGE", false), Configuration.getBoolean("DEBUG", false), Configuration.getBoolean("MULTI", true)); } /** * <p> ( ) * <p> . * <p> 1 , . * @param in */ public static void printLatestVersionInfo(BufferedReader in){ // null == 1 if(LATEST_VERSION_INFO == null){ System.out.println(" ..."); try{ Document doc = Jsoup.connect(LATEST_VERSION_URL).get(); Elements e = doc.getElementsByClass("highlight tab-size js-file-line-container"); LATEST_VERSION = e.select("#LC1").text().split("=")[1]; LATEST_UPDATED_DATE = e.select("#LC2").text().split("=")[1]; LATEST_WINDOWS = e.select("#LC3").text().split("=")[1]; LATEST_OTHERS = e.select("#LC4").text().split("=")[1]; LATEST_VERSION_INFO = String.format(": %s (%s)", LATEST_VERSION, LATEST_UPDATED_DATE); } catch(Exception e){ ErrorHandling.saveErrLog(" ", "", e); return; } } System.out.println(VERSION_INFO); System.out.println(LATEST_VERSION_INFO); if(LATEST_VERSION_INFO != null && LATEST_VERSION_INFO.length() > 0){ int curVersion = Integer.parseInt(VERSION.replace(".", "")); int latestVersion = Integer.parseInt(LATEST_VERSION.replace(".", "")); if(curVersion < latestVersion) downloadLatestVersion(in); else if(curVersion == latestVersion) System.out.println(" !"); else System.out.println(" ! ᕙ(•̀‸•́‶)ᕗ"); } } /** * <p> . * <p> . * <p> OS / (, ) * @param in */ private static void downloadLatestVersion(final BufferedReader in){ try{ final int BUF_SIZE = 10485760; // , MB , MB int len = 0, MB = 1024*1024, preDownloadedMB = 0; double accumSize = 0, totalSize = 0; String select, fileName = null, fileURL = null; boolean isCorrectlySelected = false; while(!isCorrectlySelected){ // (y) (n) . System.out.printf(" (%s) ? (Y/n): ", LATEST_VERSION); select = in.readLine(); if(select.equalsIgnoreCase("y")){ isCorrectlySelected = true; makeDir(); //Marumaru /* OS , = MMdownloader_0.5.0.0_Windows.zip */ if(OS_NAME.contains("Windows")){ fileName = LATEST_WINDOWS.substring(LATEST_WINDOWS.lastIndexOf("/")+1); fileURL = LATEST_WINDOWS; } /* OS = MMdownloader_0.5.0.0_Mac,Linux.zip */ else{ fileName = LATEST_OTHERS.substring(LATEST_OTHERS.lastIndexOf("/")+1); fileURL = LATEST_OTHERS; } System.out.println(" ..."); System.out.println(" : "+DEFAULT_PATH+fileSeparator+fileName); BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(DEFAULT_PATH+fileSeparator+fileName), BUF_SIZE); HttpURLConnection conn = (HttpURLConnection)new URL(fileURL).openConnection(); conn.setConnectTimeout(60000); BufferedInputStream bis = new BufferedInputStream(conn.getInputStream(), BUF_SIZE); totalSize = (double)conn.getContentLength() / MB; while((len = bis.read()) != -1){ bos.write(len); accumSize += (double)len / MB; if(preDownloadedMB < (int)accumSize){ System.out.printf("%5.2fMB / %5.2fMB ... !\n", accumSize, totalSize); preDownloadedMB = (int)accumSize; } } bos.close(); bis.close(); System.out.printf("%5.2fMB / %5.2fMB ... !\n", accumSize, totalSize); System.out.println(" ! (: "+SystemInfo.DEFAULT_PATH+")"); } else if(select.equalsIgnoreCase("n")){ isCorrectlySelected = true; System.out.println(" ."); } } } catch(Exception e){ ErrorHandling.saveErrLog(" ", "", e); } } public static void openBrowser(){ openBrowser(MARU_ADDR); } /** * <p> * <p> new URI(uri) * <p> * @param uri String uri */ public static void openBrowser(String uri){ try{ Desktop.getDesktop().browse(new URI(uri)); } catch(Exception e){ ErrorHandling.saveErrLog(uri+" ", "", e); } } /** * <p> * <p> void DEFAULT_PATH(System.getProperty("user.home")) */ public static void openDir(){ openDir(DEFAULT_PATH); } /** * <p> * <p> * <p> * @param path String path */ public static void openDir(String path){ try{ Desktop.getDesktop().open(new File(path)); } catch(Exception e){ ErrorHandling.saveErrLog(" ", "", e); } } /** * <p> * <p> DEFAULT_PATH */ public static void makeDir(){ makeDir(DEFAULT_PATH); } /** * <p> * <p> * @param path String */ public static void makeDir(String path){ new File(path).mkdirs(); } public static void help(){ final String MESSAGE = " + "1. \n" + " - . 3 .\n" + " -- wasabisyrup : 1 .\n" + " ex) http://wasabisyrup.com/archives/807EZuSyjwA\n" + " -- mangaup : .\n" + " ex) http://marumaru.in/b/mangaup/204237\n" + " + " ex) http://marumaru.in/b/manga/198822\n" + "\n2. \n" + " - .\n" + " - ' ' .\n" + " - .\n" + " - .\n" + " -- 1 .\n" + " + " ex) 5, 3, 1, 7\n" + " + " ex) 4 ~ 10, 9-1\n" + " + " ex) 1, 2, 3 1, 2,3 .\n" + " + " ex) 17 ~ 15, 1-3 1,2,3,15,16,17 .\n" + " + " ex) 1, 3, 3, 2~4 1,2,3,4 .\n" + " + " ex) 5 , 4~6 4~5 .\n" + " , 6,8 \n" + "\n3. \n" + " - GUI . .\n" + " -- Windows C:\\Users\\\\Marumaru\\ .\n" + " -- Mac Linux home//marumaru/ .\n" + "\n4. \n" + " - GUI . PC .\n" + "\n8. \n" + " 1) \n" + " - .\n" + " - (Y/n)\n" + " - OS Windows / (Mac, Linux) .\n" + " - (Marumaru ) \n" + " 2) \n" + " - . .\n" + " - , , , .\n" + " - : C\\Users\\\\Marumaru /home//Marumaru\n" + " 3) \n" + " - .\n" + " , , .\n" + " - : false\n" + " 4) \n" + " - .\n" + " - : false\n" + " 5) \n" + " - .\n" + " , .\n" + " - .\n" + " - : true\n" + "\n0. \n" + " - .\n" + "\n: occidere\t: 2017.12.16\n\n"; System.out.println(MESSAGE); } private static void printSystemProperties(){ System.getProperties().list(System.out); } } /* MULTI BufferedInputStream, BufferedOutputStream */
package ttaomae.exactcover.polycubes; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Set; public class Polycube { private final Set<Cube> cubes; private final int xLength; private final int yLength; private final int zLength; public Polycube(Collection<Cube> cubes) { if (cubes == null) { throw new IllegalArgumentException("cubes should not be null"); } if (cubes.isEmpty()) { throw new IllegalArgumentException("cubes should not be empty"); } this.cubes = new HashSet<>(); int minX = Integer.MAX_VALUE; int minY = Integer.MAX_VALUE; int minZ = Integer.MAX_VALUE; int maxX = Integer.MIN_VALUE; int maxY = Integer.MIN_VALUE; int maxZ = Integer.MIN_VALUE; for (Cube c : cubes) { minX = Math.min(minX, c.x); minY = Math.min(minY, c.y); minZ = Math.min(minZ, c.z); maxX = Math.max(maxX, c.x); maxY = Math.max(maxY, c.y); maxZ = Math.max(maxZ, c.z); } this.xLength = 1 + (maxX - minX); this.yLength = 1 + (maxY - minY); this.zLength = 1 + (maxZ - minZ); for (Cube c : cubes) { if (minX != 0 || minY != 0 || minZ != 0) { this.cubes.add(new Cube(c.x - minX, c.y - minY, c.z - minZ)); } else { this.cubes.add(new Cube(c.x, c.y, c.z)); } } } public Set<Cube> getCubes() { return Collections.<Cube> unmodifiableSet(this.cubes); } private Polycube transpose(Axis axis) { Collection<Cube> newCubes = new ArrayList<>(); for (Cube c : this.cubes) { switch (axis) { case X: newCubes.add(new Cube(c.x, c.z, c.y)); break; case Y: newCubes.add(new Cube(c.z, c.y, c.x)); break; case Z: newCubes.add(new Cube(c.y, c.x, c.z)); break; } } return new Polycube(newCubes); } /** * Returns the Polycube given by reflecting this Polycube across the plane * given by the two axes. */ private Polycube reflect(Axis a, Axis b) { assert (a != b); Collection<Cube> newCubes = new ArrayList<>(); for (Cube c : this.cubes) { int newX = (a != Axis.X && b != Axis.X) ? (this.xLength - 1) - c.x : c.x; int newY = (a != Axis.Y && b != Axis.Y) ? (this.yLength - 1) - c.y : c.y; int newZ = (a != Axis.Z && b != Axis.Z) ? (this.zLength - 1) - c.z : c.z; newCubes.add(new Cube(newX, newY, newZ)); } return new Polycube(newCubes); } public Polycube rotateCW(Axis axis) { switch (axis) { case X: return transpose(Axis.X).reflect(Axis.X, Axis.Z); case Y: return transpose(Axis.Y).reflect(Axis.Y, Axis.X); case Z: return transpose(Axis.Z).reflect(Axis.Z, Axis.Y); default: return this; } } public Polycube rotateCCW(Axis axis) { switch (axis) { case X: return transpose(Axis.X).reflect(Axis.X, Axis.Y); case Y: return transpose(Axis.Y).reflect(Axis.Y, Axis.Z); case Z: return transpose(Axis.Z).reflect(Axis.Z, Axis.X); default: return this; } } public Set<Polycube> getRotations() { Set<Polycube> result = new HashSet<>(); // a subset of the possible orientations // one for each "face" aligned with the z-axis List<Polycube> subset = new ArrayList<>(); subset.add(this); subset.add(this.rotateCW(Axis.X)); subset.add(this.rotateCCW(Axis.X)); subset.add(this.rotateCW(Axis.Y)); subset.add(this.rotateCCW(Axis.Y)); subset.add(this.rotateCW(Axis.X).rotateCW(Axis.X)); // rotate each element of the subset around the z-axis for (int i = 0; i < subset.size(); i++) { for (int rot = 0; rot < 4; rot++) { result.add(subset.get(i)); subset.set(i, subset.get(i).rotateCW(Axis.Z)); } } return result; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((cubes == null) ? 0 : cubes.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } Polycube other = (Polycube) obj; if (cubes == null) { if (other.cubes != null) { return false; } } else if (!cubes.equals(other.cubes)) { return false; } return true; } @Override public String toString() { StringBuilder sb = new StringBuilder(); boolean[][][] cubeArray = new boolean[this.zLength][this.yLength][this.xLength]; for (Cube c : cubes) { cubeArray[c.z][c.y][c.x] = true; } for (int y = 0; y < this.yLength; y++) { sb.append("|"); for (int z = 0; z < this.zLength; z++) { for (int x = 0; x < this.xLength; x++) { if (cubeArray[z][y][x]) { sb.append(" } else { sb.append(" "); } } sb.append("|"); } sb.append("\n"); } // delete extra newline sb.deleteCharAt(sb.length() - 1); return sb.toString(); } public static class Cube implements Comparable<Cube> { private final int x; private final int y; private final int z; public Cube(int x, int y, int z) { this.x = x; this.y = y; this.z = z; } public int getX() { return x; } public int getY() { return y; } public int getZ() { return z; } @Override public String toString() { return String.format("(%d, %d, %d)", this.x, this.y, this.z); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + x; result = prime * result + y; result = prime * result + z; return result; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } Cube other = (Cube) obj; if (x != other.x) { return false; } if (y != other.y) { return false; } if (z != other.z) { return false; } return true; } @Override public int compareTo(Cube o) { if (this.x < o.x) { return -1; } else if (this.x > o.x) { return 1; } // this.x == o.x else if (this.y < o.y) { return -1; } else if (this.y > o.y) { return 1; } // x and y are equal else if (this.z < o.z) { return -1; } else if (this.z > o.z) { return 1; } // x, y, and z are equal else { return 0; } } } public enum Axis { X, Y, Z; } }
package uk.org.cinquin.mutinack; import static uk.org.cinquin.mutinack.misc_util.Util.blueF; import static uk.org.cinquin.mutinack.misc_util.Util.greenB; import static uk.org.cinquin.mutinack.misc_util.Util.reset; import static uk.org.cinquin.mutinack.statistics.PrintInStatus.OutputLevel.TERSE; import static uk.org.cinquin.mutinack.statistics.PrintInStatus.OutputLevel.VERBOSE; import static uk.org.cinquin.mutinack.statistics.PrintInStatus.OutputLevel.VERY_VERBOSE; import java.io.OutputStreamWriter; import java.io.PrintStream; import java.io.Serializable; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.text.DecimalFormat; import java.text.NumberFormat; import java.util.Arrays; import java.util.ConcurrentModificationException; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.atomic.DoubleAdder; import java.util.concurrent.atomic.LongAdder; import java.util.function.Function; import java.util.stream.Collectors; import javax.jdo.annotations.Extension; import javax.jdo.annotations.Join; import javax.jdo.annotations.PersistenceCapable; import javax.jdo.annotations.Persistent; import org.eclipse.jdt.annotation.NonNull; import org.eclipse.jdt.annotation.Nullable; import uk.org.cinquin.final_annotation.Final; import uk.org.cinquin.mutinack.candidate_sequences.Quality; import uk.org.cinquin.mutinack.features.PosByPosNumbersPB.GenomeNumbers.Builder; import uk.org.cinquin.mutinack.misc_util.Assert; import uk.org.cinquin.mutinack.misc_util.ComparablePair; import uk.org.cinquin.mutinack.misc_util.Util; import uk.org.cinquin.mutinack.misc_util.collections.MutationHistogramMap; import uk.org.cinquin.mutinack.output.LocationAnalysis; import uk.org.cinquin.mutinack.statistics.Actualizable; import uk.org.cinquin.mutinack.statistics.CounterWithSeqLocOnly; import uk.org.cinquin.mutinack.statistics.CounterWithSeqLocOnlyReportAll; import uk.org.cinquin.mutinack.statistics.CounterWithSeqLocation; import uk.org.cinquin.mutinack.statistics.DivideByTwo; import uk.org.cinquin.mutinack.statistics.DoubleAdderFormatter; import uk.org.cinquin.mutinack.statistics.Histogram; import uk.org.cinquin.mutinack.statistics.LongAdderFormatter; import uk.org.cinquin.mutinack.statistics.MultiCounter; import uk.org.cinquin.mutinack.statistics.PrintInStatus; import uk.org.cinquin.mutinack.statistics.PrintInStatus.OutputLevel; import uk.org.cinquin.mutinack.statistics.StatsCollector; import uk.org.cinquin.mutinack.statistics.SwitchableStats; import uk.org.cinquin.mutinack.statistics.Traceable; @PersistenceCapable public class AnalysisStats implements Serializable, Actualizable { private @Final @Persistent @NonNull String name; OutputLevel outputLevel; final MutinackGroup groupSettings; @Final @Persistent Set<String> mutinackVersions = new HashSet<>(); @Final @Persistent public Map<String, String> inputBAMHashes = new HashMap<>(); @Final @Persistent Parameters analysisParameters; @Final @Persistent boolean forInsertions; //Changed to Map instead of ConcurrentMap to please datanucleus @Final @Persistent @Join Map<SequenceLocation, LocationAnalysis> detections = new ConcurrentHashMap<>(); public transient PrintStream detectionOutputStream; public transient OutputStreamWriter annotationOutputStream; public transient @Nullable OutputStreamWriter topBottomDisagreementWriter, noWtDisagreementWriter, mutationBEDWriter, coverageBEDWriter; public boolean canSkipDuplexLoading = false; public AnalysisStats(@NonNull String name, @NonNull Parameters param, boolean forInsertions, @NonNull MutinackGroup groupSettings, boolean reportCoverageAtAllPositions) { this.name = name; this.analysisParameters = param; this.forInsertions = forInsertions; this.groupSettings = groupSettings; if (reportCoverageAtAllPositions) { nPosDuplexCandidatesForDisagreementQ2 = new MultiCounter<>(null, () -> new CounterWithSeqLocOnlyReportAll(false, groupSettings)); nPosDuplexQualityQ2OthersQ1Q2 = new MultiCounter<>(null, () -> new CounterWithSeqLocOnlyReportAll(false, groupSettings)); nPosDuplexTooFewReadsPerStrand1 = new MultiCounter<>(null, () -> new CounterWithSeqLocOnlyReportAll(false, groupSettings)); nPosDuplexTooFewReadsPerStrand2 = new MultiCounter<>(null, () -> new CounterWithSeqLocOnlyReportAll(false, groupSettings)); nPosDuplexTooFewReadsAboveQ2Phred = new MultiCounter<>(null, () -> new CounterWithSeqLocOnlyReportAll(false, groupSettings)); } else { nPosDuplexCandidatesForDisagreementQ2 = new MultiCounter<>(null, () -> new CounterWithSeqLocOnly(false, groupSettings)); nPosDuplexQualityQ2OthersQ1Q2 = new MultiCounter<>(null, () -> new CounterWithSeqLocOnly(false, groupSettings)); nPosDuplexTooFewReadsPerStrand1 = new MultiCounter<>(null, () -> new CounterWithSeqLocOnly(false, groupSettings)); nPosDuplexTooFewReadsPerStrand2 = new MultiCounter<>(null, () -> new CounterWithSeqLocOnly(false, groupSettings)); nPosDuplexTooFewReadsAboveQ2Phred = new MultiCounter<>(null, () -> new CounterWithSeqLocOnly(false, groupSettings)); } nRecordsNotInIntersection1 = new MultiCounter<>(null, () -> new CounterWithSeqLocOnly(false, groupSettings)); nRecordsNotInIntersection2 = new MultiCounter<>(null, () -> new CounterWithSeqLocOnly(false, groupSettings)); nTooLowMapQIntersect = new MultiCounter<>(null, () -> new CounterWithSeqLocOnly(false, groupSettings)); nPosDuplex = new MultiCounter<>(null, () -> new CounterWithSeqLocOnly(false, groupSettings)); nPosDuplexBothStrandsPresent = new MultiCounter<>(null, () -> new CounterWithSeqLocOnly(false, groupSettings)); nPosIgnoredBecauseTooHighCoverage = new StatsCollector(); nReadMedianPhredBelowThreshold = new MultiCounter<>(null, () -> new CounterWithSeqLocOnly(false, groupSettings)); phredAndLigSiteDistance = new MultiCounter<>(() -> new CounterWithSeqLocation<>(true, groupSettings), null, false); nDuplexesTooMuchClipping = new MultiCounter<>(null, () -> new CounterWithSeqLocOnly(false, groupSettings)); nDuplexesNoStats = new DoubleAdder(); nDuplexesWithStats = new DoubleAdder(); nPosDuplexWithTopBottomDuplexDisagreementNoWT = new MultiCounter<>(null, () -> new CounterWithSeqLocOnly(false, groupSettings)); nPosDuplexWithTopBottomDuplexDisagreementNotASub = new MultiCounter<>(null, () -> new CounterWithSeqLocOnly(false, groupSettings)); rawMismatchesQ1 = new MultiCounter<>(() -> new CounterWithSeqLocation<>(true, groupSettings), null, true); vBarcodeMismatches1M = new MultiCounter<>(() -> new CounterWithSeqLocation<>(true, groupSettings), null, true); vBarcodeMismatches2M = new MultiCounter<>(() -> new CounterWithSeqLocation<>(true, groupSettings), null, true); vBarcodeMismatches3OrMore = new MultiCounter<>(() -> new CounterWithSeqLocation<>(true, groupSettings), null, true); rawDeletionsQ1 = new MultiCounter<>(() -> new CounterWithSeqLocation<>(true, groupSettings), null, true); rawDeletionLengthQ1 = new Histogram(200); rawInsertionsQ1 = new MultiCounter<>(() -> new CounterWithSeqLocation<>(true, groupSettings), null, true); rawInsertionLengthQ1 = new Histogram(200); rawMismatchesQ2 = new MultiCounter<>(() -> new CounterWithSeqLocation<>(true, groupSettings), null, true); rawDeletionsQ2 = new MultiCounter<>(() -> new CounterWithSeqLocation<>(true, groupSettings), null, true); rawDeletionLengthQ2 = new Histogram(200); rawInsertionsQ2 = new MultiCounter<>(() -> new CounterWithSeqLocation<>(true, groupSettings), null, true); rawInsertionLengthQ2 = new Histogram(200); topBottomSubstDisagreementsQ2 = new MultiCounter<>(() -> new CounterWithSeqLocation<>(false, groupSettings), null); alleleFrequencies = new MultiCounter<>(() -> new CounterWithSeqLocation<>(false, groupSettings), null); topBottomDelDisagreementsQ2 = new MultiCounter<>(() -> new CounterWithSeqLocation<>(true, groupSettings), null); topBottomInsDisagreementsQ2 = new MultiCounter<>(() -> new CounterWithSeqLocation<>(true, groupSettings), null); codingStrandSubstQ2 = new MultiCounter<>(() -> new CounterWithSeqLocation<>(false, groupSettings), null); templateStrandSubstQ2 = new MultiCounter<>(() -> new CounterWithSeqLocation<>(false, groupSettings), null); codingStrandDelQ2 = new MultiCounter<>(() -> new CounterWithSeqLocation<>(groupSettings), null); templateStrandDelQ2 = new MultiCounter<>(() -> new CounterWithSeqLocation<>(groupSettings), null); codingStrandInsQ2 = new MultiCounter<>(() -> new CounterWithSeqLocation<>(groupSettings), null); templateStrandInsQ2 = new MultiCounter<>(() -> new CounterWithSeqLocation<>(groupSettings), null); topBottomDisagreementsQ2TooHighCoverage = new MultiCounter<>(() -> new CounterWithSeqLocation<>(groupSettings), null); nPosDuplexCandidatesForDisagreementQ2TooHighCoverage = new MultiCounter<>(null, () -> new CounterWithSeqLocOnly(false, groupSettings)); nPosDuplexWithLackOfStrandConsensus1 = new StatsCollector(); nPosDuplexWithLackOfStrandConsensus2 = new StatsCollector(); nPosDuplexCompletePairOverlap = new StatsCollector(); nPosUncovered = new StatsCollector(); nQ2PromotionsBasedOnFractionReads = new StatsCollector(); nPosQualityPoor = new StatsCollector(); nPosQualityPoorA = new StatsCollector(); nPosQualityPoorT = new StatsCollector(); nPosQualityPoorG = new StatsCollector(); nPosQualityPoorC = new StatsCollector(); nConsensusQ1NotMet = new StatsCollector(); nMedianPhredAtPositionTooLow = new StatsCollector(); nFractionWrongPairsAtPositionTooHigh = new StatsCollector(); nPosQualityQ1 = new StatsCollector(); nPosQualityQ2 = new StatsCollector(); nPosQualityQ2OthersQ1Q2 = new StatsCollector(); nPosDuplexQualityQ2OthersQ1Q2CodingOrTemplate = new MultiCounter<>(null, () -> new CounterWithSeqLocOnly(false, groupSettings)); nPosCandidatesForUniqueMutation = new MultiCounter<>(null, () -> new CounterWithSeqLocOnly(false, groupSettings)); nReadsInPrefetchQueue = new Histogram(1_000); { //Force output of fields annotated with AddChromosomeBins to be broken down by //bins for each contig (bin size as defined by CounterWithSeqLocation.BIN_SIZE, for now) List<String> contigNames = groupSettings.getContigNames(); for (Field field : AnalysisStats.class.getDeclaredFields()) { @Nullable AddChromosomeBins annotation = field.getAnnotation(AddChromosomeBins.class); if (annotation != null) { for (int contig = 0; contig < contigNames.size(); contig++) { int contigCopy = contig; for (int c = 0; c < Objects.requireNonNull(groupSettings.getContigSizes().get( contigNames.get(contig))) / groupSettings.BIN_SIZE; c++) { int cCopy = c; try { MultiCounter <?> counter = ((MultiCounter<?>) field.get(this)); counter.addPredicate(contigNames.get(contig) + "_bin_" + String.format("%03d", c), loc -> { final int min = groupSettings.BIN_SIZE * cCopy; final int max = groupSettings.BIN_SIZE * (cCopy + 1); return loc.contigIndex == contigCopy && loc.position >= min && loc.position < max; }); counter.accept(new SequenceLocation(contig, Objects.requireNonNull(contigNames.get(contig)), c * groupSettings.BIN_SIZE), 0); } catch (IllegalArgumentException | IllegalAccessException e) { throw new RuntimeException(e); } } } } } } { //Force initialization of counters for all possible substitutions: //it is easier to put the output of multiple samples together if //unencountered substitutions have a 0-count entry for (byte mut: Arrays.asList((byte) 'A', (byte) 'T', (byte) 'G', (byte) 'C')) { for (byte wt: Arrays.asList((byte) 'A', (byte) 'T', (byte) 'G', (byte) 'C')) { if (wt == mut) { continue; } Mutation wtM = new Mutation(MutationType.WILDTYPE, wt, false, null, Util.emptyOptional()); Mutation to = new Mutation(MutationType.SUBSTITUTION, wt, false, new byte [] {mut}, Util.emptyOptional()); List<String> contigNames = groupSettings.getContigNames(); for (int contig = 0; contig < contigNames.size(); contig++) { for (int c = 0; c < Objects.requireNonNull(groupSettings.getContigSizes().get( contigNames.get(contig))) / groupSettings.BIN_SIZE; c++) { SequenceLocation location = new SequenceLocation(contig, Objects.requireNonNull(contigNames.get(contig)), c * groupSettings.BIN_SIZE); topBottomSubstDisagreementsQ2.accept(location, new DuplexDisagreement(wtM, to, true, Quality.GOOD), 0); codingStrandSubstQ2.accept(location, new ComparablePair<>(wtM, to), 0); templateStrandSubstQ2.accept(location, new ComparablePair<>(wtM, to), 0); } } } } } //Assert that annotations have not been discarded //This does not need to be done on every instance, but exceptions are better //handled in a non-static context try { Assert.isNonNull(AnalysisStats.class.getDeclaredField("duplexGroupingDepth"). getAnnotation(PrintInStatus.class)); } catch (NoSuchFieldException | SecurityException e) { throw new RuntimeException(e); } } public @NonNull String getName() { return name; } private static final long serialVersionUID = -7786797851357308577L; @Retention(RetentionPolicy.RUNTIME) private @interface AddChromosomeBins {}; @PrintInStatus(outputLevel = VERBOSE) @Final @Persistent(serialized="true") @Extension(vendorName = "datanucleus", key = "is-second-class", value="false") Histogram duplexGroupingDepth = new Histogram(100); @PrintInStatus(outputLevel = VERBOSE) @Final @Persistent(serialized = "true") @Extension(vendorName = "datanucleus", key = "is-second-class", value="false") Histogram duplexTotalRecords = new Histogram(500); @PrintInStatus(outputLevel = VERBOSE) @Final @Persistent(serialized = "true") @Extension(vendorName = "datanucleus", key = "is-second-class", value="false") Histogram rejectedIndelDistanceToLigationSite = new Histogram(200); @PrintInStatus(outputLevel = VERBOSE) @Final @Persistent(serialized = "true") @Extension(vendorName = "datanucleus", key = "is-second-class", value="false") Histogram rejectedSubstDistanceToLigationSite = new Histogram(200); @PrintInStatus(outputLevel = VERBOSE) @Final @Persistent(serialized = "true") @Extension(vendorName = "datanucleus", key = "is-second-class", value="false") Histogram wtRejectedDistanceToLigationSite = new Histogram(200); @PrintInStatus(outputLevel = VERBOSE) @Final @Persistent(serialized = "true") @Extension(vendorName = "datanucleus", key = "is-second-class", value="false") Histogram wtAcceptedBaseDistanceToLigationSite = new Histogram(200); @PrintInStatus(outputLevel = VERBOSE) @Final @Persistent(serialized = "true") @Extension(vendorName = "datanucleus", key = "is-second-class", value="false") Histogram singleAnalyzerQ2CandidateDistanceToLigationSite = new Histogram(200); @PrintInStatus(outputLevel = VERBOSE) @Final @Persistent(serialized = "true") @Extension(vendorName = "datanucleus", key = "is-second-class", value="false") Histogram crossAnalyzerQ2CandidateDistanceToLigationSite = new Histogram(200); @PrintInStatus(outputLevel = VERBOSE) @Final @Persistent(serialized = "true") @Extension(vendorName = "datanucleus", key = "is-second-class", value="false") ConcurrentMap<Mutation, Histogram> disagMutConsensus = new MutationHistogramMap(); @PrintInStatus(outputLevel = VERBOSE) @Final @Persistent(serialized = "true") @Extension(vendorName = "datanucleus", key = "is-second-class", value="false") ConcurrentMap<Mutation, Histogram> disagWtConsensus = new MutationHistogramMap(); @PrintInStatus(outputLevel = VERBOSE) @Final @Persistent(serialized = "true") @Extension(vendorName = "datanucleus", key = "is-second-class", value="false") Histogram substDisagDistanceToLigationSite = new Histogram(200); @PrintInStatus(outputLevel = VERBOSE) @Final @Persistent(serialized = "true") @Extension(vendorName = "datanucleus", key = "is-second-class", value="false") Histogram insDisagDistanceToLigationSite = new Histogram(200); @PrintInStatus(outputLevel = VERBOSE) @Final @Persistent(serialized = "true") @Extension(vendorName = "datanucleus", key = "is-second-class", value="false") Histogram delDisagDistanceToLigationSite = new Histogram(200); @PrintInStatus(outputLevel = VERBOSE) @Final @Persistent(serialized = "true") @Extension(vendorName = "datanucleus", key = "is-second-class", value="false") Histogram disagDelSize = new Histogram(200); @PrintInStatus(outputLevel = VERBOSE) @Final @Persistent(serialized = "true") @Extension(vendorName = "datanucleus", key = "is-second-class", value="false") Histogram Q2CandidateDistanceToLigationSiteN = new Histogram(200); @PrintInStatus(outputLevel = VERBOSE) @Final @Persistent(serialized = "true") @Extension(vendorName = "datanucleus", key = "is-second-class", value="false") Histogram wtQ2CandidateQ1Q2Coverage = new Histogram(200); @PrintInStatus(outputLevel = VERBOSE) @Final @Persistent(serialized = "true") @Extension(vendorName = "datanucleus", key = "is-second-class", value="false") Histogram wtQ2CandidateQ1Q2CoverageRepetitive = new Histogram(200); @PrintInStatus(outputLevel = VERBOSE) @Final @Persistent(serialized = "true") @Extension(vendorName = "datanucleus", key = "is-second-class", value="false") Histogram wtQ2CandidateQ1Q2CoverageNonRepetitive = new Histogram(200); @PrintInStatus(outputLevel = VERBOSE) @Final @Persistent(serialized = "true") @Extension(vendorName = "datanucleus", key = "is-second-class", value="false") Histogram mutantQ2CandidateQ1Q2Coverage = new Histogram(200); @PrintInStatus(outputLevel = VERBOSE) @Final @Persistent(serialized = "true") @Extension(vendorName = "datanucleus", key = "is-second-class", value="false") Histogram mutantQ2CandidateQ1Q2DCoverageRepetitive = new Histogram(200); @PrintInStatus(outputLevel = VERBOSE) @Final @Persistent(serialized = "true") @Extension(vendorName = "datanucleus", key = "is-second-class", value="false") Histogram mutantQ2CandidateQ1Q2DCoverageNonRepetitive = new Histogram(200); @PrintInStatus(outputLevel = VERBOSE) @Final @Persistent(serialized = "true") @Extension(vendorName = "datanucleus", key = "is-second-class", value="false") Histogram uniqueMutantQ2CandidateQ1Q2DCoverage = new Histogram(200); @PrintInStatus(outputLevel = VERBOSE) @Final @Persistent(serialized = "true") @Extension(vendorName = "datanucleus", key = "is-second-class", value="false") Histogram uniqueMutantQ2CandidateQ1Q2DCoverageRepetitive = new Histogram(200); @PrintInStatus(outputLevel = VERBOSE) @Final @Persistent(serialized = "true") @Extension(vendorName = "datanucleus", key = "is-second-class", value="false") Histogram uniqueMutantQ2CandidateQ1Q2DCoverageNonRepetitive = new Histogram(200); @PrintInStatus(outputLevel = VERBOSE) public @Final @Persistent StatsCollector nPosExcluded = new StatsCollector(); @PrintInStatus(outputLevel = TERSE) public @Final @Persistent StatsCollector nRecordsProcessed = new StatsCollector(); @PrintInStatus(outputLevel = TERSE) public @Final @Persistent StatsCollector ignoredUnpairedReads = new StatsCollector(); @PrintInStatus(outputLevel = VERBOSE) public @Final @Persistent StatsCollector nRecordsInFile = new StatsCollector(); @PrintInStatus(outputLevel = VERBOSE) public @Final @Persistent StatsCollector nRecordsUnmapped = new StatsCollector(); @PrintInStatus(outputLevel = VERBOSE) public @Final @Persistent StatsCollector nRecordsBelowMappingQualityThreshold = new StatsCollector(); @PrintInStatus(outputLevel = VERBOSE) public @Final @Persistent(serialized = "true") @Extension(vendorName = "datanucleus", key = "is-second-class", value="false") Histogram mappingQualityKeptRecords = new Histogram(500); @PrintInStatus(outputLevel = VERBOSE) public @Final @Persistent(serialized = "true") @Extension(vendorName = "datanucleus", key = "is-second-class", value="false") Histogram mappingQualityAllRecords = new Histogram(500); @PrintInStatus(outputLevel = VERBOSE) @Final @Persistent(serialized = "true") @Extension(vendorName = "datanucleus", key = "is-second-class", value="false") Histogram averageReadPhredQuality0 = new Histogram(500); @PrintInStatus(outputLevel = VERBOSE) @Final @Persistent(serialized = "true") @Extension(vendorName = "datanucleus", key = "is-second-class", value="false") Histogram averageReadPhredQuality1 = new Histogram(500); @PrintInStatus(outputLevel = VERBOSE) @Final @Persistent(serialized = "true") @Extension(vendorName = "datanucleus", key = "is-second-class", value="false") MultiCounter<ComparablePair<Integer, Integer>> phredAndLigSiteDistance; @PrintInStatus(outputLevel = VERY_VERBOSE) @Final @Persistent(serialized = "true") @Extension(vendorName = "datanucleus", key = "is-second-class", value="false") Histogram medianReadPhredQuality = new Histogram(500); @PrintInStatus(outputLevel = VERY_VERBOSE) public @Final @Persistent(serialized = "true") @Extension(vendorName = "datanucleus", key = "is-second-class", value="false") Histogram medianPositionPhredQuality = new Histogram(500); @PrintInStatus(outputLevel = VERBOSE) public @Final @Persistent(serialized = "true") @Extension(vendorName = "datanucleus", key = "is-second-class", value="false") Histogram averageDuplexReferenceDisagreementRate = new Histogram(500); @PrintInStatus(outputLevel = VERBOSE) public @Final @Persistent(serialized = "true") @Extension(vendorName = "datanucleus", key = "is-second-class", value="false") Histogram duplexinsertSize = new Histogram(1000); @PrintInStatus(outputLevel = VERBOSE) public @Persistent(serialized = "true") @Extension(vendorName = "datanucleus", key = "is-second-class", value="false") double[] approximateReadInsertSize = null; @PrintInStatus(outputLevel = VERBOSE) public @Persistent(serialized = "true") @Extension(vendorName = "datanucleus", key = "is-second-class", value="false") double[] approximateReadInsertSizeRaw = null; @PrintInStatus(outputLevel = VERBOSE) public @Final @Persistent(serialized = "true") @Extension(vendorName = "datanucleus", key = "is-second-class", value="false") Histogram duplexAverageNClipped = new Histogram(500); @PrintInStatus(outputLevel = VERY_VERBOSE) public @Final @Persistent(serialized = "true") @Extension(vendorName = "datanucleus", key = "is-second-class", value="false") Histogram duplexInsert130_180averageNClipped = new Histogram(500); @PrintInStatus(outputLevel = VERY_VERBOSE) public @Final @Persistent(serialized = "true") @Extension(vendorName = "datanucleus", key = "is-second-class", value="false") Histogram duplexInsert100_130AverageNClipped = new Histogram(500); @PrintInStatus(outputLevel = VERY_VERBOSE) public @Final @Persistent(serialized = "true") @Extension(vendorName = "datanucleus", key = "is-second-class", value="false") Histogram disagreementOrientationProportions1 = new Histogram(10); @PrintInStatus(outputLevel = VERY_VERBOSE) public @Final @Persistent(serialized = "true") @Extension(vendorName = "datanucleus", key = "is-second-class", value="false") Histogram disagreementOrientationProportions2 = new Histogram(10); @PrintInStatus(outputLevel = VERY_VERBOSE) public @Final @Persistent StatsCollector disagreementMatesSameOrientation = new StatsCollector(); @PrintInStatus(outputLevel = VERY_VERBOSE) public @Final @Persistent StatsCollector nComplexDisagreementsQ2 = new StatsCollector(); @PrintInStatus(outputLevel = VERY_VERBOSE) public @Final @Persistent StatsCollector nRecordsIgnoredBecauseSecondary = new StatsCollector(); @PrintInStatus(outputLevel = VERY_VERBOSE) public @Final @Persistent(serialized = "true") MultiCounter<?> nRecordsNotInIntersection1; @PrintInStatus(outputLevel = VERY_VERBOSE) public @Final @Persistent(serialized = "true") MultiCounter<?> nRecordsNotInIntersection2; @PrintInStatus(outputLevel = VERY_VERBOSE) public @Final @Persistent(serialized = "true") MultiCounter<?> nTooLowMapQIntersect; @PrintInStatus(outputLevel = TERSE) public @Final @Persistent(serialized = "true") MultiCounter<?> nPosDuplex; @PrintInStatus(outputLevel = VERBOSE) public @Final @Persistent(serialized = "true") MultiCounter<?> nPosDuplexBothStrandsPresent; @PrintInStatus(outputLevel = TERSE) public @Final @Persistent(serialized = "true") MultiCounter<?> nReadMedianPhredBelowThreshold; @PrintInStatus(outputLevel = TERSE) public @Final @Persistent(serialized = "true") MultiCounter<?> nDuplexesTooMuchClipping; @PrintInStatus(outputLevel = VERY_VERBOSE) public @Final @Persistent DoubleAdder nDuplexesNoStats; @PrintInStatus(outputLevel = VERY_VERBOSE) public @Final @Persistent DoubleAdder nDuplexesWithStats; @PrintInStatus(outputLevel = TERSE) public @Final @Persistent(serialized = "true") MultiCounter<?> nPosDuplexTooFewReadsPerStrand1; @PrintInStatus(outputLevel = TERSE) public @Final @Persistent(serialized = "true") MultiCounter<?> nPosDuplexTooFewReadsPerStrand2; @PrintInStatus(outputLevel = TERSE) public @Final @Persistent(serialized = "true") MultiCounter<?> nPosDuplexTooFewReadsAboveQ2Phred; @PrintInStatus(outputLevel = TERSE) public @Final @Persistent StatsCollector nPosIgnoredBecauseTooHighCoverage; @PrintInStatus(outputLevel = VERY_VERBOSE) public @Final @Persistent(serialized = "true") MultiCounter<?> nPosDuplexWithTopBottomDuplexDisagreementNoWT; @PrintInStatus(outputLevel = VERY_VERBOSE) public @Final @Persistent(serialized = "true") MultiCounter<?> nPosDuplexWithTopBottomDuplexDisagreementNotASub; @PrintInStatus(outputLevel = VERBOSE) public @Final @Persistent(serialized = "true") MultiCounter<ComparablePair<String, String>> rawMismatchesQ1; @PrintInStatus(outputLevel = VERBOSE) public @Final @Persistent(serialized = "true") MultiCounter<ComparablePair<String, String>> vBarcodeMismatches1M; @PrintInStatus(outputLevel = VERBOSE) public @Final @Persistent(serialized = "true") MultiCounter<ComparablePair<String, String>> vBarcodeMismatches2M; @PrintInStatus(outputLevel = VERBOSE) public @Final @Persistent(serialized = "true") MultiCounter<ComparablePair<String, String>> vBarcodeMismatches3OrMore; @PrintInStatus(outputLevel = VERBOSE) public @Final @Persistent(serialized = "true") MultiCounter<ComparablePair<String, String>> rawDeletionsQ1; @PrintInStatus(outputLevel = VERBOSE) @Final @Persistent(serialized = "true") @Extension(vendorName = "datanucleus", key = "is-second-class", value="false") Histogram rawDeletionLengthQ1; @PrintInStatus(outputLevel = VERBOSE) public @Final @Persistent(serialized = "true") MultiCounter<ComparablePair<String, String>> rawInsertionsQ1; @PrintInStatus(outputLevel = VERBOSE) @Final @Persistent(serialized = "true") @Extension(vendorName = "datanucleus", key = "is-second-class", value="false") Histogram rawInsertionLengthQ1; @PrintInStatus(outputLevel = VERBOSE) public @Final @Persistent(serialized = "true") MultiCounter<ComparablePair<String, String>> rawMismatchesQ2; @PrintInStatus(outputLevel = VERBOSE) public @Final @Persistent(serialized = "true") MultiCounter<ComparablePair<String, String>> rawDeletionsQ2; @PrintInStatus(outputLevel = VERBOSE) @Final @Persistent(serialized = "true") @Extension(vendorName = "datanucleus", key = "is-second-class", value="false") Histogram rawDeletionLengthQ2; @PrintInStatus(outputLevel = VERBOSE) public @Final @Persistent(serialized = "true") MultiCounter<ComparablePair<String, String>> rawInsertionsQ2; @PrintInStatus(outputLevel = VERBOSE) @Final @Persistent(serialized = "true") @Extension(vendorName = "datanucleus", key = "is-second-class", value="false") Histogram rawInsertionLengthQ2; @PrintInStatus(outputLevel = TERSE) @AddChromosomeBins public @Final @Persistent(serialized = "true") MultiCounter<DuplexDisagreement> topBottomSubstDisagreementsQ2; @PrintInStatus(outputLevel = TERSE) @AddChromosomeBins public @Final @Persistent(serialized = "true") MultiCounter<DuplexDisagreement> topBottomDelDisagreementsQ2; @PrintInStatus(outputLevel = TERSE) @AddChromosomeBins public @Final @Persistent(serialized = "true") MultiCounter<List<Integer>> alleleFrequencies; @PrintInStatus(outputLevel = TERSE) @AddChromosomeBins public @Final @Persistent(serialized = "true") MultiCounter<DuplexDisagreement> topBottomInsDisagreementsQ2; @PrintInStatus(outputLevel = VERBOSE) public @Final @Persistent(serialized = "true") MultiCounter<ComparablePair<Mutation, Mutation>> codingStrandSubstQ2; @PrintInStatus(outputLevel = VERBOSE) public @Final @Persistent(serialized = "true") MultiCounter<ComparablePair<Mutation, Mutation>> templateStrandSubstQ2; @PrintInStatus(outputLevel = VERBOSE) public @Final @Persistent(serialized = "true") MultiCounter<ComparablePair<Mutation, Mutation>> codingStrandDelQ2; @PrintInStatus(outputLevel = VERBOSE) public @Final @Persistent(serialized = "true") MultiCounter<ComparablePair<Mutation, Mutation>> templateStrandDelQ2; @PrintInStatus(outputLevel = VERBOSE) public @Final @Persistent(serialized = "true") MultiCounter<ComparablePair<Mutation, Mutation>> codingStrandInsQ2; @PrintInStatus(outputLevel = VERBOSE) public @Final @Persistent(serialized = "true") MultiCounter<ComparablePair<Mutation, Mutation>> templateStrandInsQ2; @PrintInStatus(outputLevel = VERY_VERBOSE) public @Final @Persistent(serialized = "true") MultiCounter<DuplexDisagreement> topBottomDisagreementsQ2TooHighCoverage; @PrintInStatus(outputLevel = TERSE) @AddChromosomeBins public @Final @Persistent(serialized = "true") MultiCounter<?> nPosDuplexCandidatesForDisagreementQ2; @PrintInStatus(outputLevel = VERY_VERBOSE) public @Final @Persistent(serialized = "true") MultiCounter<?> nPosDuplexCandidatesForDisagreementQ2TooHighCoverage; @PrintInStatus(outputLevel = VERY_VERBOSE) public @Final @Persistent StatsCollector nPosDuplexWithLackOfStrandConsensus1; @PrintInStatus(outputLevel = VERY_VERBOSE) public @Final @Persistent StatsCollector nPosDuplexWithLackOfStrandConsensus2; @PrintInStatus(outputLevel = VERY_VERBOSE) public @Final @Persistent StatsCollector nPosDuplexCompletePairOverlap; @PrintInStatus(outputLevel = VERBOSE) public @Final @Persistent StatsCollector nPosUncovered; @PrintInStatus(outputLevel = VERBOSE) public @Final @Persistent StatsCollector nQ2PromotionsBasedOnFractionReads; @PrintInStatus(outputLevel = VERBOSE) public @Final @Persistent StatsCollector nPosQualityPoor; @PrintInStatus(outputLevel = VERY_VERBOSE) public @Final @Persistent StatsCollector nPosQualityPoorA; @PrintInStatus(outputLevel = VERY_VERBOSE) public @Final @Persistent StatsCollector nPosQualityPoorT; @PrintInStatus(outputLevel = VERY_VERBOSE) public @Final @Persistent StatsCollector nPosQualityPoorG; @PrintInStatus(outputLevel = VERY_VERBOSE) public @Final @Persistent StatsCollector nPosQualityPoorC; @PrintInStatus(outputLevel = VERY_VERBOSE) public @Final @Persistent StatsCollector nConsensusQ1NotMet; @PrintInStatus(outputLevel = VERY_VERBOSE) public @Final @Persistent StatsCollector nMedianPhredAtPositionTooLow; @PrintInStatus(outputLevel = VERY_VERBOSE) public @Final @Persistent StatsCollector nFractionWrongPairsAtPositionTooHigh; @PrintInStatus(outputLevel = VERBOSE) public @Final @Persistent StatsCollector nPosQualityQ1; @PrintInStatus(outputLevel = VERBOSE) public @Final @Persistent StatsCollector nPosQualityQ2; @PrintInStatus(outputLevel = VERBOSE) public @Final @Persistent StatsCollector nPosQualityQ2OthersQ1Q2; @PrintInStatus(outputLevel = TERSE) public @Final @Persistent(serialized = "true") MultiCounter<?> nPosDuplexQualityQ2OthersQ1Q2; @PrintInStatus(outputLevel = TERSE) public @Final @Persistent(serialized = "true") MultiCounter<?> nPosDuplexQualityQ2OthersQ1Q2CodingOrTemplate; @PrintInStatus(color = "greenBackground", outputLevel = TERSE) public @Final @Persistent(serialized = "true") MultiCounter<?> nPosCandidatesForUniqueMutation; @PrintInStatus(outputLevel = VERY_VERBOSE) public @Final @Persistent(serialized = "true") @Extension(vendorName = "datanucleus", key = "is-second-class", value="false") Histogram nReadsAtPosQualityQ2OthersQ1Q2 = new Histogram(500); @PrintInStatus(outputLevel = VERY_VERBOSE) public @Final @Persistent(serialized = "true") @Extension(vendorName = "datanucleus", key = "is-second-class", value="false") Histogram nReadsAtPosWithSomeCandidateForQ2UniqueMutation = new Histogram(500); @PrintInStatus(outputLevel = VERBOSE) public @Final @Persistent(serialized = "true") @Extension(vendorName = "datanucleus", key = "is-second-class", value="false") Histogram nQ1Q2AtPosQualityQ2OthersQ1Q2 = new Histogram(500); @PrintInStatus(outputLevel = VERBOSE) public @Final @Persistent(serialized = "true") @Extension(vendorName = "datanucleus", key = "is-second-class", value="false") Histogram nQ1Q2AtPosWithSomeCandidateForQ2UniqueMutation = new Histogram(500); @PrintInStatus(outputLevel = VERBOSE, description = "Q1 or Q2 duplex coverage histogram") public @Final @Persistent(serialized = "true") @Extension(vendorName = "datanucleus", key = "is-second-class", value="false") Histogram Q1Q2DuplexCoverage = new Histogram(500); @PrintInStatus(outputLevel = VERBOSE, description = "Q2 duplex coverage histogram") public @Final @Persistent(serialized = "true") @Extension(vendorName = "datanucleus", key = "is-second-class", value="false") Histogram Q2DuplexCoverage = new Histogram(500); @PrintInStatus(outputLevel = VERY_VERBOSE, description = "Missing strands for positions that have no usable duplex") public @Final @Persistent(serialized = "true") @Extension(vendorName = "datanucleus", key = "is-second-class", value="false") Histogram missingStrandsWhenNoUsableDuplex = new Histogram(500); @PrintInStatus(outputLevel = VERY_VERBOSE, description = "Top/bottom coverage imbalance for positions that have no usable duplex") public @Final @Persistent(serialized = "true") @Extension(vendorName = "datanucleus", key = "is-second-class", value="false") Histogram strandCoverageImbalanceWhenNoUsableDuplex = new Histogram(500); @PrintInStatus(outputLevel = VERY_VERBOSE, description = "Histogram of copy number for duplex bottom strands") public @Final @Persistent(serialized = "true") @Extension(vendorName = "datanucleus", key = "is-second-class", value="false") Histogram copyNumberOfDuplexBottomStrands = new Histogram(500) { private static final long serialVersionUID = 6597978073262739721L; private final NumberFormat formatter = new DecimalFormat("0. @Override public String toString() { final double nPosDuplexf = nPosDuplex.sum(); return stream().map(a -> formatter.format((float) (a.sum() / nPosDuplexf))). collect(Collectors.toList()).toString(); } }; @PrintInStatus(outputLevel = VERY_VERBOSE, description = "Histogram of copy number for duplex top strands") public @Final @Persistent(serialized = "true") @Extension(vendorName = "datanucleus", key = "is-second-class", value="false") Histogram copyNumberOfDuplexTopStrands = new Histogram(500) { private static final long serialVersionUID = -8213283701959613589L; private final NumberFormat formatter = new DecimalFormat("0. @Override public String toString() { final double nPosDuplexf = nPosDuplex.sum(); return stream().map(a -> formatter.format((float) (a.sum() / nPosDuplexf))). collect(Collectors.toList()).toString(); } }; @PrintInStatus(outputLevel = VERY_VERBOSE, description = "Duplex collision probability") public @Final @Persistent(serialized = "true") @Extension(vendorName = "datanucleus", key = "is-second-class", value="false") Histogram duplexCollisionProbability = new Histogram(100); @PrintInStatus(outputLevel = VERY_VERBOSE, description = "Duplex collision probability at Q2 sites") public @Final @Persistent(serialized = "true") @Extension(vendorName = "datanucleus", key = "is-second-class", value="false") Histogram duplexCollisionProbabilityAtQ2 = new Histogram(100); @PrintInStatus(outputLevel = VERY_VERBOSE, description = "Duplex collision probability when both strands represented") public @Final @Persistent(serialized = "true") @Extension(vendorName = "datanucleus", key = "is-second-class", value="false") Histogram duplexCollisionProbabilityWhen2Strands = new Histogram(100); @PrintInStatus(outputLevel = VERY_VERBOSE, description = "Duplex collision probability at disagreement") public @Final @Persistent(serialized = "true") @Extension(vendorName = "datanucleus", key = "is-second-class", value="false") Histogram duplexCollisionProbabilityAtDisag = new Histogram(100); @PrintInStatus(outputLevel = VERY_VERBOSE, description = "Average duplex collision probability for duplexes covering genome position of disagreement") public @Final @Persistent(serialized = "true") @Extension(vendorName = "datanucleus", key = "is-second-class", value="false") Histogram duplexCollisionProbabilityLocalAvAtDisag = new Histogram(100); /* @PrintInStatus(outputLevel = VERY_VERBOSE, description = "Histogram of variable barcode mapping distance mismatch") public final Histogram sameBarcodeButPositionMismatch = new Histogram(500); @PrintInStatus(outputLevel = VERBOSE, description = "Candidates with top good coverage") public final PriorityBlockingQueue<CandidateSequence> topQ2DuplexCoverage = new PriorityBlockingQueue<CandidateSequence> (100, (c1, c2) -> Integer.compare(c1.getnGoodDuplexes(),c2.getnGoodDuplexes())) { private static final long serialVersionUID = 8206630026701622788L; @Override public String toString() { return stream().collect(Collectors.toList()).toString(); } };*/ @PrintInStatus(outputLevel = VERY_VERBOSE) public @Final @Persistent StatsCollector nBasesBelowPhredScore = new StatsCollector(); @PrintInStatus(outputLevel = VERY_VERBOSE) public @Final @Persistent StatsCollector nConstantBarcodeMissing = new StatsCollector(), nConstantBarcodeDodgy = new StatsCollector(), nConstantBarcodeDodgyNStrand = new StatsCollector(); @PrintInStatus(outputLevel = VERY_VERBOSE) public @Final @Persistent StatsCollector nReadsConstantBarcodeOK = new StatsCollector(); @PrintInStatus(outputLevel = VERY_VERBOSE) public @Final @Persistent StatsCollector nCandidateSubstitutionsConsidered = new StatsCollector(); @PrintInStatus(outputLevel = VERY_VERBOSE) public @Final @Persistent StatsCollector nCandidateSubstitutionsToA = new StatsCollector(); @PrintInStatus(outputLevel = VERY_VERBOSE) public @Final @Persistent StatsCollector nCandidateSubstitutionsToT = new StatsCollector(); @PrintInStatus(outputLevel = VERY_VERBOSE) public @Final @Persistent StatsCollector nCandidateSubstitutionsToG = new StatsCollector(); @PrintInStatus(outputLevel = VERY_VERBOSE) public @Final @Persistent StatsCollector nCandidateSubstitutionsToC = new StatsCollector(); @PrintInStatus(outputLevel = VERY_VERBOSE) public @Final @Persistent StatsCollector nNs = new StatsCollector(); @PrintInStatus(outputLevel = TERSE) public @Final @Persistent StatsCollector nCandidateInsertions = new StatsCollector(); @PrintInStatus(outputLevel = TERSE) public @Final @Persistent StatsCollector nCandidateDeletions = new StatsCollector(); @PrintInStatus(outputLevel = VERY_VERBOSE) public @Final @Persistent StatsCollector nCandidateSubstitutionsAfterLastNBases = new StatsCollector(); @PrintInStatus(outputLevel = VERY_VERBOSE) public @Final @Persistent StatsCollector nCandidateWildtypeAfterLastNBases = new StatsCollector(); @PrintInStatus(outputLevel = VERY_VERBOSE) public @Final @Persistent StatsCollector nCandidateSubstitutionsBeforeFirstNBases = new StatsCollector(); @PrintInStatus(outputLevel = VERY_VERBOSE) public @Final @Persistent StatsCollector nCandidateIndelAfterLastNBases = new StatsCollector(); @PrintInStatus(outputLevel = VERY_VERBOSE) public @Final @Persistent StatsCollector nCandidateIndelBeforeFirstNBases = new StatsCollector(); /* @PrintInStatus(outputLevel = VERY_VERBOSE) public final StatsCollector nVariableBarcodeCandidateExaminations = new StatsCollector(); @PrintInStatus(outputLevel = VERY_VERBOSE) public final StatsCollector nVariableBarcodeLeftEqual = new StatsCollector(); @PrintInStatus(outputLevel = VERY_VERBOSE) public final StatsCollector nVariableBarcodeRightEqual = new StatsCollector(); @PrintInStatus(outputLevel = VERY_VERBOSE) public final StatsCollector nVariableBarcodeMateDoesNotMatch = new StatsCollector(); @PrintInStatus(outputLevel = VERY_VERBOSE) public final StatsCollector nVariableBarcodeMateMatches = new StatsCollector(); @PrintInStatus(outputLevel = VERY_VERBOSE) public final StatsCollector nVariableBarcodeMatchAfterPositionCheck = new StatsCollector(); @PrintInStatus(outputLevel = VERY_VERBOSE) public final StatsCollector nVariableBarcodesCloseMisses = new StatsCollector();*/ @PrintInStatus(outputLevel = VERY_VERBOSE) public @Final @Persistent StatsCollector nReadsInsertNoSize = new StatsCollector(); @PrintInStatus(outputLevel = VERY_VERBOSE) @DivideByTwo public @Final @Persistent StatsCollector nReadsPairRF = new StatsCollector(); @PrintInStatus(outputLevel = VERY_VERBOSE) @DivideByTwo public @Final @Persistent StatsCollector nReadsPairTandem = new StatsCollector(); @PrintInStatus(outputLevel = VERY_VERBOSE) @DivideByTwo public @Final @Persistent StatsCollector nReadsInsertSizeAboveMaximum = new StatsCollector(); @PrintInStatus(outputLevel = VERY_VERBOSE) @DivideByTwo public @Final @Persistent StatsCollector nReadsInsertSizeBelowMinimum = new StatsCollector(); @PrintInStatus(outputLevel = VERY_VERBOSE) public @Final @Persistent StatsCollector nMateOutOfReach = new StatsCollector(); @PrintInStatus(outputLevel = TERSE) @Final @Persistent StatsCollector nProcessedBases = new StatsCollector(); @PrintInStatus(outputLevel = TERSE) boolean analysisTruncated; @PrintInStatus(outputLevel = VERBOSE) @Final @Persistent(serialized = "true") @Extension(vendorName = "datanucleus", key = "is-second-class", value="false") Histogram nReadsInPrefetchQueue; /* @PrintInStatus(outputLevel = VERY_VERBOSE) public final StatsCollector nProcessedFirst6BasesFirstOfPair = new StatsCollector(); @PrintInStatus(outputLevel = VERY_VERBOSE) public final StatsCollector nProcessedFirst6BasesSecondOfPair = new StatsCollector();*/ @PrintInStatus(outputLevel = VERY_VERBOSE) @Final @Persistent DoubleAdder phredSumProcessedbases = new DoubleAdder(); /* @PrintInStatus(outputLevel = VERY_VERBOSE) public final DoubleAdder phredSumFirst6basesFirstOfPair = new DoubleAdder(); @PrintInStatus(outputLevel = VERY_VERBOSE) public final DoubleAdder phredSumFirst6basesSecondOfPair = new DoubleAdder();*/ public @Persistent Map<String, int[]> positionByPositionCoverage; transient Builder positionByPositionCoverageProtobuilder; @SuppressWarnings("null") public void print(PrintStream stream, boolean colorize) { stream.println(); NumberFormat formatter = DoubleAdderFormatter.nf.get(); ConcurrentModificationException cme = null; for (Field field: AnalysisStats.class.getDeclaredFields()) { PrintInStatus annotation = field.getAnnotation(PrintInStatus.class); if ((annotation != null && annotation.outputLevel().compareTo(outputLevel) <= 0) || (annotation == null && (field.getType().equals(LongAdderFormatter.class) || field.getType().equals(StatsCollector.class) || field.getType().equals(Histogram.class)))) { try { final Object fieldValue = field.get(this); if (fieldValue == null) { continue; } if (annotation != null && annotation.color().equals("greenBackground")) { stream.print(greenB(colorize)); } long divisor; if (field.getAnnotation(DivideByTwo.class) != null) divisor = 2; else divisor = 1; boolean hasDescription = annotation != null && !annotation.description().isEmpty(); stream.print(blueF(colorize) + (hasDescription ? annotation.description() : field.getName()) + ": " + reset(colorize)); if (field.getType().equals(LongAdderFormatter.class)) { stream.println(formatter.format(((Long) longAdderFormatterSum. invoke(fieldValue)) / divisor)); } else if (field.getType().equals(StatsCollector.class)) { Function<Long, Long> transformer = l-> l / divisor; stream.println((String) statsCollectorToString.invoke(fieldValue, transformer)); } else { stream.println(fieldValue.toString()); } } catch (IllegalArgumentException | IllegalAccessException | InvocationTargetException e) { throw new RuntimeException(e); } catch (ConcurrentModificationException e) { cme = e; } finally { if (annotation != null && annotation.color().equals("greenBackground")) { stream.print(reset(colorize)); } } } } if (cme != null) { throw cme; } } private static final Method longAdderFormatterSum, statsCollectorToString, turnOnMethod, turnOffMethod; static { try { longAdderFormatterSum = LongAdder.class.getDeclaredMethod("sum"); statsCollectorToString = StatsCollector.class.getDeclaredMethod("toString", Function.class); turnOnMethod = SwitchableStats.class.getDeclaredMethod("turnOn"); turnOffMethod = SwitchableStats.class.getDeclaredMethod("turnOff"); } catch (NoSuchMethodException | SecurityException e) { e.printStackTrace(); throw new RuntimeException(e); } } public void setOutputLevel(OutputLevel level) { this.outputLevel = level; for (Field field : AnalysisStats.class.getDeclaredFields()) { if (!SwitchableStats.class.isAssignableFrom(field.getType())) { continue; } @Nullable PrintInStatus annotation = field.getAnnotation(PrintInStatus.class); if (annotation == null) { continue; } try { if (annotation.outputLevel().compareTo(outputLevel) <= 0) { turnOnMethod.invoke(field.get(this)); } else { turnOffMethod.invoke(field.get(this)); } } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { throw new RuntimeException(e); } } } public void traceField(String fieldName, String prefix) throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException { Object o = this.getClass().getDeclaredField(fieldName).get(this); if (o instanceof Traceable) { ((Traceable) o).setPrefix(prefix); } else { throw new IllegalArgumentException("Field " + fieldName + " not currently traceable"); } } @Override public void actualize() { for (Field field: AnalysisStats.class.getDeclaredFields()) { if (!Actualizable.class.isAssignableFrom(field.getType())) { continue; } try { if (field.get(this) != null) { ((Actualizable) field.get(this)).actualize(); } } catch (IllegalArgumentException | IllegalAccessException e) { throw new RuntimeException(e); }; } } }
package dk.netarkivet.common.utils; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.List; import java.util.Map; import junit.framework.TestCase; import org.dom4j.Document; import dk.netarkivet.common.exceptions.ArgumentNotValid; import dk.netarkivet.common.exceptions.IllegalState; import dk.netarkivet.testutils.CollectionAsserts; import dk.netarkivet.testutils.ReflectUtils; import dk.netarkivet.testutils.preconfigured.MoveTestFiles; public class XmlTreeTester extends TestCase { private MoveTestFiles mtf = new MoveTestFiles(TestInfo.DATADIR, TestInfo.TEMPDIR); public XmlTreeTester(String s) { super(s); } public void setUp() throws Exception { super.setUp(); mtf.setUp(); } public void tearDown() throws Exception { mtf.tearDown(); super.tearDown(); } public void testGetStringTree() { StringTree<String> tree1 = getTree(); assertNotNull("Should get non-null tree", tree1); assertEquals("Should have node from backing XML", "what is the question", tree1.getSubTree("dk").getSubTrees("netarkivet") .get(0).getSubTree("test") .getSubTree("q").getValue()); try { XmlTree.getStringTree(null); fail("Should die on null argument"); } catch (ArgumentNotValid e) { // expected } } public void testGetSubTree() { StringTree<String> tree1 = getTree(); tree1 = tree1.getSubTree("dk"); assertNotNull("Should have non-null direct subtree", tree1); tree1 = tree1.getSubTrees("netarkivet").get(1).getSubTree("answer"); assertNotNull("Should have non-null direct subtree", tree1); tree1 = getTree(); // Test dotted paths assertNotNull("Should have non-null dotted subtree", tree1.getSubTree("dk.heroes.hero")); // Test it can find the right way to the subtree assertNotNull("Should have non-null dotted subtree", tree1.getSubTree("dk.netarkivet.test")); tree1 = tree1.getSubTree("dk"); try { tree1.getSubTree("netarkivet"); fail("Should die on multiple subtrees"); } catch (IllegalState e) { // expected } try { tree1.getSubTree("netarkvet"); fail("Should die on no subtrees"); } catch (IllegalState e) { // expected } } public void testGetValue() { StringTree<String> tree1 = getTree(); tree1 = tree1.getSubTree("dk").getSubTrees("netarkivet").get(0) .getSubTree("answer"); assertEquals("Should have value in leaf node", "42", tree1.getValue()); tree1 = getTree(); try { tree1.getValue(); fail("Should throw IllegalState when getValue()ing a root"); } catch (IllegalState e) { // expected } tree1 = tree1.getSubTree("dk"); try { tree1.getValue(); fail("Should throw IllegalState when getValue()ing a node"); } catch (IllegalState e) { // expected } tree1 = getTree(); try { tree1.getValue("dk"); fail("Should die when the named node is the root"); } catch (IllegalState e) { // Expected } // Test dotted paths assertEquals("Should get value in unique leaf node", "Batman", tree1.getValue("dk.heroes.hero")); try { tree1.getValue("dk.netarkivet.answer"); fail("Should fail due to multiple subtrees"); } catch (IllegalState e) { // Expected } try { tree1.getValue("dk.heroes"); fail("Should fail due to non-leafness"); } catch (IllegalState e) { // Expected } try { tree1.getValue("dk.heroes.bystander"); fail("Should fail due to missing leaf"); } catch (IllegalState e) { // Expected } tree1 = tree1.getSubTree("dk"); tree1 = tree1.getSubTrees("netarkivet").get(0); assertEquals("Should be possible to get value of subnode", "42", tree1.getValue("answer")); try { tree1.getValue("test"); fail("Should die when the named node is not a leaf"); } catch (IllegalState e) { // Expected } try { tree1.getValue("foobar"); fail("Should die when the named node does not exist"); } catch (IllegalState e) { // Expected } try { tree1.getSubTree("test").getValue("list1"); fail("Should die when the named node has multiple candidates"); } catch (IllegalState e) { // Expected } } /** Get the default tree from the test.xml file */ private StringTree<String> getTree() { Document doc = XmlUtils.getXmlDoc(TestInfo.TESTXML); StringTree<String> tree1 = XmlTree.getStringTree(doc); return tree1; } public void testIsLeaf() { StringTree<String> tree1 = getTree(); tree1 = tree1.getSubTree("dk").getSubTrees("netarkivet").get(0) .getSubTree("answer"); assertTrue("Should have true on leaf node", tree1.isLeaf()); tree1 = getTree(); assertFalse("Should have false on root node", tree1.isLeaf()); assertFalse("Should have false on non-leaf node", tree1.getSubTree("dk").isLeaf()); } public void testGetSubTrees() { StringTree<String> tree1 = getTree(); List<StringTree<String>> rootTrees = tree1.getSubTrees("dk"); assertEquals("Should get subtrees on root", 1, rootTrees.size()); List<StringTree<String>> subTrees = rootTrees.get(0) .getSubTrees("netarkivet"); assertEquals("Should have found two netarkivet subtrees", 2, subTrees.size()); assertEquals("Tree one should have a 42 answer", "42", subTrees.get(0).getSubTree("answer").getValue()); assertEquals("Tree two should have a 43 answer", "43", subTrees.get(1).getSubTree("answer").getValue()); List<StringTree<String>> nonTrees = tree1.getSubTrees("fop"); assertEquals("Should have found no fop subtrees", 0, nonTrees.size()); try { tree1.getSubTree("dk").getSubTrees("netarkivet").get(0) .getSubTree("answer").getSubTrees("foo"); fail("Should throw IllegalState on asking for subtree in leaf"); } catch (IllegalState e) { // expected } assertEquals("Should find 2 netarkivet subtrees with dotted path", 2, tree1.getSubTrees("dk.netarkivet").size()); subTrees = tree1.getSubTrees( "dk.netarkivet.answer"); assertEquals("Should find 2 answer subtrees with dotted path", 2, subTrees.size()); assertEquals("The first answer should be 42", "42", subTrees.get(0).getValue()); assertEquals("The second answer should be 43", "43", subTrees.get(1).getValue()); // This one taken from HTMLUtils Document doc = XmlUtils.getXmlDoc(TestInfo.SETTINGS_FILE); tree1 = XmlTree.getStringTree(doc); StringTree<String> subTree = tree1.getSubTree("settings"); assertNotNull("Should find settings subtree", subTree); assertNotNull("Should find common subtree of settings in multimap", subTree.getChildMap().get("common")); assertNotNull("Should find common subtree of settings", subTree.getSubTree("common")); assertNotNull("Should find webinterface subtree of common", subTree.getSubTree("common").getSubTrees("webinterface")); List<StringTree<String>> languages = tree1.getSubTree("settings.common.webinterface"). getSubTrees("language"); assertEquals("Should have found two language objects", 2, languages.size()); } public void testGetChildMultimap() { StringTree<String> tree1 = getTree(); final Map<String, List<StringTree<String>>> rootChildren = tree1 .getChildMultimap(); assertEquals("Should be able to get child map of the root element", 1, rootChildren.size()); tree1 = tree1.getSubTree("dk"); Map<String, List<StringTree<String>>> children = tree1.getChildMultimap(); assertEquals("Multimap should have one entry", 2, children.size()); assertEquals("Netarkivet child should have two entries", 2, children.get("netarkivet").size()); StringTree<String> tree2 = children.get("netarkivet").get(0); tree2 = tree2.getSubTree("test"); children = tree2.getChildMultimap(); assertEquals("Multimap should have two entries", 2, children.size()); assertTrue("Should have list1 key", children.containsKey("list1")); assertTrue("Should have q key", children.containsKey("q")); try { children.get("q").get(0).getChildMultimap(); fail("Should have thrown error on leaf"); } catch (IllegalState e) { // expected } } public void testGetLeafMultimap() { StringTree<String> tree1 = getTree(); try { tree1.getLeafMultimap(); fail("Should get error when no children are leafs"); } catch (IllegalState e) { // Expected } tree1 = tree1.getSubTree("dk").getSubTrees("netarkivet").get(0); try { tree1.getLeafMultimap(); fail("Should get error when some children are not leafs"); } catch (IllegalState e) { // Expected } tree1 = tree1.getSubTree("test"); Map<String, List<String>> leaves = tree1.getLeafMultimap(); assertEquals("Should have two leaves", 2, leaves.size()); assertTrue("Should have list1 key", leaves.containsKey("list1")); assertTrue("Should have q key", leaves.containsKey("q")); assertEquals("list1 should have three elements", 3, leaves.get("list1").size()); CollectionAsserts.assertListEquals("list1 should have right leaves", leaves.get("list1"), "item1", "item2", "item3"); CollectionAsserts.assertListEquals("q should have right leaf", leaves.get("q"), "what is the question"); tree1 = tree1.getSubTree("q"); try { tree1.getLeafMultimap(); fail("Should fail when there are no children"); } catch (IllegalState e) { // Expected } } public void testGetChildMap() { StringTree<String> tree1 = getTree(); final Map<String, StringTree<String>> rootChildren = tree1 .getChildMap(); assertEquals("Should be able to get child map of the root element", 1, rootChildren.size()); tree1 = tree1.getSubTree("dk"); try { tree1.getChildMap(); fail("Should not be allowed to get childmap of node with " + "several of the same subnode."); } catch (IllegalState e) { // Expected } StringTree<String> tree2 = tree1.getSubTrees("netarkivet").get(0); Map<String, StringTree<String>> children = tree2.getChildMap(); assertEquals("Map should have two entries", 2, children.size()); assertTrue("Should have test key", children.containsKey("test")); assertTrue("Should have answer key", children.containsKey("answer")); try { children.get("answer").getChildMap(); fail("Should have thrown error on leaf"); } catch (IllegalState e) { // expected } } public void testGetLeafMap() { StringTree<String> tree1 = getTree(); try { tree1.getLeafMap(); fail("Should get error when no children are leafs"); } catch (IllegalState e) { // Expected } tree1 = tree1.getSubTree("dk").getSubTrees("netarkivet").get(0); try { tree1.getLeafMap(); fail("Should get error when some children are not leafs"); } catch (IllegalState e) { // Expected } tree1 = getTree(); tree1 = tree1.getSubTree("dk").getSubTrees("netarkivet").get(1); Map<String, String> leaves = tree1.getLeafMap(); assertEquals("Should have one leaf", 1, leaves.size()); assertTrue("Should have answer key", leaves.containsKey("answer")); assertEquals("Should have right answer", "43", leaves.get("answer")); tree1 = tree1.getSubTree("answer"); try { tree1.getLeafMap(); fail("Should fail when there are no children"); } catch (IllegalState e) { // Expected } tree1 = getTree(); tree1 = tree1.getSubTree("dk").getSubTree("heroes"); leaves = tree1.getLeafMap(); assertEquals("Should have three leaves", 3, leaves.size()); assertEquals("Should have right hero", "Batman", leaves.get("hero")); assertEquals("Should have right sidekick", "Robin", leaves.get("sidekick")); assertEquals("Should have right villain", "Dr. Evil", leaves.get("villain")); } public void testSelectSingleNode() throws Exception { Method selectSingleNode = ReflectUtils.getPrivateMethod(XmlTree.class, "selectSingleNode", String.class); StringTree<String> tree1 = getTree(); assertNotNull("Should be able to get root node", selectSingleNode.invoke(tree1, "dk")); assertNotNull("Should be able to get two levels of nodes", selectSingleNode.invoke(tree1, "dk.heroes")); try { selectSingleNode.invoke(tree1, "dk/heroes"); fail("Should fail on invalid syntax"); } catch (InvocationTargetException e) { // Expected } try { selectSingleNode.invoke(tree1, "dk.netarkivet"); fail("Should fail on multiple possibilities"); } catch (InvocationTargetException e) { // Expected } try { selectSingleNode.invoke(tree1, ""); fail("Should fail on empty parameter"); } catch (InvocationTargetException e) { // Expected } } }
package retrieve; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.List; import java.util.Locale; import model.ChannelProgram; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; import setting.GlobalSetting; import util.CommonUtil; import db.DBclass; /** * * * @author lenovo * */ public class SuntvHtmlParser { final static String SUNTV_WEEKLY_URL = "http://sun-tv.co.jp/weekly"; final static String CHANNEL = ""; static Connection conn; static PreparedStatement existsCheckPS; static PreparedStatement getPrevProgramPS; static PreparedStatement insertPS; // static PreparedStatement deletePS; public static Date date; public static String[] channelNames = { "" }; private static void delete(String date) throws ParseException, SQLException { for (String channelName : channelNames) { List<ChannelProgram> cps = GlobalSetting .onSetChannelname(channelName); Date dt = GlobalSetting.DB_DATETIME_FORMATTER4.parse(date); Calendar calendar = Calendar.getInstance(); calendar.setTime(dt); calendar.add(Calendar.DATE, 1); String date1 = GlobalSetting.DB_DATETIME_FORMATTER4.format(calendar .getTime()); date1 = date1.substring(0, 4) + "-" + date1.substring(4, 6) + "-" + date1.substring(6, 8) + " " + "00:00"; String date2 = date.substring(0, 4) + "-" + date.substring(4, 6) + "-" + date.substring(6, 8) + " " + "00:00"; // for (ChannelProgram cp : cps) { // deletePS.setInt(1, cp.channelid); // deletePS.setString(2, date1); // deletePS.setString(3, date2); // deletePS.executeUpdate(); } } public static void help() { CommonUtil.print("java -cp epg-service.jar retrieve.SuntvHtmlParser"); } /** * @param args * @throws Exception * @throws Exception */ public static void main(String[] args) throws Exception { try { CommonUtil.print("SuntvHtmlParser .getDateTimeInstance().format(new Date())); date = new Date(); conn = DBclass.getConn(); existsCheckPS = conn.prepareStatement(GlobalSetting.existsCheck); getPrevProgramPS = conn .prepareStatement(GlobalSetting.getPrevProgram); insertPS = conn.prepareStatement(GlobalSetting.insert_suntv); // deletePS = conn.prepareStatement(GlobalSetting.delete); // retrieve delete(GlobalSetting.DB_DATETIME_FORMATTER4.format(new Date())); retrieveProgramByUrl(SUNTV_WEEKLY_URL, CHANNEL); //String html = readFileByLines("D:/logs/epgdata/suntv-21080917.html"); //parseDoc(html, ""); existsCheckPS.close(); getPrevProgramPS.close(); insertPS.close(); // deletePS.close(); conn.createStatement().execute(GlobalSetting.deleteOldProgram); } catch (Exception e) { e.printStackTrace(System.out); } finally { if (conn != null && !conn.isClosed()) { conn.close(); } } CommonUtil.print("-- over --"); } public static void parseDoc(String htmlStr, String channelName) throws SQLException, ParseException { Document doc = Jsoup.parse(htmlStr); parseDoc(doc, channelName); } public static void parseDoc(Document doc, String channelName) throws SQLException, ParseException { Date program_date = new Date(); // getDateAfterSpecifiedDay(new Date(), // day); String program_date_string = GlobalSetting.DB_DATETIME_FORMATTER5 .format(program_date); String current_year = new SimpleDateFormat("yyyy", Locale.getDefault()) .format(new Date()); boolean timeFlg = true; Elements box = doc.getElementById("divboxBOX").children(); int total_count = 0; for (int i = 0; i < box.size(); i++) { Element div = box.get(i); String attr = div.attr("class"); if (null != attr && attr.indexOf("float_divbox daybox day") > -1) { Elements day_data = div.children(); for (Element sub_day_data : day_data) { attr = sub_day_data.attr("class"); if (("weekbox").equals(attr)) { program_date_string = current_year + CommonUtil.xmlFilter(sub_day_data.text()) .trim(); // int end = program_date_string.indexOf("("); // program_date_string = // program_date_string.substring(0, end); program_date = GlobalSetting.DB_DATETIME_FORMATTER12 .parse(program_date_string); program_date_string = GlobalSetting.DB_DATETIME_FORMATTER5 .format(program_date); } else if (attr != null && (attr.indexOf("box sv0 day") > -1 || attr .indexOf("box sv1 day") > -1)) { String title = ""; String contents = ""; String program_time = ""; Elements detail = sub_day_data.children().get(0) .children(); for (Element program : detail) { if (("st-time").equals(program.attr("class"))) { String hour_min = CommonUtil.xmlFilter( program.text()).trim(); if (("00:00").equals(hour_min)) { program_date = CommonUtil .getDateAfterSpecifiedDay( program_date, 1); program_date_string = GlobalSetting.DB_DATETIME_FORMATTER5 .format(program_date); program_time = GlobalSetting.DB_DATETIME_FORMATTER5 .format(program_date) + " " + hour_min; } else { program_time = program_date_string + " " + hour_min; } } else if (("prg-icon-re").equals(program .attr("class"))) { title += "" + CommonUtil.xmlFilter(program.text()) .trim() + ""; } else if (("prg-icon-end").equals(program .attr("class"))) { title += "" + CommonUtil.xmlFilter(program.text()) .trim() + ""; } else if (("prg-icon-new").equals(program .attr("class"))) { title += "" + CommonUtil.xmlFilter(program.text()) .trim() + ""; } else if (("prg-icon-lang").equals(program .attr("class"))) { title += "" + CommonUtil.xmlFilter(program.text()) .trim() + ""; } else if (("st-title").equals(program .attr("class"))) { Elements program_children = program.children(); title += CommonUtil.xmlFilter(program.text()) .trim(); } else if (("st-detail").equals(program .attr("class"))) { Elements program_children = program.children(); for (Element content_el : program_children) { if (("st-number").equals(content_el .attr("class"))) { contents += CommonUtil.xmlFilter( content_el.text()).trim() + ""; } else if (("st-detailtxt") .equals(content_el.attr("class"))) { contents += CommonUtil.xmlFilter( content_el.text()).trim(); } } } } if (!("").equals(program_time) && !("").equals(title)) { List<ChannelProgram> cps = GlobalSetting .onSetChannelname(channelName); for (ChannelProgram cp : cps) { cp.program_time = program_time; cp.title = title; cp.content = contents; if (cp.channelid != -1 && timeFlg) { CommonUtil .print("SuntvHtmlParser cp.channelid, cp.title, cp.program_time); DBclass.addToDbWithProgramEndTime(cp, getPrevProgramPS, insertPS, existsCheckPS); total_count++; } else { CommonUtil .print("SuntvHtmlParser cp.channelid, cp.title, cp.program_time, timeFlg); } } } } } } } CommonUtil.print( "SuntvHtmlParser total_count); } private static void retrieveProgramByUrl(String url, String channel_name) throws IOException { Document doc = null; for (int i = 0; doc == null && i < 5; i++) { CommonUtil.print("%d. retrieving %s", i + 1, url); try { doc = Jsoup .connect(url) .userAgent( "Mozilla/5.0 (Windows NT 6.1; rv:11.0) Gecko/20100101 Firefox/11.0") .timeout(50000).get(); } catch (Exception e1) { e1.printStackTrace(System.out); } } try { parseDoc(doc, channel_name); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public static String readFileByLines(String fileName) { String result_str = ""; File file = new File(fileName); BufferedReader reader = null; try { reader = new BufferedReader(new FileReader(file)); String tempString = null; // int line = 1; // null while ((tempString = reader.readLine()) != null) { // System.out.println("line " + line + ": " + tempString); result_str += tempString; // line++; } reader.close(); } catch (IOException e) { e.printStackTrace(); } finally { if (reader != null) { try { reader.close(); } catch (IOException e1) { } } } ; return result_str; } }
package de.lmu.ifi.dbs.elki.result.textwriter; import java.io.FileNotFoundException; import java.io.IOException; import java.io.PrintStream; import java.util.ArrayList; import java.util.BitSet; import java.util.Collection; import java.util.HashSet; import java.util.Iterator; import java.util.List; import de.lmu.ifi.dbs.elki.data.Clustering; import de.lmu.ifi.dbs.elki.data.DatabaseObject; import de.lmu.ifi.dbs.elki.data.HierarchicalClassLabel; import de.lmu.ifi.dbs.elki.data.SimpleClassLabel; import de.lmu.ifi.dbs.elki.data.cluster.Cluster; import de.lmu.ifi.dbs.elki.data.cluster.naming.NamingScheme; import de.lmu.ifi.dbs.elki.data.cluster.naming.SimpleEnumeratingScheme; import de.lmu.ifi.dbs.elki.data.model.Model; import de.lmu.ifi.dbs.elki.database.Database; import de.lmu.ifi.dbs.elki.database.ids.DBID; import de.lmu.ifi.dbs.elki.database.ids.DBIDs; import de.lmu.ifi.dbs.elki.distance.distancevalue.Distance; import de.lmu.ifi.dbs.elki.logging.Logging; import de.lmu.ifi.dbs.elki.math.linearalgebra.Vector; import de.lmu.ifi.dbs.elki.normalization.Normalization; import de.lmu.ifi.dbs.elki.result.AnnotationResult; import de.lmu.ifi.dbs.elki.result.AnyResult; import de.lmu.ifi.dbs.elki.result.CollectionResult; import de.lmu.ifi.dbs.elki.result.IterableResult; import de.lmu.ifi.dbs.elki.result.OrderingResult; import de.lmu.ifi.dbs.elki.result.Result; import de.lmu.ifi.dbs.elki.result.ResultUtil; import de.lmu.ifi.dbs.elki.result.SettingsResult; import de.lmu.ifi.dbs.elki.result.textwriter.writers.TextWriterDatabaseObjectInline; import de.lmu.ifi.dbs.elki.result.textwriter.writers.TextWriterDoubleDoublePair; import de.lmu.ifi.dbs.elki.result.textwriter.writers.TextWriterObjectArray; import de.lmu.ifi.dbs.elki.result.textwriter.writers.TextWriterObjectComment; import de.lmu.ifi.dbs.elki.result.textwriter.writers.TextWriterObjectInline; import de.lmu.ifi.dbs.elki.result.textwriter.writers.TextWriterPair; import de.lmu.ifi.dbs.elki.result.textwriter.writers.TextWriterTextWriteable; import de.lmu.ifi.dbs.elki.result.textwriter.writers.TextWriterTriple; import de.lmu.ifi.dbs.elki.result.textwriter.writers.TextWriterVector; import de.lmu.ifi.dbs.elki.utilities.HandlerList; import de.lmu.ifi.dbs.elki.utilities.exceptions.UnableToComplyException; import de.lmu.ifi.dbs.elki.utilities.optionhandling.parameterization.SerializedParameterization; import de.lmu.ifi.dbs.elki.utilities.optionhandling.parameters.ClassParameter; import de.lmu.ifi.dbs.elki.utilities.optionhandling.parameters.Parameter; import de.lmu.ifi.dbs.elki.utilities.pairs.DoubleDoublePair; import de.lmu.ifi.dbs.elki.utilities.pairs.Pair; import de.lmu.ifi.dbs.elki.utilities.pairs.Triple; /** * Class to write a result to human-readable text output * * @author Erich Schubert * * @param <O> Object type */ public class TextWriter<O extends DatabaseObject> { /** * Logger */ private static final Logging logger = Logging.getLogger(TextWriter.class); /** * Extension for txt-files. */ public static final String FILE_EXTENSION = ".txt"; /** * Hash map for supported classes in writer. */ public final static HandlerList<TextWriterWriterInterface<?>> writers = new HandlerList<TextWriterWriterInterface<?>>(); /** * Add some default handlers */ static { TextWriterObjectInline trivialwriter = new TextWriterObjectInline(); writers.insertHandler(Object.class, new TextWriterObjectComment()); writers.insertHandler(DatabaseObject.class, new TextWriterDatabaseObjectInline<DatabaseObject>()); // these object can be serialized inline with toString() writers.insertHandler(String.class, trivialwriter); writers.insertHandler(Double.class, trivialwriter); writers.insertHandler(Integer.class, trivialwriter); writers.insertHandler(String[].class, new TextWriterObjectArray<String>()); writers.insertHandler(Double[].class, new TextWriterObjectArray<Double>()); writers.insertHandler(Integer[].class, new TextWriterObjectArray<Integer>()); writers.insertHandler(BitSet.class, trivialwriter); writers.insertHandler(Vector.class, new TextWriterVector()); writers.insertHandler(Distance.class, trivialwriter); writers.insertHandler(SimpleClassLabel.class, trivialwriter); writers.insertHandler(HierarchicalClassLabel.class, trivialwriter); writers.insertHandler(Pair.class, new TextWriterPair()); writers.insertHandler(DoubleDoublePair.class, new TextWriterDoubleDoublePair()); writers.insertHandler(Triple.class, new TextWriterTriple()); // Objects that have an own writeToText method. writers.insertHandler(TextWriteable.class, new TextWriterTextWriteable()); } /** * Normalization to use. */ private Normalization<O> normalization; /** * Writes a header providing information concerning the underlying database * and the specified parameter-settings. * * @param db to retrieve meta information from * @param out the print stream where to write * @param sr the settings to be written into the header */ protected void printSettings(Database<O> db, TextWriterStream out, List<SettingsResult> sr) { out.commentPrintSeparator(); out.commentPrintLn("Settings and meta information:"); out.commentPrintLn("db size = " + db.size()); // noinspection EmptyCatchBlock try { int dimensionality = db.dimensionality(); out.commentPrintLn("db dimensionality = " + dimensionality); } catch(UnsupportedOperationException e) { // dimensionality is unsupported - do nothing } out.commentPrintLn(""); if(sr != null) { for(SettingsResult settings : sr) { Object last = null; for(Pair<Object, Parameter<?, ?>> setting : settings.getSettings()) { if(setting.first != last && setting.first != null) { if(last != null) { out.commentPrintLn(""); } String name = setting.first.getClass().getName(); if(ClassParameter.class.isInstance(setting.first)) { name = ((ClassParameter<?>) setting.first).getValue().getName(); } out.commentPrintLn(name); last = setting.first; } String name = setting.second.getOptionID().getName(); String value = "[unset]"; try { if(setting.second.isDefined()) { value = setting.second.getValueAsString(); } } catch(NullPointerException e) { value = "[null]"; } out.commentPrintLn(SerializedParameterization.OPTION_PREFIX + name + " " + value); } } } out.commentPrintSeparator(); out.flush(); } /** * Stream output. * * @param db Database object * @param r Result class * @param streamOpener output stream manager * @throws UnableToComplyException when no usable results were found * @throws IOException on IO error */ public void output(Database<O> db, Result r, StreamFactory streamOpener) throws UnableToComplyException, IOException { List<AnnotationResult<?>> ra = null; List<OrderingResult> ro = null; List<Clustering<? extends Model>> rc = null; List<IterableResult<?>> ri = null; List<SettingsResult> rs = null; HashSet<AnyResult> otherres = null; Collection<DBIDs> groups = null; ra = ResultUtil.getAnnotationResults(r); ro = ResultUtil.getOrderingResults(r); rc = ResultUtil.getClusteringResults(r); ri = ResultUtil.getIterableResults(r); rs = ResultUtil.getSettingsResults(r); // collect other results { final List<AnyResult> resultList = ResultUtil.filterResults(r, AnyResult.class); otherres = new HashSet<AnyResult>(resultList); otherres.removeAll(ra); otherres.removeAll(ro); otherres.removeAll(rc); otherres.removeAll(ri); otherres.removeAll(rs); otherres.remove(db); Iterator<AnyResult> it = otherres.iterator(); while(it.hasNext()) { if(it.next() instanceof Result) { it.remove(); } } } if(ra == null && ro == null && rc == null && ri == null) { throw new UnableToComplyException("No printable result found."); } NamingScheme naming = null; // Process groups or all data in a flat manner? if(rc != null && rc.size() > 0) { groups = new ArrayList<DBIDs>(); for(Cluster<?> c : rc.get(0).getAllClusters()) { groups.add(c.getIDs()); } // force an update of cluster names. naming = new SimpleEnumeratingScheme(rc.get(0)); } else { // only 'magically' create a group if we don't have iterators either. // if(ri == null || ri.size() == 0) { groups = new ArrayList<DBIDs>(); groups.add(db.getIDs()); } if(ri != null && ri.size() > 0) { // TODO: associations are not passed to ri results. for(IterableResult<?> rii : ri) { writeIterableResult(db, streamOpener, rii, r, rs); } } if(groups != null && groups.size() > 0) { for(DBIDs group : groups) { writeGroupResult(db, streamOpener, group, ra, ro, naming, rs); } } if(otherres != null && otherres.size() > 0) { for(AnyResult otherr : otherres) { writeOtherResult(db, streamOpener, otherr, rs); } } } private void writeOtherResult(Database<O> db, StreamFactory streamOpener, AnyResult r, List<SettingsResult> rs) throws UnableToComplyException, IOException { String filename = r.getShortName(); if(filename == null) { throw new UnableToComplyException("No result name for result class: " + r.getClass().getName()); } PrintStream outStream = streamOpener.openStream(filename); TextWriterStream out = new TextWriterStreamNormalizing<O>(outStream, writers, getNormalization()); TextWriterWriterInterface<?> owriter = out.getWriterFor(r); if(owriter == null) { throw new UnableToComplyException("No handler for result class: " + r.getClass().getSimpleName()); } // Write settings preamble printSettings(db, out, rs); // Write data owriter.writeObject(out, null, r); out.flush(); } private void printObject(TextWriterStream out, O obj, List<Pair<String, Object>> anns) throws UnableToComplyException, IOException { // Write database element itself. { TextWriterWriterInterface<?> owriter = out.getWriterFor(obj); if(owriter == null) { throw new UnableToComplyException("No handler for database object itself: " + obj.getClass().getSimpleName()); } owriter.writeObject(out, null, obj); } // print the annotations if(anns != null) { for(Pair<String, Object> a : anns) { if(a.getSecond() == null) { continue; } TextWriterWriterInterface<?> writer = out.getWriterFor(a.getSecond()); if(writer == null) { throw new UnableToComplyException("No handler for annotation " + a.getFirst() + " in Output: " + a.getSecond().getClass().getSimpleName()); } writer.writeObject(out, a.getFirst(), a.getSecond()); } } out.flush(); } @SuppressWarnings("unchecked") private void writeGroupResult(Database<O> db, StreamFactory streamOpener, DBIDs group, List<AnnotationResult<?>> ra, List<OrderingResult> ro, NamingScheme naming, List<SettingsResult> sr) throws FileNotFoundException, UnableToComplyException, IOException { String filename = null; // for clusters, use naming. if(group instanceof Cluster) { if(naming != null) { filename = filenameFromLabel(naming.getNameFor(group)); } } if(filename == null) { if(ro != null && ro.size() > 0) { filename = ro.get(0).getShortName(); } } PrintStream outStream = streamOpener.openStream(filename); TextWriterStream out = new TextWriterStreamNormalizing<O>(outStream, writers, getNormalization()); printSettings(db, out, sr); // print group information... if(group instanceof TextWriteable) { TextWriterWriterInterface<?> writer = out.getWriterFor(group); out.commentPrintLn("Group class: " + group.getClass().getCanonicalName()); if(writer != null) { writer.writeObject(out, null, group); out.commentPrintSeparator(); out.flush(); } } // print ids. DBIDs ids = group; Iterator<DBID> iter = ids.iterator(); // apply sorting. if(ro != null && ro.size() > 0) { try { iter = ro.get(0).iter(ids); } catch(Exception e) { logger.warning("Exception while trying to sort results.", e); } } while(iter.hasNext()) { DBID objID = iter.next(); if(objID == null) { // shoulnd't really happen? continue; } O obj = db.get(objID); if(obj == null) { continue; } // do we have annotations to print? List<Pair<String, Object>> objs = new ArrayList<Pair<String, Object>>(); if(ra != null) { for(AnnotationResult<?> a : ra) { objs.add(new Pair<String, Object>(a.getAssociationID().getLabel(), a.getValueFor(objID))); } } // print the object with its annotations. printObject(out, obj, objs); } out.commentPrintSeparator(); out.flush(); } private void writeIterableResult(Database<O> db, StreamFactory streamOpener, IterableResult<?> ri, Result mr, List<SettingsResult> sr) throws UnableToComplyException, IOException { String filename = ri.getShortName(); logger.debugFine("Filename is " + filename); if(filename == null) { filename = "list"; } PrintStream outStream = streamOpener.openStream(filename); TextWriterStream out = new TextWriterStreamNormalizing<O>(outStream, writers, getNormalization()); printSettings(db, out, sr); if(mr != null) { // TODO: this is an ugly hack! out.setForceincomments(true); /* * for(AssociationID<?> assoc : mr.getAssociations()) { Object o = * mr.getAssociation(assoc); TextWriterWriterInterface<?> writer = * out.getWriterFor(o); if(writer != null) { writer.writeObject(out, * assoc.getLabel(), o); } out.flush(); } */ // TODO: this is an ugly hack! out.setForceincomments(false); } // hack to print collectionResult header information if(ri instanceof CollectionResult<?>) { final Collection<String> hdr = ((CollectionResult<?>) ri).getHeader(); if(hdr != null) { for(String header : hdr) { out.commentPrintLn(header); } out.flush(); } } Iterator<?> i = ri.iterator(); while(i.hasNext()) { Object o = i.next(); TextWriterWriterInterface<?> writer = out.getWriterFor(o); if(writer != null) { writer.writeObject(out, null, o); } out.flush(); } out.commentPrintSeparator(); out.flush(); } /** * Setter for normalization * * @param normalization new normalization object */ public void setNormalization(Normalization<O> normalization) { this.normalization = normalization; } /** * Getter for normalization * * @return normalization object */ public Normalization<O> getNormalization() { return normalization; } /** * Derive a file name from the cluster label. * * @param label cluster label * @return cleaned label suitable for file names. */ private String filenameFromLabel(String label) { return label.toLowerCase().replaceAll("[^a-zA-Z0-9_.\\[\\]-]", "_"); } }
package dr.app.beauti.options; import dr.app.beauti.types.*; import dr.evolution.datatype.DataType; import dr.evolution.datatype.Microsatellite; import dr.evomodel.substmodel.AminoAcidModelType; import dr.evomodel.substmodel.NucModelType; import dr.inference.operators.RateBitExchangeOperator; import java.util.HashSet; import java.util.List; import java.util.Set; /** * @author Alexei Drummond * @author Andrew Rambaut * @author Walter Xie */ public class PartitionSubstitutionModel extends PartitionOptions { // Instance variables public static final String[] GTR_RATE_NAMES = {"ac", "ag", "at", "cg", "gt"}; private static final String[] GTR_TRANSITIONS = {"A-C", "A-G", "A-T", "C-G", "G-T"}; private NucModelType nucSubstitutionModel = NucModelType.HKY; private AminoAcidModelType aaSubstitutionModel = AminoAcidModelType.BLOSUM_62; private BinaryModelType binarySubstitutionModel = BinaryModelType.BIN_SIMPLE; private DiscreteSubstModelType discreteSubstType = DiscreteSubstModelType.SYM_SUBST; private MicroSatModelType microsatSubstModel = MicroSatModelType.LINEAR_BIAS_MODEL; private boolean activateBSSVS = false; public boolean useAmbiguitiesTreeLikelihood = false; private FrequencyPolicyType frequencyPolicy = FrequencyPolicyType.ESTIMATED; private boolean gammaHetero = false; private int gammaCategories = 4; private boolean invarHetero = false; private String codonHeteroPattern = null; private boolean unlinkedSubstitutionModel = true; private boolean unlinkedHeterogeneityModel = true; private boolean unlinkedFrequencyModel = true; private boolean dolloModel = false; public PartitionSubstitutionModel(BeautiOptions options, AbstractPartitionData partition) { // this(options, partition.getName(),(partition.getTrait() == null) // ? partition.getDataType() : GeneralDataType.INSTANCE); super(options, partition.getName()); } /** * A copy constructor * * @param options the beauti options * @param name the name of the new model * @param source the source model */ public PartitionSubstitutionModel(BeautiOptions options, String name, PartitionSubstitutionModel source) { super(options, name); nucSubstitutionModel = source.nucSubstitutionModel; aaSubstitutionModel = source.aaSubstitutionModel; binarySubstitutionModel = source.binarySubstitutionModel; frequencyPolicy = source.frequencyPolicy; gammaHetero = source.gammaHetero; gammaCategories = source.gammaCategories; invarHetero = source.invarHetero; codonHeteroPattern = source.codonHeteroPattern; unlinkedSubstitutionModel = source.unlinkedSubstitutionModel; unlinkedHeterogeneityModel = source.unlinkedHeterogeneityModel; unlinkedFrequencyModel = source.unlinkedFrequencyModel; } public PartitionSubstitutionModel(BeautiOptions options, String name) { super(options, name); } // only init in PartitionSubstitutionModel protected void initModelParaAndOpers() { double substWeights = 0.1; //Substitution model parameters createParameterUniformPrior("frequencies", "base frequencies", PriorScaleType.UNITY_SCALE, 0.25, 0.0, 1.0, 0.0, 1.0); createParameterUniformPrior("CP1.frequencies", "base frequencies for codon position 1", PriorScaleType.UNITY_SCALE, 0.25, 0.0, 1.0, 0.0, 1.0); createParameterUniformPrior("CP2.frequencies", "base frequencies for codon position 2", PriorScaleType.UNITY_SCALE, 0.25, 0.0, 1.0, 0.0, 1.0); createParameterUniformPrior("CP1+2.frequencies", "base frequencies for codon positions 1 & 2", PriorScaleType.UNITY_SCALE, 0.25, 0.0, 1.0, 0.0, 1.0); createParameterUniformPrior("CP3.frequencies", "base frequencies for codon position 3", PriorScaleType.UNITY_SCALE, 0.25, 0.0, 1.0, 0.0, 1.0); //This prior is moderately diffuse with a median of 2.718 createParameterLognormalPrior("kappa", "HKY transition-transversion parameter", PriorScaleType.SUBSTITUTION_PARAMETER_SCALE, 2.0, 1.0, 1.25, 0.0, 0, Double.POSITIVE_INFINITY); createParameterLognormalPrior("CP1.kappa", "HKY transition-transversion parameter for codon position 1", PriorScaleType.SUBSTITUTION_PARAMETER_SCALE, 2.0, 1.0, 1.25, 0.0, 0, Double.POSITIVE_INFINITY); createParameterLognormalPrior("CP2.kappa", "HKY transition-transversion parameter for codon position 2", PriorScaleType.SUBSTITUTION_PARAMETER_SCALE, 2.0, 1.0, 1.25, 0.0, 0, Double.POSITIVE_INFINITY); createParameterLognormalPrior("CP1+2.kappa", "HKY transition-transversion parameter for codon positions 1 & 2", PriorScaleType.SUBSTITUTION_PARAMETER_SCALE, 2.0, 1.0, 1.25, 0.0, 0, Double.POSITIVE_INFINITY); createParameterLognormalPrior("CP3.kappa", "HKY transition-transversion parameter for codon position 3", PriorScaleType.SUBSTITUTION_PARAMETER_SCALE, 2.0, 1.0, 1.25, 0.0, 0, Double.POSITIVE_INFINITY); createParameterLognormalPrior("kappa1", "TN93 1st transition-transversion parameter", PriorScaleType.SUBSTITUTION_PARAMETER_SCALE, 2.0, 1.0, 1.25, 0.0, 0, Double.POSITIVE_INFINITY); createParameterLognormalPrior("CP1.kappa1", "TN93 1st transition-transversion parameter for codon position 1", PriorScaleType.SUBSTITUTION_PARAMETER_SCALE, 2.0, 1.0, 1.25, 0.0, 0, Double.POSITIVE_INFINITY); createParameterLognormalPrior("CP2.kappa1", "TN93 1st transition-transversion parameter for codon position 2", PriorScaleType.SUBSTITUTION_PARAMETER_SCALE, 2.0, 1.0, 1.25, 0.0, 0, Double.POSITIVE_INFINITY); createParameterLognormalPrior("CP1+2.kappa1", "TN93 1st transition-transversion parameter for codon positions 1 & 2", PriorScaleType.SUBSTITUTION_PARAMETER_SCALE, 2.0, 1.0, 1.25, 0.0, 0, Double.POSITIVE_INFINITY); createParameterLognormalPrior("CP3.kappa1", "TN93 1st transition-transversion parameter for codon position 3", PriorScaleType.SUBSTITUTION_PARAMETER_SCALE, 2.0, 1.0, 1.25, 0.0, 0, Double.POSITIVE_INFINITY); createParameterLognormalPrior("kappa2", "TN93 2nd transition-transversion parameter", PriorScaleType.SUBSTITUTION_PARAMETER_SCALE, 2.0, 1.0, 1.25, 0.0, 0, Double.POSITIVE_INFINITY); createParameterLognormalPrior("CP1.kappa2", "TN93 2nd transition-transversion parameter for codon position 1", PriorScaleType.SUBSTITUTION_PARAMETER_SCALE, 2.0, 1.0, 1.25, 0.0, 0, Double.POSITIVE_INFINITY); createParameterLognormalPrior("CP2.kappa2", "TN93 2nd transition-transversion parameter for codon position 2", PriorScaleType.SUBSTITUTION_PARAMETER_SCALE, 2.0, 1.0, 1.25, 0.0, 0, Double.POSITIVE_INFINITY); createParameterLognormalPrior("CP1+2.kappa2", "TN93 2nd transition-transversion parameter for codon positions 1 & 2", PriorScaleType.SUBSTITUTION_PARAMETER_SCALE, 2.0, 1.0, 1.25, 0.0, 0, Double.POSITIVE_INFINITY); createParameterLognormalPrior("CP3.kappa2", "TN93 2nd transition-transversion parameter for codon position 3", PriorScaleType.SUBSTITUTION_PARAMETER_SCALE, 2.0, 1.0, 1.25, 0.0, 0, Double.POSITIVE_INFINITY); // createParameter("frequencies", "GTR base frequencies", UNITY_SCALE, 0.25, 0.0, 1.0); // createParameter("CP1.frequencies", "GTR base frequencies for codon position 1", UNITY_SCALE, 0.25, 0.0, 1.0); // createParameter("CP2.frequencies", "GTR base frequencies for codon position 2", UNITY_SCALE, 0.25, 0.0, 1.0); // createParameter("CP1+2.frequencies", "GTR base frequencies for codon positions 1 & 2", UNITY_SCALE, 0.25, 0.0, 1.0); // createParameter("CP3.frequencies", "GTR base frequencies for codon position 3", UNITY_SCALE, 0.25, 0.0, 1.0); // create the relative rate parameters for the GTR rate matrix for (int j = 0; j < 5; j++) { if (j == 1) { createParameterGammaPrior(GTR_RATE_NAMES[j], "GTR " + GTR_TRANSITIONS[j] + " substitution parameter", PriorScaleType.SUBSTITUTION_PARAMETER_SCALE, 1.0, 0.05, 20, 0, Double.POSITIVE_INFINITY, false); } else { createParameterGammaPrior(GTR_RATE_NAMES[j], "GTR " + GTR_TRANSITIONS[j] + " substitution parameter", PriorScaleType.SUBSTITUTION_PARAMETER_SCALE, 1.0, 0.05, 10, 0, Double.POSITIVE_INFINITY, false); } for (int i = 1; i <= 3; i++) { if (j == 1) { createParameterGammaPrior("CP" + i + "." + GTR_RATE_NAMES[j], "GTR " + GTR_TRANSITIONS[j] + " substitution parameter for codon position " + i, PriorScaleType.SUBSTITUTION_PARAMETER_SCALE, 1.0, 0.05, 20, 0, Double.POSITIVE_INFINITY, false); } else { createParameterGammaPrior("CP" + i + "." + GTR_RATE_NAMES[j], "GTR " + GTR_TRANSITIONS[j] + " substitution parameter for codon position " + i, PriorScaleType.SUBSTITUTION_PARAMETER_SCALE, 1.0, 0.05, 10, 0, Double.POSITIVE_INFINITY, false); } } if (j == 1) { createParameterGammaPrior("CP1+2." + GTR_RATE_NAMES[j], "GTR " + GTR_TRANSITIONS[j] + " substitution parameter for codon positions 1 & 2", PriorScaleType.SUBSTITUTION_PARAMETER_SCALE, 1.0, 0.05, 20, 0, Double.POSITIVE_INFINITY, false); } else { createParameterGammaPrior("CP1+2." + GTR_RATE_NAMES[j], "GTR " + GTR_TRANSITIONS[j] + " substitution parameter for codon positions 1 & 2", PriorScaleType.SUBSTITUTION_PARAMETER_SCALE, 1.0, 0.05, 10, 0, Double.POSITIVE_INFINITY, false); } } // createParameter("frequencies", "Binary Simple frequencies", UNITY_SCALE, 0.5, 0.0, 1.0); // createParameter("frequencies", "Binary Covarion frequencies of the visible states", UNITY_SCALE, 0.5, 0.0, 1.0); createParameterUniformPrior("hfrequencies", "Binary Covarion frequencies of the hidden rates", PriorScaleType.UNITY_SCALE, 0.5, 0.0, 1.0, 0.0, 1.0); createParameterUniformPrior("bcov.alpha", "Binary Covarion rate of evolution in slow mode", PriorScaleType.UNITY_SCALE, 0.5, 0.0, 1.0, 0.0, 1.0); createParameterGammaPrior("bcov.s", "Binary Covarion rate of flipping between slow and fast modes", PriorScaleType.SUBSTITUTION_PARAMETER_SCALE, 0.5, 0.05, 10, 0, Double.POSITIVE_INFINITY, false); createParameterExponentialPrior("alpha", "gamma shape parameter", PriorScaleType.SUBSTITUTION_PARAMETER_SCALE, 0.5, 0.5, 0.0, 0.0, 1000.0); createParameterExponentialPrior("CP1.alpha", "gamma shape parameter for codon position 1", PriorScaleType.SUBSTITUTION_PARAMETER_SCALE, 0.5, 0.5, 0.0, 0.0, 1000.0); createParameterExponentialPrior("CP2.alpha", "gamma shape parameter for codon position 2", PriorScaleType.SUBSTITUTION_PARAMETER_SCALE, 0.5, 0.5, 0.0, 0.0, 1000.0); createParameterExponentialPrior("CP1+2.alpha", "gamma shape parameter for codon positions 1 & 2", PriorScaleType.SUBSTITUTION_PARAMETER_SCALE, 0.5, 0.5, 0.0, 0.0, 1000.0); createParameterExponentialPrior("CP3.alpha", "gamma shape parameter for codon position 3", PriorScaleType.SUBSTITUTION_PARAMETER_SCALE, 0.5, 0.5, 0.0, 0.0, 1000.0); createParameterUniformPrior("pInv", "proportion of invariant sites parameter", PriorScaleType.NONE, 0.5, 0.0, 1.0, 0.0, 1.0); createParameterUniformPrior("CP1.pInv", "proportion of invariant sites parameter for codon position 1", PriorScaleType.NONE, 0.5, 0.0, 1.0, 0.0, 1.0); createParameterUniformPrior("CP2.pInv", "proportion of invariant sites parameter for codon position 2", PriorScaleType.NONE, 0.5, 0.0, 1.0, 0.0, 1.0); createParameterUniformPrior("CP1+2.pInv", "proportion of invariant sites parameter for codon positions 1 & 2", PriorScaleType.NONE, 0.5, 0.0, 1.0, 0.0, 1.0); createParameterUniformPrior("CP3.pInv", "proportion of invariant sites parameter for codon position 3", PriorScaleType.NONE, 0.5, 0.0, 1.0, 0.0, 1.0); createParameterUniformPrior("mu", "relative rate parameter", PriorScaleType.SUBSTITUTION_PARAMETER_SCALE, 1.0, 0.0, Double.MAX_VALUE, 0.0, Double.POSITIVE_INFINITY); createParameterUniformPrior("CP1.mu", "relative rate parameter for codon position 1", PriorScaleType.SUBSTITUTION_PARAMETER_SCALE, 1.0, 0.0, Double.MAX_VALUE, 0.0, Double.POSITIVE_INFINITY); createParameterUniformPrior("CP2.mu", "relative rate parameter for codon position 2", PriorScaleType.SUBSTITUTION_PARAMETER_SCALE, 1.0, 0.0, Double.MAX_VALUE, 0.0, Double.POSITIVE_INFINITY); createParameterUniformPrior("CP1+2.mu", "relative rate parameter for codon positions 1 & 2", PriorScaleType.SUBSTITUTION_PARAMETER_SCALE, 1.0, 0.0, Double.MAX_VALUE, 0.0, Double.POSITIVE_INFINITY); createParameterUniformPrior("CP3.mu", "relative rate parameter for codon position 3", PriorScaleType.SUBSTITUTION_PARAMETER_SCALE, 1.0, 0.0, Double.MAX_VALUE, 0.0, Double.POSITIVE_INFINITY); // A vector of relative rates across all partitions... createAllMusParameter(this, "allMus", "All the relative rates regarding codon positions"); createParameter("biasConst", "", 0.5); createOperator("deltaBiasConst", "", "", "biasConst", OperatorType.DELTA_EXCHANGE, 0.001, 1.6); // This only works if the partitions are of the same size... // createOperator("centeredMu", "Relative rates", // "Scales codon position rates relative to each other maintaining mean", "allMus", // OperatorType.CENTERED_SCALE, 0.75, 3.0); createOperator("deltaMu", RelativeRatesType.MU_RELATIVE_RATES.toString(), "Currently use to scale codon position rates relative to each other maintaining mean", "allMus", OperatorType.DELTA_EXCHANGE, 0.75, 3.0); createScaleOperator("kappa", demoTuning, substWeights); createScaleOperator("CP1.kappa", demoTuning, substWeights); createScaleOperator("CP2.kappa", demoTuning, substWeights); createScaleOperator("CP1+2.kappa", demoTuning, substWeights); createScaleOperator("CP3.kappa", demoTuning, substWeights); createScaleOperator("kappa1", demoTuning, substWeights); createScaleOperator("CP1.kappa1", demoTuning, substWeights); createScaleOperator("CP2.kappa1", demoTuning, substWeights); createScaleOperator("CP1+2.kappa1", demoTuning, substWeights); createScaleOperator("CP3.kappa1", demoTuning, substWeights); createScaleOperator("kappa2", demoTuning, substWeights); createScaleOperator("CP1.kappa2", demoTuning, substWeights); createScaleOperator("CP2.kappa2", demoTuning, substWeights); createScaleOperator("CP1+2.kappa2", demoTuning, substWeights); createScaleOperator("CP3.kappa2", demoTuning, substWeights); createOperator("frequencies", OperatorType.DELTA_EXCHANGE, 0.01, substWeights); createOperator("CP1.frequencies", OperatorType.DELTA_EXCHANGE, 0.01, substWeights); createOperator("CP2.frequencies", OperatorType.DELTA_EXCHANGE, 0.01, substWeights); createOperator("CP1+2.frequencies", OperatorType.DELTA_EXCHANGE, 0.01, substWeights); createOperator("CP3.frequencies", OperatorType.DELTA_EXCHANGE, 0.01, substWeights); for (String rateName : GTR_RATE_NAMES) { createScaleOperator(rateName, demoTuning, substWeights); for (int j = 1; j <= 3; j++) { createScaleOperator("CP" + j + "." + rateName, demoTuning, substWeights); } createScaleOperator("CP1+2." + rateName, demoTuning, substWeights); } createScaleOperator("alpha", demoTuning, substWeights); for (int i = 1; i <= 3; i++) { createScaleOperator("CP" + i + ".alpha", demoTuning, substWeights); } createScaleOperator("CP1+2.alpha", demoTuning, substWeights); createScaleOperator("pInv", demoTuning, substWeights); for (int i = 1; i <= 3; i++) { createScaleOperator("CP" + i + ".pInv", demoTuning, substWeights); } createScaleOperator("CP1+2.pInv", demoTuning, substWeights); createScaleOperator("bcov.alpha", demoTuning, substWeights); createScaleOperator("bcov.s", demoTuning, substWeights); // createOperator("hfrequencies", OperatorType.DELTA_EXCHANGE, 0.01, substWeights); /** * @return true either if the options have more than one partition or any partition is * broken into codon positions. */ public boolean hasCodon() { return getCodonPartitionCount() > 1; } public int getCodonPartitionCount() { if (codonHeteroPattern == null || codonHeteroPattern.equals("111")) { return 1; } if (codonHeteroPattern.equals("123")) { return 3; } if (codonHeteroPattern.equals("112")) { return 2; } throw new IllegalArgumentException("codonHeteroPattern must be one of '111', '112' or '123'"); } public void addWeightsForPartition(AbstractPartitionData partition, int[] weights, int offset) { int n = partition.getSiteCount(); int codonCount = n / 3; int remainder = n % 3; if (codonHeteroPattern == null || codonHeteroPattern.equals("111")) { weights[offset] += n; return; } if (codonHeteroPattern.equals("123")) { weights[offset] += codonCount + (remainder > 0 ? 1 : 0); weights[offset + 1] += codonCount + (remainder > 1 ? 1 : 0); weights[offset + 2] += codonCount; return; } if (codonHeteroPattern.equals("112")) { weights[offset] += codonCount * 2 + remainder; // positions 1 + 2 weights[offset + 1] += codonCount; // position 3 return; } throw new IllegalArgumentException("codonHeteroPattern must be one of '111', '112' or '123'"); } /** * This returns an integer vector of the number of sites in each partition (including any codon partitions). These * are strictly in the same order as the 'mu' relative rates are listed. * * @return weights for each partition model */ public int[] getPartitionCodonWeights() { int[] weights = new int[getCodonPartitionCount()]; int k = 0; for (AbstractPartitionData partition : options.getAllPartitionData(this)) { if (partition.getPartitionSubstitutionModel() == this) { addWeightsForPartition(partition, weights, k); } } k += getCodonPartitionCount(); assert (k == weights.length); return weights; } public NucModelType getNucSubstitutionModel() { return nucSubstitutionModel; } public void setNucSubstitutionModel(NucModelType nucSubstitutionModel) { this.nucSubstitutionModel = nucSubstitutionModel; } public AminoAcidModelType getAaSubstitutionModel() { return aaSubstitutionModel; } public void setAaSubstitutionModel(AminoAcidModelType aaSubstitutionModel) { this.aaSubstitutionModel = aaSubstitutionModel; } public BinaryModelType getBinarySubstitutionModel() { return binarySubstitutionModel; } public void setBinarySubstitutionModel(BinaryModelType binarySubstitutionModel) { this.binarySubstitutionModel = binarySubstitutionModel; } public DiscreteSubstModelType getDiscreteSubstType() { return discreteSubstType; } public void setDiscreteSubstType(DiscreteSubstModelType discreteSubstType) { this.discreteSubstType = discreteSubstType; } public MicroSatModelType getMicrosatSubstModel() { return microsatSubstModel; } public void setMicrosatSubstModel(MicroSatModelType microsatSubstModel) { this.microsatSubstModel = microsatSubstModel; } public Microsatellite getMicrosatellite() { return (Microsatellite) getDataType(); } public boolean isActivateBSSVS() { return activateBSSVS; } public void setActivateBSSVS(boolean activateBSSVS) { this.activateBSSVS = activateBSSVS; } public FrequencyPolicyType getFrequencyPolicy() { return frequencyPolicy; } public void setFrequencyPolicy(FrequencyPolicyType frequencyPolicy) { this.frequencyPolicy = frequencyPolicy; } public boolean isGammaHetero() { return gammaHetero; } public void setGammaHetero(boolean gammaHetero) { this.gammaHetero = gammaHetero; } public int getGammaCategories() { return gammaCategories; } public void setGammaCategories(int gammaCategories) { this.gammaCategories = gammaCategories; } public boolean isInvarHetero() { return invarHetero; } public void setInvarHetero(boolean invarHetero) { this.invarHetero = invarHetero; } public String getCodonHeteroPattern() { return codonHeteroPattern; } public void setCodonHeteroPattern(String codonHeteroPattern) { this.codonHeteroPattern = codonHeteroPattern; } /** * @return true if the rate matrix parameters are unlinked across codon positions */ public boolean isUnlinkedSubstitutionModel() { return unlinkedSubstitutionModel; } public void setUnlinkedSubstitutionModel(boolean unlinkedSubstitutionModel) { this.unlinkedSubstitutionModel = unlinkedSubstitutionModel; } public boolean isUnlinkedHeterogeneityModel() { return unlinkedHeterogeneityModel; } public void setUnlinkedHeterogeneityModel(boolean unlinkedHeterogeneityModel) { this.unlinkedHeterogeneityModel = unlinkedHeterogeneityModel; } public boolean isUnlinkedFrequencyModel() { return unlinkedFrequencyModel; } public void setUnlinkedFrequencyModel(boolean unlinkedFrequencyModel) { this.unlinkedFrequencyModel = unlinkedFrequencyModel; } public boolean isDolloModel() { return dolloModel; } public void setDolloModel(boolean dolloModel) { this.dolloModel = dolloModel; } public boolean isUseAmbiguitiesTreeLikelihood() { return useAmbiguitiesTreeLikelihood; } public void setUseAmbiguitiesTreeLikelihood(boolean useAmbiguitiesTreeLikelihood) { this.useAmbiguitiesTreeLikelihood = useAmbiguitiesTreeLikelihood; } public String getPrefix() { String prefix = ""; if (options.getPartitionSubstitutionModels().size() > 1) { // There is more than one active partition model, or doing species analysis prefix += getName() + "."; } return prefix; } public String getPrefix(int codonPartitionNumber) { String prefix = ""; prefix += getPrefix(); prefix += getPrefixCodon(codonPartitionNumber); return prefix; } public String getPrefixCodon(int codonPartitionNumber) { String prefix = ""; if (getCodonPartitionCount() > 1 && codonPartitionNumber > 0) { if (getCodonHeteroPattern().equals("123")) { prefix += "CP" + codonPartitionNumber + "."; } else if (getCodonHeteroPattern().equals("112")) { if (codonPartitionNumber == 1) { prefix += "CP1+2."; } else { prefix += "CP3."; } } else { throw new IllegalArgumentException("unsupported codon hetero pattern"); } } return prefix; } /** * returns the union of the set of states for all traits using this discrete CTMC model * @return */ public Set<String> getDiscreteStateSet() { Set<String> states = new HashSet<String>(); for (AbstractPartitionData partition : options.getAllPartitionData(this)) { if (partition.getTrait() != null) { states.addAll(partition.getTrait().getStatesOfTrait(options.taxonList)); } } return states; } }
package dr.app.beauti.treespanel; import dr.app.beauti.options.PartitionTreeModel; import dr.app.beauti.options.PartitionTreePrior; import dr.app.beauti.types.TreePriorParameterizationType; import dr.app.beauti.types.TreePriorType; import dr.app.beauti.util.PanelUtils; import dr.app.gui.components.WholeNumberField; import dr.app.util.OSType; import dr.evomodel.coalescent.VariableDemographicModel; import dr.evomodelxml.speciation.BirthDeathModelParser; import dr.evomodelxml.speciation.BirthDeathSerialSamplingModelParser; import jam.panels.OptionsPanel; import javax.swing.*; import java.awt.event.ItemEvent; import java.awt.event.ItemListener; import java.util.EnumSet; /** * @author Andrew Rambaut * @author Alexei Drummond * @author Walter Xie * @version $Id: PriorsPanel.java,v 1.9 2006/09/05 13:29:34 rambaut Exp $ */ public class PartitionTreePriorPanel extends OptionsPanel { private static final long serialVersionUID = 5016996360264782252L; private JComboBox treePriorCombo = new JComboBox(EnumSet.range(TreePriorType.CONSTANT, TreePriorType.BIRTH_DEATH_SERI_SAMP_ESTIM).toArray()); private JComboBox parameterizationCombo = new JComboBox(EnumSet.range(TreePriorParameterizationType.GROWTH_RATE, TreePriorParameterizationType.DOUBLING_TIME).toArray()); // private JComboBox parameterizationCombo1 = new JComboBox(EnumSet.of(TreePriorParameterizationType.DOUBLING_TIME).toArray()); private JComboBox bayesianSkylineCombo = new JComboBox(EnumSet.range(TreePriorParameterizationType.CONSTANT_SKYLINE, TreePriorParameterizationType.LINEAR_SKYLINE).toArray()); private WholeNumberField groupCountField = new WholeNumberField(2, Integer.MAX_VALUE); private JComboBox extendedBayesianSkylineCombo = new JComboBox( new VariableDemographicModel.Type[]{VariableDemographicModel.Type.LINEAR, VariableDemographicModel.Type.STEPWISE}); private JComboBox gmrfBayesianSkyrideCombo = new JComboBox(EnumSet.range(TreePriorParameterizationType.UNIFORM_SKYRIDE, TreePriorParameterizationType.TIME_AWARE_SKYRIDE).toArray()); // RealNumberField samplingProportionField = new RealNumberField(Double.MIN_VALUE, 1.0); // private BeautiFrame frame = null; // private BeautiOptions options = null; PartitionTreePrior partitionTreePrior; private final TreesPanel treesPanel; private boolean settingOptions = false; public PartitionTreePriorPanel(PartitionTreePrior parTreePrior, TreesPanel parent) { super(12, (OSType.isMac() ? 6 : 24)); this.partitionTreePrior = parTreePrior; this.treesPanel = parent; PanelUtils.setupComponent(treePriorCombo); treePriorCombo.addItemListener(new ItemListener() { public void itemStateChanged(ItemEvent ev) { partitionTreePrior.setNodeHeightPrior((TreePriorType) treePriorCombo.getSelectedItem()); setupPanel(); } }); PanelUtils.setupComponent(parameterizationCombo); parameterizationCombo.addItemListener(new ItemListener() { public void itemStateChanged(ItemEvent ev) { partitionTreePrior.setParameterization((TreePriorParameterizationType) parameterizationCombo.getSelectedItem()); } }); // PanelUtils.setupComponent(parameterizationCombo1); // parameterizationCombo1.addItemListener(new ItemListener() { // public void itemStateChanged(ItemEvent ev) { // partitionTreePrior.setParameterization((TreePriorParameterizationType) parameterizationCombo1.getSelectedItem()); PanelUtils.setupComponent(groupCountField); groupCountField.addKeyListener(new java.awt.event.KeyAdapter() { public void keyTyped(java.awt.event.KeyEvent ev) { // move to here? } }); PanelUtils.setupComponent(bayesianSkylineCombo); bayesianSkylineCombo.addItemListener(new ItemListener() { public void itemStateChanged(ItemEvent ev) { partitionTreePrior.setSkylineModel((TreePriorParameterizationType) bayesianSkylineCombo.getSelectedItem()); } }); PanelUtils.setupComponent(extendedBayesianSkylineCombo); extendedBayesianSkylineCombo.addItemListener(new ItemListener() { public void itemStateChanged(ItemEvent ev) { partitionTreePrior.setExtendedSkylineModel(((VariableDemographicModel.Type) extendedBayesianSkylineCombo.getSelectedItem())); } }); PanelUtils.setupComponent(gmrfBayesianSkyrideCombo); gmrfBayesianSkyrideCombo.addItemListener(new ItemListener() { public void itemStateChanged(ItemEvent ev) { partitionTreePrior.setSkyrideSmoothing((TreePriorParameterizationType) gmrfBayesianSkyrideCombo.getSelectedItem()); } }); // samplingProportionField.addKeyListener(keyListener); setupPanel(); } private void setupPanel() { removeAll(); JTextArea citationText = new JTextArea(1, 200); citationText.setLineWrap(true); citationText.setEditable(false); citationText.setFont(this.getFont()); // JScrollPane scrollPane = new JScrollPane(citation, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, // JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED); // scrollPane.setOpaque(true); String citation = null; addComponentWithLabel("Tree Prior:", treePriorCombo); if (treePriorCombo.getSelectedItem() == TreePriorType.EXPONENTIAL || treePriorCombo.getSelectedItem() == TreePriorType.LOGISTIC || treePriorCombo.getSelectedItem() == TreePriorType.EXPANSION) { addComponentWithLabel("Parameterization for growth:", parameterizationCombo); partitionTreePrior.setParameterization((TreePriorParameterizationType) parameterizationCombo.getSelectedItem()); // } else if (treePriorCombo.getSelectedItem() == TreePriorType.LOGISTIC //) {//TODO Issue 93 // || treePriorCombo.getSelectedItem() == TreePriorType.EXPANSION) { //TODO Issue 266 // addComponentWithLabel("Parameterization for growth:", parameterizationCombo1); // partitionTreePrior.setParameterization((TreePriorParameterizationType) parameterizationCombo1.getSelectedItem()); } else if (treePriorCombo.getSelectedItem() == TreePriorType.SKYLINE) { groupCountField.setColumns(6); addComponentWithLabel("Number of groups:", groupCountField); addComponentWithLabel("Skyline Model:", bayesianSkylineCombo); citation = "Drummond AJ, Rambaut A & Shapiro B and Pybus OG (2005) Mol Biol Evol 22, 1185-1192."; } else if (treePriorCombo.getSelectedItem() == TreePriorType.EXTENDED_SKYLINE) { addComponentWithLabel("Model Type:", extendedBayesianSkylineCombo); treesPanel.linkTreePriorCheck.setSelected(true); treesPanel.updateShareSameTreePriorChanged(); citation = "Insert citation here..."; // treesPanel.getFrame().setupEBSP(); TODO } else if (treePriorCombo.getSelectedItem() == TreePriorType.GMRF_SKYRIDE) { addComponentWithLabel("Smoothing:", gmrfBayesianSkyrideCombo); //For GMRF, one tree prior has to be associated to one tree model. The validation is in BeastGenerator.checkOptions() addLabel("<html>For GMRF, tree model/tree prior combination not implemented by BEAST yet. " + "It is only available for single tree model partition for this release. " + "Please go to Data Partition panel to link all tree models." + "</html>"); citation = "Minin, Bloomquist and Suchard (2008) Mol Biol Evol, 25, 1459-1471."; // treesPanel.linkTreePriorCheck.setSelected(false); // treesPanel.linkTreePriorCheck.setEnabled(false); // treesPanel.linkTreeModel(); // treesPanel.updateShareSameTreePriorChanged(); } else if (treePriorCombo.getSelectedItem() == TreePriorType.BIRTH_DEATH) { // samplingProportionField.setColumns(8); // treePriorPanel.addComponentWithLabel("Proportion of taxa sampled:", samplingProportionField); citation = BirthDeathModelParser.getCitation(); } else if (treePriorCombo.getSelectedItem() == TreePriorType.BIRTH_DEATH_INCOM_SAMP) { citation = BirthDeathModelParser.getCitationRHO(); } else if (treePriorCombo.getSelectedItem() == TreePriorType.BIRTH_DEATH_SERI_SAMP) { citation = BirthDeathSerialSamplingModelParser.getCitationPsiOrg(); } else if (treePriorCombo.getSelectedItem() == TreePriorType.BIRTH_DEATH_SERI_SAMP_ESTIM) { citation = BirthDeathSerialSamplingModelParser.getCitationRT(); } else { // treesPanel.linkTreePriorCheck.setEnabled(true); // treesPanel.linkTreePriorCheck.setSelected(true); // treesPanel.updateShareSameTreePriorChanged(); } if (citation != null) { addComponentWithLabel("Citation:", citationText); citationText.setText(citation); } // getOptions(); // treesPanel.treeModelPanels.get(treesPanel.currentTreeModel).setOptions(); for (PartitionTreeModel model : treesPanel.treeModelPanels.keySet()) { if (model != null) { treesPanel.treeModelPanels.get(model).setOptions(); } } // createTreeAction.setEnabled(options != null && options.dataPartitions.size() > 0); // fireTableDataChanged(); validate(); repaint(); } public void setOptions() { if (partitionTreePrior == null) { return; } settingOptions = true; treePriorCombo.setSelectedItem(partitionTreePrior.getNodeHeightPrior()); groupCountField.setValue(partitionTreePrior.getSkylineGroupCount()); //samplingProportionField.setValue(partitionTreePrior.birthDeathSamplingProportion); parameterizationCombo.setSelectedItem(partitionTreePrior.getParameterization()); bayesianSkylineCombo.setSelectedItem(partitionTreePrior.getSkylineModel()); extendedBayesianSkylineCombo.setSelectedItem(partitionTreePrior.getExtendedSkylineModel()); gmrfBayesianSkyrideCombo.setSelectedItem(partitionTreePrior.getSkyrideSmoothing()); // setupPanel(); settingOptions = false; validate(); repaint(); } public void getOptions() { if (settingOptions) return; // partitionTreePrior.setNodeHeightPrior((TreePriorType) treePriorCombo.getSelectedItem()); if (partitionTreePrior.getNodeHeightPrior() == TreePriorType.SKYLINE) { Integer groupCount = groupCountField.getValue(); if (groupCount != null) { partitionTreePrior.setSkylineGroupCount(groupCount); } else { partitionTreePrior.setSkylineGroupCount(5); } } else if (partitionTreePrior.getNodeHeightPrior() == TreePriorType.BIRTH_DEATH) { // Double samplingProportion = samplingProportionField.getValue(); // if (samplingProportion != null) { // partitionTreePrior.birthDeathSamplingProportion = samplingProportion; // } else { // partitionTreePrior.birthDeathSamplingProportion = 1.0; } // partitionTreePrior.setParameterization(parameterizationCombo.getSelectedIndex()); // partitionTreePrior.setSkylineModel(bayesianSkylineCombo.getSelectedIndex()); // partitionTreePrior.setExtendedSkylineModel(((VariableDemographicModel.Type) extendedBayesianSkylineCombo.getSelectedItem()).toString()); // partitionTreePrior.setSkyrideSmoothing(gmrfBayesianSkyrideCombo.getSelectedIndex()); // the taxon list may not exist yet... this should be set when generating... // partitionTreePrior.skyrideIntervalCount = partitionTreePrior.taxonList.getTaxonCount() - 1; } public void setMicrosatelliteTreePrior() { treePriorCombo.removeAllItems(); treePriorCombo.addItem(TreePriorType.CONSTANT); } public void removeCertainPriorFromTreePriorCombo() { treePriorCombo.removeItem(TreePriorType.YULE); treePriorCombo.removeItem(TreePriorType.BIRTH_DEATH); treePriorCombo.removeItem(TreePriorType.BIRTH_DEATH_INCOM_SAMP); } public void recoveryTreePriorCombo() { if (treePriorCombo.getItemCount() < EnumSet.range(TreePriorType.CONSTANT, TreePriorType.BIRTH_DEATH_SERI_SAMP_ESTIM).size()) { treePriorCombo.removeAllItems(); for (TreePriorType tpt : EnumSet.range(TreePriorType.CONSTANT, TreePriorType.BIRTH_DEATH_SERI_SAMP_ESTIM)) { treePriorCombo.addItem(tpt); } } } }
package lombok.eclipse.agent; import java.lang.instrument.Instrumentation; import java.util.Collection; import java.util.Collections; import java.util.List; import lombok.core.Agent; import lombok.patcher.Hook; import lombok.patcher.MethodTarget; import lombok.patcher.ScriptManager; import lombok.patcher.StackRequest; import lombok.patcher.TargetMatcher; import lombok.patcher.equinox.EquinoxClassLoader; import lombok.patcher.scripts.ScriptBuilder; /** * This is a java-agent that patches some of eclipse's classes so AST Nodes are handed off to Lombok * for modification before Eclipse actually uses them to compile, render errors, show code outlines, * create auto-completion dialogs, and anything else eclipse does with java code. See the *Transformer * classes in this package for more information about which classes are transformed and how they are * transformed. */ public class EclipsePatcher extends Agent { @Override public void runAgent(String agentArgs, Instrumentation instrumentation, boolean injected) throws Exception { registerPatchScripts(instrumentation, injected, injected); } private static void registerPatchScripts(Instrumentation instrumentation, boolean reloadExistingClasses, boolean ecjOnly) { ScriptManager sm = new ScriptManager(); sm.registerTransformer(instrumentation); if (!ecjOnly) { EquinoxClassLoader.addPrefix("lombok."); EquinoxClassLoader.registerScripts(sm); } patchAvoidReparsingGeneratedCode(sm); if (!ecjOnly) { patchLombokizeAST(sm); patchCatchReparse(sm); patchSetGeneratedFlag(sm); patchHideGeneratedNodes(sm); } if (reloadExistingClasses) sm.reloadClasses(instrumentation); } private static void patchHideGeneratedNodes(ScriptManager sm) { sm.addScript(ScriptBuilder.wrapReturnValue() .target(new MethodTarget("org.eclipse.jdt.internal.corext.dom.LinkedNodeFinder", "findByNode")) .target(new MethodTarget("org.eclipse.jdt.internal.corext.dom.LinkedNodeFinder", "findByBinding")) .wrapMethod(new Hook("lombok.eclipse.agent.PatchFixes", "removeGeneratedSimpleNames", "org.eclipse.jdt.core.dom.SimpleName[]", "org.eclipse.jdt.core.dom.SimpleName[]")) .request(StackRequest.RETURN_VALUE).build()); patchRefactorScripts(sm); patchFormatters(sm); } private static void patchFormatters(ScriptManager sm) { sm.addScript(ScriptBuilder.setSymbolDuringMethodCall() .target(new MethodTarget("org.eclipse.jdt.internal.ui.text.java.JavaFormattingStrategy", "format", "void")) .callToWrap(new Hook("org.eclipse.jdt.internal.corext.util.CodeFormatterUtil", "reformat", "org.eclipse.text.edits.TextEdit", "int", "java.lang.String", "int", "int", "int", "java.lang.String", "java.util.Map")) .symbol("lombok.disable").build()); } private static void patchRefactorScripts(ScriptManager sm) { sm.addScript(ScriptBuilder.exitEarly() .target(new MethodTarget("org.eclipse.jdt.core.dom.rewrite.ASTRewrite", "replace")) .target(new MethodTarget("org.eclipse.jdt.core.dom.rewrite.ASTRewrite", "remove")) .decisionMethod(new Hook("lombok.eclipse.agent.PatchFixes", "skipRewritingGeneratedNodes", "boolean", "org.eclipse.jdt.core.dom.ASTNode")) .transplant().request(StackRequest.PARAM1).build()); sm.addScript(ScriptBuilder.wrapMethodCall() .target(new MethodTarget("org.eclipse.jdt.internal.corext.refactoring.rename.RenameTypeProcessor", "addConstructorRenames")) .methodToWrap(new Hook("org.eclipse.jdt.core.IType", "getMethods", "org.eclipse.jdt.core.IMethod[]")) .wrapMethod(new Hook("lombok.eclipse.agent.PatchFixes", "removeGeneratedMethods", "org.eclipse.jdt.core.IMethod[]", "org.eclipse.jdt.core.IMethod[]")) .transplant().build()); } private static void patchCatchReparse(ScriptManager sm) { sm.addScript(ScriptBuilder.wrapReturnValue() .target(new MethodTarget("org.eclipse.jdt.core.dom.ASTConverter", "retrieveStartingCatchPosition")) .wrapMethod(new Hook("lombok.eclipse.agent.PatchFixes", "fixRetrieveStartingCatchPosition", "int", "int")) .transplant().request(StackRequest.PARAM1).build()); } private static void patchSetGeneratedFlag(ScriptManager sm) { sm.addScript(ScriptBuilder.addField() .targetClass("org.eclipse.jdt.internal.compiler.ast.ASTNode") .fieldName("$generatedBy") .fieldType("Lorg/eclipse/jdt/internal/compiler/ast/ASTNode;") .setPublic().setTransient().build()); sm.addScript(ScriptBuilder.addField() .targetClass("org.eclipse.jdt.core.dom.ASTNode") .fieldName("$isGenerated").fieldType("Z") .setPublic().setTransient().build()); sm.addScript(ScriptBuilder.wrapReturnValue() .target(new TargetMatcher() { @Override public boolean matches(String classSpec, String methodName, String descriptor) { if (!"convert".equals(methodName)) return false; List<String> fullDesc = MethodTarget.decomposeFullDesc(descriptor); if ("V".equals(fullDesc.get(0))) return false; if (fullDesc.size() < 2) return false; if (!fullDesc.get(1).startsWith("Lorg/eclipse/jdt/internal/compiler/ast/")) return false; return true; } @Override public Collection<String> getAffectedClasses() { return Collections.singleton("org.eclipse.jdt.core.dom.ASTConverter"); } }).request(StackRequest.PARAM1, StackRequest.RETURN_VALUE) .wrapMethod(new Hook("lombok.eclipse.agent.PatchFixes", "setIsGeneratedFlag", "void", "org.eclipse.jdt.core.dom.ASTNode", "org.eclipse.jdt.internal.compiler.ast.ASTNode")) .transplant().build()); sm.addScript(ScriptBuilder.wrapMethodCall() .target(new TargetMatcher() { @Override public boolean matches(String classSpec, String methodName, String descriptor) { if (!methodName.startsWith("convert")) return false; List<String> fullDesc = MethodTarget.decomposeFullDesc(descriptor); if (fullDesc.size() < 2) return false; if (!fullDesc.get(1).startsWith("Lorg/eclipse/jdt/internal/compiler/ast/")) return false; return true; } @Override public Collection<String> getAffectedClasses() { return Collections.singleton("org.eclipse.jdt.core.dom.ASTConverter"); } }).methodToWrap(new Hook("org.eclipse.jdt.core.dom.SimpleName", "<init>", "void", "org.eclipse.jdt.core.dom.AST")) .requestExtra(StackRequest.PARAM1) .wrapMethod(new Hook("lombok.eclipse.agent.PatchFixes", "setIsGeneratedFlagForSimpleName", "void", "org.eclipse.jdt.core.dom.SimpleName", "java.lang.Object")) .transplant().build()); } private static void patchAvoidReparsingGeneratedCode(ScriptManager sm) { final String PARSER_SIG = "org.eclipse.jdt.internal.compiler.parser.Parser"; sm.addScript(ScriptBuilder.exitEarly() .target(new MethodTarget(PARSER_SIG, "parse", "void", "org.eclipse.jdt.internal.compiler.ast.MethodDeclaration", "org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration")) .decisionMethod(new Hook("lombok.eclipse.agent.PatchFixes", "checkBit24", "boolean", "java.lang.Object")) .request(StackRequest.PARAM1).build()); sm.addScript(ScriptBuilder.exitEarly() .target(new MethodTarget(PARSER_SIG, "parse", "void", "org.eclipse.jdt.internal.compiler.ast.ConstructorDeclaration", "org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration", "boolean")) .decisionMethod(new Hook("lombok.eclipse.agent.PatchFixes", "checkBit24", "boolean", "java.lang.Object")) .request(StackRequest.PARAM1).build()); sm.addScript(ScriptBuilder.exitEarly() .target(new MethodTarget(PARSER_SIG, "parse", "void", "org.eclipse.jdt.internal.compiler.ast.Initializer", "org.eclipse.jdt.internal.compiler.ast.TypeDeclaration", "org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration")) .decisionMethod(new Hook("lombok.eclipse.agent.PatchFixes", "checkBit24", "boolean", "java.lang.Object")) .request(StackRequest.PARAM1).build()); } private static void patchLombokizeAST(ScriptManager sm) { sm.addScript(ScriptBuilder.addField() .targetClass("org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration") .fieldName("$lombokAST").fieldType("Ljava/lang/Object;") .setPublic().setTransient().build()); final String PARSER_SIG = "org.eclipse.jdt.internal.compiler.parser.Parser"; final String CUD_SIG = "org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration"; sm.addScript(ScriptBuilder.wrapReturnValue() .target(new MethodTarget(PARSER_SIG, "getMethodBodies", "void", CUD_SIG)) .wrapMethod(new Hook("lombok.eclipse.TransformEclipseAST", "transform", "void", PARSER_SIG, CUD_SIG)) .request(StackRequest.THIS, StackRequest.PARAM1).build()); sm.addScript(ScriptBuilder.wrapReturnValue() .target(new MethodTarget(PARSER_SIG, "endParse", CUD_SIG, "int")) .wrapMethod(new Hook("lombok.eclipse.TransformEclipseAST", "transform_swapped", "void", CUD_SIG, PARSER_SIG)) .request(StackRequest.THIS, StackRequest.RETURN_VALUE).build()); } }
package edu.cornell.pserc.jpower.tdcomplex; import cern.colt.list.tint.IntArrayList; import cern.colt.matrix.tdcomplex.DComplexFactory1D; import cern.colt.matrix.tdcomplex.DComplexMatrix1D; import cern.colt.matrix.tdcomplex.impl.SparseRCDComplexMatrix2D; import cern.colt.matrix.tdouble.DoubleMatrix2D; /** * Builds the vector of complex bus power injections. * * @author Ray Zimmerman (rz10@cornell.edu) * @author Richard Lincoln (r.w.lincoln@gmail.com) * */ public class DZjp_makeSbus extends DZjp_idx { /** * Returns the vector of complex bus * power injections, that is, generation minus load. Power is expressed * in per unit. * * @see makeYbus * @param baseMVA system base MVA * @param bus bus data * @param gen generator data * @return vector of complex bus power injections */ @SuppressWarnings("static-access") public static DComplexMatrix1D jp_makeSbus(double baseMVA, DoubleMatrix2D bus, DoubleMatrix2D gen) { /* generator info */ IntArrayList on = new IntArrayList(); // which generators are on? gen.viewColumn(GEN_STATUS).assign(dfunc.greater(0)).getNonZeros(on, null); int[] gbus = inta(gen.viewColumn(GEN_BUS).viewSelection(on.elements())); /* form net complex bus power injection vector */ int nb = bus.rows(); int ngon = on.size(); // connection matrix, element i, j is 1 if gen on(j) at bus i is ON SparseRCDComplexMatrix2D Cg = new SparseRCDComplexMatrix2D(nb, ngon, gbus, irange(ngon), 1, 0, false); DComplexMatrix1D Sg = DComplexFactory1D.dense.make(nb); Sg.assignReal(gen.viewColumn(PG).viewSelection(on.elements())); Sg.assignImaginary(gen.viewColumn(QG).viewSelection(on.elements())); DComplexMatrix1D Sd = DComplexFactory1D.dense.make(nb); Sd.assignReal(bus.viewColumn(PD)); Sd.assignImaginary(bus.viewColumn(QD)); // power injected by generators plus power injected by loads ... DComplexMatrix1D Sbus = Cg.zMult(Sg.assign(Sd, cfunc.minus), null); Sbus.assign(cfunc.div(baseMVA)); // converted to p.u. return Sbus; } }
package gov.nih.nci.nautilus.resultset; import gov.nih.nci.nautilus.de.BioSpecimenIdentifierDE; import gov.nih.nci.nautilus.de.DatumDE; import gov.nih.nci.nautilus.de.DiseaseNameDE; import gov.nih.nci.nautilus.de.GenderDE; import gov.nih.nci.nautilus.queryprocessing.ge.GeneExpr; public class SampleViewHandler { public SampleViewResultsContainer handleSampleView(SampleViewResultsContainer sampleViewContainer, GeneExpr.GeneExprSingle exprObj, GroupType groupType){ SampleResultset sampleResultset = null; GeneExprSingleViewHandler geneExprSingleViewHandler = geneExprSingleViewHandler = new GeneExprSingleViewHandler(); if (sampleViewContainer != null && exprObj != null){ sampleResultset = handleBioSpecimenResultset(sampleViewContainer,exprObj); //Propulate the GeneExprSingleResultsContainer GeneExprSingleViewResultsContainer geneExprSingleViewContainer = sampleResultset.getGeneExprSingleViewResultsContainer(); if(geneExprSingleViewContainer == null){ geneExprSingleViewContainer = new geneExprSingleViewcaontainer(); } geneExprSingleViewContainer = geneExprSingleViewHandler.handleGeneSingleView(geneExprSingleViewcaontainer,exprObj, groupType); sampleResultset.setGeneExprSingleViewResultsContainer(geneExprSingleViewContainer); //Populate the SampleViewResultsContainer sampleViewContainer.addBioSpecimenResultset(sampleResultset); } return sampleViewContainer; } public SampleResultset handleBioSpecimenResultset(SampleViewResultsContainer sampleViewContainer, GeneExpr.GeneExprSingle exprObj){ //get the gene accessesion number for this record //check if the gene exsists in the GeneExprSingleViewResultsContainer, otherwise add a new one. SampleResultset sampleResultset = (SampleResultset) sampleViewContainer.getBioSpecimenResultset(exprObj.getSampleId()); if(sampleResultset == null){ // no record found sampleResultset = new SampleResultset(); } //find out the biospecimenID associated with the GeneExpr.GeneExprSingle //populate the BiospecimenResuluset BioSpecimenIdentifierDE biospecimenID = new BioSpecimenIdentifierDE(exprObj.getSampleId().toString()); sampleResultset.setBiospecimen(biospecimenID); sampleResultset.setAgeGroup(new DatumDE(DatumDE.AGE_GROUP,exprObj.getAgeGroup())); sampleResultset.setSurvivalLengthRange(new DatumDE(DatumDE.SURVIVAL_LENGTH_RANGE,exprObj.getSurvivalLengthRange())); sampleResultset.setGenderCode(new GenderDE(exprObj.getGenderCode())); sampleResultset.setDisease(new DiseaseNameDE(exprObj.getDiseaseType())); return sampleResultset; } }
package org._3pq.jgrapht.generate; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.Map; import java.util.Set; import junit.framework.TestCase; import org._3pq.jgrapht.DirectedGraph; import org._3pq.jgrapht.Edge; import org._3pq.jgrapht.VertexFactory; import org._3pq.jgrapht.graph.DefaultDirectedGraph; /** * . * * @author John V. Sichi * * @since Sep 17, 2003 */ public class GraphGeneratorTest extends TestCase { private static final int SIZE = 10; private VertexFactory m_vertexFactory = new VertexFactory( ) { private int m_i; public Object createVertex( ) { return new Integer( ++m_i ); } }; public void testEmptyGraphGenerator( ) { GraphGenerator gen = new EmptyGraphGenerator( SIZE ); DirectedGraph g = new DefaultDirectedGraph( ); Map resultMap = new HashMap( ); gen.generateGraph( g, m_vertexFactory, resultMap ); assertEquals( SIZE, g.vertexSet( ).size( ) ); assertEquals( 0, g.edgeSet( ).size( ) ); assertTrue( resultMap.isEmpty( ) ); } public void testLinearGraphGenerator( ) { GraphGenerator gen = new LinearGraphGenerator( SIZE ); DirectedGraph g = new DefaultDirectedGraph( ); Map resultMap = new HashMap( ); gen.generateGraph( g, m_vertexFactory, resultMap ); assertEquals( SIZE, g.vertexSet( ).size( ) ); assertEquals( SIZE - 1, g.edgeSet( ).size( ) ); Object startVertex = resultMap.get( LinearGraphGenerator.START_VERTEX ); Object endVertex = resultMap.get( LinearGraphGenerator.END_VERTEX ); Iterator vertexIter = g.vertexSet( ).iterator( ); while( vertexIter.hasNext( ) ) { Object vertex = vertexIter.next( ); if( vertex == startVertex ) { assertEquals( 0, g.inDegreeOf( vertex ) ); assertEquals( 1, g.outDegreeOf( vertex ) ); continue; } if( vertex == endVertex ) { assertEquals( 1, g.inDegreeOf( vertex ) ); assertEquals( 0, g.outDegreeOf( vertex ) ); continue; } assertEquals( 1, g.inDegreeOf( vertex ) ); assertEquals( 1, g.outDegreeOf( vertex ) ); } } public void testRingGraphGenerator( ) { GraphGenerator gen = new RingGraphGenerator( SIZE ); DirectedGraph g = new DefaultDirectedGraph( ); Map resultMap = new HashMap( ); gen.generateGraph( g, m_vertexFactory, resultMap ); assertEquals( SIZE, g.vertexSet( ).size( ) ); assertEquals( SIZE, g.edgeSet( ).size( ) ); Object startVertex = g.vertexSet( ).iterator( ).next( ); assertEquals( 1, g.outDegreeOf( startVertex ) ); Object nextVertex = startVertex; Set seen = new HashSet( ); for( int i = 0; i < SIZE; ++i ) { Edge nextEdge = (Edge) g.outgoingEdgesOf( nextVertex ).get( 0 ); nextVertex = nextEdge.getTarget( ); assertEquals( 1, g.inDegreeOf( nextVertex ) ); assertEquals( 1, g.outDegreeOf( nextVertex ) ); assertTrue( !seen.contains( nextVertex ) ); seen.add( nextVertex ); } // do you ever get the feeling you're going in circles? assertTrue( nextVertex == startVertex ); assertTrue( resultMap.isEmpty( ) ); } // TODO: testWheelGraphGenerator }
package org.jboss.xnio; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.concurrent.TimeUnit; import java.util.concurrent.CancellationException; import java.util.concurrent.Executor; import org.jboss.xnio.log.Logger; /** * An abstract base class for {@code IoFuture} objects. Used to easily produce implementations. * * @param <T> the type of result that this operation produces */ public abstract class AbstractIoFuture<T> implements IoFuture<T> { private static final Logger log = Logger.getLogger("org.jboss.xnio.future"); private final Object lock = new Object(); private Status status = Status.WAITING; private Object result; private List<Runnable> notifierList; /** * Construct a new instance. */ protected AbstractIoFuture() { } /** * {@inheritDoc} */ public Status getStatus() { synchronized (lock) { return status; } } /** * {@inheritDoc} */ public Status await() { synchronized (lock) { boolean intr = Thread.interrupted(); try { while (status == Status.WAITING) try { lock.wait(); } catch (InterruptedException e) { intr = true; } } finally { if (intr) { Thread.currentThread().interrupt(); } } return status; } } /** * {@inheritDoc} */ public Status await(long time, final TimeUnit timeUnit) { if (time < 0L) { time = 0L; } long duration = timeUnit.toMillis(time); long deadline = duration + System.currentTimeMillis(); if (deadline < 0L) { deadline = Long.MAX_VALUE; } synchronized (lock) { boolean intr = Thread.interrupted(); try { while (status == Status.WAITING) try { lock.wait(duration); } catch (InterruptedException e) { intr = true; } duration = deadline - System.currentTimeMillis(); if (duration <= 0L) { return Status.WAITING; } } finally { if (intr) { Thread.currentThread().interrupt(); } } return status; } } /** * {@inheritDoc} */ public Status awaitInterruptibly() throws InterruptedException { synchronized (lock) { while (status == Status.WAITING) { lock.wait(); } return status; } } /** * {@inheritDoc} */ public Status awaitInterruptibly(long time, final TimeUnit timeUnit) throws InterruptedException { if (time < 0L) { time = 0L; } long duration = timeUnit.toMillis(time); long deadline = duration + System.currentTimeMillis(); if (deadline < 0L) { deadline = Long.MAX_VALUE; } synchronized (lock) { while (status == Status.WAITING) { lock.wait(duration); duration = deadline - System.currentTimeMillis(); if (duration <= 0L) { return Status.WAITING; } } return status; } } /** * {@inheritDoc} */ @SuppressWarnings({"unchecked"}) public T get() throws IOException, CancellationException { synchronized (lock) { switch (await()) { case DONE: return (T) result; case FAILED: throw (IOException) result; case CANCELLED: throw new CancellationException("Operation was cancelled"); default: throw new IllegalStateException("Unexpected state " + status); } } } /** * {@inheritDoc} */ @SuppressWarnings({"unchecked"}) public T getInterruptibly() throws IOException, InterruptedException, CancellationException { synchronized (lock) { switch (awaitInterruptibly()) { case DONE: return (T) result; case FAILED: throw (IOException) result; case CANCELLED: throw new CancellationException("Operation was cancelled"); default: throw new IllegalStateException("Unexpected state " + status); } } } /** * {@inheritDoc} */ public IOException getException() throws IllegalStateException { synchronized (lock) { if (status == Status.FAILED) { return (IOException) result; } else { throw new IllegalStateException("getException() when state is not FAILED"); } } } /** * {@inheritDoc} */ public <A> IoFuture<T> addNotifier(final Notifier<? super T, A> notifier, final A attachment) { final Runnable runnable = new Runnable() { public void run() { try { notifier.notify(AbstractIoFuture.this, attachment); } catch (Throwable t) { log.warn(t, "Running notifier failed"); } } }; synchronized (lock) { if (status == Status.WAITING) { if (notifierList == null) { notifierList = new ArrayList<Runnable>(); } notifierList.add(runnable); return this; } } runNotifier(runnable); return this; } private void runAllNotifiers() { if (notifierList != null) { for (final Runnable runnable : notifierList) { runNotifier(runnable); } notifierList = null; } } /** * Set the exception for this operation. Any threads blocking on this instance will be unblocked. * * @param exception the exception to set * @return {@code false} if the operation was already completed, {@code true} otherwise */ protected boolean setException(IOException exception) { synchronized (lock) { if (status == Status.WAITING) { status = Status.FAILED; result = exception; runAllNotifiers(); lock.notifyAll(); return true; } else { return false; } } } /** * Set the result for this operation. Any threads blocking on this instance will be unblocked. * * @param result the result to set * @return {@code false} if the operation was already completed, {@code true} otherwise */ protected boolean setResult(T result) { synchronized (lock) { if (status == Status.WAITING) { status = Status.DONE; this.result = result; runAllNotifiers(); lock.notifyAll(); return true; } else { return false; } } } /** * Acknowledge the cancellation of this operation. * * @return {@code false} if the operation was already completed, {@code true} otherwise */ protected boolean finishCancel() { synchronized (lock) { if (status == Status.WAITING) { status = Status.CANCELLED; runAllNotifiers(); lock.notifyAll(); return true; } else { return false; } } } /** * Cancel an operation. The actual cancel may be synchronous or asynchronous. Implementors will use this method * to initiate the cancel; use the {@link #finishCancel()} method to indicate that the cancel was successful. The * default implementation does nothing. * * @return this {@code IoFuture} instance */ public IoFuture<T> cancel() { return this; } /** * Run a notifier. Implementors will run the notifier, preferably in another thread. The default implementation * runs the notifier using the {@code Executor} retrieved via {@link #getNotifierExecutor()}. * * @param runnable */ protected void runNotifier(final Runnable runnable) { getNotifierExecutor().execute(runnable); } /** * Get the executor used to run asynchronous notifiers. By default, this implementation simply returns the direct * executor. * * @return the executor to use */ protected Executor getNotifierExecutor() { return IoUtils.directExecutor(); } }
package to.etc.log.handler; import java.sql.*; import java.text.*; import javax.annotation.*; import org.slf4j.*; import to.etc.log.event.*; public class EtcLogFormatter { @Nonnull private static final ThreadLocal<SimpleDateFormat> TIMEFORMATTER = new ThreadLocal<SimpleDateFormat>() { @Override protected SimpleDateFormat initialValue() { return new SimpleDateFormat(EtcLogFormat.TIMESTAMP); } }; @Nonnull static String format(@Nonnull EtcLogEvent event, @Nonnull String format, @Nullable String filterData) { StringBuilder sb = new StringBuilder(); //-- Get all % markers and replace it with log values. int ix = 0; int len = format.length(); while(ix < len) { char c = format.charAt(ix++); if(c == '%') { //detecting if we are in some of format pattern markers if(ix + 1 < len) { char nextChar = format.charAt(ix++); boolean notReplaced = false; switch(nextChar){ case 'd': case 'D': //%d (timestamp) sb.append(TIMEFORMATTER.get().format(event.getTimestamp())); break; case 'l': case 'L': //%l (logger name) sb.append(event.getLogger().getName()); break; case 'n': case 'N': //%n (new line) sb.append("\n"); break; case 'p': case 'P': //%p (level) sb.append(event.getLevel()); break; case 't': case 'T': //%t (thread) sb.append(event.getThread().getName()); break; case 'm': case 'M': //multiple choices if((len >= ix + 2) && "msg".equalsIgnoreCase(format.substring(ix - 1, ix + 2))) { ix += 2; handleMsg(event, sb); } else if((len >= ix + 2) && "mdc".equalsIgnoreCase(format.substring(ix - 1, ix + 2))) { ix += 2; ix = handleMdc(format, ix, sb); } else if((len >= ix + 5) && "marker".equalsIgnoreCase(format.substring(ix - 1, ix + 5))) { ix += 5; Marker marker = event.getMarker(); sb.append(marker != null ? marker.getName() : ""); } else { sb.append("%").append(nextChar); } break; default: sb.append("%").append(nextChar); } } } else { sb.append(c); } } Throwable t = event.getThrown(); if(t != null) { sb.append("\n").append(" logThrowable(sb, 0, t, true); int loggedCauses = 0; while(t.getCause() != null && t != t.getCause()) { t = t.getCause(); loggedCauses++; sb.append(" logThrowable(sb, loggedCauses, t, true); } } return sb.toString(); } private static void handleMsg(@Nonnull EtcLogEvent event, @Nonnull StringBuilder sb) { Object[] args = event.getArgs(); if(args != null && args.length > 0) { if(args.length == 1) { sb.append(org.slf4j.helpers.MessageFormatter.format(event.getMsg(), args)); } else if(args.length == 2) { sb.append(org.slf4j.helpers.MessageFormatter.format(event.getMsg(), args[0], args[1])); } else { sb.append(org.slf4j.helpers.MessageFormatter.arrayFormat(event.getMsg(), args)); } } else { sb.append(event.getMsg()); } } private static int handleMdc(@Nonnull String format, int ix, @Nonnull StringBuilder sb) { if(format.charAt(ix) != '{') { return ix; } else { int pos = format.indexOf("}", ix); if(pos == -1) { return ix; } else { String key = format.substring(ix + 1, pos).trim(); String value = MDC.get(key); if(value != null) { sb.append(value); } return pos + 1; } } } private static void logThrowable(@Nonnull StringBuilder sb, int causeIndex, @Nonnull Throwable t, boolean checkNextExceptions) { if(t.getMessage() != null) { sb.append("- message: ").append(t.getMessage()).append("\n"); } StackTraceElement[] stacktrace = t.getStackTrace(); for(StackTraceElement stack : stacktrace) { sb.append(" ").append(stack.toString()).append("\n"); } if(!checkNextExceptions) { return; } if(t instanceof SQLException) { SQLException sx = (SQLException) t; int loggedNextExceptions = 0; while(sx.getNextException() != null && sx != sx.getNextException()) { sx = sx.getNextException(); loggedNextExceptions++; sb.append(" logThrowable(sb, loggedNextExceptions, sx, false); } } } }
package gov.nih.nci.ncicb.cadsr.loader.parser; import gov.nih.nci.ncicb.cadsr.domain.*; import gov.nih.nci.ncicb.cadsr.loader.*; import gov.nih.nci.ncicb.cadsr.loader.util.*; import gov.nih.nci.ncicb.cadsr.loader.event.ProgressListener; import gov.nih.nci.ncicb.cadsr.loader.event.ProgressEvent; import gov.nih.nci.ncicb.xmiinout.handler.*; import gov.nih.nci.ncicb.xmiinout.domain.*; import org.apache.log4j.Logger; import java.util.*; /** * A writer for XMI files * * @author <a href="mailto:chris.ludet@oracle.com">Christophe Ludet</a> */ public class XMIWriter2 implements ElementWriter { private String output = null; private HashMap<String, UMLClass> classMap = new HashMap<String, UMLClass>(); private HashMap<String, UMLAttribute> attributeMap = new HashMap<String, UMLAttribute>(); private HashMap<String, UMLAssociation> assocMap = new HashMap<String, UMLAssociation>(); private HashMap<String, UMLAssociationEnd> assocEndMap = new HashMap<String, UMLAssociationEnd>(); private ElementsLists cadsrObjects = null; private ReviewTracker ownerReviewTracker = ReviewTracker.getInstance(ReviewTrackerType.Owner), curatorReviewTracker = ReviewTracker.getInstance(ReviewTrackerType.Curator); private ChangeTracker changeTracker = ChangeTracker.getInstance(); private ProgressListener progressListener; private UMLModel model = null; private XmiInOutHandler handler = null; private Logger logger = Logger.getLogger(XMIWriter2.class.getName()); public XMIWriter2() { } public void write(ElementsLists elements) throws ParserException { try { handler = (XmiInOutHandler)(UserSelections.getInstance().getProperty("XMI_HANDLER")); model = handler.getModel(); this.cadsrObjects = elements; sendProgressEvent(0, 0, "Parsing Model"); readModel(); // doReviewTagLogic(); sendProgressEvent(0, 0, "Marking Human reviewed"); markHumanReviewed(); sendProgressEvent(0, 0, "Updating Elements"); updateChangedElements(); sendProgressEvent(0, 0, "ReWriting Model"); handler.save(output); } catch (Exception ex) { throw new RuntimeException("Error initializing model", ex); } } public void setOutput(String url) { this.output = url; } public void setProgressListener(ProgressListener listener) { progressListener = listener; } private void readModel() { for(UMLPackage pkg : model.getPackages()) doPackage(pkg); int xi = 0; for(UMLAssociation assoc : model.getAssociations()) { List<UMLAssociationEnd> ends = assoc.getAssociationEnds(); UMLAssociationEnd aEnd = ends.get(0); UMLAssociationEnd bEnd = ends.get(1); UMLAssociationEnd source = bEnd, target = aEnd; // direction B? if (bEnd.isNavigable() && !aEnd.isNavigable()) { source = aEnd; target = bEnd; } // The assocMap is used in parallel with the Object Class Relationships (OCR). To easily find the // corresponding OCR for an Association and the reverse, the key for the map represents the index // of the OCR in its list. This works because the same XMI is read/parsed for to create both. In this // loop the model.getAssociations() will be in the same order so we can use an artificial index // counter. String key = String.valueOf(xi); // assoc.getRoleName()+"~"+source.getRoleName()+"~"+target.getRoleName(); assocMap.put(key,assoc); assocEndMap.put(key+"~source",source); assocEndMap.put(key+"~target",target); ++xi; } } private void updateChangedElements() { List<ObjectClass> ocs = cadsrObjects.getElements(DomainObjectFactory.newObjectClass()); List<DataElement> des = cadsrObjects.getElements(DomainObjectFactory.newDataElement()); List<ValueDomain> vds = cadsrObjects.getElements(DomainObjectFactory.newValueDomain()); List<ObjectClassRelationship> ocrs = cadsrObjects.getElements(DomainObjectFactory.newObjectClassRelationship()); int goal = ocs.size() + des.size() + vds.size() + ocrs.size(); int status = 0; sendProgressEvent(status, goal, ""); for(ObjectClass oc : ocs) { String fullClassName = null; for(AlternateName an : oc.getAlternateNames()) { if(an.getType().equals(AlternateName.TYPE_CLASS_FULL_NAME)) fullClassName = an.getName(); } sendProgressEvent(status++, goal, "Class: " + fullClassName); UMLClass clazz = classMap.get(fullClassName); String [] conceptCodes = oc.getPreferredName().split(":"); boolean changed = changeTracker.get(fullClassName); // is one of the concepts in this OC changed? for(String s : conceptCodes) changed = changed | changeTracker.get(s); if(changed) { // drop all current concept tagged values Collection<UMLTaggedValue> allTvs = clazz.getTaggedValues(); for(UMLTaggedValue tv : allTvs) { if(tv.getName().startsWith("ObjectClass") || tv.getName().startsWith("ObjectQualifier")) clazz.removeTaggedValue(tv.getName()); } addConceptTvs(clazz, conceptCodes, XMIParser2.TV_TYPE_CLASS); } } InheritedAttributeList inheritedList = InheritedAttributeList.getInstance(); for(DataElement de : des) { DataElementConcept dec = de.getDataElementConcept(); String fullPropName = null; for(AlternateName an : de.getAlternateNames()) { if(an.getType().equals(AlternateName.TYPE_FULL_NAME)) fullPropName = an.getName(); } sendProgressEvent(status++, goal, "Attribute: " + fullPropName); UMLAttribute att = attributeMap.get(fullPropName); boolean changed = changeTracker.get(fullPropName); String [] conceptCodes = dec.getProperty().getPreferredName().split(":"); // is one of the concepts in this Property changed? for(String s : conceptCodes) changed = changed | changeTracker.get(s); if(changed) { if(!inheritedList.isInherited(de)) { // drop all current concept tagged values Collection<UMLTaggedValue> allTvs = att.getTaggedValues(); for(UMLTaggedValue tv : allTvs) { if(tv.getName().startsWith("Property") || tv.getName().startsWith("PropertyQualifier")) att.removeTaggedValue(tv.getName()); } // Map to Existing DE if(!StringUtil.isEmpty(de.getPublicId()) && de.getVersion() != null) { att.removeTaggedValue(XMIParser2.TV_DE_ID); att.removeTaggedValue(XMIParser2.TV_DE_VERSION); att.addTaggedValue(XMIParser2.TV_DE_ID, de.getPublicId()); att.addTaggedValue(XMIParser2.TV_DE_VERSION, de.getVersion().toString()); } else { att.removeTaggedValue(XMIParser2.TV_DE_ID); att.removeTaggedValue(XMIParser2.TV_DE_VERSION); if(!StringUtil.isEmpty(de.getValueDomain().getPublicId()) && de.getValueDomain().getVersion() != null) { att.removeTaggedValue(XMIParser2.TV_VD_ID); att.removeTaggedValue(XMIParser2.TV_VD_VERSION); att.addTaggedValue(XMIParser2.TV_VD_ID, de.getValueDomain().getPublicId()); att.addTaggedValue(XMIParser2.TV_VD_VERSION, de.getValueDomain().getVersion().toString()); } else { att.removeTaggedValue(XMIParser2.TV_VD_ID); att.removeTaggedValue(XMIParser2.TV_VD_VERSION); } addConceptTvs(att, conceptCodes, XMIParser2.TV_TYPE_PROPERTY); } } else { // in case of inherited attribute ObjectClass oc = de.getDataElementConcept().getObjectClass(); String fullClassName = LookupUtil.lookupFullName(oc); UMLClass clazz = classMap.get(fullClassName); String attributeName = LookupUtil.lookupFullName(de); attributeName = attributeName.substring(attributeName.lastIndexOf(".") + 1); clazz.removeTaggedValue(XMIParser2.TV_INHERITED_DE_ID.replace("{1}", attributeName)); clazz.removeTaggedValue(XMIParser2.TV_INHERITED_DE_VERSION.replace("{1}", attributeName)); clazz.removeTaggedValue(XMIParser2.TV_INHERITED_VD_ID.replace("{1}", attributeName)); clazz.removeTaggedValue(XMIParser2.TV_INHERITED_VD_VERSION.replace("{1}", attributeName)); if(!StringUtil.isEmpty(de.getPublicId())) { clazz.addTaggedValue(XMIParser2.TV_INHERITED_DE_ID.replace("{1}", attributeName), de.getPublicId()); clazz.addTaggedValue(XMIParser2.TV_INHERITED_DE_VERSION.replace("{1}", attributeName), de.getVersion().toString()); } else if(!StringUtil.isEmpty(de.getValueDomain().getPublicId())) { clazz.addTaggedValue(XMIParser2.TV_INHERITED_VD_ID.replace("{1}", attributeName), de.getValueDomain().getPublicId()); clazz.addTaggedValue(XMIParser2.TV_INHERITED_VD_VERSION.replace("{1}", attributeName), de.getValueDomain().getVersion().toString()); } } } } for(ValueDomain vd : vds) { sendProgressEvent(status++, goal, "Value Domain: " + vd.getLongName()); for(PermissibleValue pv : vd.getPermissibleValues()) { ValueMeaning vm = pv.getValueMeaning(); String fullPropName = "ValueDomains." + vd.getLongName() + "." + vm.getLongName(); UMLAttribute att = attributeMap.get(fullPropName); boolean changed = changeTracker.get(fullPropName); String [] conceptCodes = ConceptUtil.getConceptCodes(vm); // is one of the concepts in this VM changed? for(String s : conceptCodes) changed = changed | changeTracker.get(s); if(changed) { // drop all current concept tagged values Collection<UMLTaggedValue> allTvs = att.getTaggedValues(); for(UMLTaggedValue tv : allTvs) { if(tv.getName().startsWith(XMIParser2.TV_TYPE_VM) || tv.getName().startsWith(XMIParser2.TV_TYPE_VM + "Qualifier")) att.removeTaggedValue(tv.getName()); } addConceptTvs(att, conceptCodes, XMIParser2.TV_TYPE_VM); } } } for(int xi = 0; xi < ocrs.size(); ++xi) { // For this to work the OCRS must appear in the same order as the model.getAssociations(). // This is further noted in the readModel() method with the assocMap.put(...) reference. ObjectClassRelationship ocr = ocrs.get(xi); ConceptDerivationRule rule = ocr.getConceptDerivationRule(); ConceptDerivationRule srule = ocr.getSourceRoleConceptDerivationRule(); ConceptDerivationRule trule = ocr.getTargetRoleConceptDerivationRule(); OCRRoleNameBuilder nameBuilder = new OCRRoleNameBuilder(); String fullName = nameBuilder.buildRoleName(ocr); sendProgressEvent(status++, goal, "Relationship: " + fullName); // The key assigned to the assocMap entry is the index from the OCRS list. See the readModel() // method for more information at the assocMap.put(...) String key = String.valueOf(xi); // ocr.getLongName()+"~"+ocr.getSourceRole()+"~"+ocr.getTargetRole(); UMLAssociation assoc = assocMap.get(key); UMLAssociationEnd source = assocEndMap.get(key+"~source"); UMLAssociationEnd target = assocEndMap.get(key+"~target"); // Role Level if (rule != null ){ List<ComponentConcept> rConcepts = rule.getComponentConcepts(); String[] rcodes = new String[rConcepts.size()]; int i = 0; for (ComponentConcept con: rConcepts) { rcodes[i++] = con.getConcept().getPreferredName(); } boolean changed = changeTracker.get(fullName); for(String s : rcodes) changed = changed | changeTracker.get(s); if(changed) { dropCurrentAssocTvs(assoc); addConceptTvs(assoc, rcodes, XMIParser2.TV_TYPE_ASSOC_ROLE); } } // Source Level if (srule != null) { List<ComponentConcept> sConcepts = srule.getComponentConcepts(); String[] scodes = new String[sConcepts.size()]; int i = 0; for (ComponentConcept con: sConcepts) { scodes[i++] = con.getConcept().getPreferredName(); } boolean changedSource = changeTracker.get(fullName+" Source"); for(String s : scodes) changedSource = changedSource | changeTracker.get(s); if(changedSource) { dropCurrentAssocTvs(source); addConceptTvs(source, scodes, XMIParser2.TV_TYPE_ASSOC_SOURCE); } } // Target Level if(trule != null) { List<ComponentConcept> tConcepts = trule.getComponentConcepts(); String[] tcodes = new String[tConcepts.size()]; int i = 0; for (ComponentConcept con: tConcepts) { tcodes[i++] = con.getConcept().getPreferredName(); } boolean changedTarget = changeTracker.get(fullName+" Target"); for(String s : tcodes) changedTarget = changedTarget | changeTracker.get(s); if(changedTarget) { dropCurrentAssocTvs(target); addConceptTvs(target, tcodes, XMIParser2.TV_TYPE_ASSOC_TARGET); } } } changeTracker.clear(); } private void dropCurrentAssocTvs(UMLTaggableElement elt) { Collection<UMLTaggedValue> allTvs = elt.getTaggedValues(); for(UMLTaggedValue tv : allTvs) { String name = tv.getName(); if(name.startsWith(XMIParser2.TV_TYPE_ASSOC_ROLE) || name.startsWith(XMIParser2.TV_TYPE_ASSOC_SOURCE)|| name.startsWith(XMIParser2.TV_TYPE_ASSOC_TARGET)) { elt.removeTaggedValue(name); } } } private void addConceptTvs(UMLTaggableElement elt, String[] conceptCodes, String type) { if(conceptCodes.length == 0) return; addConceptTv(elt, conceptCodes[conceptCodes.length - 1], type, "", 0); for(int i= 1; i < conceptCodes.length; i++) { addConceptTv(elt, conceptCodes[conceptCodes.length - i - 1], type, XMIParser2.TV_QUALIFIER, i); } } private void addConceptTv(UMLTaggableElement elt, String conceptCode, String type, String pre, int n) { Concept con = LookupUtil.lookupConcept(conceptCode); if(con == null) return; String tvName = type + pre + XMIParser2.TV_CONCEPT_CODE + ((n>0)?""+n:""); if(con.getPreferredName() != null) elt.addTaggedValue(tvName,con.getPreferredName()); tvName = type + pre + XMIParser2.TV_CONCEPT_DEFINITION + ((n>0)?""+n:""); if(con.getPreferredDefinition() != null) addSplitTaggedValue(elt, tvName, con.getPreferredDefinition(), "_"); // elt.addTaggedValue(tvName,con.getPreferredDefinition()); tvName = type + pre + XMIParser2.TV_CONCEPT_DEFINITION_SOURCE + ((n>0)?""+n:""); if(con.getDefinitionSource() != null) elt.addTaggedValue(tvName,con.getDefinitionSource()); tvName = type + pre + XMIParser2.TV_CONCEPT_PREFERRED_NAME + ((n>0)?""+n:""); if(con.getLongName() != null) elt.addTaggedValue (tvName, con.getLongName()); // tvName = type + pre + XMIParser2.TV_TYPE_VM + ((n>0)?""+n:""); // if(con.getLongName() != null) // elt.addTaggedValue // (tvName, // con.getLongName()); } private void markHumanReviewed() throws ParserException { try{ List<ObjectClass> ocs = cadsrObjects.getElements(DomainObjectFactory.newObjectClass()); List<DataElement> des = cadsrObjects.getElements(DomainObjectFactory.newDataElement()); List<ValueDomain> vds = cadsrObjects.getElements(DomainObjectFactory.newValueDomain()); List<ObjectClassRelationship> ocrs = cadsrObjects.getElements(DomainObjectFactory.newObjectClassRelationship()); for(ObjectClass oc : ocs) { String fullClassName = null; for(AlternateName an : oc.getAlternateNames()) { if(an.getType().equals(AlternateName.TYPE_CLASS_FULL_NAME)) fullClassName = an.getName(); } UMLClass clazz = classMap.get(fullClassName); Boolean reviewed = ownerReviewTracker.get(fullClassName); if(reviewed != null) { clazz.removeTaggedValue(XMIParser2.TV_OWNER_REVIEWED); clazz.addTaggedValue(XMIParser2.TV_OWNER_REVIEWED, reviewed?"1":"0"); } reviewed = curatorReviewTracker.get(fullClassName); if(reviewed != null) { clazz.removeTaggedValue(XMIParser2.TV_CURATOR_REVIEWED); clazz.addTaggedValue(XMIParser2.TV_CURATOR_REVIEWED, reviewed?"1":"0"); } } InheritedAttributeList inheritedList = InheritedAttributeList.getInstance(); for(DataElement de : des) { DataElementConcept dec = de.getDataElementConcept(); String fullClassName = LookupUtil.lookupFullName(de.getDataElementConcept().getObjectClass()); String fullPropName = fullClassName + "." + dec.getProperty().getLongName(); String attributeName = LookupUtil.lookupFullName(de); attributeName = attributeName.substring(attributeName.lastIndexOf(".") + 1); Boolean reviewed = ownerReviewTracker.get(fullPropName); if(reviewed != null) { if(!inheritedList.isInherited(de)) { UMLAttribute umlAtt = attributeMap.get(fullPropName); umlAtt.removeTaggedValue(XMIParser2.TV_OWNER_REVIEWED); umlAtt.addTaggedValue(XMIParser2.TV_OWNER_REVIEWED, reviewed?"1":"0"); } else { UMLClass clazz = classMap.get(fullClassName); clazz.removeTaggedValue(XMIParser2.TV_INHERITED_OWNER_REVIEWED.replace("{1}", attributeName)); clazz.addTaggedValue(XMIParser2.TV_INHERITED_OWNER_REVIEWED.replace("{1}", attributeName), reviewed?"1":"0"); } } reviewed = curatorReviewTracker.get(fullPropName); if(reviewed != null) { if(!inheritedList.isInherited(de)) { UMLAttribute umlAtt = attributeMap.get(fullPropName); umlAtt.removeTaggedValue(XMIParser2.TV_CURATOR_REVIEWED); umlAtt.addTaggedValue(XMIParser2.TV_CURATOR_REVIEWED, reviewed?"1":"0"); } else { UMLClass clazz = classMap.get(fullClassName); clazz.removeTaggedValue(XMIParser2.TV_INHERITED_CURATOR_REVIEWED.replace("{1}", attributeName)); clazz.addTaggedValue(XMIParser2.TV_INHERITED_CURATOR_REVIEWED.replace("{1}", attributeName), reviewed?"1":"0"); } } } for(ValueDomain vd : vds) { for(PermissibleValue pv : vd.getPermissibleValues()) { ValueMeaning vm = pv.getValueMeaning(); String fullPropName = "ValueDomains." + vd.getLongName() + "." + vm.getLongName(); Boolean reviewed = ownerReviewTracker.get(fullPropName); UMLAttribute umlAtt = null; if(reviewed != null) { umlAtt = attributeMap.get(fullPropName); umlAtt.removeTaggedValue(XMIParser2.TV_OWNER_REVIEWED); umlAtt.addTaggedValue(XMIParser2.TV_OWNER_REVIEWED, reviewed?"1":"0"); } reviewed = curatorReviewTracker.get(fullPropName); if(reviewed != null) { umlAtt = attributeMap.get(fullPropName); umlAtt.removeTaggedValue(XMIParser2.TV_CURATOR_REVIEWED); umlAtt.addTaggedValue(XMIParser2.TV_CURATOR_REVIEWED, reviewed?"1":"0"); } } } for(int xi = 0; xi < ocrs.size(); ++xi) { // For this to work the OCRS must appear in the same order as the model.getAssociations(). // This is further noted in the readModel() method with the assocMap.put(...) reference. ObjectClassRelationship ocr = ocrs.get(xi); final OCRRoleNameBuilder nameBuilder = new OCRRoleNameBuilder(); final String fullPropName = nameBuilder.buildRoleName(ocr); final String tPropName = fullPropName + " Target"; final String sPropName = fullPropName + " Source"; // The key assigned to the assocMap entry is the index from the OCRS list. See the readModel() // method for more information at the assocMap.put(...) final String key = String.valueOf(xi); // ocr.getLongName()+"~"+ocr.getSourceRole()+"~"+ocr.getTargetRole(); final UMLAssociation assoc = assocMap.get(key); final UMLAssociationEnd target = assocEndMap.get(key+"~target"); final UMLAssociationEnd source = assocEndMap.get(key+"~source"); // ROLE Boolean reviewed = ownerReviewTracker.get(fullPropName); if(reviewed != null) refreshOwnerTag(assoc, reviewed); reviewed = curatorReviewTracker.get(fullPropName); if(reviewed != null) refreshCuratorTag(assoc, reviewed); // SOURCE reviewed = ownerReviewTracker.get(sPropName); if(reviewed != null) refreshOwnerTag(source, reviewed); reviewed = curatorReviewTracker.get(sPropName); if(reviewed != null) refreshCuratorTag(source, reviewed); // TARGET reviewed = ownerReviewTracker.get(tPropName); if(reviewed != null) refreshOwnerTag(target, reviewed); reviewed = curatorReviewTracker.get(tPropName); if(reviewed != null) refreshCuratorTag(target, reviewed); } } catch (RuntimeException e) { throw new ParserException(e); } } private void refreshCuratorTag(UMLTaggableElement umlElement, boolean reviewed) { umlElement.removeTaggedValue(XMIParser2.TV_CURATOR_REVIEWED); umlElement.addTaggedValue(XMIParser2.TV_CURATOR_REVIEWED, reviewed?"1":"0"); } private void refreshOwnerTag(UMLTaggableElement umlElement, boolean reviewed) { umlElement.removeTaggedValue(XMIParser2.TV_OWNER_REVIEWED); umlElement.addTaggedValue(XMIParser2.TV_OWNER_REVIEWED, reviewed?"1":"0"); } private void doPackage(UMLPackage pkg) { for(UMLClass clazz : pkg.getClasses()) { String className = null; String st = clazz.getStereotype(); boolean foundVd = false; if(st != null) for(int i=0; i < XMIParser2.validVdStereotypes.length; i++) { if(st.equalsIgnoreCase(XMIParser2.validVdStereotypes[i])) foundVd = true; } if(foundVd) { className = "ValueDomains." + clazz.getName(); } else { className = getPackageName(pkg) + "." + clazz.getName(); } classMap.put(className, clazz); for(UMLAttribute att : clazz.getAttributes()) { attributeMap.put(className + "." + att.getName(), att); } } for(UMLPackage subPkg : pkg.getPackages()) { doPackage(subPkg); } } protected void sendProgressEvent(int status, int goal, String message) { if(progressListener != null) { ProgressEvent pEvent = new ProgressEvent(); pEvent.setMessage(message); pEvent.setStatus(status); pEvent.setGoal(goal); progressListener.newProgressEvent(pEvent); } } private String getPackageName(UMLPackage pkg) { StringBuffer pack = new StringBuffer(); String s = null; do { s = null; if(pkg != null) { s = pkg.getName(); if(s.indexOf(" ") == -1) { if(pack.length() > 0) pack.insert(0, '.'); pack.insert(0, s); } pkg = pkg.getParent(); } } while (s != null); return pack.toString(); } /** * This method moved to DefinitionSplitter. Remove in next version. * @deprecated */ private void addSplitTaggedValue(UMLTaggableElement elt, String tag, String value, String separator) { final int MAX_TV_SIZE = 255; if(value.length() > MAX_TV_SIZE) { int nbOfTags = (int)(Math.ceil((double)value.length() / (double)MAX_TV_SIZE)); for(int i = 0; i < nbOfTags; i++) { String thisTag = (i==0)?tag:tag + separator + (i+1); int index = i*MAX_TV_SIZE; String thisValue = (index + MAX_TV_SIZE > value.length())?value.substring(index):value.substring(index, index + MAX_TV_SIZE); elt.addTaggedValue(thisTag, thisValue); } } else { elt.addTaggedValue(tag, value); } } }
package com.khacks.srp; import android.content.Context; import android.graphics.Color; import android.graphics.Point; import android.location.Location; import android.support.v4.app.FragmentActivity; import android.os.Bundle; import android.util.Log; import android.view.Display; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import com.android.volley.Request; import com.android.volley.RequestQueue; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.toolbox.JsonObjectRequest; import com.android.volley.toolbox.Volley; import com.google.android.gms.common.ConnectionResult; import com.google.android.gms.common.api.GoogleApiClient; import com.google.android.gms.location.LocationServices; import com.google.android.gms.maps.CameraUpdateFactory; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.SupportMapFragment; import com.google.android.gms.maps.model.BitmapDescriptorFactory; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.maps.model.LatLngBounds; import com.google.android.gms.maps.model.MarkerOptions; import com.google.android.gms.maps.model.Polyline; import com.google.android.gms.maps.model.PolylineOptions; import org.json.JSONArray; import org.json.JSONObject; import java.net.URLEncoder; import java.util.ArrayList; public class MapsActivity extends FragmentActivity implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener { private GoogleMap mMap; // Might be null if Google Play services APK is not available. private EditText mFromField; private EditText mToField; private Button mSend; private RequestQueue mQueue; private String mMapQuestUrl; private GoogleApiClient mGoogleApiClient; private Location mLastLocation; @Override protected void onStart() { super.onStart(); mGoogleApiClient.connect(); } @Override protected void onStop() { mGoogleApiClient.disconnect(); super.onStop(); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_maps); buildGoogleApiClient(); setUpMapIfNeeded(); // Setup the layout elements mFromField = (EditText) findViewById(R.id.fromField); mToField = (EditText) findViewById(R.id.toField); mSend = (Button) findViewById(R.id.searchButton); // Instantiate the RequestQueue. mQueue = Volley.newRequestQueue(this); mSend.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { String from = mFromField.getText().toString(); String to = mToField.getText().toString(); if (!from.isEmpty() && !to.isEmpty()) { // Initialize variables try { mMapQuestUrl ="http://open.mapquestapi.com/directions/v2/route?key=Fmjtd%7Cluu8210ynq%2C8w%3Do5-94r504&ambiguities=ignore&avoidTimedConditions=false&outFormat=json&routeType=fastest&enhancedNarrative=false&shapeFormat=raw&generalize=0&locale=en_US&unit=m&from="+ URLEncoder.encode(from, "utf-8")+"&to="+ URLEncoder.encode(to, "utf-8"); } catch (Exception e) { } Log.v("LO", mMapQuestUrl); doGETRequest(mMapQuestUrl, new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject response) { Context context = getApplicationContext(); int duration = Toast.LENGTH_SHORT; Toast.makeText(context, response.toString(), duration).show(); drawJSONDirection(response); callJSolaServer(response); } }); } } }); } void callJSolaServer(JSONObject response) { String url = "http://37.187.81.177:8000/point/route"; JSONArray array = new JSONArray(); JSONObject query = new JSONObject(); try { array = response.getJSONObject("route").getJSONArray("legs"). getJSONObject(0).getJSONArray("maneuvers"); query.accumulate("maneuvers", array); } catch (Exception e) { } Log.v("LO", response.toString()); doPOSTRequest(url, query, new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject response) { searchControlPoints(response); } }); } void doGETRequest(String url, Response.Listener<JSONObject> listener) { // Request a string response from the provided URL. Log.v("LO", "WOLO"); JsonObjectRequest jsObjRequest = new JsonObjectRequest (Request.Method.GET, url, null, listener, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { // TODO Auto-generated method stub Log.v("LO", error.getMessage()); } }); // Add the request to the RequestQueue. mQueue.add(jsObjRequest); } private void doPOSTRequest(String url, JSONObject query, Response.Listener<JSONObject> listener) { // Request a string response from the provided URL. Log.v("LO", "WOLO"); JsonObjectRequest jsObjRequest = new JsonObjectRequest (Request.Method.POST, url, query, listener, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { // TODO Auto-generated method stub Log.v("LO", error.getMessage()); } }); // Add the request to the RequestQueue. mQueue.add(jsObjRequest); } private void searchControlPoints(JSONObject jsonObject) { try { JSONObject query = new JSONObject(); JSONArray array = jsonObject.getJSONArray("blackPoints"); for (int i = 0; i < array.length(); i++) { JSONObject info = new JSONObject(); double lat = array.getJSONObject(i).getDouble("lat"); double lng = array.getJSONObject(i).getDouble("lng"); info.put("lat",lat); info.put("lng",lng); info.put("weight",100); info.put("radius",5); query.accumulate("routeControlPointCollection",info); addBlueMarker(new LatLng(lat, lng), "Point " + i); } doPOSTRequest(mMapQuestUrl, query, new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject response) { Context context = getApplicationContext(); int duration = Toast.LENGTH_SHORT; Toast.makeText(context, "CONTROL POINTS!", duration).show(); JSONArray array2 = new JSONArray(); try { array2 = response.getJSONObject("route").getJSONArray("shapePoints"); } catch (Exception e) { } } }); } catch (Exception e) { // WOLOLO } } @Override protected void onResume() { super.onResume(); setUpMapIfNeeded(); } /** * Sets up the map if it is possible to do so (i.e., the Google Play services APK is correctly * installed) and the map has not already been instantiated.. This will ensure that we only ever * call {@link #setUpMap()} once when {@link #mMap} is not null. * <p/> * If it isn't installed {@link SupportMapFragment} (and * {@link com.google.android.gms.maps.MapView MapView}) will show a prompt for the user to * install/update the Google Play services APK on their device. * <p/> * A user can return to this FragmentActivity after following the prompt and correctly * installing/updating/enabling the Google Play services. Since the FragmentActivity may not * have been completely destroyed during this process (it is likely that it would only be * stopped or paused), {@link #onCreate(Bundle)} may not be called again so we should call this * method in {@link #onResume()} to guarantee that it will be called. */ private void setUpMapIfNeeded() { // Do a null check to confirm that we have not already instantiated the map. if (mMap == null) { // Try to obtain the map from the SupportMapFragment. mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)) .getMap(); // Check if we were successful in obtaining the map. if (mMap != null) { setUpMap(); } } } /** * This is where we can add markers or lines, add listeners or move the camera. In this case, we * just add a marker near Africa. * <p/> * This should only be called once and when we are sure that {@link #mMap} is not null. */ private void setUpMap() { mMap.setMyLocationEnabled(true); mMap.getUiSettings().setMyLocationButtonEnabled(false); } /** * Draw the route from the JSON object in the map */ private void drawJSONDirection(JSONObject direction) { Polyline line = mMap.addPolyline(new PolylineOptions() .add(new LatLng(51.5, -0.1), new LatLng(40.7, -74.0)) .width(5) .color(Color.RED)); JSONArray jArray = null; ArrayList<LatLng> points = new ArrayList<LatLng>(); try { jArray = direction.getJSONObject("route").getJSONObject("shape"). getJSONArray("shapePoints"); if (jArray != null) { for (int i=0;i<jArray.length();i+=2){ points.add(new LatLng((double)jArray.get(i), (double)jArray.get(i+1))); } } } catch (Exception e) { e.printStackTrace(); } // Remove previous roads and marks mMap.clear(); mMap.addPolyline(new PolylineOptions().addAll(points).width(5).color(Color.RED)); focusCameraOnPath(points); } /** * Zooms the camera so that the path fits in the screen * @param path set of points that form the path */ private void focusCameraOnPath(ArrayList<LatLng> path) { LatLngBounds.Builder builder = new LatLngBounds.Builder(); for (LatLng point : path) { builder.include(point); } Display display = getWindowManager().getDefaultDisplay(); Point size = new Point(); display.getSize(size); final int width = size.x; final int height = size.y; final int padding = 40; mMap.animateCamera(CameraUpdateFactory.newLatLngBounds( builder.build(), width, height, padding)); } private void addBlueMarker(LatLng coord, String markerString) { if (markerString == null) markerString = "Blue Marker"; mMap.addMarker(new MarkerOptions().position(coord).title(markerString). icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_BLUE))); } protected synchronized void buildGoogleApiClient() { mGoogleApiClient = new GoogleApiClient.Builder(this) .addConnectionCallbacks(this) .addOnConnectionFailedListener(this) .addApi(LocationServices.API) .build(); } @Override public void onConnected(Bundle connectionHint) { // Connected to Google Play services! // The good stuff goes here. Log.v("LO", "WOLO"); mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient); mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(mLastLocation.getLatitude(), mLastLocation.getLongitude()), 13)); } @Override public void onConnectionSuspended(int cause) { // The connection has been interrupted. // Disable any UI components that depend on Google APIs // until onConnected() is called. Log.v("LO", "WOLO :("); } @Override public void onConnectionFailed(ConnectionResult result) { // This callback is important for handling errors that // may occur while attempting to connect with Google. // More about this in the next section. Log.v("LO", "WOLO :(((((((("); } }
package ilearnrw.languagetools.english; import ilearnrw.textclassification.GraphemePhonemePair; import ilearnrw.textclassification.WordType; import ilearnrw.textclassification.english.EnglishWord; import java.io.BufferedReader; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.Map; public class EnglishDictionary { private Map<String, EnglishWord> dictionary; public EnglishDictionary(String fileName){ dictionary = new HashMap<String, EnglishWord>(); loadDictionary(fileName); } public Map<String, EnglishWord> getDictionary(){ return dictionary; } public EnglishWord getWord(String w){ if(dictionary.containsKey(w)){ return dictionary.get(w); } return null; } private void loadDictionary(String fileName){ try { BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream("data/" + fileName), "UTF-8")); String strLine; //Read File Line By Line while ((strLine = br.readLine()) != null) { String[] results = strLine.split("\t"); String word, stem, phonetic; ArrayList<GraphemePhonemePair> phoneticList; ArrayList<String> graphemeSyllables = new ArrayList<String>(); ArrayList<String> phoneticSyllables = new ArrayList<String>(); int numChars, numPhons, numSyllables; double frequency; String suffixType, suffix; // Add this when it's possible // partOfSpeech word = results[0]; stem = results[1]; phonetic = results[2]; phoneticList = new ArrayList<GraphemePhonemePair>(); numPhons = 0; if(!results[2].contains("<")){ String[] phoneticMatches = results[3].split(","); for(String s : phoneticMatches){ String[] values = s.split("-", -1); if(values.length>2){ for(int i=1; i<values.length-1; i++){ values[0] += values[i]; if(values[i].isEmpty()) values[0] += "-"; } values[1] = values[values.length-1]; } GraphemePhonemePair pair = new GraphemePhonemePair(values[0], values[1]); phoneticList.add(pair); } numPhons = Integer.parseInt(results[9]); } suffixType = results[4]; suffix = results[5]; graphemeSyllables = new ArrayList<String>(Arrays.asList(results[6].split(","))); phoneticSyllables = new ArrayList<String>(Arrays.asList(results[7].split(","))); numChars = Integer.parseInt(results[8]); numSyllables = Integer.parseInt(results[10]); frequency = Double.parseDouble(results[11]); EnglishWord w = new EnglishWord(word, phonetic, stem, phoneticList, suffix, suffixType, numSyllables, frequency, WordType.Unknown); if(!dictionary.containsKey(word)){ dictionary.put(word, w); } } //Close the input stream br.close(); } catch (IOException e) { e.printStackTrace(); } } }
package org.xins.common.http; import org.xins.common.collections.PropertyReader; import org.xins.common.collections.PropertyReaderUtils; import org.xins.common.Log; import org.xins.common.MandatoryArgumentChecker; import org.xins.common.service.CallRequest; import org.xins.common.text.FastStringBuffer; import org.xins.common.text.TextUtils; /** * A request towards an HTTP service. * * <p>Since XINS 1.1.0, an HTTP method is not a mandatory property anymore. If * the HTTP method is not specified in a request, then it will from the * applicable {@link HTTPCallConfig}. * * @version $Revision$ $Date$ * @author Ernst de Haan (<a href="mailto:ernst.dehaan@nl.wanadoo.com">ernst.dehaan@nl.wanadoo.com</a>) * * @since XINS 1.0.0 * * @see HTTPServiceCaller */ public final class HTTPCallRequest extends CallRequest { // Class fields /** * Fully-qualified name of this class. */ private static final String CLASSNAME = HTTPCallRequest.class.getName(); /** * The number of instances of this class. Initially zero. */ private static int INSTANCE_COUNT; // Class functions // Constructors /** * Constructs a new <code>HTTPCallRequest</code> with the specified * parameters and status code verifier. * * @param parameters * the parameters for the HTTP call, can be <code>null</code> if there * are none to pass down. * * @param statusCodeVerifier * the HTTP status code verifier, or <code>null</code> if all HTTP * status codes are allowed. * * @since XINS 1.1.0 */ public HTTPCallRequest(PropertyReader parameters, HTTPStatusCodeVerifier statusCodeVerifier) { // Determine instance number first _instanceNumber = ++INSTANCE_COUNT; // TRACE: Enter constructor Log.log_1000(CLASSNAME, "#" + _instanceNumber); // Store information _parameters = (parameters != null) ? parameters : PropertyReaderUtils.EMPTY_PROPERTY_READER; _statusCodeVerifier = statusCodeVerifier; // TRACE: Leave constructor Log.log_1002(CLASSNAME, "#" + _instanceNumber); // Note that _asString is lazily initialized. } /** * Constructs a new <code>HTTPCallRequest</code> with the specified * parameters. * * @param parameters * the parameters for the HTTP call, can be <code>null</code> if there * are none to pass down. * * @since XINS 1.1.0 */ public HTTPCallRequest(PropertyReader parameters) { this(parameters, (HTTPStatusCodeVerifier) null); } /** * Constructs a new <code>HTTPCallRequest</code> with no parameters. * * @since XINS 1.1.0 */ public HTTPCallRequest() { this((PropertyReader) null, (HTTPStatusCodeVerifier) null); } /** * Constructs a new <code>HTTPCallRequest</code> with the specified HTTP * method. No arguments are be passed to the URL. Fail-over is disallowed, * unless the request was definitely not processed by the other end. * * @param method * the HTTP method to use, or <code>null</code> if the method should be * determined when the call is made * (<em>since XINS 1.1.0 this argument can be null</em>). * * @deprecated * Deprecated since XINS 1.1.0. * Use {@link #HTTPCallRequest(PropertyReader)} * instead, in combination with * {@link #setHTTPCallConfig(HTTPCallConfig)}. * This constructor is guaranteed not to be removed before XINS 2.0.0. */ public HTTPCallRequest(HTTPMethod method) { this(method, null, false, null); } /** * Constructs a new <code>HTTPCallRequest</code> with the specified HTTP * method and parameters. Fail-over is disallowed, unless the request was * definitely not processed by the other end. * * @param method * the HTTP method to use, or <code>null</code> if the method should be * determined when the call is made * (<em>since XINS 1.1.0 this argument can be null</em>). * * @param parameters * the parameters for the HTTP call, can be <code>null</code>. * * @deprecated * Deprecated since XINS 1.1.0. * Use {@link #HTTPCallRequest(PropertyReader)} * instead, in combination with * {@link #setHTTPCallConfig(HTTPCallConfig)}. * This constructor is guaranteed not to be removed before XINS 2.0.0. */ public HTTPCallRequest(HTTPMethod method, PropertyReader parameters) { this(method, parameters, false, null); } /** * Constructs a new <code>HTTPCallRequest</code> with the specified HTTP * method, parameters and status code verifier, optionally allowing * fail-over in all cases. * * @param method * the HTTP method to use, or <code>null</code> if the method should be * determined when the call is made * (<em>since XINS 1.1.0 this argument can be null</em>). * * @param parameters * the parameters for the HTTP call, can be <code>null</code>. * * @param failOverAllowed * flag that indicates whether fail-over is in principle allowed, even * if the request was already sent to the other end. * * @param statusCodeVerifier * the HTTP status code verifier, or <code>null</code> if all HTTP * status codes are allowed. * * @deprecated * Deprecated since XINS 1.1.0. * Use {@link #HTTPCallRequest(PropertyReader,HTTPStatusCodeVerifier)} * instead, in combination with * {@link #setHTTPCallConfig(HTTPCallConfig)}. * This constructor is guaranteed not to be removed before XINS 2.0.0. */ public HTTPCallRequest(HTTPMethod method, PropertyReader parameters, boolean failOverAllowed, HTTPStatusCodeVerifier statusCodeVerifier) throws IllegalArgumentException { this(parameters, statusCodeVerifier); // Create an HTTPCallConfig object HTTPCallConfig callConfig = new HTTPCallConfig(); callConfig.setFailOverAllowed(failOverAllowed); if (method != null) { callConfig.setMethod(method); } setCallConfig(callConfig); } // Fields /** * The 1-based sequence number of this instance. Since this number is * 1-based, the first instance of this class will have instance number 1 * assigned to it. */ private final int _instanceNumber; /** * Description of this HTTP call request. This field cannot be * <code>null</code>, it is initialized during construction. */ private String _asString; /** * The parameters for the HTTP call. This field cannot be * <code>null</code>, it is initialized during construction. */ private final PropertyReader _parameters; /** * The HTTP status code verifier, or <code>null</code> if all HTTP status * codes are allowed. */ private final HTTPStatusCodeVerifier _statusCodeVerifier; // Methods /** * Describes this request. * * @return * the description of this request, never <code>null</code>. */ public String describe() { // Lazily initialize the description of this call request object if (_asString == null) { FastStringBuffer buffer = new FastStringBuffer(193, "HTTP request // Request number buffer.append(_instanceNumber); // HTTP method buffer.append(" [config="); buffer.append(TextUtils.quote(getCallConfig())); // Parameters if (_parameters == null || _parameters.size() < 1) { buffer.append("; parameters=(null)"); } else { buffer.append("; parameters=\""); PropertyReaderUtils.serialize(_parameters, buffer, "(null)"); buffer.append('"'); } _asString = buffer.toString(); } return _asString; } /** * Returns the HTTP call configuration. * * @return * the HTTP call configuration object, or <code>null</code>. * * @since XINS 1.1.0 */ public HTTPCallConfig getHTTPCallConfig() { return (HTTPCallConfig) getCallConfig(); } /** * Sets the associated HTTP call configuration. * * @param callConfig * the HTTP call configuration object to associate with this request, or * <code>null</code>. * * @since XINS 1.1.0 */ public void setHTTPCallConfig(HTTPCallConfig callConfig) { setCallConfig(callConfig); } /** * Returns the HTTP method associated with this call request. * * <p><em>Since XINS 1.1.0, this method may return <code>null</code>.</em> * * @return * the HTTP method, or <code>null</code>. * * @deprecated * Deprecated since XINS 1.1.0. * Use {@link #getHTTPCallConfig()} instead. * This method is guaranteed not to be removed before XINS 2.0.0. */ public HTTPMethod getMethod() { HTTPCallConfig callConfig = getHTTPCallConfig(); if (callConfig == null) { return null; } else { return callConfig.getMethod(); } } /** * Returns the parameters associated with this call request. * * <p>Since XINS 1.1.0, this method will never return <code>null</code>. * * @return * the parameters, never <code>null</code>. */ public PropertyReader getParameters() { return _parameters; } /** * Determines whether fail-over is in principle allowed, even if the * request was already sent to the other end. * * @return * <code>true</code> if fail-over is in principle allowed, even if the * request was already sent to the other end, <code>false</code> * otherwise. */ public boolean isFailOverAllowed() { return getHTTPCallConfig().isFailOverAllowed(); } /** * Returns the HTTP status code verifier. If all HTTP status codes are * allowed, then <code>null</code> is returned. * * @return * the HTTP status code verifier, or <code>null</code>. */ public HTTPStatusCodeVerifier getStatusCodeVerifier() { return _statusCodeVerifier; } }
package org.xins.server; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.PrintWriter; import java.lang.reflect.Field; import java.util.Enumeration; import java.util.Properties; import javax.servlet.ServletConfig; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.log4j.Logger; import org.apache.log4j.PropertyConfigurator; import org.apache.log4j.helpers.NullEnumeration; import org.xins.util.MandatoryArgumentChecker; import org.xins.util.collections.BasicPropertyReader; import org.xins.util.collections.PropertiesPropertyReader; import org.xins.util.collections.PropertyReader; import org.xins.util.collections.ProtectedPropertyReader; import org.xins.util.io.FileWatcher; import org.xins.util.servlet.ServletConfigPropertyReader; /** * Servlet that forwards requests to an <code>API</code>. * * @version $Revision$ $Date$ * @author Ernst de Haan (<a href="mailto:znerd@FreeBSD.org">znerd@FreeBSD.org</a>) */ public final class APIServlet extends HttpServlet { // Class fields /** * The <em>INITIAL</em> state. */ private static final State INITIAL = new State("INITIAL"); /** * The <em>BOOTSTRAPPING_FRAMEWORK</em> state. */ private static final State BOOTSTRAPPING_FRAMEWORK = new State("BOOTSTRAPPING_FRAMEWORK"); /** * The <em>FRAMEWORK_BOOTSTRAP_FAILED</em> state. */ private static final State FRAMEWORK_BOOTSTRAP_FAILED = new State("FRAMEWORK_BOOTSTRAP_FAILED"); /** * The <em>CONSTRUCTING_API</em> state. */ private static final State CONSTRUCTING_API = new State("CONSTRUCTING_API"); /** * The <em>API_CONSTRUCTION_FAILED</em> state. */ private static final State API_CONSTRUCTION_FAILED = new State("API_CONSTRUCTION_FAILED"); /** * The <em>BOOTSTRAPPING_API</em> state. */ private static final State BOOTSTRAPPING_API = new State("BOOTSTRAPPING_API"); /** * The <em>API_BOOTSTRAP_FAILED</em> state. */ private static final State API_BOOTSTRAP_FAILED = new State("API_BOOTSTRAP_FAILED"); /** * The <em>INITIALIZING_API</em> state. */ private static final State INITIALIZING_API = new State("INITIALIZING_API"); /** * The <em>API_INITIALIZATION_FAILED</em> state. */ private static final State API_INITIALIZATION_FAILED = new State("API_INITIALIZATION_FAILED"); /** * The <em>READY</em> state. */ private static final State READY = new State("READY"); /** * The <em>DISPOSING</em> state. */ private static final State DISPOSING = new State("DISPOSING"); /** * The <em>DISPOSED</em> state. */ private static final State DISPOSED = new State("DISPOSED"); /** * The expected version of the Java Servlet Specification, major part. */ private static final int EXPECTED_SERVLET_VERSION_MAJOR = 2; /** * The expected version of the Java Servlet Specification, minor part. */ private static final int EXPECTED_SERVLET_VERSION_MINOR = 3; /** * The name of the system property that specifies the location of the * configuration file. */ public static final String CONFIG_FILE_SYSTEM_PROPERTY = "org.xins.server.config"; /** * The name of the configuration property that specifies the interval * for the configuration file modification checks, in seconds. */ public static final String CONFIG_RELOAD_INTERVAL_PROPERTY = "org.xins.server.config.reload"; /** * The default configuration file modification check interval, in seconds. */ public static final int DEFAULT_CONFIG_RELOAD_INTERVAL = 60; /** * The name of the build property that specifies the name of the * API class to load. */ public static final String API_CLASS_PROPERTY = "org.xins.api.class"; // Class functions // Constructors /** * Constructs a new <code>APIServlet</code> object. */ public APIServlet() { _stateLock = new Object(); _state = INITIAL; _configFileListener = new ConfigurationFileListener(); } // Fields /** * The current state. */ private State _state; /** * Lock for <code>_state</code> */ private final Object _stateLock; /** * The stored servlet configuration object. */ private ServletConfig _servletConfig; /** * The name of the configuration file. */ private String _configFile; /** * The API that this servlet forwards requests to. */ private API _api; /** * Description of the current error, if any. Will be returned by * {@link #service(HttpServletRequest,HttpServletResponse)} if and only if * the state is not {@link #READY}. */ private String _error; /** * The listener that is notified when the configuration file changes. Only * one instance is created ever. */ private final ConfigurationFileListener _configFileListener; /** * Configuration file watcher. */ private FileWatcher _configFileWatcher; // Methods /** * Initializes this servlet using the specified configuration. The * (required) {@link ServletConfig} argument is stored internally and is * returned from {@link #getServletConfig()}. * * <p>The initialization procedure will take required information from 3 * sources, initially: * * <dl> * <dt><strong>1. Build-time settings</strong></dt> * <dd>The application package contains a <code>web.xml</code> file with * build-time settings. Some of these settings are required in order * for the XINS/Java Server Framework to start up, while others are * optional. These build-time settings are passed to the servlet by * the application server as a {@link ServletConfig} object. See * {@link #init(ServletConfig)}. * <br />The servlet configuration is the responsibility of the * <em>assembler</em>.</dd> * * <dt><strong>2. System properties</strong></dt> * <dd>The location of the configuration file must be passed to the * Java VM at startup, as a system property. * <br />System properties are the responsibility of the * <em>system administrator</em>. * <br />Example: * <br /><code>java -Dorg.xins.server.config=`pwd`/conf/xins.properties orion.jar</code></dd> * * <dt><strong>3. Configuration file</strong></dt> * <dd>The configuration file should contain runtime configuration * settings, like the settings for the logging subsystem. * <br />System properties are the responsibility of the * <em>system administrator</em>. * <br />Example contents for a configuration file: * <blockquote><code>log4j.rootLogger=DEBUG, console * <br />log4j.appender.console=org.apache.log4j.ConsoleAppender * <br />log4j.appender.console.layout=org.apache.log4j.PatternLayout * <br />log4j.appender.console.layout.ConversionPattern=%d %-5p [%c] %m%n</code></blockquote> * </dl> * * @param config * the {@link ServletConfig} object which contains build properties for * this servlet, as specified by the <em>assembler</em>, cannot be * <code>null</code>. * * @throws ServletException * if <code>config == null</code>, if this servlet is not uninitialized * or if the initialization failed for some other reason. */ public void init(ServletConfig config) { // Checks and preparations // // Make sure the Library class is initialized String version = Library.getVersion(); // Get a reference to the appropriate logger Logger log = Library.BOOTSTRAP_LOG; // Check preconditions synchronized (_stateLock) { if (_state != INITIAL) { String message = "Application server malfunction detected. Cannot initialize servlet. State is " + _state + " instead of " + INITIAL + '.'; // This is not fatal, but an error, since the framework is already // initialized. log.error(message); throw new Error(message); } else if (config == null) { String message = "Application server malfunction detected. Cannot initialize servlet. No servlet configuration object passed."; log.fatal(message); throw new Error(message); } // Get the ServletContext ServletContext context = config.getServletContext(); if (context == null) { String message = "Application server malfunction detected. Cannot initialize servlet. No servlet context available."; log.fatal(message); throw new Error(message); } // Check the expected vs implemented Java Servlet API version int major = context.getMajorVersion(); int minor = context.getMinorVersion(); if (major != EXPECTED_SERVLET_VERSION_MAJOR || minor != EXPECTED_SERVLET_VERSION_MINOR) { log.warn("Application server implements Java Servlet API version " + major + '.' + minor + " instead of the expected version " + EXPECTED_SERVLET_VERSION_MAJOR + '.' + EXPECTED_SERVLET_VERSION_MINOR + ". The application may or may not work correctly."); } // Store the ServletConfig object, per the Servlet API Spec, see: // http://java.sun.com/products/servlet/2.3/javadoc/javax/servlet/Servlet.html#getServletConfig() _servletConfig = config; // Bootstrap framework // // Proceed to first actual stage _state = BOOTSTRAPPING_FRAMEWORK; log.debug("Bootstrapping XINS/Java Server Framework."); // Determine configuration file location try { _configFile = System.getProperty(CONFIG_FILE_SYSTEM_PROPERTY); } catch (SecurityException exception) { _state = FRAMEWORK_BOOTSTRAP_FAILED; _error = "System administration issue detected. Unable to get system property \"" + CONFIG_FILE_SYSTEM_PROPERTY + "\" due to a security restriction."; log.error(_error, exception); return; } // Property value must be set // NOTE: Don't trim the configuration file name, since it may start // with a space or other whitespace character. if (_configFile == null || _configFile.length() < 1) { _state = FRAMEWORK_BOOTSTRAP_FAILED; _error = "System administration issue detected. System property \"" + CONFIG_FILE_SYSTEM_PROPERTY + "\" is not set."; log.error(_error); return; } // Apply the properties to the framework PropertyReader runtimeProperties = applyConfigFile(log); // Construct API // // Proceed to next stage _state = CONSTRUCTING_API; log.debug("Constructing API."); // Determine the API class String apiClassName = config.getInitParameter(API_CLASS_PROPERTY); if (apiClassName == null || apiClassName.trim().length() < 1) { _state = API_CONSTRUCTION_FAILED; _error = "Invalid application package. API class name not set in build property \"" + API_CLASS_PROPERTY + "\"."; log.fatal(_error); return; } // Load the API class Class apiClass; try { apiClass = Class.forName(apiClassName); } catch (Throwable exception) { _state = API_CONSTRUCTION_FAILED; _error = "Invalid application package. Failed to load API class \"" + apiClassName + "\", as set in build property \"" + API_CLASS_PROPERTY + "\" due to unexpected " + exception.getClass().getName() + '.'; log.fatal(_error); return; } // Check that the loaded API class is derived from the API base class if (! API.class.isAssignableFrom(apiClass)) { _state = API_CONSTRUCTION_FAILED; _error = "Invalid application package. The \"" + apiClassName + "\" is not derived from class " + API.class.getName() + '.'; log.fatal(_error); return; } // Get the SINGLETON field Field singletonField; try { singletonField = apiClass.getDeclaredField("SINGLETON"); } catch (Exception exception) { _state = API_CONSTRUCTION_FAILED; _error = "Invalid application package. Failed to lookup class field SINGLETON in API class \"" + apiClassName + "\" due to unexpected " + exception.getClass().getName() + '.'; log.fatal(_error, exception); return; } // Get the value of the SINGLETON field try { _api = (API) singletonField.get(null); } catch (Exception exception) { _state = API_CONSTRUCTION_FAILED; _error = "Invalid application package. Failed to get value of the SINGLETON field of API class \"" + apiClassName + "\". Caught unexpected " + exception.getClass().getName() + '.'; log.fatal(_error, exception); return; } // Make sure that the field is an instance of that same class if (_api == null) { _state = API_CONSTRUCTION_FAILED; _error = "Invalid application package. The value of the SINGLETON field of API class \"" + apiClassName + "\" is null."; log.fatal(_error); return; } else if (_api.getClass() != apiClass) { _state = API_CONSTRUCTION_FAILED; _error = "Invalid application package. The value of the SINGLETON field of API class \"" + apiClassName + "\" is not an instance of that class."; log.fatal(_error); return; } // Get the name of the API String apiName = _api.getName(); log.debug("Constructed " + apiName + " API."); // Bootstrap API // // Proceed to next stage _state = BOOTSTRAPPING_API; log.debug("Bootstrapping " + apiName + " API."); try { _api.bootstrap(new ServletConfigPropertyReader(config)); } catch (Throwable exception) { _state = API_BOOTSTRAP_FAILED; _error = "Application package may be invalid. Unable to bootstrap \"" + apiName + "\" API due to unexpected " + exception.getClass().getName() + '.'; log.fatal(_error, exception); return; } log.info("Bootstrapped " + apiName + " API."); // Initialize the API // initAPI(runtimeProperties); // Watch the config file // // Get the runtime property String s = runtimeProperties.get(CONFIG_RELOAD_INTERVAL_PROPERTY); int interval; // If the property is set, parse it if (s != null && s.length() >= 1) { try { interval = Integer.parseInt(s); if (interval < 1) { log.error("System administration issue detected. Configuration file reload interval \"" + s + "\", specified in runtime property \"" + CONFIG_RELOAD_INTERVAL_PROPERTY + "\" is less than 1. Using fallback default of " + DEFAULT_CONFIG_RELOAD_INTERVAL + " second(s)."); interval = DEFAULT_CONFIG_RELOAD_INTERVAL; } else { log.debug("Using configuration file check interval of " + interval + " second(s) as specified in runtime property \"" + CONFIG_RELOAD_INTERVAL_PROPERTY + "\"."); } } catch (NumberFormatException nfe) { log.error("System administration issue detected. Unable to parse configuration file reload interval \"" + s + "\", specified in runtime property \"" + CONFIG_RELOAD_INTERVAL_PROPERTY + "\". Using fallback default of " + DEFAULT_CONFIG_RELOAD_INTERVAL + " second(s)."); interval = DEFAULT_CONFIG_RELOAD_INTERVAL; } // Otherwise, if the property is not set, use the default } else { log.debug("Property \"" + CONFIG_RELOAD_INTERVAL_PROPERTY + "\" is not set. Using fallback default configuration file reload interval of " + DEFAULT_CONFIG_RELOAD_INTERVAL + " second(s)."); interval = DEFAULT_CONFIG_RELOAD_INTERVAL; } // Create a file watch thread and start it _configFileWatcher = new FileWatcher(_configFile, interval, _configFileListener); log.info("Using config file \"" + _configFile + "\". Checking for modifications every " + interval + " second(s)."); _configFileWatcher.start(); } } /** * Initializes the API using the specified runtime settings. * * @param runtimeProperties * the runtime settings, guaranteed not to be <code>null</code>. */ private final void initAPI(PropertyReader runtimeProperties) { _state = INITIALIZING_API; try { _api.init(runtimeProperties); } catch (Throwable e) { _state = API_INITIALIZATION_FAILED; _error = "Failed to initialize " + _api.getName() + " API."; Library.INIT_LOG.error(_error, e); return; } _state = READY; } private PropertyReader applyConfigFile(Logger log) throws IllegalArgumentException { // Check preconditions MandatoryArgumentChecker.check("log", log); Properties properties = new Properties(); PropertyReader pr = new ProtectedPropertyReader(new Object()); try { FileInputStream in = new FileInputStream(_configFile); properties.load(in); pr = new PropertiesPropertyReader(properties); Library.configure(log, properties); } catch (FileNotFoundException exception) { log.error("System administration issue detected. Configuration file \"" + _configFile + "\" cannot be opened."); } catch (SecurityException exception) { log.error("System administration issue detected. Access denied while loading configuration file \"" + _configFile + "\"."); } catch (IOException exception) { log.error("System administration issue detected. Unable to read configuration", exception); } return pr; } /** * Returns the <code>ServletConfig</code> object which contains the * build properties for this servlet. The returned {@link ServletConfig} * object is the one passed to the {@link #init(ServletConfig)} method. * * @return * the {@link ServletConfig} object that was used to initialize this * servlet, not <code>null</code> if this servlet is indeed already * initialized. */ public ServletConfig getServletConfig() { return _servletConfig; } /** * Handles a request to this servlet. * * @param request * the servlet request, should not be <code>null</code>. * * @param response * the servlet response, should not be <code>null</code>. * * @throws ServletException * if the state of this servlet is not <em>ready</em>, or * if <code>request == null || response == null</code>. * * @throws IOException * if there is an error error writing to the response output stream. */ public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Determine current time long start = System.currentTimeMillis(); // Check arguments if (request == null || response == null) { String message = "Application server malfunction detected. "; if (request == null && response == null) { message += "Both request and response are null."; } else if (request == null) { message += "Request is null."; } else { message += "Response is null."; } Library.RUNTIME_LOG.error(message); throw new ServletException(message); } // Check the HTTP request method String method = request.getMethod(); boolean sendOutput = "GET".equals(method) || "POST".equals(method); if (!sendOutput) { if ("OPTIONS".equals(method)) { response.setContentLength(0); response.setHeader("Accept", "GET, HEAD, POST"); response.setStatus(HttpServletResponse.SC_OK); return; } else if ("HEAD".equals(method)) { response.setContentLength(0); } else { response.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED); return; } } // TODO: Use OutputStream instead of Writer, for improved performance // Call the API if the state is READY CallResult result; if (_state == READY) { result = _api.handleCall(start, request); // Otherwise return InternalError } else { BasicPropertyReader parameters = new BasicPropertyReader(); parameters.set("_message", _error); result = new BasicCallResult(false, "InternalError", parameters, null); } // Send the output only if GET or POST if (sendOutput) { // Determine the XSLT to link to String xslt = request.getParameter("_xslt"); // Send the XML output to the stream and flush PrintWriter out = response.getWriter(); response.setContentType("text/xml"); response.setStatus(HttpServletResponse.SC_OK); CallResultOutputter.output(out, result, xslt); out.flush(); } } /** * Returns information about this servlet, as plain text. * * @return * textual description of this servlet, not <code>null</code> and not an * empty character string. */ public String getServletInfo() { return "XINS/Java Server Framework " + Library.getVersion(); } /** * Destroys this servlet. A best attempt will be made to release all * resources. * * <p>After this method has finished, it will set the state to * <em>disposed</em>. In that state no more requests will be handled. */ public void destroy() { Library.SHUTDOWN_LOG.debug("Shutting down XINS/Java Server Framework."); synchronized (_stateLock) { // Set the state temporarily to DISPOSING _state = DISPOSING; // Destroy the API if (_api != null) { _api.destroy(); } // Set the state to DISPOSED _state = DISPOSED; } Library.SHUTDOWN_LOG.info("XINS/Java Server Framework shutdown completed."); } // Inner classes /** * State of an <code>APIServlet</code>. * * @version $Revision$ $Date$ * @author Ernst de Haan (<a href="mailto:znerd@FreeBSD.org">znerd@FreeBSD.org</a>) * * @since XINS 0.121 */ private static final class State extends Object { // Constructors private State(String name) throws IllegalArgumentException { // Check preconditions MandatoryArgumentChecker.check("name", name); _name = name; } // Fields /** * The name of this state. Cannot be <code>null</code>. */ private final String _name; // Methods /** * Returns the name of this state. * * @return * the name of this state, cannot be <code>null</code>. */ String getName() { return _name; } /** * Returns a textual representation of this object. * * @return * the name of this state, never <code>null</code>. */ public String toString() { return _name; } } /** * Listener that reloads the configuration file if it changes. * * @version $Revision$ $Date$ * @author Ernst de Haan (<a href="mailto:znerd@FreeBSD.org">znerd@FreeBSD.org</a>) * * @since XINS 0.121 */ private final class ConfigurationFileListener extends Object implements FileWatcher.Listener { // Constructors /** * Constructs a new <code>ConfigurationFileListener</code> object. */ private ConfigurationFileListener() { // empty } // Fields // Methods public void fileModified() { Logger log = Library.INIT_LOG; log.info("Configuration file \"" + _configFile + "\" is modified. Re-initializing XINS/Java Server Framework."); // Apply the new runtime settings to the logging subsystem PropertyReader runtimeProperties = applyConfigFile(log); // Re-initialize the API initAPI(runtimeProperties); // Determine the interval String s = runtimeProperties.get(CONFIG_RELOAD_INTERVAL_PROPERTY); int interval; // If the property is set, parse it if (s != null && s.length() >= 1) { try { interval = Integer.parseInt(s); if (interval < 1) { log.error("System administration issue detected. Configuration file reload interval \"" + s + "\", specified in runtime property \"" + CONFIG_RELOAD_INTERVAL_PROPERTY + "\" is less than 1. Using fallback default of " + DEFAULT_CONFIG_RELOAD_INTERVAL + " second(s)."); interval = DEFAULT_CONFIG_RELOAD_INTERVAL; } else { log.debug("Using configuration file check interval of " + interval + " second(s) as specified in runtime property \"" + CONFIG_RELOAD_INTERVAL_PROPERTY + "\"."); } } catch (NumberFormatException nfe) { log.error("System administration issue detected. Unable to parse configuration file reload interval \"" + s + "\", specified in runtime property \"" + CONFIG_RELOAD_INTERVAL_PROPERTY + "\". Using fallback default of " + DEFAULT_CONFIG_RELOAD_INTERVAL + " second(s)."); interval = DEFAULT_CONFIG_RELOAD_INTERVAL; } // Otherwise, if the property is not set, use the default } else { log.debug("Property \"" + CONFIG_RELOAD_INTERVAL_PROPERTY + "\" is not set. Using fallback default configuration file reload interval of " + DEFAULT_CONFIG_RELOAD_INTERVAL + " second(s)."); interval = DEFAULT_CONFIG_RELOAD_INTERVAL; } // Update the file watch interval _configFileWatcher.setInterval(interval); log.info("Using config file \"" + _configFile + "\". Checking for modifications every " + interval + " second(s)."); log.info("XINS/Java Server Framework re-initialized."); } public void fileNotFound() { Library.INIT_LOG.error("System administration issue detected. Configuration file \"" + _configFile + "\" cannot be opened."); } public void fileNotModified() { Library.INIT_LOG.debug("Configuration file \"" + _configFile + "\" is not modified."); } public void securityException(SecurityException exception) { Library.INIT_LOG.error("System administration issue detected. Access denied while reading file \"" + _configFile + "\"."); } } }
package com.astoev.cave.survey.activity.map; import android.content.Context; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.DashPathEffect; import android.graphics.Paint; import android.graphics.Point; import android.graphics.drawable.Drawable; import android.util.AttributeSet; import android.util.Log; import android.util.SparseArray; import android.util.SparseIntArray; import android.view.View; import com.astoev.cave.survey.Constants; import com.astoev.cave.survey.R; import com.astoev.cave.survey.activity.UIUtilities; import com.astoev.cave.survey.model.Gallery; import com.astoev.cave.survey.model.Leg; import com.astoev.cave.survey.model.Option; import com.astoev.cave.survey.model.Vector; import com.astoev.cave.survey.service.Options; import com.astoev.cave.survey.service.Workspace; import com.astoev.cave.survey.util.DaoUtil; import java.io.ByteArrayOutputStream; import java.util.ArrayList; import java.util.List; public class MapView extends View { public static final int POINT_RADIUS = 3; public static final int MIDDLE_POINT_RADIUS = 2; public static final int MEASURE_POINT_RADIUS = 2; public static final int CURR_POINT_RADIUS = 8; private final static int LABEL_DEVIATION_X = 10; private final static int LABEL_DEVIATION_Y = 15; private static final int [] GRID_STEPS = new int[] {20,10, 5, 5, 2, 2, 2, 2, 1, 1, 1}; private final int SPACING = 5; private final Paint polygonPaint = new Paint(); private final Paint polygonWidthPaint = new Paint(); private final Paint overlayPaint = new Paint(); private final Paint youAreHerePaint = new Paint(); private final Paint gridPaint = new Paint(); private final Paint vectorsPaint = new Paint(); private final Paint vectorPointPaint = new Paint(); private int scale = 10; private int mapCenterMoveX = 0; private int mapCenterMoveY = 0; private float initialMoveX = 0; private float initialMoveY = 0; private Point northCenter = new Point(); private List<Integer> processedLegs = new ArrayList<Integer>(); private SparseArray<Point2D> mapPoints = new SparseArray<Point2D>(); private SparseIntArray galleryColors = new SparseIntArray(); private SparseArray<String> galleryNames = new SparseArray<String>(); private boolean horizontalPlan = true; public MapView(Context context, AttributeSet attrs) { super(context, attrs); polygonPaint.setColor(Color.RED); polygonPaint.setStrokeWidth(2); polygonWidthPaint.setColor(Color.RED); polygonWidthPaint.setStrokeWidth(1); overlayPaint.setColor(Color.WHITE); youAreHerePaint.setColor(Color.WHITE); youAreHerePaint.setAlpha(50); // semi transparent white gridPaint.setColor(Color.parseColor("#11FFFFFF")); gridPaint.setStrokeWidth(1); vectorsPaint.setStrokeWidth(1); vectorsPaint.setStyle(Paint.Style.STROKE); vectorsPaint.setPathEffect(new DashPathEffect(new float[]{2, 6}, 0)); vectorsPaint.setAlpha(50); vectorPointPaint.setStrokeWidth(1); vectorPointPaint.setAlpha(50); // need to instruct that changes to the canvas will be made, otherwise the screen might become blank setWillNotDraw(false); } @Override public void onDraw(Canvas canvas) { // need to call parent super.onDraw(canvas); try { processedLegs.clear(); mapPoints.clear(); galleryColors.clear(); galleryNames.clear(); // prepare map surface int maxX = canvas.getWidth(); int maxY = canvas.getHeight(); int centerX; int centerY; if (horizontalPlan) { // starting from the center of the screen centerX = maxX / 2; centerY = maxY / 2; } else { // slightly more left for the vertical plan (advancing to right) centerX = maxX / 4; centerY = maxY / 2; } String azimuthUnits = Options.getOptionValue(Option.CODE_AZIMUTH_UNITS); String slopeUnits = Options.getOptionValue(Option.CODE_SLOPE_UNITS); int gridStepIndex = scale/5; // grid scale int gridStep = GRID_STEPS[gridStepIndex] * scale; // grid start int gridStartX = mapCenterMoveX % gridStep - SPACING + centerX - (centerX / gridStep) * gridStep; int gridStartY = mapCenterMoveY % gridStep - SPACING + centerY - (centerY / gridStep) * gridStep; // grid horizontal lines for (int x=0; x<maxX/gridStep; x++) { canvas.drawLine(x*gridStep + SPACING + gridStartX, SPACING, x*gridStep + SPACING + gridStartX, maxY - SPACING, gridPaint); } // grid vertical lines for (int y=0; y<maxY/gridStep; y++) { canvas.drawLine(SPACING, y*gridStep + SPACING + gridStartY, maxX - SPACING, y*gridStep + SPACING + gridStartY, gridPaint); } // load the points List<Leg> legs = DaoUtil.getCurrProjectLegs(true); String pointLabel; while (processedLegs.size() < legs.size()) { for (Leg l : legs) { if (processedLegs.size() == legs.size()) { break; } if (!processedLegs.contains(l.getId())) { // first leg ever Point2D first; if (processedLegs.size() == 0) { if (horizontalPlan) { first = new Point2D(Float.valueOf(centerX), Float.valueOf(centerY), l.getLeft(), l.getRight(), MapUtilities.getAzimuthInDegrees(l.getAzimuth(), azimuthUnits)); } else { first = new Point2D(Float.valueOf(centerX), Float.valueOf(centerY), l.getTop(), l.getDown(), MapUtilities.getSlopeInDegrees(l.getSlope(), slopeUnits)); } } else { // update previously created point with the correct values for left/right/up/down first = mapPoints.get(l.getFromPoint().getId()); if (horizontalPlan) { first.setLeft(l.getLeft()); first.setRight(l.getRight()); if (l.getAzimuth() != null) { first.setAngle(MapUtilities.getAzimuthInDegrees(l.getAzimuth(), azimuthUnits)); } else { first.setAngle(null); } } else { first.setLeft(l.getTop()); first.setRight(l.getDown()); if (l.getSlope() != null) { first.setAngle(MapUtilities.getSlopeInDegrees(l.getSlope(), slopeUnits)); } else { first.setAngle(null); } } } if (mapPoints.get(l.getFromPoint().getId()) == null) { if (!l.isMiddle()) { mapPoints.put(l.getFromPoint().getId(), first); } // draw first point if (!l.isMiddle()) { //color if (galleryColors.get(l.getGalleryId(), Constants.NOT_FOUND) == Constants.NOT_FOUND) { galleryColors.put(l.getGalleryId(), MapUtilities.getNextGalleryColor(galleryColors.size())); Gallery gallery = DaoUtil.getGallery(l.getGalleryId()); galleryNames.put(l.getGalleryId(), gallery.getName()); } polygonPaint.setColor(galleryColors.get(l.getGalleryId())); polygonWidthPaint.setColor(galleryColors.get(l.getGalleryId())); vectorsPaint.setColor(galleryColors.get(l.getGalleryId())); vectorPointPaint.setColor(galleryColors.get(l.getGalleryId())); DaoUtil.refreshPoint(l.getFromPoint()); pointLabel = galleryNames.get(l.getGalleryId()) + l.getFromPoint().getName(); if (scale >= 3) { canvas.drawText(pointLabel, mapCenterMoveX + first.getX() + LABEL_DEVIATION_X, mapCenterMoveY + first.getY() + LABEL_DEVIATION_Y, polygonPaint); } canvas.drawCircle(mapCenterMoveX + first.getX(), mapCenterMoveY + first.getY(), POINT_RADIUS, polygonPaint); } } float deltaX; float deltaY; if (horizontalPlan) { if (l.getDistance() == null || l.getAzimuth() == null) { deltaX = 0; deltaY = 0; } else { float legDistance; if (l.isMiddle()) { legDistance = MapUtilities.applySlopeToDistance(l.getMiddlePointDistance(), MapUtilities.getSlopeInDegrees(l.getSlope(), slopeUnits)); } else { legDistance = MapUtilities.applySlopeToDistance(l.getDistance(), MapUtilities.getSlopeInDegrees(l.getSlope(), slopeUnits)); } deltaY = -(float) (legDistance * Math.cos(Math.toRadians(MapUtilities.getAzimuthInDegrees(l.getAzimuth(), azimuthUnits)))) * scale; deltaX = (float) (legDistance * Math.sin(Math.toRadians(MapUtilities.getAzimuthInDegrees(l.getAzimuth(), azimuthUnits)))) * scale; } } else { if (l.getDistance() == null || l.getDistance() == 0) { deltaX = 0; deltaY = 0; } else { float legDistance; if (l.isMiddle()) { legDistance = l.getMiddlePointDistance(); } else { legDistance = l.getDistance(); } deltaY = (float) (legDistance * Math.cos(Math.toRadians(MapUtilities.add90Degrees(MapUtilities.getSlopeInDegrees(l.getSlope() == null ? 0 : l.getSlope(), slopeUnits))))) * scale; deltaX = (float) (legDistance * Math.sin(Math.toRadians(MapUtilities.add90Degrees(MapUtilities.getSlopeInDegrees(l.getSlope() == null ? 0 : l.getSlope(), slopeUnits))))) * scale; } } Point2D second = new Point2D(first.getX() + deltaX, first.getY() + deltaY); if (mapPoints.get(l.getToPoint().getId()) == null || l.isMiddle()) { if (!l.isMiddle()) { mapPoints.put(l.getToPoint().getId(), second); } // color if (galleryColors.get(l.getGalleryId(), Constants.NOT_FOUND) == Constants.NOT_FOUND) { galleryColors.put(l.getGalleryId(), MapUtilities.getNextGalleryColor(galleryColors.size())); Gallery gallery = DaoUtil.getGallery(l.getGalleryId()); galleryNames.put(l.getGalleryId(), gallery.getName()); } polygonPaint.setColor(galleryColors.get(l.getGalleryId())); polygonWidthPaint.setColor(galleryColors.get(l.getGalleryId())); vectorsPaint.setColor(galleryColors.get(l.getGalleryId())); vectorPointPaint.setColor(galleryColors.get(l.getGalleryId())); // Log.i(Constants.LOG_TAG_UI, "Drawing leg " + l.getFromPoint().getName() + ":" + l.getToPoint().getName() + "-" + l.getGalleryId()); if (Workspace.getCurrentInstance().getActiveLegId().equals(l.getId())) { // you are here if (l.isMiddle()) { canvas.drawCircle(mapCenterMoveX + second.getX(), mapCenterMoveY + second.getY(), CURR_POINT_RADIUS, youAreHerePaint); } else { canvas.drawCircle(mapCenterMoveX + first.getX(), mapCenterMoveY + first.getY(), CURR_POINT_RADIUS, youAreHerePaint); } } DaoUtil.refreshPoint(l.getToPoint()); if (l.isMiddle()) { canvas.drawCircle(mapCenterMoveX + second.getX(), mapCenterMoveY + second.getY(), MIDDLE_POINT_RADIUS, polygonPaint); } else { pointLabel = galleryNames.get(l.getGalleryId()) + l.getToPoint().getName(); if (scale >= 3) { canvas.drawText(pointLabel, mapCenterMoveX + second.getX() + LABEL_DEVIATION_X, mapCenterMoveY + second.getY() + LABEL_DEVIATION_Y, polygonPaint); } canvas.drawCircle(mapCenterMoveX + second.getX(), mapCenterMoveY + second.getY(), POINT_RADIUS, polygonPaint); } } // leg if (!l.isMiddle()) { canvas.drawLine(mapCenterMoveX + first.getX(), mapCenterMoveY + first.getY(), mapCenterMoveX + second.getX(), mapCenterMoveY + second.getY(), polygonPaint); } Leg prevLeg = DaoUtil.getLegByToPointId(l.getFromPoint().getId()); if (scale >= 5) { if (horizontalPlan) { // left calculateAndDrawSide(canvas, l, first, second, prevLeg, first.getLeft(), azimuthUnits, true); // right calculateAndDrawSide(canvas, l, first, second, prevLeg, first.getRight(), azimuthUnits, false); } else { // top calculateAndDrawSide(canvas, l, first, second, prevLeg, first.getLeft(), slopeUnits, true); // down calculateAndDrawSide(canvas, l, first, second, prevLeg, first.getRight(), slopeUnits, false); } } if (!l.isMiddle() && scale >= 10) { // vectors List<Vector> vectors = DaoUtil.getLegVectors(l); if (vectors != null) { for (Vector v : vectors) { if (horizontalPlan) { float legDistance = MapUtilities.applySlopeToDistance(v.getDistance(), MapUtilities.getSlopeInDegrees(v.getSlope(), slopeUnits)); deltaY = -(float) (legDistance * Math.cos(Math.toRadians(MapUtilities.getAzimuthInDegrees(v.getAzimuth(), azimuthUnits)))) * scale; deltaX = (float) (legDistance * Math.sin(Math.toRadians(MapUtilities.getAzimuthInDegrees(v.getAzimuth(), azimuthUnits)))) * scale; } else { float legDistance = v.getDistance(); deltaY = (float) (legDistance * Math.cos(Math.toRadians(MapUtilities.add90Degrees( MapUtilities.getSlopeInDegrees(MapUtilities.getSlopeOrHorizontallyIfMissing(v.getSlope()), slopeUnits))))) * scale; deltaX = (float) (legDistance * Math.sin(Math.toRadians(MapUtilities.add90Degrees( MapUtilities.getSlopeInDegrees(MapUtilities.getSlopeOrHorizontallyIfMissing(v.getSlope()), slopeUnits))))) * scale; } canvas.drawLine(mapCenterMoveX + first.getX(), mapCenterMoveY + first.getY(), mapCenterMoveX + first.getX() + deltaX, mapCenterMoveY + first.getY() + deltaY, vectorsPaint); canvas.drawCircle(mapCenterMoveX + first.getX() + deltaX, mapCenterMoveY + first.getY() + deltaY, 2, vectorPointPaint); } } } processedLegs.add(l.getId()); } } } // borders //top canvas.drawLine(SPACING, SPACING, maxX - SPACING, SPACING, overlayPaint); //right canvas.drawLine(maxX - SPACING, SPACING, maxX - SPACING, maxY - SPACING, overlayPaint); // bottom canvas.drawLine(SPACING, maxY - SPACING, maxX - SPACING, maxY - SPACING, overlayPaint); //left canvas.drawLine(SPACING, maxY - SPACING, SPACING, SPACING, overlayPaint); if (horizontalPlan) { // north arrow northCenter.set(maxX - 20, 30); canvas.drawLine(northCenter.x, northCenter.y, northCenter.x + 10, northCenter.y + 10, overlayPaint); canvas.drawLine(northCenter.x + 10, northCenter.y + 10, northCenter.x, northCenter.y - 20, overlayPaint); canvas.drawLine(northCenter.x, northCenter.y - 20, northCenter.x - 10, northCenter.y + 10, overlayPaint); canvas.drawLine(northCenter.x - 10, northCenter.y + 10, northCenter.x, northCenter.y, overlayPaint); canvas.drawText("N", northCenter.x + 5, northCenter.y - 10, overlayPaint); } else { // up wrrow northCenter.set(maxX - 15, 10); canvas.drawLine(northCenter.x + 1, northCenter.y, northCenter.x + 6, northCenter.y + 10, overlayPaint); canvas.drawLine(northCenter.x - 5, northCenter.y + 10, northCenter.x, northCenter.y, overlayPaint); canvas.drawLine(northCenter.x, northCenter.y -1, northCenter.x, northCenter.y + 20, overlayPaint); } // scale canvas.drawText("x" + scale, 25 + gridStep/2, 45, overlayPaint); canvas.drawLine(30, 25, 30, 35, overlayPaint); canvas.drawLine(30, 30, 30 + gridStep, 30, overlayPaint); canvas.drawLine(30 + gridStep, 25, 30 + gridStep, 35, overlayPaint); canvas.drawText(GRID_STEPS[gridStepIndex] + "m" , 25 + gridStep/2, 25, overlayPaint); } catch (Exception e) { Log.e(Constants.LOG_TAG_UI, "Failed to draw map activity", e); UIUtilities.showNotification(R.string.error); } } public void zoomOut() { scale invalidate(); } public void zoomIn() { scale++; invalidate(); } public boolean canZoomOut() { return scale > 1; } public boolean canZoomIn() { return scale < 50; } public boolean isHorizontalPlan() { return horizontalPlan; } public void setHorizontalPlan(boolean horizontalPlan) { this.horizontalPlan = horizontalPlan; scale = 10; mapCenterMoveX = 0; mapCenterMoveY = 0; invalidate(); } public void resetMove(float aX, float aY) { initialMoveX = aX; initialMoveY = aY; } public void move(float x, float y) { mapCenterMoveX += (x - initialMoveX); initialMoveX = x; mapCenterMoveY += (y - initialMoveY); initialMoveY = y; invalidate(); } public byte[] getPngDump() { // render Bitmap returnedBitmap = Bitmap.createBitmap(this.getWidth(), this.getHeight(),Bitmap.Config.ARGB_8888); Canvas canvas = new Canvas(returnedBitmap); Drawable bgDrawable = this.getBackground(); if (bgDrawable!=null) { bgDrawable.draw(canvas); } draw(canvas); // crop borders etc returnedBitmap = Bitmap.createBitmap(returnedBitmap, 6, 6, this.getWidth() - 50, this.getHeight() - 70); // return ByteArrayOutputStream buff = new ByteArrayOutputStream(); returnedBitmap.compress(Bitmap.CompressFormat.PNG, 50, buff); return buff.toByteArray(); } private void calculateAndDrawSide(Canvas canvas, Leg l, Point2D first, Point2D second, Leg prevLeg, Float aMeasure, String anUnits, boolean left) { double galleryWidthAngle; if (aMeasure != null && aMeasure > 0) { // first or middle by 90' if (prevLeg == null || l.isMiddle()) { float angle = first.getAngle(); if (horizontalPlan) { if (left) { angle = MapUtilities.minus90Degrees(angle); } else { angle = MapUtilities.add90Degrees(angle); } } else { if (left) { angle = Option.MIN_VALUE_AZIMUTH; } else { angle = Option.MAX_VALUE_AZIMUTH_DEGREES / 2; } } galleryWidthAngle = Math.toRadians(angle); } else { float angle = first.getAngle(); // each next in the gallery by the bisector if (l.getGalleryId().equals(prevLeg.getGalleryId())) { if (horizontalPlan) { angle = MapUtilities.getMiddleAngle(MapUtilities.getAzimuthInDegrees(prevLeg.getAzimuth(), anUnits), angle); if (left) { angle = MapUtilities.minus90Degrees(angle); } else { angle = MapUtilities.add90Degrees(angle); } } else { if (left) { angle = Option.MIN_VALUE_AZIMUTH; } else { angle = Option.MAX_VALUE_AZIMUTH_DEGREES / 2; } } } else { // new galleries again by 90' if (horizontalPlan) { if (left) { angle = MapUtilities.minus90Degrees(angle); } else { angle = MapUtilities.add90Degrees(angle); } } else { if (left) { angle = Option.MIN_VALUE_AZIMUTH; } else { angle = Option.MAX_VALUE_AZIMUTH_DEGREES / 2; } } } galleryWidthAngle = Math.toRadians(angle); } float deltaY = -(float) (aMeasure * Math.cos(galleryWidthAngle) * scale); float deltaX = (float) (aMeasure * Math.sin(galleryWidthAngle) * scale); drawSideMeasurePoint(canvas, l.isMiddle(), first, second, deltaX, deltaY); } } private void drawSideMeasurePoint(Canvas aCanvas, boolean isMiddle, Point2D aFirst, Point2D aSecond, float aDeltaX, float aDeltaY) { if (isMiddle) { aCanvas.drawCircle(mapCenterMoveX + aSecond.getX() + aDeltaX, mapCenterMoveY + aSecond.getY() + aDeltaY, MEASURE_POINT_RADIUS, polygonWidthPaint); } else { aCanvas.drawCircle(mapCenterMoveX + aFirst.getX() + aDeltaX, mapCenterMoveY + aFirst.getY() + aDeltaY, MEASURE_POINT_RADIUS, polygonWidthPaint); } } }
// $Id: PlaceController.java,v 1.13 2004/08/16 22:57:44 mdb Exp $ package com.threerings.crowd.client; import java.awt.event.ActionEvent; import java.util.ArrayList; import com.samskivert.swing.Controller; import com.threerings.crowd.data.PlaceConfig; import com.threerings.crowd.data.PlaceObject; import com.threerings.crowd.util.CrowdContext; /** * Controls the user interface that is used to display a place. When the * client moves to a new place, the appropriate place controller is * constructed and requested to create and display the appopriate user * interface for that place. */ public abstract class PlaceController extends Controller { /** * Initializes this place controller with a reference to the context * that they can use to access client services and to the * configuration record for this place. The controller should create * as much of its user interface that it can without having access to * the place object because this will be invoked in parallel with the * fetching of the place object. When the place object is obtained, * the controller will be notified and it can then finish the user * interface configuration and put the user interface into operation. * * @param ctx the client context. * @param config the place configuration for this place. */ public void init (CrowdContext ctx, PlaceConfig config) { // keep these around _ctx = ctx; _config = config; // create our user interface _view = createPlaceView(); // initialize our delegates applyToDelegates(new DelegateOp() { public void apply (PlaceControllerDelegate delegate) { delegate.init(_ctx, _config); } }); // let the derived classes do any initialization stuff didInit(); } /** * Derived classes can override this and perform any * initialization-time processing they might need. They should of * course be sure to call <code>super.didInit()</code>. */ protected void didInit () { } /** * Returns a reference to the place view associated with this * controller. This is only valid after a call has been made to {@link * #init}. */ public PlaceView getPlaceView () { return _view; } /** * Returns the {@link PlaceConfig} associated with this place. */ public PlaceConfig getPlaceConfig () { return _config; } /** * Creates the user interface that will be used to display this place. * The view instance returned will later be configured with the place * object, once it becomes available. */ protected abstract PlaceView createPlaceView (); /** * This is called by the location director once the place object has * been fetched. The place controller will dispatch the place object * to the user interface hierarchy via {@link * PlaceViewUtil#dispatchWillEnterPlace}. Derived classes can override * this and perform any other starting up that they need to do */ public void willEnterPlace (final PlaceObject plobj) { // keep a handle on our place object _plobj = plobj; if (_view != null ) { // let the UI hierarchy know that we've got our place PlaceViewUtil.dispatchWillEnterPlace(_view, plobj); // and display the user interface _ctx.setPlaceView(_view); } // let our delegates know what's up applyToDelegates(new DelegateOp() { public void apply (PlaceControllerDelegate delegate) { delegate.willEnterPlace(plobj); } }); } /** * Called before a request is submitted to the server to leave the * current place. As such, this method may be called multiple times * before {@link #didLeavePlace} is finally called. The request to * leave may be rejected, but if a place controller needs to flush any * information to the place manager before it leaves, it should so do * here. This is the only place in which the controller is guaranteed * to be able to communicate to the place manager, as by the time * {@link #didLeavePlace} is called, the place manager may have * already been destroyed. */ public void mayLeavePlace (final PlaceObject plobj) { // let our delegates know what's up applyToDelegates(new DelegateOp() { public void apply (PlaceControllerDelegate delegate) { delegate.mayLeavePlace(plobj); } }); } /** * This is called by the location director when we are leaving this * place and need to clean up after ourselves and shutdown. Derived * classes should override this method (being sure to call * <code>super.didLeavePlace</code>) and perform any necessary * cleanup. */ public void didLeavePlace (final PlaceObject plobj) { // let our delegates know what's up applyToDelegates(new DelegateOp() { public void apply (PlaceControllerDelegate delegate) { delegate.didLeavePlace(plobj); } }); // let the UI hierarchy know that we're outta here if (_view != null ) { PlaceViewUtil.dispatchDidLeavePlace(_view, plobj); _ctx.clearPlaceView(_view); _view = null; } _plobj = null; } /** * Handles basic place controller action events. Derived classes * should be sure to call <code>super.handleAction</code> for events * they don't specifically handle. */ public boolean handleAction (final ActionEvent action) { final boolean[] handled = new boolean[1]; // let our delegates have a crack at the action applyToDelegates(new DelegateOp() { public void apply (PlaceControllerDelegate delegate) { // we take advantage of short-circuiting here handled[0] = handled[0] || delegate.handleAction(action); } }); // if they didn't handly it, pass it off to the super class return handled[0] ? true : super.handleAction(action); } /** * Adds the supplied delegate to the list for this controller. */ protected void addDelegate (PlaceControllerDelegate delegate) { if (_delegates == null) { _delegates = new ArrayList(); } _delegates.add(delegate); } /** * Used to call methods in delegates. */ protected static interface DelegateOp { public void apply (PlaceControllerDelegate delegate); } /** * Applies the supplied operation to the registered delegates. */ protected void applyToDelegates (DelegateOp op) { if (_delegates != null) { int dcount = _delegates.size(); for (int i = 0; i < dcount; i++) { op.apply((PlaceControllerDelegate)_delegates.get(i)); } } } /** * Applies the supplied operation to the registered delegates that * derive from the specified class. */ protected void applyToDelegates (Class dclass, DelegateOp op) { if (_delegates != null) { int dcount = _delegates.size(); for (int i = 0; i < dcount; i++) { PlaceControllerDelegate delegate = (PlaceControllerDelegate)_delegates.get(i); if (dclass.isAssignableFrom(delegate.getClass())) { op.apply(delegate); } } } } /** A reference to the active client context. */ protected CrowdContext _ctx; /** A reference to our place configuration. */ protected PlaceConfig _config; /** A reference to the place object for which we're controlling a user * interface. */ protected PlaceObject _plobj; /** A reference to the root user interface component. */ protected PlaceView _view; /** A list of the delegates in use by this controller. */ protected ArrayList _delegates; }
// Narya library - tools for developing networked games // This library is free software; you can redistribute it and/or modify it // (at your option) any later version. // This library is distributed in the hope that it will be useful, // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // You should have received a copy of the GNU Lesser General Public // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA package com.threerings.parlor.card.client; import java.awt.Color; import java.awt.Graphics2D; import java.awt.Point; import java.awt.Rectangle; import java.awt.event.MouseEvent; import java.util.ArrayList; import java.util.Iterator; import javax.swing.event.MouseInputAdapter; import com.samskivert.util.ObserverList; import com.samskivert.util.QuickSort; import com.threerings.media.FrameManager; import com.threerings.media.VirtualMediaPanel; import com.threerings.media.image.Mirage; import com.threerings.media.sprite.PathAdapter; import com.threerings.media.sprite.Sprite; import com.threerings.media.util.LinePath; import com.threerings.media.util.Path; import com.threerings.media.util.PathSequence; import com.threerings.media.util.Pathable; import com.threerings.parlor.card.Log; import com.threerings.parlor.card.data.Card; import com.threerings.parlor.card.data.CardCodes; import com.threerings.parlor.card.data.Deck; import com.threerings.parlor.card.data.Hand; /** * Extends VirtualMediaPanel to provide services specific to rendering * and manipulating playing cards. */ public abstract class CardPanel extends VirtualMediaPanel implements CardCodes { /** The selection mode in which cards are not selectable. */ public static final int NONE = 0; /** The selection mode in which the user can select a single card. */ public static final int SINGLE = 2; /** The selection mode in which the user can select multiple cards. */ public static final int MULTIPLE = 3; /** * A predicate class for {@link CardSprite}s. Provides control over which * cards are selectable, playable, etc. */ public static interface CardSpritePredicate { /** * Evaluates the specified sprite. */ public boolean evaluate (CardSprite sprite); } /** * A listener for card selection/deselection. */ public static interface CardSelectionObserver { /** * Called when a card has been selected. */ public void cardSpriteSelected (CardSprite sprite); /** * Called when a card has been deselected. */ public void cardSpriteDeselected (CardSprite sprite); } /** * Constructor. * * @param frameManager the frame manager */ public CardPanel (FrameManager frameManager) { super(frameManager); // add a listener for mouse events CardListener cl = new CardListener(); addMouseListener(cl); addMouseMotionListener(cl); } /** * Returns the full-sized image for the back of a playing card. */ public abstract Mirage getCardBackImage (); /** * Returns the full-sized image for the front of the specified card. */ public abstract Mirage getCardImage (Card card); /** * Returns the small-sized image for the back of a playing card. */ public abstract Mirage getMicroCardBackImage (); /** * Returns the small-sized image for the front of the specified card. */ public abstract Mirage getMicroCardImage (Card card); /** * Sets the location of the hand (the location of the center of the hand's * upper edge). */ public void setHandLocation (int x, int y) { _handLocation.setLocation(x, y); } /** * Sets the horizontal spacing between cards in the hand. */ public void setHandSpacing (int spacing) { _handSpacing = spacing; } /** * Sets the vertical distance to offset cards that are selectable or * playable. */ public void setSelectableCardOffset (int offset) { _selectableCardOffset = offset; } /** * Sets the vertical distance to offset cards that are selected. */ public void setSelectedCardOffset (int offset) { _selectedCardOffset = offset; } /** * Sets the selection mode for the hand (NONE, PLAY_SINGLE, SINGLE, * or MULTIPLE). Changing the selection mode does not change the * current selection. */ public void setHandSelectionMode (int mode) { _handSelectionMode = mode; // update the offsets of all cards in the hand updateHandOffsets(); } /** * Sets the selection predicate that determines which cards from the hand * may be selected (if null, all cards may be selected). Changing the * predicate does not change the current selection. */ public void setHandSelectionPredicate (CardSpritePredicate pred) { _handSelectionPredicate = pred; // update the offsets of all cards in the hand updateHandOffsets(); } /** * Returns the currently selected hand sprite (null if no sprites are * selected, the first sprite if multiple sprites are selected). */ public CardSprite getSelectedHandSprite () { return _selectedHandSprites.size() == 0 ? null : (CardSprite)_selectedHandSprites.get(0); } /** * Returns an array containing the currently selected hand sprites * (returns an empty array if no sprites are selected). */ public CardSprite[] getSelectedHandSprites () { return (CardSprite[])_selectedHandSprites.toArray( new CardSprite[_selectedHandSprites.size()]); } /** * Programmatically selects a sprite in the hand. */ public void selectHandSprite (final CardSprite sprite) { // make sure it's not already selected if (_selectedHandSprites.contains(sprite)) { return; } // if in single card mode and there's another card selected, // deselect it if (_handSelectionMode == SINGLE) { CardSprite oldSprite = getSelectedHandSprite(); if (oldSprite != null) { deselectHandSprite(oldSprite); } } // add to list and update offset _selectedHandSprites.add(sprite); sprite.setLocation(sprite.getX(), getHandY(sprite)); // notify the observers ObserverList.ObserverOp op = new ObserverList.ObserverOp() { public boolean apply (Object obs) { ((CardSelectionObserver)obs).cardSpriteSelected(sprite); return true; } }; _handSelectionObservers.apply(op); } /** * Programmatically deselects a sprite in the hand. */ public void deselectHandSprite (final CardSprite sprite) { // make sure it's selected if (!_selectedHandSprites.contains(sprite)) { return; } // remove from list and update offset _selectedHandSprites.remove(sprite); sprite.setLocation(sprite.getX(), getHandY(sprite)); // notify the observers ObserverList.ObserverOp op = new ObserverList.ObserverOp() { public boolean apply (Object obs) { ((CardSelectionObserver)obs).cardSpriteDeselected(sprite); return true; } }; _handSelectionObservers.apply(op); } /** * Clears any existing hand sprite selection. */ public void clearHandSelection () { CardSprite[] sprites = getSelectedHandSprites(); for (int i = 0; i < sprites.length; i++) { deselectHandSprite(sprites[i]); } } /** * Adds an object to the list of observers to notify when cards in the * hand are selected/deselected. */ public void addHandSelectionObserver (CardSelectionObserver obs) { _handSelectionObservers.add(obs); } /** * Removes an object from the hand selection observer list. */ public void removeHandSelectionObserver (CardSelectionObserver obs) { _handSelectionObservers.remove(obs); } /** * Fades a hand of cards in. * * @param hand the hand of cards * @param fadeDuration the amount of time to spend fading in * the entire hand */ public void setHand (Hand hand, long fadeDuration) { // make sure no cards are hanging around clearHand(); // create the sprites int size = hand.size(); for (int i = 0; i < size; i++) { CardSprite cs = new CardSprite(this, (Card)hand.get(i)); _handSprites.add(cs); } // sort them QuickSort.sort(_handSprites); // fade them in at proper locations and layers long cardDuration = fadeDuration / size; for (int i = 0; i < size; i++) { CardSprite cs = (CardSprite)_handSprites.get(i); cs.setLocation(getHandX(size, i), _handLocation.y); cs.setRenderOrder(i); cs.addSpriteObserver(_handSpriteObserver); addSprite(cs); cs.fadeIn(i * cardDuration, cardDuration); } // make sure we have the right card sprite active updateActiveCardSprite(); } /** * Fades a hand of cards in face-down. * * @param size the size of the hand * @param fadeDuration the amount of time to spend fading in * each card */ public void setHand (int size, long fadeDuration) { // fill hand will null entries to signify unknown cards Hand hand = new Hand(); for (int i = 0; i < size; i++) { hand.add(null); } setHand(hand, fadeDuration); } /** * Shows a hand that was previous set face-down. * * @param hand the hand of cards */ public void showHand (Hand hand) { // sort the hand QuickSort.sort(hand); // set the sprites int len = Math.min(_handSprites.size(), hand.size()); for (int i = 0; i < len; i++) { CardSprite cs = (CardSprite)_handSprites.get(i); cs.setCard((Card)hand.get(i)); } } /** * Returns the first sprite in the hand that corresponds to the * specified card, or null if the card is not in the hand. */ public CardSprite getHandSprite (Card card) { return getCardSprite(_handSprites, card); } /** * Clears all cards from the hand. */ public void clearHand () { clearHandSelection(); clearSprites(_handSprites); } /** * Clears all cards from the board. */ public void clearBoard () { clearSprites(_boardSprites); } /** * Flies a set of cards from the hand into the ether. Clears any selected * cards. * * @param cards the card sprites to remove from the hand * @param dest the point to fly the cards to * @param flightDuration the duration of the cards' flight * @param fadePortion the amount of time to spend fading out * as a proportion of the flight duration */ public void flyFromHand (CardSprite[] cards, Point dest, long flightDuration, float fadePortion) { // fly each sprite over, removing it from the hand immediately and // from the board when it finishes its path for (int i = 0; i < cards.length; i++) { removeFromHand(cards[i]); LinePath flight = new LinePath(dest, flightDuration); cards[i].addSpriteObserver(_pathEndRemover); cards[i].moveAndFadeOut(flight, flightDuration, fadePortion); } // adjust the hand to cover the hole adjustHand(flightDuration, false); } /** * Flies a set of cards from the ether into the hand. Clears any selected * cards. The cards will first fly to the selected card offset, pause for * the specified duration, and then drop into the hand. * * @param cards the cards to add to the hand * @param src the point to fly the cards from * @param flightDuration the duration of the cards' flight * @param pauseDuration the duration of the pause before dropping into the * hand * @param dropDuration the duration of the cards' drop into the * hand * @param fadePortion the amount of time to spend fading in * as a proportion of the flight duration */ public void flyIntoHand (Card[] cards, Point src, long flightDuration, long pauseDuration, long dropDuration, float fadePortion) { // first create the sprites and add them to the list CardSprite[] sprites = new CardSprite[cards.length]; for (int i = 0; i < cards.length; i++) { sprites[i] = new CardSprite(this, cards[i]); _handSprites.add(sprites[i]); } // settle the hand adjustHand(flightDuration, true); // then set the layers and fly the cards in int size = _handSprites.size(); for (int i = 0; i < sprites.length; i++) { int idx = _handSprites.indexOf(sprites[i]); sprites[i].setLocation(src.x, src.y); sprites[i].setRenderOrder(idx); sprites[i].addSpriteObserver(_handSpriteObserver); addSprite(sprites[i]); // create a path sequence containing flight, pause, and drop ArrayList paths = new ArrayList(); Point hp2 = new Point(getHandX(size, idx), _handLocation.y), hp1 = new Point(hp2.x, hp2.y - _selectedCardOffset); paths.add(new LinePath(hp1, flightDuration)); paths.add(new LinePath(hp1, pauseDuration)); paths.add(new LinePath(hp2, dropDuration)); sprites[i].moveAndFadeIn(new PathSequence(paths), flightDuration + pauseDuration + dropDuration, fadePortion); } } /** * Flies a set of cards from the ether into the ether. * * @param cards the cards to fly across * @param src the point to fly the cards from * @param dest the point to fly the cards to * @param flightDuration the duration of the cards' flight * @param cardDelay the amount of time to wait between cards * @param fadePortion the amount of time to spend fading in and out * as a proportion of the flight duration */ public void flyAcross (Card[] cards, Point src, Point dest, long flightDuration, long cardDelay, float fadePortion) { for (int i = 0; i < cards.length; i++) { // add on top of all board sprites CardSprite cs = new CardSprite(this, cards[i]); cs.setRenderOrder(getHighestBoardLayer() + 1 + i); cs.setLocation(src.x, src.y); addSprite(cs); // prepend an initial delay to all cards after the first Path path; long pathDuration; LinePath flight = new LinePath(dest, flightDuration); if (i > 0) { long delayDuration = cardDelay * i; LinePath delay = new LinePath(src, delayDuration); path = new PathSequence(delay, flight); pathDuration = delayDuration + flightDuration; } else { path = flight; pathDuration = flightDuration; } cs.addSpriteObserver(_pathEndRemover); cs.moveAndFadeInAndOut(path, pathDuration, fadePortion); } } /** * Flies a set of cards from the ether into the ether face-down. * * @param number the number of cards to fly across * @param src the point to fly the cards from * @param dest the point to fly the cards to * @param flightDuration the duration of the cards' flight * @param cardDelay the amount of time to wait between cards * @param fadePortion the amount of time to spend fading in and out * as a proportion of the flight duration */ public void flyAcross (int number, Point src, Point dest, long flightDuration, long cardDelay, float fadePortion) { // use null values to signify unknown cards flyAcross(new Card[number], src, dest, flightDuration, cardDelay, fadePortion); } /** * Flies a card from the hand onto the board. Clears any cards selected. * * @param card the sprite to remove from the hand * @param dest the point to fly the card to * @param flightDuration the duration of the card's flight */ public void flyFromHandToBoard (CardSprite card, Point dest, long flightDuration) { // fly it over LinePath flight = new LinePath(dest, flightDuration); card.move(flight); // lower the board so that the card from hand is on top lowerBoardSprites(card.getRenderOrder() - 1); // move from one list to the other removeFromHand(card); _boardSprites.add(card); // adjust the hand to cover the hole adjustHand(flightDuration, false); } /** * Flies a card from the ether onto the board. * * @param card the card to add to the board * @param src the point to fly the card from * @param dest the point to fly the card to * @param flightDuration the duration of the card's flight * @param fadePortion the amount of time to spend fading in as a * proportion of the flight duration */ public void flyToBoard (Card card, Point src, Point dest, long flightDuration, float fadePortion) { // add it on top of the existing cards CardSprite cs = new CardSprite(this, card); cs.setRenderOrder(getHighestBoardLayer() + 1); cs.setLocation(src.x, src.y); addSprite(cs); _boardSprites.add(cs); // and fly it over LinePath flight = new LinePath(dest, flightDuration); cs.moveAndFadeIn(flight, flightDuration, fadePortion); } /** * Adds a card to the board immediately. * * @param card the card to add to the board * @param dest the point at which to add the card */ public void addToBoard (Card card, Point dest) { CardSprite cs = new CardSprite(this, card); cs.setRenderOrder(getHighestBoardLayer() + 1); cs.setLocation(dest.x, dest.y); addSprite(cs); _boardSprites.add(cs); } /** * Flies a set of cards from the board into the ether. * * @param cards the cards to remove from the board * @param dest the point to fly the cards to * @param flightDuration the duration of the cards' flight * @param fadePortion the amount of time to spend fading out as a * proportion of the flight duration */ public void flyFromBoard (CardSprite[] cards, Point dest, long flightDuration, float fadePortion) { for (int i = 0; i < cards.length; i++) { LinePath flight = new LinePath(dest, flightDuration); cards[i].addSpriteObserver(_pathEndRemover); cards[i].moveAndFadeOut(flight, flightDuration, fadePortion); _boardSprites.remove(cards[i]); } } // documentation inherited protected void paintBehind (Graphics2D gfx, Rectangle dirtyRect) { gfx.setColor(DEFAULT_BACKGROUND); gfx.fill(dirtyRect); super.paintBehind(gfx, dirtyRect); } /** * Flies a set of cards from the board into the ether through an * intermediate point. * * @param cards the cards to remove from the board * @param dest1 the first point to fly the cards to * @param dest2 the final destination of the cards * @param flightDuration the duration of the cards' flight * @param fadePortion the amount of time to spend fading out as a * proportion of the flight duration */ public void flyFromBoard (CardSprite[] cards, Point dest1, Point dest2, long flightDuration, float fadePortion) { for (int i = 0; i < cards.length; i++) { PathSequence flight = new PathSequence( new LinePath(dest1, flightDuration/2), new LinePath(dest1, dest2, flightDuration/2)); cards[i].addSpriteObserver(_pathEndRemover); cards[i].moveAndFadeOut(flight, flightDuration, fadePortion); _boardSprites.remove(cards[i]); } } /** * Returns the first card sprite in the specified list that represents * the specified card, or null if there is no such sprite in the list. */ protected CardSprite getCardSprite (ArrayList list, Card card) { for (int i = 0; i < list.size(); i++) { CardSprite cs = (CardSprite)list.get(i); if (card.equals(cs.getCard())) { return cs; } } return null; } /** * Expands or collapses the hand to accommodate new cards or cover the * space left by removed cards. Skips unmanaged sprites. Clears out * any selected cards. * * @param adjustDuration the amount of time to spend settling the cards * into their new locations * @param updateLayers whether or not to update the layers of the cards */ protected void adjustHand (long adjustDuration, boolean updateLayers) { // clear out selected cards clearHandSelection(); // Sort the hand QuickSort.sort(_handSprites); // Move each card to its proper position (and, optionally, layer) int size = _handSprites.size(); for (int i = 0; i < size; i++) { CardSprite cs = (CardSprite)_handSprites.get(i); if (!isManaged(cs)) { continue; } if (updateLayers) { removeSprite(cs); cs.setRenderOrder(i); addSprite(cs); } LinePath adjust = new LinePath(new Point(getHandX(size, i), _handLocation.y), adjustDuration); cs.move(adjust); } } /** * Removes a card from the hand. */ protected void removeFromHand (CardSprite card) { _selectedHandSprites.remove(card); _handSprites.remove(card); } /** * Updates the offsets of all the cards in the hand. If there is only * one selectable card, that card will always be raised slightly. */ protected void updateHandOffsets () { // make active card sprite is up-to-date updateActiveCardSprite(); int size = _handSprites.size(); for (int i = 0; i < size; i++) { CardSprite cs = (CardSprite)_handSprites.get(i); if (!cs.isMoving()) { cs.setLocation(cs.getX(), getHandY(cs)); } } } /** * Given the location and spacing of the hand, returns the x location of * the card at the specified index within a hand of the specified size. */ protected int getHandX (int size, int idx) { // get the card width from the image if not yet known if (_cardWidth == 0) { _cardWidth = getCardBackImage().getWidth(); } // first compute the width of the entire hand, then use that to // determine the centered location int width = (size - 1) * _handSpacing + _cardWidth; return (_handLocation.x - width/2) + idx * _handSpacing; } /** * Determines the y location of the specified card sprite, given its * selection state. */ protected int getHandY (CardSprite sprite) { if (_selectedHandSprites.contains(sprite)) { return _handLocation.y - _selectedCardOffset; } else if (isSelectable(sprite) && (sprite == _activeCardSprite || isOnlySelectable(sprite))) { return _handLocation.y - _selectableCardOffset; } else { return _handLocation.y; } } /** * Given the current selection mode and predicate, determines if the * specified sprite is selectable. */ protected boolean isSelectable (CardSprite sprite) { return _handSelectionMode != NONE && (_handSelectionPredicate == null || _handSelectionPredicate.evaluate(sprite)); } /** * Determines whether the specified sprite is the only selectable sprite * in the hand according to the selection predicate. */ protected boolean isOnlySelectable (CardSprite sprite) { // if there's no predicate, last remaining card is only selectable if (_handSelectionPredicate == null) { return _handSprites.size() == 1 && _handSprites.contains(sprite); } // otherwise, look for a sprite that fits the predicate and isn't the // parameter int size = _handSprites.size(); for (int i = 0; i < size; i++) { CardSprite cs = (CardSprite)_handSprites.get(i); if (cs != sprite && _handSelectionPredicate.evaluate(cs)) { return false; } } return true; } /** * Lowers all board sprites so that they are rendered at or below the * specified layer. */ protected void lowerBoardSprites (int layer) { // see if they're already lower int highest = getHighestBoardLayer(); if (highest <= layer) { return; } // lower them just enough int size = _boardSprites.size(), adjustment = layer - highest; for (int i = 0; i < size; i++) { CardSprite cs = (CardSprite)_boardSprites.get(i); removeSprite(cs); cs.setRenderOrder(cs.getRenderOrder() + adjustment); addSprite(cs); } } /** * Returns the highest render order of any sprite on the board. */ protected int getHighestBoardLayer () { // must be at least zero, because that's the lowest number we can push // the sprites down to (the layer of the first card in the hand) int size = _boardSprites.size(), highest = 0; for (int i = 0; i < size; i++) { highest = Math.max(highest, ((CardSprite)_boardSprites.get(i)).getRenderOrder()); } return highest; } /** * Clears an array of sprites from the specified list and from the panel. */ protected void clearSprites (ArrayList sprites) { for (Iterator it = sprites.iterator(); it.hasNext(); ) { removeSprite((CardSprite)it.next()); it.remove(); } } /** * Updates the active card sprite based on the location of the mouse * pointer. */ protected void updateActiveCardSprite () { // can't do anything if we don't know where the mouse pointer is if (_mouseEvent == null) { return; } Sprite newHighestHit = _spritemgr.getHighestHitSprite( _mouseEvent.getX(), _mouseEvent.getY()); CardSprite newActiveCardSprite = (newHighestHit instanceof CardSprite ? (CardSprite)newHighestHit : null); if (_activeCardSprite != newActiveCardSprite) { if (_activeCardSprite != null && isManaged(_activeCardSprite)) { _activeCardSprite.queueNotification( new CardSpriteExitedOp(_activeCardSprite, _mouseEvent) ); } _activeCardSprite = newActiveCardSprite; if (_activeCardSprite != null) { _activeCardSprite.queueNotification( new CardSpriteEnteredOp(_activeCardSprite, _mouseEvent) ); } } } /** The width of the playing cards. */ protected int _cardWidth; /** The last motion/entrance/exit event received from the mouse. */ protected MouseEvent _mouseEvent; /** The currently active card sprite (the one that the mouse is over). */ protected CardSprite _activeCardSprite; /** The sprites for cards within the hand. */ protected ArrayList _handSprites = new ArrayList(); /** The sprites for cards within the hand that have been selected. */ protected ArrayList _selectedHandSprites = new ArrayList(); /** The current selection mode for the hand. */ protected int _handSelectionMode; /** The predicate that determines which cards are selectable (if null, all * cards are selectable). */ protected CardSpritePredicate _handSelectionPredicate; /** Observers of hand card selection/deselection. */ protected ObserverList _handSelectionObservers = new ObserverList( ObserverList.FAST_UNSAFE_NOTIFY); /** The location of the center of the hand's upper edge. */ protected Point _handLocation = new Point(); /** The horizontal distance between cards in the hand. */ protected int _handSpacing; /** The vertical distance to offset cards that are selectable. */ protected int _selectableCardOffset; /** The vertical distance to offset cards that are selected. */ protected int _selectedCardOffset; /** The sprites for cards on the board. */ protected ArrayList _boardSprites = new ArrayList(); /** The hand sprite observer instance. */ protected HandSpriteObserver _handSpriteObserver = new HandSpriteObserver(); /** A path observer that removes the sprite at the end of its path. */ protected PathAdapter _pathEndRemover = new PathAdapter() { public void pathCompleted (Sprite sprite, Path path, long when) { removeSprite(sprite); } }; /** Listens for interactions with cards in hand. */ protected class HandSpriteObserver extends PathAdapter implements CardSpriteObserver { public void pathCompleted (Sprite sprite, Path path, long when) { updateActiveCardSprite(); maybeUpdateOffset((CardSprite)sprite); } public void cardSpriteClicked (CardSprite sprite, MouseEvent me) { // select, deselect, or play card in hand if (_selectedHandSprites.contains(sprite) && _handSelectionMode != NONE) { deselectHandSprite(sprite); } else if (_handSprites.contains(sprite) && isSelectable(sprite)) { selectHandSprite(sprite); } } public void cardSpriteEntered (CardSprite sprite, MouseEvent me) { maybeUpdateOffset(sprite); } public void cardSpriteExited (CardSprite sprite, MouseEvent me) { maybeUpdateOffset(sprite); } public void cardSpriteDragged (CardSprite sprite, MouseEvent me) {} protected void maybeUpdateOffset (CardSprite sprite) { // update the offset if it's in the hand and isn't moving if (_handSprites.contains(sprite) && !sprite.isMoving()) { sprite.setLocation(sprite.getX(), getHandY(sprite)); } } }; /** Listens for mouse interactions with cards. */ protected class CardListener extends MouseInputAdapter { public void mousePressed (MouseEvent me) { if (_activeCardSprite != null && isManaged(_activeCardSprite)) { _handleX = _activeCardSprite.getX() - me.getX(); _handleY = _activeCardSprite.getY() - me.getY(); _hasBeenDragged = false; } } public void mouseReleased (MouseEvent me) { if (_activeCardSprite != null && isManaged(_activeCardSprite) && _hasBeenDragged) { _activeCardSprite.queueNotification( new CardSpriteDraggedOp(_activeCardSprite, me) ); } } public void mouseClicked (MouseEvent me) { if (_activeCardSprite != null && isManaged(_activeCardSprite)) { _activeCardSprite.queueNotification( new CardSpriteClickedOp(_activeCardSprite, me) ); } } public void mouseMoved (MouseEvent me) { _mouseEvent = me; updateActiveCardSprite(); } public void mouseDragged (MouseEvent me) { _mouseEvent = me; if (_activeCardSprite != null && isManaged(_activeCardSprite) && _activeCardSprite.isDraggable()) { _activeCardSprite.setLocation( me.getX() + _handleX, me.getY() + _handleY ); _hasBeenDragged = true; } else { updateActiveCardSprite(); } } public void mouseEntered (MouseEvent me) { _mouseEvent = me; } public void mouseExited (MouseEvent me) { _mouseEvent = me; } protected int _handleX, _handleY; protected boolean _hasBeenDragged; } /** Calls CardSpriteObserver.cardSpriteClicked. */ protected static class CardSpriteClickedOp implements ObserverList.ObserverOp { public CardSpriteClickedOp (CardSprite sprite, MouseEvent me) { _sprite = sprite; _me = me; } public boolean apply (Object observer) { if (observer instanceof CardSpriteObserver) { ((CardSpriteObserver)observer).cardSpriteClicked(_sprite, _me); } return true; } protected CardSprite _sprite; protected MouseEvent _me; } /** Calls CardSpriteObserver.cardSpriteEntered. */ protected static class CardSpriteEnteredOp implements ObserverList.ObserverOp { public CardSpriteEnteredOp (CardSprite sprite, MouseEvent me) { _sprite = sprite; _me = me; } public boolean apply (Object observer) { if (observer instanceof CardSpriteObserver) { ((CardSpriteObserver)observer).cardSpriteEntered(_sprite, _me); } return true; } protected CardSprite _sprite; protected MouseEvent _me; } /** Calls CardSpriteObserver.cardSpriteExited. */ protected static class CardSpriteExitedOp implements ObserverList.ObserverOp { public CardSpriteExitedOp (CardSprite sprite, MouseEvent me) { _sprite = sprite; _me = me; } public boolean apply (Object observer) { if (observer instanceof CardSpriteObserver) { ((CardSpriteObserver)observer).cardSpriteExited(_sprite, _me); } return true; } protected CardSprite _sprite; protected MouseEvent _me; } /** Calls CardSpriteObserver.cardSpriteDragged. */ protected static class CardSpriteDraggedOp implements ObserverList.ObserverOp { public CardSpriteDraggedOp (CardSprite sprite, MouseEvent me) { _sprite = sprite; _me = me; } public boolean apply (Object observer) { if (observer instanceof CardSpriteObserver) { ((CardSpriteObserver)observer).cardSpriteDragged(_sprite, _me); } return true; } protected CardSprite _sprite; protected MouseEvent _me; } /** A nice default green card table background color. */ protected static Color DEFAULT_BACKGROUND = new Color(0x326D36); }
// $Id: SafeSubscriber.java,v 1.3 2003/12/11 18:47:43 mdb Exp $ package com.threerings.presents.util; import com.samskivert.util.StringUtil; import com.threerings.presents.Log; import com.threerings.presents.dobj.DObject; import com.threerings.presents.dobj.DObjectManager; import com.threerings.presents.dobj.ObjectAccessException; import com.threerings.presents.dobj.Subscriber; /** * A class that safely handles the asynchronous subscription to a * distributed object when it is not know if the subscription will * complete before the subscriber decides they no longer wish to be * subscribed. */ public class SafeSubscriber implements Subscriber { /** * Creates a safe subscriber for the specified distributed object * which will interact with the specified subscriber. */ public SafeSubscriber (int oid, Subscriber subscriber) { // make sure they're not fucking us around if (oid <= 0) { throw new IllegalArgumentException( "Invalid oid provided to safesub [oid=" + oid + "]"); } if (subscriber == null) { throw new IllegalArgumentException( "Null subscriber provided to safesub [oid=" + oid + "]"); } _oid = oid; _subscriber = subscriber; } /** * Initiates the subscription process. */ public void subscribe (DObjectManager omgr) { if (_active) { Log.warning("Active safesub asked to resubscribe " + this + "."); Thread.dumpStack(); return; } // note that we are now again in the "wishing to be subscribed" state _active = true; // make sure we dont have an object reference (which should be // logically impossible) if (_object != null) { Log.warning("Incroyable! A safesub has an object and was " + "non-active!? " + this + "."); Thread.dumpStack(); // make do in the face of insanity _subscriber.objectAvailable(_object); return; } if (_pending) { // we were previously asked to subscribe, then they asked to // unsubscribe and now they've asked to subscribe again, all // before the original subscription even completed; we need do // nothing here except as the original subscription request // will eventually come through and all will be well return; } // we're not pending and we just became active, that means we need // to request to subscribe to our object _pending = true; omgr.subscribeToObject(_oid, this); } /** * Terminates the object subscription. If the initial subscription has * not yet completed, the desire to terminate will be noted and the * subscription will be terminated as soon as it completes. */ public void unsubscribe (DObjectManager omgr) { if (!_active) { // we may be non-active and have no object which could mean // that subscription failed; in which case we don't want to // complain about anything, just quietly ignore the // unsubscribe request if (_object == null && !_pending) { return; } Log.warning("Inactive safesub asked to unsubscribe " + this + "."); Thread.dumpStack(); } // note that we no longer desire to be subscribed _active = false; if (_pending) { // make sure we don't have an object reference if (_object != null) { Log.warning("Incroyable! A safesub has an object and is " + "pending!? " + this + "."); Thread.dumpStack(); } else { // nothing to do but wait for the subscription to complete // at which point we'll pitch the object post-haste return; } } // make sure we have our object if (_object == null) { Log.warning("Zut alors! A safesub _was_ active and not " + "pending yet has no object!? " + this + "."); Thread.dumpStack(); // nothing to do since we're apparently already unsubscribed return; } // finally effect our unsubscription _object = null; omgr.unsubscribeFromObject(_oid, this); } // documentation inherited from interface public void objectAvailable (DObject object) { // make sure life is not too cruel if (_object != null) { Log.warning("Madre de dios! Our object came available but " + "we've already got one!? " + this); // go ahead and pitch the old one, God knows what's going on _object = null; } if (!_pending) { Log.warning("J.C. on a pogo stick! Our object came available " + "but we're not pending!? " + this); // go with our badselves, it's the only way } // we're no longer pending _pending = false; // if we are no longer active, we don't want this damned thing if (!_active) { DObjectManager omgr = object.getManager(); // if the object's manager is null, that means the object is // already destroyed and we need not trouble ourselves with // unsubscription as it has already been pitched to the dogs if (omgr != null) { omgr.unsubscribeFromObject(_oid, this); } return; } // otherwise the air is fresh and clean and we can do our job _object = object; _subscriber.objectAvailable(object); } // documentation inherited from interface public void requestFailed (int oid, ObjectAccessException cause) { // do the right thing with our pending state if (!_pending) { Log.warning("Criminy creole! Our subscribe failed but we're " + "not pending!? " + this); // go with our badselves, it's the only way } _pending = false; // if we're active, let our subscriber know that the shit hit the fan if (_active) { _subscriber.requestFailed(oid, cause); // and deactivate ourselves as we never got our object (and // thus the real subscriber need not call unsubscribe()) _active = false; } } /** * Returns a string representation of this instance. */ public String toString () { return "[oid=" + _oid + ", sub=" + StringUtil.shortClassName(_subscriber) + ", active=" + _active + ", pending=" + _pending + ", dobj=" + StringUtil.shortClassName(_object) + "]"; } protected int _oid; protected Subscriber _subscriber; protected DObject _object; protected boolean _active; protected boolean _pending; }
// $Id: SafeSubscriber.java,v 1.2 2003/12/11 18:46:02 mdb Exp $ package com.threerings.presents.util; import com.samskivert.util.StringUtil; import com.threerings.presents.Log; import com.threerings.presents.dobj.DObject; import com.threerings.presents.dobj.DObjectManager; import com.threerings.presents.dobj.ObjectAccessException; import com.threerings.presents.dobj.Subscriber; /** * A class that safely handles the asynchronous subscription to a * distributed object when it is not know if the subscription will * complete before the subscriber decides they no longer wish to be * subscribed. */ public class SafeSubscriber implements Subscriber { /** * Creates a safe subscriber for the specified distributed object * which will interact with the specified subscriber. */ public SafeSubscriber (int oid, Subscriber subscriber) { // make sure they're not fucking us around if (oid <= 0) { throw new IllegalArgumentException( "Invalid oid provided to safesub [oid=" + oid + "]"); } if (subscriber == null) { throw new IllegalArgumentException( "Null subscriber provided to safesub [oid=" + oid + "]"); } _oid = oid; _subscriber = subscriber; } /** * Initiates the subscription process. */ public void subscribe (DObjectManager omgr) { if (_active) { Log.warning("Active safesub asked to resubscribe " + this + "."); Thread.dumpStack(); return; } // note that we are now again in the "wishing to be subscribed" state _active = true; // make sure we dont have an object reference (which should be // logically impossible) if (_object != null) { Log.warning("Incroyable! A safesub has an object and was " + "non-active!? " + this + "."); Thread.dumpStack(); // make do in the face of insanity _subscriber.objectAvailable(_object); return; } if (_pending) { // we were previously asked to subscribe, then they asked to // unsubscribe and now they've asked to subscribe again, all // before the original subscription even completed; we need do // nothing here except as the original subscription request // will eventually come through and all will be well return; } // we're not pending and we just became active, that means we need // to request to subscribe to our object _pending = true; omgr.subscribeToObject(_oid, this); } /** * Terminates the object subscription. If the initial subscription has * not yet completed, the desire to terminate will be noted and the * subscription will be terminated as soon as it completes. */ public void unsubscribe (DObjectManager omgr) { if (!_active) { // we may be non-active and have no object which could mean // that subscription failed; in which case we don't want to // complain about anything, just quietly ignore the // unsubscribe request if (_object == null && !_pending) { return; } Log.warning("Inactive safesub asked to unsubscribe " + this + "."); Thread.dumpStack(); } // note that we no longer desire to be subscribed _active = false; if (_pending) { // make sure we don't have an object reference if (_object != null) { Log.warning("Incroyable! A safesub has an object and is " + "pending!? " + this + "."); Thread.dumpStack(); } else { // nothing to do but wait for the subscription to complete // at which point we'll pitch the object post-haste return; } } // make sure we have our object if (_object == null) { Log.warning("Zut alors! A safesub _was_ active and not " + "pending yet has no object!? " + this + "."); Thread.dumpStack(); // nothing to do since we're apparently already unsubscribed return; } // finally effect our unsubscription _object = null; omgr.unsubscribeFromObject(_oid, this); } // documentation inherited from interface public void objectAvailable (DObject object) { // make sure life is not too cruel if (_object != null) { Log.warning("Madre de dios! Our object came available but " + "we've already got one!? " + this); // go ahead and pitch the old one, God knows what's going on _object = null; } if (!_pending) { Log.warning("J.C. on a pogo stick! Our object came available " + "but we're not pending!? " + this); // go with our badselves, it's the only way } // we're no longer pending _pending = false; // if we are no longer active, we don't want this damned thing if (!_active) { DObjectManager omgr = object.getManager(); // if the object's manager is null, that means the object is // already destroyed and we need not trouble ourselves with // unsubscription as it has already been pitched to the dogs if (omgr != null) { omgr.unsubscribeFromObject(_oid, this); } return; } // otherwise the air is fresh and clean and we can do our job _object = object; _subscriber.objectAvailable(object); } // documentation inherited from interface public void requestFailed (int oid, ObjectAccessException cause) { // if we're active, let our subscriber know that the shit hit the fan if (_active) { _subscriber.requestFailed(oid, cause); // and deactivate ourselves as we never got our object (and // thus the real subscriber need not call unsubscribe()) _active = false; } } /** * Returns a string representation of this instance. */ public String toString () { return "[oid=" + _oid + ", sub=" + StringUtil.shortClassName(_subscriber) + ", active=" + _active + ", pending=" + _pending + ", dobj=" + StringUtil.shortClassName(_object) + "]"; } protected int _oid; protected Subscriber _subscriber; protected DObject _object; protected boolean _active; protected boolean _pending; }
package com.twitter.mesos.scheduler; import java.io.IOException; import java.net.InetSocketAddress; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.atomic.AtomicReference; import java.util.logging.Logger; import com.google.common.base.Function; import com.google.common.base.Supplier; import com.google.common.collect.ImmutableList; import com.google.inject.AbstractModule; import com.google.inject.Key; import com.google.inject.Provides; import com.google.inject.Singleton; import com.google.inject.TypeLiteral; import com.google.inject.name.Names; import org.apache.mesos.MesosSchedulerDriver; import org.apache.mesos.Protos.ExecutorID; import org.apache.mesos.Protos.ExecutorInfo; import org.apache.mesos.Protos.FrameworkID; import org.apache.mesos.Scheduler; import org.apache.mesos.SchedulerDriver; import com.twitter.common.application.ActionRegistry; import com.twitter.common.application.ShutdownStage; import com.twitter.common.application.http.Registration; import com.twitter.common.args.Arg; import com.twitter.common.args.CmdLine; import com.twitter.common.args.constraints.NotNull; import com.twitter.common.base.Closure; import com.twitter.common.base.Closures; import com.twitter.common.inject.TimedInterceptor; import com.twitter.common.logging.ScribeLog; import com.twitter.common.quantity.Amount; import com.twitter.common.quantity.Data; import com.twitter.common.quantity.Time; import com.twitter.common.thrift.ThriftFactory.ThriftFactoryException; import com.twitter.common.thrift.ThriftServer; import com.twitter.common.util.Clock; import com.twitter.common.zookeeper.SingletonService; import com.twitter.common.zookeeper.ZooKeeperClient; import com.twitter.common.zookeeper.ZooKeeperClient.Credentials; import com.twitter.common.zookeeper.ZooKeeperUtils; import com.twitter.common.zookeeper.testing.ZooKeeperTestServer; import com.twitter.common_internal.cuckoo.CuckooWriter; import com.twitter.common_internal.zookeeper.TwitterZk; import com.twitter.mesos.ExecutorKey; import com.twitter.mesos.gen.MesosAdmin; import com.twitter.mesos.gen.TwitterTaskInfo; import com.twitter.mesos.scheduler.PulseMonitor.PulseMonitorImpl; import com.twitter.mesos.scheduler.SchedulingFilter.SchedulingFilterImpl; import com.twitter.mesos.scheduler.auth.SessionValidator; import com.twitter.mesos.scheduler.auth.SessionValidator.SessionValidatorImpl; import com.twitter.mesos.scheduler.httphandlers.CreateJob; import com.twitter.mesos.scheduler.httphandlers.Mname; import com.twitter.mesos.scheduler.httphandlers.SchedulerzHome; import com.twitter.mesos.scheduler.httphandlers.SchedulerzJob; import com.twitter.mesos.scheduler.httphandlers.SchedulerzRole; import com.twitter.mesos.scheduler.quota.QuotaModule; import com.twitter.mesos.scheduler.storage.db.DbStorageModule; import com.twitter.mesos.scheduler.sync.SyncModule; public class SchedulerModule extends AbstractModule { private static final Logger LOG = Logger.getLogger(SchedulerModule.class.getName()); @NotNull @CmdLine(name = "mesos_scheduler_ns", help ="The name service name for the mesos scheduler thrift server.") private static final Arg<String> mesosSchedulerNameSpec = Arg.create(); @CmdLine(name = "machine_restrictions", help ="Map of machine hosts to job keys." + " If A maps to B, only B can run on A and B can only run on A.") public static final Arg<Map<String, String>> machineRestrictions = Arg.create(Collections.<String, String>emptyMap()); @CmdLine(name = "job_updater_hdfs_path", help ="HDFS path to the job updater package.") private static final Arg<String> jobUpdaterHdfsPath = Arg.create("/mesos/pkg/mesos/bin/mesos-updater.zip"); @NotNull @CmdLine(name = "mesos_master_address", help ="Mesos address for the master, can be a mesos address or zookeeper path.") private static final Arg<String> mesosMasterAddress = Arg.create(); @CmdLine(name = "zk_in_proc", help ="Launches an embedded zookeeper server for local testing") private static final Arg<Boolean> zooKeeperInProcess = Arg.create(false); @CmdLine(name = "zk_endpoints", help ="Endpoint specification for the ZooKeeper servers.") private static final Arg<List<InetSocketAddress>> zooKeeperEndpoints = Arg.<List<InetSocketAddress>>create(ImmutableList.copyOf(TwitterZk.DEFAULT_ZK_ENDPOINTS)); @CmdLine(name = "zk_session_timeout", help ="The ZooKeeper session timeout.") public static final Arg<Amount<Integer, Time>> zooKeeperSessionTimeout = Arg.create(ZooKeeperUtils.DEFAULT_ZK_SESSION_TIMEOUT); @NotNull @CmdLine(name = "executor_path", help ="Path to the executor launch script.") private static final Arg<String> executorPath = Arg.create(); @CmdLine(name = "cuckoo_scribe_endpoints", help = "Cuckoo endpoints for stat export. Leave empty to disable stat export.") private static final Arg<List<InetSocketAddress>> CUCKOO_SCRIBE_ENDPOINTS = Arg.create( Arrays.asList(InetSocketAddress.createUnresolved("localhost", 1463))); @CmdLine(name = "cuckoo_scribe_category", help = "Scribe category to send cuckoo stats to.") private static final Arg<String> CUCKOO_SCRIBE_CATEGORY = Arg.create(CuckooWriter.DEFAULT_SCRIBE_CATEGORY); @NotNull @CmdLine(name = "cuckoo_service_id", help = "Cuckoo service ID.") private static final Arg<String> CUCKOO_SERVICE_ID = Arg.create(); @CmdLine(name = "cuckoo_source_id", help = "Cuckoo stat source ID.") private static final Arg<String> CUCKOO_SOURCE_ID = Arg.create("mesos_scheduler"); @CmdLine(name = "executor_dead_threashold", help = "Time after which the scheduler will consider an executor dead and attempt to revive it.") private static final Arg<Amount<Long, Time>> EXECUTOR_DEAD_THRESHOLD = Arg.create(Amount.of(10L, Time.MINUTES)); @NotNull @CmdLine(name = "cluster_name", help = "Name to identify the cluster being served.") private static final Arg<String> CLUSTER_NAME = Arg.create(); @CmdLine(name = "executor_resources_cpus", help = "The number of CPUS that should be reserved by mesos for the executor.") private static final Arg<Double> CPUS = Arg.create(0.25); @CmdLine(name = "executor_resources_ram", help = "The amount of RAM that should be reserved by mesos for the executor.") private static final Arg<Amount<Double, Data>> RAM = Arg.create(Amount.of(2d, Data.GB)); private static final String TWITTER_EXECUTOR_ID = "twitter"; @Override protected void configure() { // Enable intercepted method timings TimedInterceptor.bind(binder()); bind(Key.get(String.class, ClusterName.class)).toInstance(CLUSTER_NAME.get()); // TODO(John Sirois): get this from /etc/keys/mesos:mesos bind(Credentials.class).toInstance(ZooKeeperClient.digestCredentials("mesos", "mesos")); // Bindings for MesosSchedulerImpl. bind(SessionValidator.class).to(SessionValidatorImpl.class); bind(SchedulerCore.class).to(SchedulerCoreImpl.class).in(Singleton.class); bind(ExecutorTracker.class).to(ExecutorTrackerImpl.class).in(Singleton.class); // Bindings for SchedulerCoreImpl. bind(CronJobManager.class).in(Singleton.class); bind(ImmediateJobManager.class).in(Singleton.class); bind(new TypeLiteral<PulseMonitor<ExecutorKey>>() {}) .toInstance(new PulseMonitorImpl<ExecutorKey>(EXECUTOR_DEAD_THRESHOLD.get())); bind(new TypeLiteral<Supplier<Set<ExecutorKey>>>() {}) .to(new TypeLiteral<PulseMonitor<ExecutorKey>>() {}); // Bindings for thrift interfaces. bind(MesosAdmin.Iface.class).to(SchedulerThriftInterface.class).in(Singleton.class); bind(ThriftServer.class).to(SchedulerThriftServer.class).in(Singleton.class); DbStorageModule.bind(binder()); bind(SchedulingFilter.class).to(SchedulingFilterImpl.class); // updaterTaskProvider handled in provider. // Bindings for SchedulingFilterImpl. bind(Key.get(new TypeLiteral<Map<String, String>>() {}, Names.named(SchedulingFilterImpl.MACHINE_RESTRICTIONS))) .toInstance(machineRestrictions.get()); bind(Scheduler.class).to(MesosSchedulerImpl.class).in(Singleton.class); // Bindings for StateManager bind(Clock.class).toInstance(Clock.SYSTEM_CLOCK); Registration.registerServlet(binder(), "/scheduler", SchedulerzHome.class, false); Registration.registerServlet(binder(), "/scheduler/role", SchedulerzRole.class, true); Registration.registerServlet(binder(), "/scheduler/job", SchedulerzJob.class, true); Registration.registerServlet(binder(), "/mname", Mname.class, false); Registration.registerServlet(binder(), "/create_job", CreateJob.class, true); QuotaModule.bind(binder()); SyncModule.bind(binder()); } // TODO(John Sirois): find a better way to bind the update job supplier that does not rely on // action at a distance @Provides @Singleton AtomicReference<InetSocketAddress> provideThriftEndpoint() { return new AtomicReference<InetSocketAddress>(); } @Provides Function<String, TwitterTaskInfo> provideUpdateTaskSupplier( final AtomicReference<InetSocketAddress> schedulerThriftPort) { return new Function<String, TwitterTaskInfo>() { @Override public TwitterTaskInfo apply(String updateToken) { InetSocketAddress thriftPort = schedulerThriftPort.get(); if (thriftPort == null) { LOG.severe("Scheduler thrift port requested for updater before it was set!"); return null; } String schedulerAddress = thriftPort.getHostName() + ":" + thriftPort.getPort(); return new TwitterTaskInfo() .setHdfsPath(jobUpdaterHdfsPath.get()) .setShardId(0) .setStartCommand( "unzip mesos-updater.zip;" + " java -cp mesos-updater.jar" + " com.twitter.common.application.AppLauncher" + " -app_class=com.twitter.mesos.updater.UpdaterMain" + " -scheduler_address=" + schedulerAddress + " -update_token=" + updateToken); } }; } @Provides @Singleton SchedulerDriver provideMesosSchedulerDriver(Scheduler scheduler, SchedulerCore schedulerCore) { String frameworkId = schedulerCore.initialize(); LOG.info("Connecting to mesos master: " + mesosMasterAddress.get()); if (frameworkId != null) { LOG.info("Found persisted framework ID: " + frameworkId); return new MesosSchedulerDriver(scheduler, mesosMasterAddress.get(), FrameworkID.newBuilder().setValue(frameworkId).build()); } else { LOG.warning("Did not find a persisted framework ID, connecting as a new framework."); return new MesosSchedulerDriver(scheduler, mesosMasterAddress.get()); } } @Provides @Singleton SingletonService provideSingletonService(ZooKeeperClient zkClient) { // Scheduler service should be closed for membership but open for discovery (by mesos client) return new SingletonService(zkClient, mesosSchedulerNameSpec.get(), ZooKeeperUtils.EVERYONE_READ_CREATOR_ALL); } @Provides @Singleton ZooKeeperClient provideZooKeeperClient(@ShutdownStage ActionRegistry shutdownRegistry, Credentials credentials) { if (zooKeeperInProcess.get()) { try { return startLocalZookeeper(shutdownRegistry, credentials); } catch (IOException e) { throw new RuntimeException("Unable to start local zookeeper", e); } catch (InterruptedException e) { throw new RuntimeException("Unable to start local zookeeper", e); } } else { return new ZooKeeperClient(zooKeeperSessionTimeout.get(), credentials, zooKeeperEndpoints.get()); } } @Provides @Singleton Closure<Map<String, ? extends Number>> provideStatSink() throws ThriftFactoryException { if (CUCKOO_SCRIBE_ENDPOINTS.get().isEmpty()) { LOG.info("No scribe hosts provided, cuckoo stat export disabled."); return Closures.noop(); } else { return new CuckooWriter(new ScribeLog(CUCKOO_SCRIBE_ENDPOINTS.get()), CUCKOO_SCRIBE_CATEGORY.get(), CUCKOO_SERVICE_ID.get(), CUCKOO_SOURCE_ID.get()); } } @Provides @Singleton ExecutorInfo provideExecutorInfo() { return ExecutorInfo.newBuilder().setUri(executorPath.get()) .setExecutorId(ExecutorID.newBuilder().setValue(TWITTER_EXECUTOR_ID)) .addResources(Resources.makeResource(Resources.CPUS, CPUS.get())) .addResources(Resources.makeResource(Resources.RAM_MB, RAM.get().as(Data.MB))) .build(); } @Provides @Singleton Function<TwitterTaskInfo, TwitterTaskInfo> provideExecutorResourceAugmenter() { final Double executorCpus = CPUS.get(); final long executorRam = RAM.get().as(Data.MB).longValue(); return new Function<TwitterTaskInfo, TwitterTaskInfo>() { @Override public TwitterTaskInfo apply(TwitterTaskInfo task) { return task.deepCopy() .setNumCpus(task.getNumCpus() + executorCpus) .setRamMb(task.getRamMb() + executorRam); } }; } private ZooKeeperClient startLocalZookeeper(ActionRegistry shutdownRegistry, Credentials credentials) throws IOException, InterruptedException { ZooKeeperTestServer zooKeeperServer = new ZooKeeperTestServer(0, shutdownRegistry); zooKeeperServer.startNetwork(); LOG.info("Embedded zookeeper cluster started on port " + zooKeeperServer.getPort()); return zooKeeperServer.createClient(zooKeeperSessionTimeout.get(), credentials); } }
package fr.paris.lutece.portal.service.init; /** * this class provides informations about application version */ public final class AppInfo { /** Defines the current version of the application */ private static final String APP_VERSION = "4.2.0"; /** * Creates a new AppInfo object. */ private AppInfo( ) { } /** * Returns the current version of the application * @return APP_VERSION The current version of the application */ public static String getVersion( ) { return APP_VERSION; } }
package nl.b3p.viewer.admin.stripes; import java.util.*; import javax.annotation.security.RolesAllowed; import net.sourceforge.stripes.action.*; import net.sourceforge.stripes.controller.LifecycleStage; import net.sourceforge.stripes.validation.Validate; import net.sourceforge.stripes.validation.ValidateNestedProperties; import nl.b3p.viewer.config.app.*; import nl.b3p.viewer.config.security.Group; import nl.b3p.viewer.config.services.*; import org.stripesstuff.stripersist.Stripersist; /** * * @author Jytte Schaeffer */ @UrlBinding("/action/layer") @StrictBinding @RolesAllowed({Group.ADMIN,Group.REGISTRY_ADMIN}) public class LayerActionBean implements ActionBean { private static final String JSP = "/WEB-INF/jsp/services/layer.jsp"; private ActionBeanContext context; @Validate @ValidateNestedProperties({ @Validate(field = "titleAlias", label="Naam"), @Validate(field = "legendImageUrl", label="Legenda") }) private Layer layer; @Validate private String parentId; private List<Group> allGroups; private SortedSet<String> applicationsUsedIn = new TreeSet(); @Validate private List<String> groupsRead = new ArrayList<String>(); @Validate private List<String> groupsWrite = new ArrayList<String>(); @Validate private Map<String, String> details = new HashMap<String, String>(); @Validate private SimpleFeatureType simpleFeatureType; @Validate private Long featureSourceId; private List featureSources; //<editor-fold defaultstate="collapsed" desc="getters & setters"> public ActionBeanContext getContext() { return context; } public void setContext(ActionBeanContext context) { this.context = context; } public Map<String, String> getDetails() { return details; } public void setDetails(Map<String, String> details) { this.details = details; } public Layer getLayer() { return layer; } public void setLayer(Layer layer) { this.layer = layer; } public List<Group> getAllGroups() { return allGroups; } public void setAllGroups(List<Group> allGroups) { this.allGroups = allGroups; } public List<String> getGroupsRead() { return groupsRead; } public void setGroupsRead(List<String> groupsRead) { this.groupsRead = groupsRead; } public List<String> getGroupsWrite() { return groupsWrite; } public void setGroupsWrite(List<String> groupsWrite) { this.groupsWrite = groupsWrite; } public SortedSet<String> getApplicationsUsedIn() { return applicationsUsedIn; } public void setApplicationsUsedIn(SortedSet<String> applicationsUsedIn) { this.applicationsUsedIn = applicationsUsedIn; } public SimpleFeatureType getSimpleFeatureType() { return simpleFeatureType; } public void setSimpleFeatureType(SimpleFeatureType simpleFeatureType) { this.simpleFeatureType = simpleFeatureType; } public Long getFeatureSourceId() { return featureSourceId; } public void setFeatureSourceId(Long featureSourceId) { this.featureSourceId = featureSourceId; } public List getFeatureSources() { return featureSources; } public void setFeatureSources(List featureSources) { this.featureSources = featureSources; } public String getParentId() { return parentId; } public void setParentId(String parentId) { this.parentId = parentId; } //</editor-fold> @Before(stages = LifecycleStage.BindingAndValidation) @SuppressWarnings("unchecked") public void load() { allGroups = Stripersist.getEntityManager().createQuery("from Group").getResultList(); featureSources = Stripersist.getEntityManager().createQuery("from FeatureSource").getResultList(); } @DefaultHandler public Resolution edit() { if (layer != null) { details = layer.getDetails(); groupsRead.addAll(layer.getReaders()); groupsWrite.addAll(layer.getWriters()); if (layer.getFeatureType() != null) { simpleFeatureType = layer.getFeatureType(); featureSourceId = simpleFeatureType.getFeatureSource().getId(); } findApplicationsUsedIn(); } return new ForwardResolution(JSP); } private void findApplicationsUsedIn() { GeoService service = layer.getService(); String layerName = layer.getName(); List<ApplicationLayer> applicationLayers = Stripersist.getEntityManager().createQuery("from ApplicationLayer where service = :service" + " and layerName = :layerName").setParameter("service", service).setParameter("layerName", layerName).getResultList(); for (Iterator it = applicationLayers.iterator(); it.hasNext();) { ApplicationLayer appLayer = (ApplicationLayer) it.next(); /* * The parent level of the applicationLayer is needed to find out in * which application the Layer is used. This solution is not good * when there are many levels. */ List<Level> levels = Stripersist.getEntityManager().createQuery("from Level").getResultList(); for (Iterator iter = levels.iterator(); iter.hasNext();) { Level level = (Level) iter.next(); if (level != null && level.getLayers().contains(appLayer)) { applicationsUsedIn.addAll(getApplicationNames(level)); } } } } private Set<String> getApplicationNames(Level level) { Set<String> names = new HashSet(); for(Application app: level.findApplications()) { names.add(app.getNameWithVersion()); } return names; } public Resolution save() { layer.getDetails().clear(); layer.getDetails().putAll(details); layer.getReaders().clear(); for (String groupName : groupsRead) { layer.getReaders().add(groupName); } layer.getWriters().clear(); for (String groupName : groupsWrite) { layer.getWriters().add(groupName); } layer.setFeatureType(simpleFeatureType); Stripersist.getEntityManager().persist(layer); layer.getService().authorizationsModified(); Stripersist.getEntityManager().getTransaction().commit(); getContext().getMessages().add(new SimpleMessage("De kaartlaag is opgeslagen")); return new ForwardResolution(JSP); } }
// This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // This library is distributed in the hope that it will be useful, // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // You should have received a copy of the GNU Lesser General Public // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. package opennlp.tools.sentdetect; import opennlp.maxent.*; import opennlp.maxent.io.*; import opennlp.maxent.IntegerPool; import opennlp.tools.util.Pair; import java.io.IOException; import java.io.File; import java.io.Reader; import java.io.BufferedReader; import java.io.FileReader; import java.util.List; import java.util.ArrayList; public class SentenceDetectorME implements SentenceDetector { /** The maximum entropy model to use to evaluate contexts. */ private MaxentModel model; /** The feature context generator. */ private final ContextGenerator cgen; /** The EndOfSentenceScanner to use when scanning for end of sentence offsets. */ private final EndOfSentenceScanner scanner; /** A pool of read-only java.lang.Integer objects in the range 0..100 */ private static final IntegerPool INT_POOL = new IntegerPool(100); /** The list of probabilities associated with each decision. */ private List sentProbs; /** * Constructor which takes a MaxentModel and calls the three-arg * constructor with that model, an SDContextGenerator, and the * default end of sentence scanner. * * @param m The MaxentModel which this SentenceDetectorME will use to * evaluate end-of-sentence decisions. */ public SentenceDetectorME(MaxentModel m) { this(m, new SDContextGenerator(DefaultEndOfSentenceScanner.eosCharacters), new DefaultEndOfSentenceScanner()); sentProbs = new ArrayList(50); } /** * Constructor which takes a MaxentModel and a ContextGenerator. * calls the three-arg constructor with a default ed of sentence scanner. * * @param m The MaxentModel which this SentenceDetectorME will use to * evaluate end-of-sentence decisions. * @param cg The ContextGenerator object which this SentenceDetectorME * will use to turn Strings into contexts for the model to * evaluate. */ public SentenceDetectorME(MaxentModel m, ContextGenerator cg) { this(m, cg, new DefaultEndOfSentenceScanner()); } /** * Creates a new <code>SentenceDetectorME</code> instance. * * @param m The MaxentModel which this SentenceDetectorME will use to * evaluate end-of-sentence decisions. * @param cg The ContextGenerator object which this SentenceDetectorME * will use to turn Strings into contexts for the model to * evaluate. * @param s the EndOfSentenceScanner which this SentenceDetectorME * will use to locate end of sentence indexes. */ public SentenceDetectorME(MaxentModel m, ContextGenerator cg, EndOfSentenceScanner s) { model = m; cgen = cg; scanner = s; } /** * Detect sentences in a String. * * @param s The string to be processed. * @return A string array containing individual sentences as elements. * */ public String[] sentDetect(String s) { int[] starts = sentPosDetect(s); if (starts.length == 0) { return new String[] {s}; } String[] sents = new String[starts.length]; sents[0] = s.substring(0,starts[0]); for (int si = 1; si < starts.length; si++) { sents[si] = s.substring(starts[si - 1], starts[si]); } //sents[starts.length - 1] = s.substring(starts[starts.length - 1]); return (sents); } private int getFirstWS(String s, int pos) { while (pos < s.length() && !Character.isWhitespace(s.charAt(pos))) pos++; return pos; } private int getFirstNonWS(String s, int pos) { while (pos < s.length() && Character.isWhitespace(s.charAt(pos))) pos++; return pos; } /** * Detect the position of the first words of sentences in a String. * * @param s The string to be processed. * @return A integer array containing the positions of the end index of * every sentence * */ public int[] sentPosDetect(String s) { double sentProb = 1; sentProbs.clear(); StringBuffer sb = new StringBuffer(s); List enders = scanner.getPositions(s); List positions = new ArrayList(enders.size()); for (int i = 0, end = enders.size(), index = 0; i < end; i++) { Integer candidate = (Integer) enders.get(i); int cint = candidate.intValue(); // skip over the leading parts of contiguous delimiters if (((i + 1) < end) && (((Integer) enders.get(i + 1)).intValue() == (cint + 1))) { continue; } Pair pair = new Pair(sb, candidate); double[] probs = model.eval(cgen.getContext(pair)); String bestOutcome = model.getBestOutcome(probs); sentProb *= probs[model.getIndex(bestOutcome)]; if (bestOutcome.equals("T") && isAcceptableBreak(s, index, cint)) { if (index != cint) { positions.add(INT_POOL.get(getFirstNonWS(s, getFirstWS(s,cint + 1)))); sentProbs.add(new Double(probs[model.getIndex(bestOutcome)])); } index = cint + 1; } } int[] sentPositions = new int[positions.size()]; for (int i = 0; i < sentPositions.length; i++) { sentPositions[i] = ((Integer) positions.get(i)).intValue(); } return sentPositions; } /** Returns the probabilities associated with the most recent * calls to sentDetect(). * @return probability for each sentence returned for the most recent * call to sentDetect. If not applicable an empty array is * returned. */ public double[] getSentenceProbabilities() { double[] sentProbArray = new double[sentProbs.size()]; for (int i = 0; i < sentProbArray.length; i++) { sentProbArray[i] = ((Double) sentProbs.get(i)).doubleValue(); } return sentProbArray; } /** * Allows subclasses to check an overzealous (read: poorly * trained) model from flagging obvious non-breaks as breaks based * on some boolean determination of a break's acceptability. * * <p>The implementation here always returns true, which means * that the MaxentModel's outcome is taken as is.</p> * * @param s the string in which the break occured. * @param fromIndex the start of the segment currently being evaluated * @param candidateIndex the index of the candidate sentence ending * @return true if the break is acceptable */ protected boolean isAcceptableBreak(String s, int fromIndex, int candidateIndex) { return true; } public static GISModel train(EventStream es, int iterations, int cut) throws IOException { return GIS.trainModel(es, iterations, cut); } /** * Use this training method if you wish to supply an end of * sentence scanner which provides a different set of ending chars * other than the default ones. They are "\\.|!|\\?|\\\"|\\)". * */ public static GISModel train(File inFile, int iterations, int cut, EndOfSentenceScanner scanner) throws IOException { EventStream es; DataStream ds; Reader reader; reader = new BufferedReader(new FileReader(inFile)); ds = new PlainTextByLineDataStream(reader); es = new SDEventStream(ds, scanner); return GIS.trainModel(es, iterations, cut); } /** * <p>Trains a new sentence detection model.</p> * * <p>Usage: java opennlp.grok.preprocess.sentdetect.SentenceDetectorME data_file new_model_name (iterations cutoff)?</p> * */ public static void main(String[] args) throws IOException { if (args.length == 0) { System.err.println("Usage: SentenceDetectorME trainData modelName"); System.exit(1); } try { File inFile = new File(args[0]); File outFile = new File(args[1]); GISModel mod; EventStream es = new SDEventStream(new PlainTextByLineDataStream(new FileReader(inFile))); if (args.length > 3) mod = train(es, Integer.parseInt(args[2]), Integer.parseInt(args[3])); else mod = train(es, 100, 5); System.out.println("Saving the model as: " + args[1]); new SuffixSensitiveGISModelWriter(mod, outFile).persist(); } catch (Exception e) { e.printStackTrace(); } } }
package org.apache.commons.collections; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Set; /** * <code>MultiHashMap</code> is the default implementation of the * {@link org.apache.commons.collections.MultiMap MultiMap} interface. * A <code>MultiMap</code> is a Map with slightly different semantics. * Instead of returning an Object, it returns a Collection. * So for example, you can put( key, new Integer(1) ); * and then a Object get( key ); will return you a Collection * instead of an Integer. * * @since 2.0 * @author Christopher Berry * @author <a href="mailto:jstrachan@apache.org">James Strachan</a> * @author Steve Downey * @author Stephen Colebourne */ public class MultiHashMap extends HashMap implements MultiMap { private static int sCount = 0; private String mName = null; public MultiHashMap() { super(); setName(); } public MultiHashMap( int initialCapacity ) { super( initialCapacity ); setName(); } public MultiHashMap(int initialCapacity, float loadFactor ) { super( initialCapacity, loadFactor); setName(); } public MultiHashMap( Map mapToCopy ) { super( mapToCopy ); } private void setName() { sCount++; mName = "MultiMap-" + sCount; } public String getName() { return mName; } public Object put( Object key, Object value ) { // NOTE:: put might be called during deserialization !!!!!! // so we must provide a hook to handle this case // This means that we cannot make MultiMaps of ArrayLists !!! if ( value instanceof ArrayList ) { return ( super.put( key, value ) ); } ArrayList keyList = (ArrayList)(super.get( key )); if ( keyList == null ) { keyList = new ArrayList(10); super.put( key, keyList ); } boolean results = keyList.add( value ); return ( results ? value : null ); } public boolean containsValue( Object value ) { Set pairs = super.entrySet(); if ( pairs == null ) return false; Iterator pairsIterator = pairs.iterator(); while ( pairsIterator.hasNext() ) { Map.Entry keyValuePair = (Map.Entry)(pairsIterator.next()); ArrayList list = (ArrayList)(keyValuePair.getValue()); if( list.contains( value ) ) return true; } return false; } public Object remove( Object key, Object item ) { ArrayList valuesForKey = (ArrayList) super.get( key ); if ( valuesForKey == null ) return null; valuesForKey.remove( item ); return item; } public void clear() { Set pairs = super.entrySet(); Iterator pairsIterator = pairs.iterator(); while ( pairsIterator.hasNext() ) { Map.Entry keyValuePair = (Map.Entry)(pairsIterator.next()); ArrayList list = (ArrayList)(keyValuePair.getValue()); list.clear(); } super.clear(); } public void putAll( Map mapToPut ) { super.putAll( mapToPut ); } public Collection values() { ArrayList returnList = new ArrayList( super.size() ); Set pairs = super.entrySet(); Iterator pairsIterator = pairs.iterator(); while ( pairsIterator.hasNext() ) { Map.Entry keyValuePair = (Map.Entry)(pairsIterator.next()); ArrayList list = (ArrayList)(keyValuePair.getValue()); Object[] values = list.toArray(); for ( int ii=0; ii < values.length; ii++ ) { returnList.add( values[ii] ); } } return returnList; } // FIXME:: do we need to implement this?? // public boolean equals( Object obj ) {} public Object clone() { MultiHashMap obj = (MultiHashMap)(super.clone()); obj.mName = mName; return obj; } }
package org.apache.velocity.servlet; import java.io.IOException; import java.io.PrintWriter; import java.io.Writer; import java.io.BufferedWriter; import java.io.OutputStreamWriter; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.velocity.Context; import org.apache.velocity.Template; import org.apache.velocity.runtime.Runtime; import org.apache.velocity.io.*; /** * Base class which simplifies the use of Velocity with Servlets. * Extend this class, implement the <code>handleRequest()</code> method, * and add your data to the context. Then call * <code>getTemplate("myTemplate.wm")</code>. * * This class puts some things into the context object that you should * be aware of: * <pre> * "req" - The HttpServletRequest object * "res" - The HttpServletResponse object * </pre> * * If you put a contentType object into the context within either your * serlvet or within your template, then that will be used to override * the default content type specified in the properties file. * * "contentType" - The value for the Content-Type: header * * @author Dave Bryson * @author <a href="mailto:jon@latchkey.com">Jon S. Stevens</a> * $Id: VelocityServlet.java,v 1.13 2000/11/04 03:08:51 jon Exp $ */ public abstract class VelocityServlet extends HttpServlet { /** * The HTTP request object context key. */ public static final String REQUEST = "req"; /** * The HTTP response object context key. */ public static final String RESPONSE = "res"; /** * The HTTP content type context key. */ public static final String CONTENT_TYPE = "contentType"; /** * The encoding to use when generating outputing. */ private static String encoding = null; /** * The default content type. */ private static String defaultContentType; /** * This is the string that is looked for when getInitParameter is * called. */ private static final String INIT_PROPS_KEY = "properties"; /** * Performs initialization of this servlet. Called by the servlet * container on loading. * * @param config The servlet configuration to apply. * * @exception ServletException */ public void init( ServletConfig config ) throws ServletException { super.init( config ); String propsFile = config.getInitParameter(INIT_PROPS_KEY); /* * This will attempt to find the location of the properties * file from the relative path to the WAR archive (ie: * docroot). Since JServ returns null for getRealPath() * because it was never implemented correctly, then we know we * will not have an issue with using it this way. I don't know * if this will break other servlet engines, but it probably * shouldn't since WAR files are the future anyways. */ if ( propsFile != null ) { String realPath = getServletContext().getRealPath(propsFile); if ( realPath != null ) propsFile = realPath; } try { Runtime.init(propsFile); defaultContentType = Runtime.getString(Runtime.DEFAULT_CONTENT_TYPE, "text/html"); encoding = Runtime.getString(Runtime.TEMPLATE_ENCODING, "8859_1"); } catch( Exception e ) { throw new ServletException("Error configuring the loader: " + e); } } /** * Handles GET */ public final void doGet( HttpServletRequest request, HttpServletResponse response ) throws ServletException, IOException { doRequest(request, response); } /** * Handle a POST */ public final void doPost( HttpServletRequest request, HttpServletResponse response ) throws ServletException, IOException { doRequest(request, response); } /** * Process the request. */ private void doRequest(HttpServletRequest request, HttpServletResponse response ) throws ServletException, IOException { ServletOutputStream output = response.getOutputStream(); String contentType = null; Writer vw = null; try { // create a new context Context context = new Context(); // put the request/response objects into the context context.put (REQUEST, request); context.put (RESPONSE, response); // check for a content type in the context if (context.containsKey(CONTENT_TYPE)) { contentType = (String) context.get (CONTENT_TYPE); } else { contentType = defaultContentType; } // set the content type response.setContentType(contentType); // call whomever extends this class and implements this method Template template = handleRequest(context); // could not find the template if ( template == null ) throw new Exception ("Cannot find the template!" ); //Writer vw = new BufferedWriter(new OutputStreamWriter(output)); vw = new JspWriterImpl(response, 4*1024, true); template.merge( context, vw); } catch (Exception e) { // display error messages error (output, e.getMessage()); } finally { try { if (vw != null) { vw.flush(); vw.close(); } } catch (Exception e) { // do nothing } } } /** * Retrieves the requested template. * * @param name The file name of the template to retrieve relative to the * <code>template.path</code> property. * @return The requested template. */ public Template getTemplate( String name ) throws Exception { return Runtime.getTemplate(name); } /** * Implement this method to add your application data to the context, * calling the <code>getTemplate()</code> method to produce your return * value. * * @param ctx The context to add your data to. * @return The template to merge with your context. */ protected abstract Template handleRequest( Context ctx ); /** * Send an error message to the client. */ private final void error( ServletOutputStream out, String message ) throws ServletException, IOException { StringBuffer html = new StringBuffer(); html.append("<html>"); html.append("<body bgcolor=\"#ffffff\">"); html.append("<h2>Error processing the template</h2>"); html.append(message); html.append("</body>"); html.append("</html>"); out.print( html.toString() ); } }
package org.orbeon.oxf.xforms; import org.orbeon.oxf.common.OXFException; import org.orbeon.oxf.common.ValidationException; import org.orbeon.oxf.externalcontext.ForwardExternalContextRequestWrapper; import org.orbeon.oxf.pipeline.api.ExternalContext; import org.orbeon.oxf.pipeline.api.PipelineContext; import org.orbeon.oxf.processor.ProcessorUtils; import org.orbeon.oxf.resources.URLFactory; import org.orbeon.oxf.resources.handler.HTTPURLConnection; import org.orbeon.oxf.util.NetUtils; import org.orbeon.oxf.xforms.event.events.XFormsSubmitDoneEvent; import org.orbeon.oxf.xforms.processor.XFormsServer; import org.orbeon.oxf.xml.XMLUtils; import org.orbeon.oxf.xml.dom4j.LocationData; import org.orbeon.saxon.om.FastStringBuffer; import java.io.*; import java.net.*; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; /** * Utilities for XForms submission processing. */ public class XFormsSubmissionUtils { /** * Perform an optimized local connection using the Servlet API instead of using a URLConnection. */ public static XFormsModelSubmission.ConnectionResult doOptimized(PipelineContext pipelineContext, ExternalContext externalContext, XFormsModelSubmission xformsModelSubmission, String method, final String action, String mediatype, boolean doReplace, byte[] messageBody, String queryString) { final XFormsContainingDocument containingDocument = (xformsModelSubmission != null) ? xformsModelSubmission.getContainingDocument() : null; try { if (isPost(method) || isPut(method) || isGet(method) || isDelete(method)) { // Case of empty body if (messageBody == null) messageBody = new byte[0]; // Create requestAdapter depending on method final ForwardExternalContextRequestWrapper requestAdapter; final String effectiveResourceURI; { if (isPost(method) || isPut(method)) { // Simulate a POST or PUT effectiveResourceURI = action; if (XFormsServer.logger.isDebugEnabled()) XFormsContainingDocument.logDebugStatic(containingDocument, "submission", "setting request body", new String[] { "body", new String(messageBody, "UTF-8") }); requestAdapter = new ForwardExternalContextRequestWrapper(externalContext.getRequest(), effectiveResourceURI, method.toUpperCase(), (mediatype != null) ? mediatype : "application/xml", messageBody); } else { // Simulate a GET { final StringBuffer updatedActionStringBuffer = new StringBuffer(action); if (queryString != null) { if (action.indexOf('?') == -1) updatedActionStringBuffer.append('?'); else updatedActionStringBuffer.append('&'); updatedActionStringBuffer.append(queryString); } effectiveResourceURI = updatedActionStringBuffer.toString(); } requestAdapter = new ForwardExternalContextRequestWrapper(externalContext.getRequest(), effectiveResourceURI, method.toUpperCase()); } } if (XFormsServer.logger.isDebugEnabled()) XFormsContainingDocument.logDebugStatic(containingDocument, "submission", "dispatching request", new String[] { "effective resource URI", effectiveResourceURI }); final ExternalContext.RequestDispatcher requestDispatcher = externalContext.getRequestDispatcher(action); final XFormsModelSubmission.ConnectionResult connectionResult = new XFormsModelSubmission.ConnectionResult(effectiveResourceURI) { public void close() { if (getResultInputStream() != null) { try { getResultInputStream().close(); } catch (IOException e) { throw new OXFException("Exception while closing input stream for action: " + action); } } } }; if (doReplace) { // "the event xforms-submit-done is dispatched" if (xformsModelSubmission != null) xformsModelSubmission.getContainingDocument().dispatchEvent(pipelineContext, new XFormsSubmitDoneEvent(xformsModelSubmission, connectionResult.resourceURI)); // Just forward the reply requestDispatcher.forward(requestAdapter, externalContext.getResponse()); connectionResult.dontHandleResponse = true; } else { // We must intercept the reply final ResponseAdapter responseAdapter = new ResponseAdapter(externalContext.getNativeResponse()); requestDispatcher.include(requestAdapter, responseAdapter); // Get response information that needs to be forwarded // NOTE: Here, the resultCode is not propagated from the included resource // when including Servlets. Similarly, it is not possible to obtain the // included resource's content type or headers. Because of this we should not // use an optimized submission from within a servlet. connectionResult.resultCode = responseAdapter.getResponseCode(); connectionResult.resultMediaType = ProcessorUtils.XML_CONTENT_TYPE; connectionResult.setResultInputStream(responseAdapter.getInputStream()); connectionResult.resultHeaders = new HashMap(); connectionResult.lastModified = 0; } return connectionResult; } else if (method.equals("multipart-post")) { // TODO throw new OXFException("xforms:submission: submission method not yet implemented: " + method); } else if (method.equals("form-data-post")) { // TODO throw new OXFException("xforms:submission: submission method not yet implemented: " + method); } else { throw new OXFException("xforms:submission: invalid submission method requested: " + method); } } catch (IOException e) { throw new OXFException(e); } } /** * Perform a connection using an URLConnection. * * @param action absolute URL or absolute path (which must include the context path) */ public static XFormsModelSubmission.ConnectionResult doRegular(ExternalContext externalContext, XFormsContainingDocument containingDocument, String method, final String action, String username, String password, String mediatype, byte[] messageBody, String queryString, List headerNames, Map headerNameValues) { // Compute absolute submission URL final URL submissionURL = createAbsoluteURL(action, queryString, externalContext); return doRegular(externalContext, containingDocument, method, submissionURL, username, password, mediatype, messageBody, headerNames, headerNameValues); } public static XFormsModelSubmission.ConnectionResult doRegular(ExternalContext externalContext, XFormsContainingDocument containingDocument, String method, final URL submissionURL, String username, String password, String mediatype, byte[] messageBody, List headerNames, Map headerNameValues) { // Perform submission final String scheme = submissionURL.getProtocol(); if (scheme.equals("http") || scheme.equals("https") || (isGet(method) && (scheme.equals("file") || scheme.equals("oxf")))) { // http MUST be supported // https SHOULD be supported // file SHOULD be supported try { if (XFormsServer.logger.isDebugEnabled()) { final URI submissionURI; try { String userInfo = submissionURL.getUserInfo(); if (userInfo != null) { final int colonIndex = userInfo.indexOf(':'); if (colonIndex != -1) userInfo = userInfo.substring(0, colonIndex + 1) + "xxxxxxxx"; } submissionURI = new URI(submissionURL.getProtocol(), userInfo, submissionURL.getHost(), submissionURL.getPort(), submissionURL.getPath(), submissionURL.getQuery(), submissionURL.getRef()); } catch (URISyntaxException e) { throw new OXFException(e); } XFormsContainingDocument.logDebugStatic(containingDocument, "submission", "opening URL connection", new String[] { "URL", submissionURI.toString() }); } final URLConnection urlConnection = submissionURL.openConnection(); final HTTPURLConnection httpURLConnection = (urlConnection instanceof HTTPURLConnection) ? (HTTPURLConnection) urlConnection : null; if (isPost(method) || isPut(method) || isGet(method) || isDelete(method)) { // Whether a message body must be sent final boolean hasRequestBody = isPost(method) || isPut(method); // Case of empty body if (messageBody == null) messageBody = new byte[0]; urlConnection.setDoInput(true); urlConnection.setDoOutput(hasRequestBody); if (httpURLConnection != null) { httpURLConnection.setRequestMethod(getHttpMethod(method)); if (username != null) { httpURLConnection.setUsername(username); if (password != null) httpURLConnection.setPassword(password); } } final String contentTypeMediaType = NetUtils.getContentTypeMediaType(mediatype); if (hasRequestBody) { if (isPost(method) && "application/soap+xml".equals(contentTypeMediaType)) { // SOAP POST XFormsContainingDocument.logDebugStatic(containingDocument, "submission", "found SOAP POST"); final Map parameters = NetUtils.getContentTypeParameters(mediatype); final FastStringBuffer sb = new FastStringBuffer("text/xml"); // Extract charset parameter if present // TODO: We have the body as bytes already, using the xforms:submission/@encoding attribute, so this is not right. if (parameters != null) { final String charsetParameter = (String) parameters.get("charset"); if (charsetParameter != null) { // Append charset parameter sb.append("; "); sb.append(charsetParameter); } } // Set new content type urlConnection.setRequestProperty("Content-Type", sb.toString()); // Extract action parameter if present if (parameters != null) { final String actionParameter = (String) parameters.get("action"); if (actionParameter != null) { // Set SOAPAction header urlConnection.setRequestProperty("SOAPAction", actionParameter); XFormsContainingDocument.logDebugStatic(containingDocument, "submission", "setting header", new String[] { "SOAPAction", actionParameter }); } } } else { urlConnection.setRequestProperty("Content-Type", (mediatype != null) ? mediatype : "application/xml"); } } else { if (isGet(method) && "application/soap+xml".equals(contentTypeMediaType)) { // SOAP GET XFormsContainingDocument.logDebugStatic(containingDocument, "submission", "found SOAP GET"); final Map parameters = NetUtils.getContentTypeParameters(mediatype); final FastStringBuffer sb = new FastStringBuffer("application/soap+xml"); // Extract charset parameter if present if (parameters != null) { final String charsetParameter = (String) parameters.get("charset"); if (charsetParameter != null) { // Append charset parameter sb.append("; "); sb.append(charsetParameter); } } // Set Accept header with optional charset urlConnection.setRequestProperty("Accept", sb.toString()); } } // Set headers if provided if (headerNames != null && headerNames.size() > 0) { for (Iterator i = headerNames.iterator(); i.hasNext();) { final String headerName = (String) i.next(); final String headerValue = (String) headerNameValues.get(headerName); urlConnection.setRequestProperty(headerName, headerValue); } } // Forward cookies for session handling // TODO: The Servlet spec mandates JSESSIONID as cookie name; we should only forward this cookie // TODO: We should also forward selected cookies such as JSESSIONIDSSO (Tomcat) and possibly more if (username == null) { final ExternalContext.Session session = externalContext.getSession(false); if (session != null) { XFormsContainingDocument.logDebugStatic(containingDocument, "submission", "setting cookie", new String[] { "JSESSIONID", session.getId() }); urlConnection.setRequestProperty("Cookie", "JSESSIONID=" + session.getId()); } // final String[] cookies = (String[]) externalContext.getRequest().getHeaderValuesMap().get("cookie"); // if (cookies != null) { // for (int i = 0; i < cookies.length; i++) { // final String cookie = cookies[i]; // XFormsServer.logger.debug("XForms - forwarding cookie: " + cookie); // urlConnection.setRequestProperty("Cookie", cookie); } // Forward authorization header // TODO: This should probably not be done automatically if (username == null) { final String authorizationHeader = (String) externalContext.getRequest().getHeaderMap().get("authorization"); if (authorizationHeader != null) { XFormsContainingDocument.logDebugStatic(containingDocument, "submission", "forwarding header", new String[] { "Authorization ", authorizationHeader }); urlConnection.setRequestProperty("Authorization", authorizationHeader); } } // Write request body if needed if (hasRequestBody) { if (XFormsServer.logger.isDebugEnabled()) containingDocument.logDebug("submission", "setting request body", new String[] { "body", new String(messageBody, "UTF-8") }); httpURLConnection.setRequestBody(messageBody); } urlConnection.connect(); // Create result final XFormsModelSubmission.ConnectionResult connectionResult = new XFormsModelSubmission.ConnectionResult(submissionURL.toExternalForm()) { public void close() { if (getResultInputStream() != null) { try { getResultInputStream().close(); } catch (IOException e) { throw new OXFException("Exception while closing input stream for action: " + submissionURL); } } if (httpURLConnection != null) httpURLConnection.disconnect(); } }; // Get response information that needs to be forwarded connectionResult.resultCode = (httpURLConnection != null) ? httpURLConnection.getResponseCode() : 200; final String contentType = urlConnection.getContentType(); connectionResult.resultMediaType = (contentType != null) ? NetUtils.getContentTypeMediaType(contentType) : "application/xml"; connectionResult.resultHeaders = urlConnection.getHeaderFields(); connectionResult.lastModified = urlConnection.getLastModified(); connectionResult.setResultInputStream(urlConnection.getInputStream()); return connectionResult; } else if (method.equals("multipart-post")) { // TODO throw new OXFException("xforms:submission: submission method not yet implemented: " + method); } else if (method.equals("form-data-post")) { // TODO throw new OXFException("xforms:submission: submission method not yet implemented: " + method); } else { throw new OXFException("xforms:submission: invalid submission method requested: " + method); } } catch (IOException e) { throw new ValidationException(e, new LocationData(submissionURL.toExternalForm(), -1, -1)); } } else if (!isGet(method) && (scheme.equals("file") || scheme.equals("oxf"))) { // TODO: implement writing to file: and oxf: // SHOULD be supported (should probably support oxf: as well) throw new OXFException("xforms:submission: submission URL scheme not yet implemented: " + scheme); } else if (scheme.equals("mailto")) { // TODO: implement sending mail // MAY be supported throw new OXFException("xforms:submission: submission URL scheme not yet implemented: " + scheme); } else { throw new OXFException("xforms:submission: submission URL scheme not supported: " + scheme); } } /** * Create an absolute URL from an action string and a search string. * * @param action absolute URL or absolute path * @param queryString optional query string to append to the action URL * @param externalContext current ExternalContext * @return an absolute URL */ public static URL createAbsoluteURL(String action, String queryString, ExternalContext externalContext) { URL resultURL; try { final String actionString; { final StringBuffer updatedActionStringBuffer = new StringBuffer(action); if (queryString != null && queryString.length() > 0) { if (action.indexOf('?') == -1) updatedActionStringBuffer.append('?'); else updatedActionStringBuffer.append('&'); updatedActionStringBuffer.append(queryString); } actionString = updatedActionStringBuffer.toString(); } if (actionString.startsWith("/")) { // Case of path absolute final String requestURL = externalContext.getRequest().getRequestURL(); resultURL = URLFactory.createURL(requestURL, actionString); } else if (NetUtils.urlHasProtocol(actionString)) { // Case of absolute URL resultURL = URLFactory.createURL(actionString); } else { throw new OXFException("Invalid URL: " + actionString); } } catch (MalformedURLException e) { throw new OXFException("Invalid URL: " + action, e); } return resultURL; } public static boolean isGet(String method) { return method.equals("get") || method.equals(XMLUtils.buildExplodedQName(XFormsConstants.XXFORMS_NAMESPACE_URI, "get")); } public static boolean isPost(String method) { return method.equals("post") || method.equals("urlencoded-post") || method.equals(XMLUtils.buildExplodedQName(XFormsConstants.XXFORMS_NAMESPACE_URI, "post")); } public static boolean isPut(String method) { return method.equals("put") || method.equals(XMLUtils.buildExplodedQName(XFormsConstants.XXFORMS_NAMESPACE_URI, "put")); } public static boolean isDelete(String method) { return method.equals("delete") || method.equals(XMLUtils.buildExplodedQName(XFormsConstants.XXFORMS_NAMESPACE_URI, "delete")); } public static String getHttpMethod(String method) { return isGet(method) ? "GET" : isPost(method) ? "POST" : isPut(method) ? "PUT" : isDelete(method) ? "DELETE" : null; } } class ResponseAdapter implements ExternalContext.Response { private Object nativeResponse; private int status = 200; private String contentType; private StringWriter stringWriter; private PrintWriter printWriter; private LocalByteArrayOutputStream byteStream; private InputStream inputStream; public ResponseAdapter(Object nativeResponse) { this.nativeResponse = nativeResponse; } public int getResponseCode() { return status; } public String getContentType() { return contentType; } public Map getHeaders() { return null; } public InputStream getInputStream() { if (inputStream == null) { if (stringWriter != null) { final byte[] bytes; try { bytes = stringWriter.getBuffer().toString().getBytes("utf-8"); } catch (UnsupportedEncodingException e) { throw new OXFException(e); // should not happen } inputStream = new ByteArrayInputStream(bytes, 0, bytes.length); // throw new OXFException("ResponseAdapter.getInputStream() does not yet support content written with getWriter()."); } else if (byteStream != null) { inputStream = new ByteArrayInputStream(byteStream.getByteArray(), 0, byteStream.size()); } } return inputStream; } public void addHeader(String name, String value) { } public boolean checkIfModifiedSince(long lastModified, boolean allowOverride) { return true; } public String getCharacterEncoding() { return null; } public String getNamespacePrefix() { return null; } public OutputStream getOutputStream() throws IOException { if (byteStream == null) byteStream = new LocalByteArrayOutputStream(); return byteStream; } public PrintWriter getWriter() throws IOException { if (stringWriter == null) { stringWriter = new StringWriter(); printWriter = new PrintWriter(stringWriter); } return printWriter; } public boolean isCommitted() { return false; } public void reset() { } public String rewriteActionURL(String urlString) { return null; } public String rewriteRenderURL(String urlString) { return null; } public String rewriteActionURL(String urlString, String portletMode, String windowState) { return null; } public String rewriteRenderURL(String urlString, String portletMode, String windowState) { return null; } public String rewriteResourceURL(String urlString, boolean absolute) { return null; } public String rewriteResourceURL(String urlString, int rewriteMode) { return null; } public void sendError(int sc) throws IOException { this.status = sc; } public void sendRedirect(String pathInfo, Map parameters, boolean isServerSide, boolean isExitPortal) throws IOException { } public void setCaching(long lastModified, boolean revalidate, boolean allowOverride) { } public void setContentLength(int len) { } public void setContentType(String contentType) { this.contentType = contentType; } public void setHeader(String name, String value) { } public void setStatus(int status) { this.status = status; } public void setTitle(String title) { } private static class LocalByteArrayOutputStream extends ByteArrayOutputStream { public byte[] getByteArray() { return buf; } } public Object getNativeResponse() { return nativeResponse; } }
package ahlers.phantom.embedded; import com.google.common.collect.ImmutableList; import de.flapdoodle.embed.process.distribution.Distribution; import de.flapdoodle.embed.process.distribution.IVersion; import de.flapdoodle.embed.process.extract.IExtractedFileSet; import java.io.IOException; import java.util.EnumSet; import java.util.List; import static java.lang.String.format; /** * @author [[mailto:michael@ahlers.consulting Michael Ahlers]] */ public enum PhantomCommand implements IPhantomCommand { Any { @Override public boolean matches(final IVersion version) { return true; } @Override public List<String> emit(final IPhantomConfig config, final IExtractedFileSet files) throws IOException { return ImmutableList .<String>builder() .add(files.executable().getAbsolutePath()) .add(format("--debug=%s", config.debug())) .build(); } }, V21 { @Override public boolean matches(final IVersion version) { return PhantomVersion.V211 == version; } @Override public List<String> emit(final IPhantomConfig config, final IExtractedFileSet files) throws IOException { return ImmutableList .<String>builder() .addAll(Any.emit(config, files)) .build(); } }; /** * {@link PhantomCommand#Any} is guaranteed to match. */ public static IPhantomCommand valueFor(final IVersion version) { for (final IPhantomCommand emitter : EnumSet.complementOf(EnumSet.of(Any))) { if (emitter.matches(version)) { return emitter; } } return Any; } public static IPhantomCommand valueFor(final Distribution distribution) { return valueFor(distribution.getVersion()); } }
package blue.lapis.pore.impl; import blue.lapis.pore.converter.vector.LocationConverter; import blue.lapis.pore.converter.wrapper.WrapperConverter; import blue.lapis.pore.impl.entity.PorePlayer; import blue.lapis.pore.util.PoreWrapper; import com.google.common.base.Optional; import org.apache.commons.lang.NotImplementedException; import org.bukkit.Location; import org.bukkit.OfflinePlayer; import org.bukkit.entity.Player; import org.spongepowered.api.entity.player.User; import org.spongepowered.api.util.ban.Bans; import java.util.Map; import java.util.UUID; public class PoreOfflinePlayer extends PoreWrapper<User> implements OfflinePlayer { public static PoreOfflinePlayer of(User handle) { return WrapperConverter.of(PoreOfflinePlayer.class, handle); } protected PoreOfflinePlayer(User handle) { super(handle); } @Override public boolean isOnline() { return getHandle().isOnline(); } @Override public String getName() { return getHandle().getName(); } @Override public UUID getUniqueId() { return getHandle().getUniqueId(); } @Override public boolean isBanned() { return getHandle().isBanned(); } @Override public void setBanned(boolean banned) { if (banned) { getHandle().ban(Bans.of(getHandle())); } else { getHandle().pardon(); } } @Override public boolean isWhitelisted() { return getHandle().isWhitelisted(); } @Override public void setWhitelisted(boolean value) { getHandle().setWhitelisted(value); } @Override public Player getPlayer() { Optional<org.spongepowered.api.entity.player.Player> player = getHandle().getPlayer(); if (player.isPresent()) { return PorePlayer.of(player.get()); } else { return null; } } @Override public long getFirstPlayed() { return getHandle().getFirstPlayed().getTime(); } @Override public long getLastPlayed() { return getHandle().getLastPlayed().getTime(); } @Override public boolean hasPlayedBefore() { return getHandle().hasJoinedBefore(); } @Override public Location getBedSpawnLocation() { return LocationConverter.of(getHandle().getBedLocation().orNull()); } @Override public Map<String, Object> serialize() { throw new NotImplementedException(); } @Override public boolean isOp() { throw new NotImplementedException(); } @Override public void setOp(boolean value) { throw new NotImplementedException(); } }
package br.com.dbsoft.ui.bean.crud; import java.lang.annotation.Annotation; import java.math.BigDecimal; import java.sql.Connection; import java.sql.Timestamp; import java.util.ArrayList; import java.util.Collection; import java.util.List; import javax.enterprise.context.Conversation; import javax.enterprise.context.ConversationScoped; import javax.faces.component.UIComponent; import javax.faces.context.FacesContext; import javax.inject.Inject; import br.com.dbsoft.core.DBSApproval; import br.com.dbsoft.core.DBSApproval.APPROVAL_STAGE; import br.com.dbsoft.core.DBSSDK; import br.com.dbsoft.error.DBSIOException; import br.com.dbsoft.io.DBSColumn; import br.com.dbsoft.io.DBSDAO; import br.com.dbsoft.io.DBSResultDataModel; import br.com.dbsoft.message.IDBSMessage; import br.com.dbsoft.message.IDBSMessage.MESSAGE_TYPE; import br.com.dbsoft.ui.bean.DBSBean; import br.com.dbsoft.ui.bean.crud.DBSCrudBeanEvent.CRUD_EVENT; import br.com.dbsoft.ui.component.DBSUIInput; import br.com.dbsoft.ui.component.DBSUIInputText; import br.com.dbsoft.ui.component.dialog.DBSDialogMessage; import br.com.dbsoft.ui.component.dialog.IDBSDialogMessage; import br.com.dbsoft.ui.core.DBSFaces; import br.com.dbsoft.util.DBSDate; import br.com.dbsoft.util.DBSIO; import br.com.dbsoft.util.DBSNumber; import br.com.dbsoft.util.DBSObject; import br.com.dbsoft.util.DBSIO.SORT_DIRECTION; public abstract class DBSCrudBean extends DBSBean{ private static final long serialVersionUID = -8550893738791483527L; public static enum FormStyle { DIALOG (0), TABLE (1), VIEW (2); private int wCode; private FormStyle(int pCode) { this.wCode = pCode; } public int getCode() { return wCode; } public static FormStyle get(int pCode) { switch (pCode) { case 0: return DIALOG; case 1: return TABLE; case 2: return VIEW; default: return DIALOG; } } } public static enum EditingMode { NONE ("Not Editing", 0), INSERTING ("Inserting", 1), UPDATING ("Updating", 2), DELETING ("Deleting", 3), APPROVING ("Approving", 4), REPROVING ("Reproving", 5); private String wName; private int wCode; private EditingMode(String pName, int pCode) { this.wName = pName; this.wCode = pCode; } public String getName() { return wName; } public int getCode() { return wCode; } public static EditingMode get(int pCode) { switch (pCode) { case 0: return NONE; case 1: return INSERTING; case 2: return UPDATING; case 3: return DELETING; case 4: return APPROVING; case 5: return REPROVING; default: return NONE; } } } public static enum EditingStage{ NONE ("None", 0), COMMITTING ("Committing", 1), IGNORING ("Ignoring", 2); private String wName; private int wCode; private EditingStage(String pName, int pCode) { this.wName = pName; this.wCode = pCode; } public String getName() { return wName; } public int getCode() { return wCode; } public static EditingStage get(int pCode) { switch (pCode) { case 0: return NONE; case 1: return COMMITTING; case 2: return IGNORING; default: return NONE; } } } @Inject private Conversation wConversation; private static final long wConversationTimeout = 600000; //10 minutos protected DBSDAO<?> wDAO; private List<IDBSCrudBeanEventsListener> wEventListeners = new ArrayList<IDBSCrudBeanEventsListener>(); private EditingMode wEditingMode = EditingMode.NONE; private EditingStage wEditingStage = EditingStage.NONE; private FormStyle wFormStyle = FormStyle.DIALOG; private List<Integer> wSelectedRowsIndexes = new ArrayList<Integer>(); private Collection<DBSColumn> wSavedCurrentColumns = null; private boolean wValueChanged; private int wCopiedRowIndex = -1; private boolean wValidateComponentHasError = false; private Boolean wDialogOpened = false; private String wDialogCaption; private Boolean wDialogCloseAfterInsert = false; private String wMessageConfirmationEdit = "Confirmar a edição?"; private String wMessageConfirmationInsert = "Confirmar a inclusão?"; private String wMessageConfirmationDelete = "Confirmar a exclusão?"; private String wMessageConfirmationApprove = "Confirmar a aprovação?"; private String wMessageConfirmationReprove = "Confirmar a reprovação?"; private String wMessageIgnoreEdit = "Ignorar a edição?"; private String wMessageIgnoreInsert = "Ignorar a inclusão?"; private String wMessageIgnoreDelete = "Ignorar a exclusão?"; private Boolean wAllowUpdate = true; private Boolean wAllowInsert = true; private Boolean wAllowDelete = true; private Boolean wAllowRefresh = true; private Boolean wAllowApproval = false; private Boolean wAllowApprove = true; private Boolean wAllowReprove = true; private Boolean wAllowCopy = true; private Boolean wAllowCopyOnUpdate = false; private Integer wApprovalUserStages = 0; private String wColumnNameApprovalStage = null; private String wColumnNameApprovalUserIdRegistered = null; private String wColumnNameApprovalUserIdVerified = null; private String wColumnNameApprovalUserIdConferred = null; private String wColumnNameApprovalUserIdApproved = null; private String wColumnNameApprovalDateApproved = null; private String wColumnNameDateOnInsert = null; private String wColumnNameDateOnUpdate = null; private String wColumnNameUserIdOnInsert = null; private String wColumnNameUserIdOnUpdate = null; private String wSortColumn = ""; private String wSortDirection = SORT_DIRECTION.DESCENDING.getCode(); private Boolean wRevalidateBeforeCommit = false; private Integer wUserId; private Boolean wMultipleSelection = false; private DBSCrudBean wParentCrudBean = null; private List<DBSCrudBean> wChildrenCrudBean = new ArrayList<DBSCrudBean>(); //Mensagens private IDBSDialogMessage wMessageNoRowComitted = new DBSDialogMessage(MESSAGE_TYPE.ERROR,"Erro durante a gravação.\n Nenhum registro foi afetado.\n"); private IDBSDialogMessage wMessageOverSize = new DBSDialogMessage(MESSAGE_TYPE.ERROR,"Quantidade de caracteres do texto digitado no campo '%s' ultrapassou a quantidade permitida de %s caracteres. Por favor, diminua o texto digitado."); private IDBSDialogMessage wMessageNoChange = new DBSDialogMessage(MESSAGE_TYPE.INFORMATION,"Não houve alteração de informação."); private IDBSDialogMessage wMessaggeApprovalSameUserError = new DBSDialogMessage(MESSAGE_TYPE.ERROR,"Não é permitida a aprovação de um registro incluido pelo próprio usuário."); public String getCID(){ return wConversation.getId(); } public void conversationBegin(){ for (Annotation xAnnotation:this.getClass().getDeclaredAnnotations()){ if (xAnnotation.annotationType() == ConversationScoped.class){ pvConversationBegin(); break; } } } @Override protected void initializeClass() { conversationBegin(); pvFireEventInitialize(); //Finaliza os outros crudbeans antes de inicializar este. // DBSFaces.finalizeDBSBeans(this, false); << Comentado pois os beans passaram a ser criados como ConversationScoped - 12/Ago/2014 } @Override protected void finalizeClass(){ pvFireEventFinalize(); //Exclui os listeners associadao, antes de finalizar wEventListeners.clear(); } public void addEventListener(IDBSCrudBeanEventsListener pEventListener) { if (!wEventListeners.contains(pEventListener)){ wEventListeners.add(pEventListener); } } public void removeEventListener(IDBSCrudBeanEventsListener pEventListener) { if (wEventListeners.contains(pEventListener)){ wEventListeners.remove(pEventListener); } } public <T> void setValue(String pColumnName, Object pColumnValue, Class<T> pValueClass){ T xValue = DBSObject.<T>toClassValue(pColumnValue, pValueClass); setValue(pColumnName, xValue); } public void setValue(String pColumnName, Object pColumnValue){ //Utiliza ListValue para controlar os valores de todas as linhas if (wFormStyle == FormStyle.TABLE){ setListValue(pColumnName, pColumnValue); }else{ pvSetValueDAO(pColumnName, pColumnValue); } } public <T> T getValue(String pColumnName){ //Utiliza ListValue para controlar os valores de todas as linhas if (wFormStyle == FormStyle.TABLE){ return getListValue(pColumnName); }else{ return pvGetValue(pColumnName); } } public <T> T getValue(String pColumnName, Class<T> pValueClass){ return DBSObject.<T>toClassValue(getValue(pColumnName), pValueClass); } @SuppressWarnings("unchecked") public <T> T getValueOriginal(String pColumnName){ //Se existir registro corrente if (wDAO != null && (wDAO.getColumns().size() > 0 || wDAO.getCommandColumns().size() > 0)){ return (T) wDAO.getValueOriginal(pColumnName); }else{ return null; } } public <T> T getValueOriginal(String pColumnName, Class<T> pValueClass){ return DBSObject.<T>toClassValue(getValueOriginal(pColumnName), pValueClass); } @SuppressWarnings("unchecked") public <T> T getListValue(String pColumnName){ if (wDAO != null){ return (T) wDAO.getListValue(pColumnName); }else{ return null; } } public <T> T getListValue(String pColumnName, Class<T> pValueClass){ return DBSObject.<T>toClassValue(getListValue(pColumnName), pValueClass); } private void setListValue(String pColumnName, Object pColumnValue){ if (wDAO != null){ wDAO.setListValue(pColumnName, pColumnValue); } } public boolean getIsListNewRow(){ if (wDAO != null){ return wDAO.getIsNewRow(); }else{ return false; } } public String getListFormattedValue(String pColumnId) throws DBSIOException{return "pColumnId '" + pColumnId + "' desconhecida";} public IDBSMessage getColumnMessage(String pColumnName){ if (wDAO != null && (wDAO.getColumns().size() > 0 || wDAO.getCommandColumns().size() > 0)){ return wDAO.getMessage(pColumnName); }else{ return null; } } public void crudFormBeforeShowComponent(UIComponent pComponent){ if (wDAO!=null){ //Configura os campos do tipo input if (pComponent instanceof DBSUIInput){ DBSColumn xColumn = pvGetDAOColumnFromInputValueExpression((DBSUIInput) pComponent); if (xColumn!=null){ if (pComponent instanceof DBSUIInputText){ DBSUIInputText xInput = (DBSUIInputText) pComponent; xInput.setMaxLength(xColumn.getSize()); } } } } } public void crudFormValidateComponent(FacesContext pContext, UIComponent pComponent, Object pValue){ if (wEditingMode!=EditingMode.NONE){ if (wDAO!=null && pValue!=null){ String xSourceId = pContext.getExternalContext().getRequestParameterMap().get(DBSFaces.PARTIAL_SOURCE_PARAM); if (xSourceId !=null && !xSourceId.endsWith(":cancel")){ //TODO verificar se existe uma forma melhor de identificar se foi um cancelamento if (pComponent instanceof DBSUIInputText){ DBSUIInputText xInput = (DBSUIInputText) pComponent; DBSColumn xColumn = pvGetDAOColumnFromInputValueExpression(xInput); if (xColumn!=null){ String xValue = pValue.toString(); if (pValue instanceof Number){ xValue = DBSNumber.getOnlyNumber(xValue); } if (xValue.length() > xColumn.getSize()){ wMessageOverSize.setMessageTextParameters(xInput.getLabel(), xColumn.getSize()); addMessage(wMessageOverSize); wValidateComponentHasError = true; } } } } } } } public EditingMode getEditingMode() { return wEditingMode; } private synchronized void setEditingMode(EditingMode pEditingMode) { if (wEditingMode != pEditingMode){ //Qualquer troca no editingMode, desativa o editingstage setEditingStage(EditingStage.NONE); if (pEditingMode.equals(EditingMode.NONE)){ pvFireEventAfterEdit(wEditingMode); setValueChanged(false); } wEditingMode = pEditingMode; } } public EditingStage getEditingStage() { return wEditingStage; } private void setEditingStage(EditingStage pEditingStage) { if (wEditingStage != pEditingStage){ //Salva novo estado wEditingStage = pEditingStage; } } public void setDialogCaption(String pDialogCaption) {wDialogCaption = pDialogCaption;} public String getDialogCaption() {return wDialogCaption;} public Boolean getDialogOpened() { return wDialogOpened; } private synchronized void setDialogOpened(Boolean pDialogOpened) { if (wFormStyle == FormStyle.DIALOG){ if (wDialogOpened != pDialogOpened){ wDialogOpened = pDialogOpened; } } } public Boolean getDialogCloseAfterInsert() { return wDialogCloseAfterInsert; } public void setDialogCloseAfterInsert(Boolean pDialogCloseAfterInsert) { wDialogCloseAfterInsert = pDialogCloseAfterInsert; } public FormStyle getFormStyle() {return wFormStyle;} public void setFormStyle(FormStyle pFormStyle) {wFormStyle = pFormStyle;} public String getMessageConfirmationEdit() {return wMessageConfirmationEdit;} public void setMessageConfirmationEdit(String pMessageConfirmationEdit) {wMessageConfirmationEdit = pMessageConfirmationEdit;} public String getMessageConfirmationInsert() {return wMessageConfirmationInsert;} public void setMessageConfirmationInsert(String pDialogConfirmationInsertMessage) {wMessageConfirmationInsert = pDialogConfirmationInsertMessage;} public String getMessageConfirmationDelete() {return wMessageConfirmationDelete;} public void setMessageConfirmationDelete(String pMessageConfirmationDelete) {wMessageConfirmationDelete = pMessageConfirmationDelete;} public String getMessageConfirmationApprove() {return wMessageConfirmationApprove;} public void setMessageConfirmationApprove(String pMessageConfirmationApprove) {wMessageConfirmationApprove = pMessageConfirmationApprove;} public String getMessageConfirmationReprove() {return wMessageConfirmationReprove;} public void setMessageConfirmationReprove(String pMessageConfirmationReprove) {wMessageConfirmationReprove = pMessageConfirmationReprove;} public String getMessageIgnoreEdit() {return wMessageIgnoreEdit;} public void setMessageIgnoreEdit(String pMessageIgnoreEdit) {wMessageIgnoreEdit = pMessageIgnoreEdit;} public String getMessageIgnoreInsert() {return wMessageIgnoreInsert;} public void setMessageIgnoreInsert(String pMessageIgnoreInsert) {wMessageIgnoreInsert = pMessageIgnoreInsert;} public String getMessageIgnoreDelete() {return wMessageIgnoreDelete;} public void setMessageIgnoreDelete(String pMessageIgnoreDelete) {wMessageIgnoreDelete = pMessageIgnoreDelete;} public Boolean getMessageConfirmationExists(){ if (getIsCommitting()){ if (getIsUpdating()){ if (DBSObject.isEmpty(getMessageConfirmationEdit())){ return false; } }else if (getIsInserting()){ if (DBSObject.isEmpty(getMessageConfirmationInsert())){ return false; } }else if (getIsDeleting()){ if (DBSObject.isEmpty(getMessageConfirmationDelete())){ return false; } }else{ return false; } return true; } return false; } public Boolean getMessageIgnoreExists(){ if (getIsIgnoring()){ if (getIsUpdating()){ if (DBSObject.isEmpty(getMessageIgnoreEdit())){ return false; } }else if (getIsInserting()){ if (DBSObject.isEmpty(getMessageIgnoreInsert())){ return false; } }else if (getIsDeleting()){ if (DBSObject.isEmpty(getMessageIgnoreDelete())){ return false; } }else{ return false; } return true; } return false; } public DBSResultDataModel getList() throws DBSIOException{ if (wDAO==null){ pvSearchList(); if (wDAO==null || wDAO.getResultDataModel() == null){ return new DBSResultDataModel(); } clearMessages(); } return wDAO.getResultDataModel(); } /** * Retorna a quantidade de registros da pesquisa principal. * @return * @throws DBSIOException */ public Integer getRowCount() throws DBSIOException{ if (getList() != null){ return getList().getRowCount(); }else{ return 0; } } public Boolean getAllowDelete() throws DBSIOException { return wAllowDelete && pvApprovalUserAllowRegister() && getApprovalStage() == APPROVAL_STAGE.REGISTERED; } public void setAllowDelete(Boolean pAllowDelete) {wAllowDelete = pAllowDelete;} public Boolean getAllowUpdate() throws DBSIOException { return wAllowUpdate && pvApprovalUserAllowRegister() && getApprovalStage() == APPROVAL_STAGE.REGISTERED; } public void setAllowUpdate(Boolean pAllowUpdate) {wAllowUpdate = pAllowUpdate;} public Boolean getAllowInsert() { return wAllowInsert && pvApprovalUserAllowRegister(); } public void setAllowInsert(Boolean pAllowInsert) { wAllowInsert = pAllowInsert; setAllowCopy(pAllowInsert); } public Boolean getAllowRefresh() {return wAllowRefresh;} public void setAllowRefresh(Boolean pAllowRefresh) {wAllowRefresh = pAllowRefresh;} public Boolean getMultipleSelection() {return wMultipleSelection;} public void setMultipleSelection(Boolean pMultipleSelection) {wMultipleSelection = pMultipleSelection;} public Boolean getAllowApproval() {return wAllowApproval;} public void setAllowApproval(Boolean pAllowApproval) {wAllowApproval = pAllowApproval;} public Boolean getAllowApprove(){return wAllowApprove;} public void setAllowApprove(Boolean pAllowApprove){wAllowApprove = pAllowApprove;} public Boolean getAllowReprove(){return wAllowReprove;} public void setAllowReprove(Boolean pAllowReprove){wAllowReprove = pAllowReprove;} public Boolean getAllowCopy(){return wAllowCopy;} public void setAllowCopy(Boolean pAllowCopy){wAllowCopy = pAllowCopy;} public Boolean getAllowCopyOnUpdate(){return wAllowCopyOnUpdate;} public void setAllowCopyOnUpdate(Boolean pAllowCopyOnUpdate){wAllowCopyOnUpdate = pAllowCopyOnUpdate;} public APPROVAL_STAGE getApprovalStage() throws DBSIOException { return pvGetApprovalStage(true); } public APPROVAL_STAGE getApprovalStageListValue() throws DBSIOException { return pvGetApprovalStage(false); } public void setApprovalStage(APPROVAL_STAGE pApprovalStage) { setValue(getColumnNameApprovalStage(), pApprovalStage.getCode()); } public APPROVAL_STAGE getApprovalUserNextStage() throws DBSIOException{ return pvGetApprovalNextUserStage(); } public APPROVAL_STAGE getApprovalUserNextStageListValue() throws DBSIOException{ return pvGetApprovalNextUserStage(); } public APPROVAL_STAGE getApprovalUserMaxStage(){ return DBSApproval.getMaxStage(getApprovalUserStages()); } public Integer getApprovalUserStages() {return wApprovalUserStages;} public void setApprovalUserStages(Integer pApprovalUserStages) {wApprovalUserStages = pApprovalUserStages;} public Boolean getIsApprovalStageRegistered() throws DBSIOException{ return getApprovalStage() == APPROVAL_STAGE.REGISTERED; } public Boolean getIsApprovalStageVerified() throws DBSIOException{ return getApprovalStage() == APPROVAL_STAGE.VERIFIED; } public Boolean getIsApprovalStageConferred() throws DBSIOException{ return getApprovalStage() == APPROVAL_STAGE.CONFERRED; } public Boolean getIsApprovalStageApproved() throws DBSIOException{ return getApprovalStage() == APPROVAL_STAGE.APPROVED; } public String getColumnNameApprovalStage() {return wColumnNameApprovalStage;} public void setColumnNameApprovalStage(String pColumnNameApprovalStage) {wColumnNameApprovalStage = pColumnNameApprovalStage;} public String getColumnNameApprovalUserIdRegistered() {return wColumnNameApprovalUserIdRegistered;} public void setColumnNameApprovalUserIdRegistered(String pColumnNameApprovalUserIdRegistered) {wColumnNameApprovalUserIdRegistered = pColumnNameApprovalUserIdRegistered;} public String getColumnNameApprovalUserIdConferred() {return wColumnNameApprovalUserIdConferred;} public void setColumnNameApprovalUserIdConferred(String pColumnNameApprovalUserIdConferred) {wColumnNameApprovalUserIdConferred = pColumnNameApprovalUserIdConferred;} public String getColumnNameApprovalUserIdVerified() {return wColumnNameApprovalUserIdVerified;} public void setColumnNameApprovalUserIdVerified(String pColumnNameApprovalUserIdVerified) {wColumnNameApprovalUserIdVerified = pColumnNameApprovalUserIdVerified;} public String getColumnNameApprovalUserIdApproved() {return wColumnNameApprovalUserIdApproved;} public void setColumnNameApprovalUserIdApproved(String pColumnNameApprovalUserIdApproved) {wColumnNameApprovalUserIdApproved = pColumnNameApprovalUserIdApproved;} public String getColumnNameApprovalDateApproved() {return wColumnNameApprovalDateApproved;} public void setColumnNameApprovalDateApproved(String pColumnNameApprovalDateApproved) {wColumnNameApprovalDateApproved = pColumnNameApprovalDateApproved;} public String getColumnNameDateOnInsert() {return wColumnNameDateOnInsert;} public void setColumnNameDateOnInsert(String pColumnNameDateOnInsert) {wColumnNameDateOnInsert = pColumnNameDateOnInsert;} public String getColumnNameDateOnUpdate() {return wColumnNameDateOnUpdate;} public void setColumnNameDateOnUpdate(String pColumnNameDateOnUpdate) {wColumnNameDateOnUpdate = pColumnNameDateOnUpdate;} public String getColumnNameUserIdOnInsert() {return wColumnNameUserIdOnInsert;} public void setColumnNameUserIdOnInsert(String pColumnNameUserIdOnInsert) {wColumnNameUserIdOnInsert = pColumnNameUserIdOnInsert;} public String getColumnNameUserIdOnUpdate() {return wColumnNameUserIdOnUpdate;} public void setColumnNameUserIdOnUpdate(String pColumnNameUserIdOnUpdate) {wColumnNameUserIdOnUpdate = pColumnNameUserIdOnUpdate;} public void setSortColumn(String pSortColumn){wSortColumn = pSortColumn;} public String getSortColumn(){return wSortColumn;} public void setSortDirection(String pSortDirection){wSortDirection = pSortDirection;} public String getSortDirection(){return wSortDirection;} public Boolean getRevalidateBeforeCommit() {return wRevalidateBeforeCommit;} public void setRevalidateBeforeCommit(Boolean pRevalidateBeforeCommit) {wRevalidateBeforeCommit = pRevalidateBeforeCommit;} public Integer getUserId() {return wUserId;} public void setUserId(Integer pUserId) {wUserId = pUserId;} public void setParentCrudBean(DBSCrudBean pCrudBean) { wParentCrudBean = pCrudBean; if (!pCrudBean.getChildrenCrudBean().contains(this)){ pCrudBean.getChildrenCrudBean().add(this); } } public DBSCrudBean getParentCrudBean() { return wParentCrudBean; } public List<DBSCrudBean> getChildrenCrudBean() { return wChildrenCrudBean; } public void setValueChanged(Boolean pChanged){ wValueChanged = pChanged; } public boolean getIsValueChanged(){ return wValueChanged; } public Boolean getIsCommitting(){ return (wEditingStage == EditingStage.COMMITTING); } public Boolean getIsUpdating(){ return (wEditingMode == EditingMode.UPDATING); } public Boolean getIsEditing(){ return (wEditingMode != EditingMode.NONE); } public Boolean getIsDeleting(){ return (wEditingMode == EditingMode.DELETING); } public Boolean getIsApproving(){ return (wEditingMode == EditingMode.APPROVING); } public Boolean getIsReproving(){ return (wEditingMode == EditingMode.REPROVING); } // public Boolean getIsApprovalStageApproved(Integer pApprovalStage){ // return DBSApproval.isApproved(pApprovalStage); // public Boolean getIsApprovalStageConferred(Integer pApprovalStage){ // return DBSApproval.isConferred(pApprovalStage); // public Boolean getIsApprovalStageVerified(Integer pApprovalStage){ // return DBSApproval.isVerified(pApprovalStage); // public Boolean getIsApprovalStageRegistered(Integer pApprovalStage){ // return DBSApproval.isRegistered(pApprovalStage); public Boolean getIsApprovingOrReproving(){ return (wEditingMode == EditingMode.APPROVING || wEditingMode == EditingMode.REPROVING); } public Boolean getIsIgnoring(){ return (wEditingStage == EditingStage.IGNORING); } public Boolean getIsFirst(){ if (wDAO != null){ return wDAO.getIsFist(); }else{ return true; } } public Boolean getIsLast(){ if (wDAO != null){ return wDAO.getIsLast(); }else{ return true; } } public Boolean getIsViewing(){ return (wEditingMode == EditingMode.NONE); } public Boolean getIsInserting(){ return (wEditingMode == EditingMode.INSERTING); } public Boolean getIsEditingDisabled(){ if (wAllowApproval || wAllowDelete || wAllowInsert || wAllowUpdate){ return false; } return true; } public void setDisableEditing(){ setAllowApproval(false); setAllowDelete(false); setAllowInsert(false); setAllowUpdate(false); } public Boolean getIsReadOnly(){ if (getIsViewing() || wEditingMode == EditingMode.DELETING){ return true; }else{ return false; } } public Boolean getIsClosed(){ return (!wDialogOpened); } /** * Se tem algumm registro copiado * @return */ public Boolean getIsCopied(){ if (wCopiedRowIndex != -1){ return true; }else{ return false; } } // Methods /** * Retorna lista dos itens selecionados * @return */ public List<Integer> getSelectedRowsIndexes(){ return wSelectedRowsIndexes; } public Boolean getSelected() throws DBSIOException { if (wSelectedRowsIndexes.contains(getList().getRowIndex())){ return true; } return false; } public void setSelected(Boolean pSelectOne) throws DBSIOException { // wDAO.synchronize(); pvSetSelected(pSelectOne); if (pvFireEventBeforeSelect()){ pvFireEventAfterSelect(); }else{ pvSetSelected(!pSelectOne); } } public boolean getHasSelected(){ if (wSelectedRowsIndexes != null){ if (wSelectedRowsIndexes.size()>0){ return true; } } return false; } /** * Selectiona todas as linhas que exibidas */ public synchronized String selectAll() throws DBSIOException{ if (!wDialogOpened){ pvSelectAll(); if (pvFireEventBeforeSelect()){ pvFireEventAfterSelect(); }else{ pvSelectAll(); } }else{ //exibir erro de procedimento } return DBSFaces.getCurrentView(); } // Methods public synchronized String confirmEditing() throws DBSIOException{ if (wEditingMode!=EditingMode.NONE){ if (wEditingStage==EditingStage.NONE){ if (wValidateComponentHasError){ wValidateComponentHasError = false; }else{ if ((getIsValueChanged() && getIsDeleting() == false) || getIsDeleting()){ if (pvFireEventBeforeValidate() && pvFireEventValidate()){ setEditingStage(EditingStage.COMMITTING); if (!getMessageConfirmationExists()){ return endEditing(true); } }else{ if(getIsDeleting() || getIsApprovingOrReproving()){ setEditingMode(EditingMode.NONE); } } }else{ addMessage(wMessageNoChange); } } }else{ //exibe mensagem de erro de procedimento } }else{ //exibe mensagem de erro de procedimento } return DBSFaces.getCurrentView(); } // Methods public synchronized String ignoreEditing() throws DBSIOException{ if (wEditingMode!=EditingMode.NONE){ if (wEditingStage==EditingStage.NONE){ //Disparado eventos antes de ignorar setEditingStage(EditingStage.IGNORING); if (!getIsValueChanged()){ return endEditing(true); } if (!getMessageIgnoreExists()){ return endEditing(true); } }else{ //exibe mensagem de erro de procedimento } }else{ //exibe mensagem de erro de procedimento } return DBSFaces.getCurrentView(); } public synchronized String endEditing(Boolean pConfirm) throws DBSIOException{ try{ if (pConfirm){ if (wEditingStage!=EditingStage.NONE){ if (wEditingStage==EditingStage.COMMITTING){ //Disparando eventos if (pvFireEventValidate() && pvFireEventBeforeCommit()){ pvFireEventAfterCommit(); pvSearchList(); pvEndEditing(true); }else{ pvEndEditing(false); } }else if (wEditingStage==EditingStage.IGNORING){ //Disparando eventos if (pvFireEventBeforeIgnore()){ pvFireEventAfterIgnore(); pvEndEditing(true); }else{ pvEndEditing(false); } } }else{ //exibe mensagem de erro de procedimento } }else{ setEditingStage(EditingStage.NONE); switch(wEditingMode){ case UPDATING: break; case INSERTING: break; case DELETING: setEditingMode(EditingMode.NONE); view(); break; case APPROVING: setEditingMode(EditingMode.NONE); close(false); break; case REPROVING: setEditingMode(EditingMode.NONE); close(false); break; default: //Exibe mensagem de erro de procedimento } } }catch(Exception e){ wLogger.error("Crud:" + getDialogCaption() + ":endEditing", e); setEditingMode(EditingMode.NONE); DBSIO.throwIOException(e); } return DBSFaces.getCurrentView(); } public String beginEditingView() throws DBSIOException{ if (getFormStyle() != FormStyle.VIEW){ return DBSFaces.getCurrentView(); } if (getEditingMode() != EditingMode.NONE){ return DBSFaces.getCurrentView(); } try{ openConnection(); //Le o registro beforeRefresh(null); if (wConnection != null){ moveFirst(); //Verifica se existe registro corrente if (wDAO != null && wDAO.getCurrentRowIndex() > -1){ return update(); }else{ return insert(); } } return insert(); }finally{ if (wConnection != null){ closeConnection(); } } } // Methods public synchronized String searchList() throws DBSIOException{ boolean xOpenConnection = false; if (wParentCrudBean!=null && !DBSIO.isConnectionOpened(wParentCrudBean.wConnection)){ xOpenConnection = true; wParentCrudBean.openConnection(); } pvSearchList(); if (xOpenConnection){ wParentCrudBean.closeConnection(); } return DBSFaces.getCurrentView(); } public synchronized String refreshList() throws DBSIOException{ boolean xOpenConnection = false; if (wParentCrudBean!=null && !DBSIO.isConnectionOpened(wParentCrudBean.wConnection)){ xOpenConnection = true; wParentCrudBean.openConnection(); } pvFireEventInitialize(); if (xOpenConnection){ wParentCrudBean.closeConnection(); } return searchList(); } public synchronized String copy() throws DBSIOException{ if (wAllowCopy || wAllowCopyOnUpdate){ wCopiedRowIndex = wDAO.getCurrentRowIndex(); pvFireEventAfterCopy(); } return DBSFaces.getCurrentView(); } /** * Seta os valores atuais com os valores do registro copiado * @throws DBSIOException */ public synchronized String paste() throws DBSIOException{ if (wAllowCopy || wAllowCopyOnUpdate){ if (pvFireEventBeforePaste()){ //Seta o registro atual como sendo o registro copiado wDAO.paste(wCopiedRowIndex); setValueChanged(true); } } return DBSFaces.getCurrentView(); } /** * Exibe todos os itens selecionados */ public synchronized String viewSelection() throws DBSIOException{ if (wFormStyle == FormStyle.TABLE){return DBSFaces.getCurrentView();} //Limpa todas as mensagens que estiverem na fila clearMessages(); if (wDAO.getCurrentRowIndex() != -1){ if (!wDialogOpened){ if (wEditingStage==EditingStage.NONE){ //Chama evento if (pvFireEventBeforeView()){ setDialogOpened(true); pvFireEventAfterView(); } }else{ //exibir erro de procedimento } }else{ //exibir erro de procedimento } } return DBSFaces.getCurrentView(); } /** * Exibe o item selecionado */ public synchronized String view() throws DBSIOException{ if (wFormStyle == FormStyle.TABLE){return DBSFaces.getCurrentView();} if (wFormStyle == FormStyle.DIALOG){ //Limpa todas as mensagens que estiverem na fila clearMessages(); } if (wConnection != null && wDAO.getCurrentRowIndex()!=-1){ if (wEditingStage==EditingStage.NONE){ //Chama evento if (pvFireEventBeforeView()){ setDialogOpened(true); pvFireEventAfterView(); } }else{ //exibir erro de procedimento } }else{ //exibir erro de procedimento } return DBSFaces.getCurrentView(); } /** * Informa com cadastro foi fechado */ public synchronized String close() throws DBSIOException{ return close(true); } /** * Informa que cadastro foi fechado */ public synchronized String close(Boolean pClearMessage) throws DBSIOException{ if (wDialogOpened){ //Dispara evento if (pvFireEventBeforeClose()){ setDialogOpened(false); if (pClearMessage) { clearMessages(); } } //getLastInstance("a"); }else{ //exibe mensagem de erro de procedimento } return DBSFaces.getCurrentView(); } public synchronized String insertSelected() throws DBSIOException{ setDialogCloseAfterInsert(true); view(); copy(); insert(); paste(); wCopiedRowIndex = -1; return DBSFaces.getCurrentView(); } public synchronized void sort() throws DBSIOException{} public synchronized String insert() throws DBSIOException{ if (wAllowInsert || wDialogCloseAfterInsert){ if (!wDialogCloseAfterInsert){ if (wFormStyle == FormStyle.DIALOG){ clearMessages(); } } if (wFormStyle == FormStyle.TABLE && wEditingMode==EditingMode.UPDATING){ pvInsertEmptyRow(); }else{ if (wEditingMode==EditingMode.NONE){ try { if (pvFireEventBeforeInsert() && pvFireEventBeforeEdit(EditingMode.INSERTING)){ //Desmarca registros selecionados wSelectedRowsIndexes.clear(); setEditingMode(EditingMode.INSERTING); setDialogOpened(true); }else{ setValueChanged(false); } // if (pvFireEventBeforeEdit(EditingMode.INSERTING)){ // //Desmarca registros selecionados // wSelectedRowsIndexes.clear(); // setEditingMode(EditingMode.INSERTING); // pvMoveBeforeFistRow(); // //Dispara evento BeforeInsert // if (pvFireEventBeforeInsert()){ // setDialogOpened(true); // }else{ // setValueChanged(false); // //exibe mensagem de erro de procedimento } catch (Exception e) { wLogger.error("Crud:" + getDialogCaption() + ":insert", e); setEditingMode(EditingMode.NONE); DBSIO.throwIOException(e); } }else{ //exibe mensagem de erro de procedimento } } } return DBSFaces.getCurrentView(); } public synchronized String update() throws DBSIOException{ if (wAllowUpdate){ clearMessages(); if (wEditingMode==EditingMode.NONE){ try { if (pvFireEventBeforeEdit(EditingMode.UPDATING)){ setEditingMode(EditingMode.UPDATING); pvInsertEmptyRow(); }else{ setValueChanged(false); //exibe mensagem de erro de procedimento } } catch (Exception e) { wLogger.error("Crud:" + getDialogCaption() + ":update", e); setEditingMode(EditingMode.NONE); DBSIO.throwIOException(e); } }else{ //exibe mensagem de erro de procedimento } } return DBSFaces.getCurrentView(); } public synchronized String delete() throws DBSIOException{ if (wAllowDelete){ clearMessages(); if (wEditingMode==EditingMode.NONE){ try { if (pvFireEventBeforeEdit(EditingMode.DELETING)){ setEditingMode(EditingMode.DELETING); confirmEditing(); //setEditingStage(EditingStage.COMMITTING); }else{ setValueChanged(false); //setEditingStage(EditingStage.COMMITTING); } } catch (Exception e) { wLogger.error("Crud:" + getDialogCaption() + ":delete", e); setEditingMode(EditingMode.NONE); DBSIO.throwIOException(e); } }else{ //exibe mensagem de erro de procedimento } } return DBSFaces.getCurrentView(); } public synchronized String approve() throws DBSIOException{ if (wAllowApproval && wAllowApprove){ if (wUserId== null){ addMessage("UserId", MESSAGE_TYPE.ERROR,"DBSCrudBean: UserId - Não informado!"); return DBSFaces.getCurrentView(); } if (wEditingMode==EditingMode.NONE){ try { if (pvFireEventBeforeEdit(EditingMode.APPROVING)){ setEditingMode(EditingMode.APPROVING); setValueChanged(true); confirmEditing(); }else{ setValueChanged(false); //exibe mensagem de erro de procedimento } } catch (Exception e) { wLogger.error("Crud:" + getDialogCaption() + ":approve", e); setEditingMode(EditingMode.NONE); DBSIO.throwIOException(e); } }else{ //exibe mensagem de erro de procedimento } } return DBSFaces.getCurrentView(); } public synchronized String reprove() throws DBSIOException{ if (wAllowApproval && wAllowApprove){ if (wUserId== null){ addMessage("UserId", MESSAGE_TYPE.ERROR,"DBSCrudBean: UserId - Não informado!"); return DBSFaces.getCurrentView(); } if (wEditingMode==EditingMode.NONE){ try { if (pvFireEventBeforeEdit(EditingMode.REPROVING)){ setEditingMode(EditingMode.REPROVING); setValueChanged(true); confirmEditing(); }else{ setValueChanged(false); //exibe mensagem de erro de procedimento } } catch (Exception e) { wLogger.error("Crud:" + getDialogCaption() + ":reprove", e); setEditingMode(EditingMode.NONE); DBSIO.throwIOException(e); } }else{ //exibe mensagem de erro de procedimento } } return DBSFaces.getCurrentView(); } /** * Move para o primeiro registro. * @return * @throws DBSIOException */ public synchronized String moveFirst() throws DBSIOException{ if (wEditingStage==EditingStage.NONE){ wDAO.moveFirstRow(); view(); } return DBSFaces.getCurrentView(); } /** * Move para o registro anterior * @return * @throws DBSIOException */ public synchronized String movePrevious() throws DBSIOException{ if (wEditingStage==EditingStage.NONE){ wDAO.movePreviousRow(); view(); } return DBSFaces.getCurrentView(); } public synchronized String moveNext() throws DBSIOException{ if (wEditingStage==EditingStage.NONE){ wDAO.moveNextRow(); view(); } return DBSFaces.getCurrentView(); } public synchronized String moveLast() throws DBSIOException{ if (wEditingStage==EditingStage.NONE){ wDAO.moveLastRow(); view(); } return DBSFaces.getCurrentView(); } @Override protected void warningMessageValidated(String pMessageKey, Boolean pIsValidated) throws DBSIOException{ //Se mensagem de warning foi validade.. if (pIsValidated){ confirmEditing(); }else{ if (getEditingMode().equals(EditingMode.DELETING)){ ignoreEditing(); } } } @Override protected boolean openConnection() { if (wParentCrudBean == null){ if (!getIsEditing() && !wBrodcastingEvent){ super.openConnection(); if (wDAO !=null){ wDAO.setConnection(wConnection); } //Configura os crudbean filhos que possam existir pvBroadcastConnection(this); return true; } } return false; } @Override protected void closeConnection() { if (wParentCrudBean == null){ if (!getIsEditing() && !wBrodcastingEvent){ super.closeConnection(); //Configura os crudbean filhos que possam existir pvBroadcastConnection(this); } } } // Abstracted protected abstract void initialize(DBSCrudBeanEvent pEvent) throws DBSIOException; protected void finalize(DBSCrudBeanEvent pEvent){}; protected void beforeClose(DBSCrudBeanEvent pEvent) throws DBSIOException {} ; protected void beforeRefresh(DBSCrudBeanEvent pEvent) throws DBSIOException{}; protected void afterRefresh(DBSCrudBeanEvent pEvent) throws DBSIOException{}; protected void beforeEdit(DBSCrudBeanEvent pEvent) throws DBSIOException {}; protected void afterEdit(DBSCrudBeanEvent pEvent) throws DBSIOException {}; protected void beforeInsert(DBSCrudBeanEvent pEvent) throws DBSIOException{}; protected void beforeView(DBSCrudBeanEvent pEvent) throws DBSIOException{}; protected void afterView(DBSCrudBeanEvent pEvent) throws DBSIOException{}; protected void beforeCommit(DBSCrudBeanEvent pEvent) throws DBSIOException { //Copia dos valores pois podem ter sido alterados durante o beforecommit if (wConnection == null){return;} if (getIsApprovingOrReproving()){ pvBeforeCommitSetAutomaticColumnsValues(pEvent); if (pEvent.isOk()){ pEvent.setCommittedRowCount(wDAO.executeUpdate()); }else{ return; } //Insert/Update/Delete }else{ pvBeforeCommitSetAutomaticColumnsValues(pEvent); if (pEvent.isOk()){ //Insert if(getIsInserting()){ if (wDAO.isAutoIncrementPK()){ wDAO.setValue(wDAO.getPK(), null); } pEvent.setCommittedRowCount(wDAO.executeInsert()); //Update }else if (getIsUpdating()){ if (wFormStyle == FormStyle.TABLE && wDAO.getIsNewRow()){ pEvent.setCommittedRowCount(wDAO.executeInsert()); }else{ pEvent.setCommittedRowCount(wDAO.executeUpdate()); } //Delete }else if(getIsDeleting()){ pEvent.setCommittedRowCount(wDAO.executeDelete()); } } } } protected void afterCommit(DBSCrudBeanEvent pEvent) throws DBSIOException {} protected void beforeIgnore(DBSCrudBeanEvent pEvent) throws DBSIOException {} protected void afterIgnore(DBSCrudBeanEvent pEvent){} protected void beforeSelect(DBSCrudBeanEvent pEvent) throws DBSIOException {} protected void afterSelect(DBSCrudBeanEvent pEvent){} protected void beforeValidate(DBSCrudBeanEvent pEvent) throws DBSIOException{} protected void validate(DBSCrudBeanEvent pEvent) throws DBSIOException{} protected void afterCopy(DBSCrudBeanEvent pEvent) throws DBSIOException{}; protected void beforePaste(DBSCrudBeanEvent pEvent) throws DBSIOException{}; private void pvConversationBegin(){ // if (!FacesContext.getCurrentInstance().isPostback() && wConversation.isTransient()){ if (wConversation.isTransient()){ wConversation.begin(); wConversation.setTimeout(wConversationTimeout); } } /** * Atualiza dados da lista e dispara os eventos beforeRefresh e afterRefresh.<br/> * @throws DBSIOException */ private void pvSearchList() throws DBSIOException{ if (getEditingMode() == EditingMode.UPDATING){ ignoreEditing(); } //Dispara evento para atualizar os dados if (pvFireEventBeforeRefresh()){ //Apaga itens selecionados, se houver. wSelectedRowsIndexes.clear(); pvFireEventAfterRefresh(); } } private void pvEndEditing(Boolean pOk) throws DBSIOException{ switch(wEditingMode){ case UPDATING: if (wEditingStage==EditingStage.IGNORING){ setEditingMode(EditingMode.NONE); pvRestoreValuesOriginal(); pvSearchList(); view(); }else{ if (pOk){ setEditingMode(EditingMode.NONE); view(); }else{ setEditingStage(EditingStage.NONE); } } break; case INSERTING: if (pOk){ if (wEditingStage==EditingStage.IGNORING || wDialogCloseAfterInsert){ setEditingMode(EditingMode.NONE); close(); }else{ setEditingMode(EditingMode.NONE); if (getFormStyle() == FormStyle.VIEW){ view(); }else{ insert(); } } }else{ setEditingStage(EditingStage.NONE); } break; case DELETING: if (wEditingStage==EditingStage.IGNORING){ setEditingMode(EditingMode.NONE); }else{ wCopiedRowIndex = -1; setEditingMode(EditingMode.NONE); if (pOk){ setDialogOpened(false); } } break; case APPROVING: setEditingMode(EditingMode.NONE); setEditingStage(EditingStage.NONE); close(false); break; case REPROVING: setEditingMode(EditingMode.NONE); setEditingStage(EditingStage.NONE); close(false); break; default: setEditingMode(EditingMode.NONE); //Exibe mensagem de erro de procedimento } } private void pvRestoreValuesOriginal(){ wDAO.restoreValuesOriginal(); } /** * Move para o registro anterior ao primeiro registro. * @throws DBSIOException */ private void pvMoveBeforeFistRow() throws DBSIOException{ wDAO.moveBeforeFirstRow(); } private void pvInsertEmptyRow() throws DBSIOException{ if (wFormStyle != FormStyle.TABLE || wEditingMode != EditingMode.UPDATING || !wAllowInsert){ return; } wDAO.insertEmptyRow(); pvFireEventBeforeInsert(); } private DBSColumn pvGetDAOColumnFromInputValueExpression(DBSUIInput pInput){ String xColumnName = DBSFaces.getAttibuteNameFromInputValueExpression(pInput).toLowerCase(); if (xColumnName!=null && !xColumnName.equals("")){ //Retira do os prefixos controlados pelo sistema para encontrar o nome da coluna if (xColumnName.startsWith(DBSSDK.UI.ID_PREFIX.FIELD_CRUD.getName())){ xColumnName = xColumnName.substring(DBSSDK.UI.ID_PREFIX.FIELD_CRUD.getName().length()); }else if (xColumnName.startsWith(DBSSDK.UI.ID_PREFIX.FIELD_AUX.getName())){ xColumnName = xColumnName.substring(DBSSDK.UI.ID_PREFIX.FIELD_AUX.getName().length()); } if (wDAO.containsColumn(xColumnName)){ return wDAO.getColumn(xColumnName); } } return null; } private void pvBroadcastConnection(DBSCrudBean pBean){ for (DBSCrudBean xChildBean:pBean.getChildrenCrudBean()){ Connection xCn = xChildBean.getConnection(); if (!xCn.equals(pBean.getConnection())){ DBSIO.closeConnection(xCn); xChildBean.setConnection(pBean.getConnection()); } //Procura pelos netos pvBroadcastConnection(xChildBean); } } /** * Salva indice do linha selacionada * @param pSelectOne * @throws DBSIOException */ private void pvSetSelected(Boolean pSelectOne) throws DBSIOException{ Integer xRowIndex = getList().getRowIndex(); if (pSelectOne){ if (wFormStyle == FormStyle.TABLE){ setValueChanged(true); } if (!wSelectedRowsIndexes.contains(xRowIndex)){ wSelectedRowsIndexes.add(xRowIndex); } }else{ if (wSelectedRowsIndexes.contains(xRowIndex)){ wSelectedRowsIndexes.remove(xRowIndex); } } } private void pvSelectAll() throws DBSIOException{ for (Integer xX = 0; xX < getList().getRowCount(); xX++){ if (wSelectedRowsIndexes.contains(xX)){ wSelectedRowsIndexes.remove(xX); }else{ wSelectedRowsIndexes.add(xX); } } } /** * Seta o valor da coluna no DAO * @param pColumnName * @param pColumnValue */ private void pvSetValueDAO(String pColumnName, Object pColumnValue){ //Utiliza ListValue para controlar os valores de todas as linhas if (wDAO != null && (wDAO.getColumns().size() > 0 || wDAO.getCommandColumns().size() > 0)){ Object xOldValue = pvGetValue(pColumnName); if (pColumnValue != null){ xOldValue = DBSObject.toClassValue(xOldValue, pColumnValue.getClass()); } if(!DBSObject.getNotNull(xOldValue,"").toString().equals(DBSObject.getNotNull(pColumnValue,"").toString())){ if (getEditingMode() == EditingMode.INSERTING && getDialogOpened()){ wLogger.info("ALTERADO:" + pColumnName + "[" + DBSObject.getNotNull(xOldValue,"") + "] para [" + DBSObject.getNotNull(pColumnValue,"") + "]"); } //marca como valor alterado setValueChanged(true); wDAO.setValue(pColumnName, pColumnValue); } } } /** * Retorna valor da coluna a partir do DAO * @param pColumnName * @return */ @SuppressWarnings("unchecked") private <T> T pvGetValue(String pColumnName){ //Se existir registro corrente if (wDAO != null && (wDAO.getColumns().size() > 0 || wDAO.getCommandColumns().size() > 0)){ return (T) wDAO.getValue(pColumnName); }else{ return null; } } private APPROVAL_STAGE pvGetApprovalStage(boolean pFromValue){ if (!getAllowApproval()){ return APPROVAL_STAGE.REGISTERED; } APPROVAL_STAGE xStage; if (pFromValue){ xStage = APPROVAL_STAGE.get(getValue(getColumnNameApprovalStage())); }else{ xStage = APPROVAL_STAGE.get(getListValue(getColumnNameApprovalStage())); } if (xStage==null){ xStage = APPROVAL_STAGE.REGISTERED; } return xStage; } private boolean pvApprovalUserAllowRegister(){ if (getAllowApproval() && !DBSApproval.isRegistered(getApprovalUserStages())){ return false; } return true; } private Integer pvGetApprovalNextUserStages() throws DBSIOException{ return DBSApproval.getNextUserStages(getApprovalStage(), getApprovalUserStages()); } private APPROVAL_STAGE pvGetApprovalNextUserStage() throws DBSIOException{ return DBSApproval.getMaxStage(pvGetApprovalNextUserStages()); } private void pvBeforeCommitSetAutomaticColumnsValues(DBSCrudBeanEvent pEvent) throws DBSIOException{ DBSColumn xColumn = null; //Delete if(wConnection == null || getIsDeleting()){ return; } //Configura os valores das assinaturas se assinatura estive habilitada. if (getAllowApproval()){ pvBeforeCommitSetAutomaticColumnsValuesApproval(pEvent); } //Insert if(getIsInserting()){ xColumn = wDAO.getCommandColumn(getColumnNameUserIdOnInsert()); if (xColumn!=null){ xColumn.setValue(getUserId()); } xColumn = wDAO.getCommandColumn(getColumnNameDateOnInsert()); if (xColumn!=null){ xColumn.setValue(DBSDate.getNowDateTime()); } //Update }else if (getIsUpdating()){ xColumn = wDAO.getCommandColumn(getColumnNameUserIdOnUpdate()); if (xColumn!=null){ xColumn.setValue(getUserId()); } xColumn = wDAO.getCommandColumn(getColumnNameDateOnUpdate()); if (xColumn!=null){ xColumn.setValue(DBSDate.getNowDateTime()); } } } private void pvBeforeCommitSetAutomaticColumnsValuesApproval(DBSCrudBeanEvent pEvent) throws DBSIOException{ DBSColumn xColumn = null; APPROVAL_STAGE xApprovalNextStage = null; Integer xUserId = null; Timestamp xApprovalDate = null; Integer xApprovalNextUserStages = null; xUserId = getUserId(); xApprovalDate = DBSDate.getNowTimestamp(); if (getIsApproving()){ xApprovalNextUserStages = pvGetApprovalNextUserStages(); xApprovalNextStage = pvGetApprovalNextUserStage(); }else if (getIsReproving()){ xApprovalNextUserStages = DBSApproval.getApprovalStage(false, true, true, true); xApprovalNextStage = APPROVAL_STAGE.REGISTERED; xUserId = null; xApprovalDate = null; }else if(getIsInserting() || getIsUpdating()){ xApprovalNextStage = APPROVAL_STAGE.REGISTERED; xApprovalNextUserStages = APPROVAL_STAGE.REGISTERED.getCode(); } if (xApprovalNextStage==APPROVAL_STAGE.REGISTERED){ xColumn = wDAO.getCommandColumn(getColumnNameApprovalUserIdRegistered()); if (xColumn!=null){xColumn.setValue(getUserId());} }else{ if (DBSApproval.isConferred(xApprovalNextUserStages)){ xColumn = wDAO.getCommandColumn(getColumnNameApprovalUserIdConferred()); if (xColumn!=null){xColumn.setValue(xUserId);} } if (DBSApproval.isVerified(xApprovalNextUserStages)){ xColumn = wDAO.getCommandColumn(getColumnNameApprovalUserIdVerified()); if (xColumn!=null){xColumn.setValue(xUserId);} } if (DBSApproval.isApproved(xApprovalNextUserStages)){ xColumn = wDAO.getCommandColumn(getColumnNameApprovalUserIdRegistered()); if (xColumn!=null){ if (DBSNumber.toInteger(xColumn.getValue()).equals(xUserId)){ addMessage(wMessaggeApprovalSameUserError); pEvent.setOk(false); return; } } xColumn = wDAO.getCommandColumn(getColumnNameApprovalUserIdApproved()); if (xColumn!=null){xColumn.setValue(xUserId);} xColumn = wDAO.getCommandColumn(getColumnNameApprovalDateApproved()); if (xColumn!=null){xColumn.setValue(xApprovalDate);} } } setApprovalStage(xApprovalNextStage); } private void pvCurrentRowSave(){ wSavedCurrentColumns = null; if (wDAO != null){ wSavedCurrentColumns = wDAO.getCommandColumns(); //utiliza as colunas da query if (wDAO.getCommandColumns() == null || wDAO.getCommandColumns().size() == 0){ wSavedCurrentColumns = wDAO.getColumns(); } } } private void pvCurrentRowRestore() throws DBSIOException{ boolean xOk; Object xSavedValue = null; Object xCurrentValue = null; BigDecimal xSavedNumberValue = null; BigDecimal xCurrentNumberValue = null; boolean xEqual; if (wDAO != null){ wDAO.moveBeforeFirstRow(); if (wSavedCurrentColumns !=null && wSavedCurrentColumns.size() > 0 && wDAO.getResultDataModel() != null){ DBSResultDataModel xQueryRows = wDAO.getResultDataModel(); for (int xRowIndex = 0; xRowIndex <= xQueryRows.getRowCount()-1; xRowIndex++){ xQueryRows.setRowIndex(xRowIndex); xOk = true; //Loop por todas as colunas da linha da query for (String xQueryColumnName:xQueryRows.getRowData().keySet()){ Object xQueryColumnValue = xQueryRows.getRowData().get(xQueryColumnName); //Procura pelo coluna que possua o mesmo nome for (DBSColumn xColumnSaved: wSavedCurrentColumns){ if (xColumnSaved.getColumnName().equalsIgnoreCase(xQueryColumnName)){ xSavedValue = DBSObject.getNotNull(xColumnSaved.getValue(),""); xCurrentValue = DBSObject.getNotNull(xQueryColumnValue,""); xEqual = false; if (xCurrentValue == null && xSavedValue == null){ xEqual = true; }else if (xCurrentValue instanceof Number){ xCurrentNumberValue = DBSNumber.toBigDecimal(xCurrentValue); if (xSavedValue instanceof Number){ xSavedNumberValue = DBSNumber.toBigDecimal(xSavedValue); } if (xSavedNumberValue != null && xCurrentNumberValue != null){ if (xCurrentNumberValue.compareTo(xSavedNumberValue) == 0){ xEqual = true; } } }else{ xEqual = xSavedValue.equals(xCurrentValue); } if (!xEqual){ xOk = false; } break; } } if (!xOk){ break; } } if (xOk){ return; } } if (wDAO != null){ wDAO.moveFirstRow(); } } } } // private void pvCurrentRowRestore() throws DBSIOException{ // boolean xOk; // Integer xRowIndex; // Object xSavedValue = null; // Object xCurrentValue = null; // BigDecimal xSavedNumberValue = null; // BigDecimal xCurrentNumberValue = null; // boolean xEqual; // if (wDAO != null // && wSavedCurrentColumns !=null // && wSavedCurrentColumns.size() > 0 // && wDAO.getResultDataModel() != null){ // //Recupera todas as linhas // Iterator<SortedMap<String, Object>> xIR = wDAO.getResultDataModel().iterator(); // xRowIndex = -1; // while (xIR.hasNext()){ // xOk = true; // xRowIndex++; // //Recupera todas as colunas da linha // SortedMap<String, Object> xColumns = xIR.next(); // //Loop por todas as colunas da linha // for (Entry<String, Object> xC:xColumns.entrySet()){ // Iterator<DBSColumn> xIS = wSavedCurrentColumns.iterator(); // //Procura pelo coluna que possua o mesmo nome // while (xIS.hasNext()){ // DBSColumn xSC = xIS.next(); // if (xSC.getColumnName().equalsIgnoreCase(xC.getKey())){ // xSavedValue = DBSObject.getNotNull(xSC.getValue(),""); // xCurrentValue = DBSObject.getNotNull(xC.getValue(),""); // xEqual = false; // if (xCurrentValue == null // && xSavedValue == null){ // xEqual = true; // }else if (xCurrentValue instanceof Number){ // xCurrentNumberValue = DBSNumber.toBigDecimal(xCurrentValue); // if (xSavedValue instanceof Number){ // xSavedNumberValue = DBSNumber.toBigDecimal(xSavedValue); // if (xSavedNumberValue != null // && xCurrentNumberValue != null){ // if (xCurrentNumberValue.compareTo(xSavedNumberValue) == 0){ // xEqual = true; // }else{ // xEqual = xSavedValue.equals(xCurrentValue); // if (!xEqual){ // xOk = false; // break; // if (!xOk){ // break; // if (xOk){ // wDAO.setCurrentRowIndex(xRowIndex); // return; //// if (wParentCrudBean == null){ // if (wDAO != null){ // wDAO.moveFirstRow(); private void pvFireEventInitialize(){ DBSCrudBeanEvent xE = new DBSCrudBeanEvent(this, CRUD_EVENT.INITIALIZE, getEditingMode()); try { pvBroadcastEvent(xE, false, true, true); } catch (Exception e) { xE.setOk(false); wLogger.error("EventInitialize",e); } } private void pvFireEventFinalize(){ DBSCrudBeanEvent xE = new DBSCrudBeanEvent(this, CRUD_EVENT.FINALIZE, getEditingMode()); try { pvBroadcastEvent(xE, false, false, true); } catch (Exception e) { xE.setOk(false); wLogger.error("EventFinalize",e); } } private boolean pvFireEventBeforeClose(){ DBSCrudBeanEvent xE = new DBSCrudBeanEvent(this, CRUD_EVENT.BEFORE_CLOSE, getEditingMode()); try { pvBroadcastEvent(xE, true, true, true); } catch (Exception e) { xE.setOk(false); wLogger.error("EventBeforeClose",e); } return xE.isOk(); } private boolean pvFireEventBeforeView(){ DBSCrudBeanEvent xE = new DBSCrudBeanEvent(this, CRUD_EVENT.BEFORE_VIEW, getEditingMode()); try { pvBroadcastEvent(xE, true, true, true); } catch (Exception e) { xE.setOk(false); wLogger.error("EventBeforeView",e); } return xE.isOk(); } private void pvFireEventAfterView(){ DBSCrudBeanEvent xE = new DBSCrudBeanEvent(this, CRUD_EVENT.AFTER_VIEW, getEditingMode()); setValueChanged(false); try { pvBroadcastEvent(xE, true, true, true); } catch (Exception e) { xE.setOk(false); wLogger.error("EventAfterView",e); } } private boolean pvFireEventBeforeInsert() throws DBSIOException{ DBSCrudBeanEvent xE = new DBSCrudBeanEvent(this, CRUD_EVENT.BEFORE_INSERT, getEditingMode()); if (wDAO != null){ openConnection(); pvMoveBeforeFistRow(); closeConnection(); } // pvBeforeInsertResetValues(wCrudForm); try { pvBroadcastEvent(xE, true, true, true); } catch (Exception e) { xE.setOk(false); wLogger.error("EventBeforeInsert",e); } setValueChanged(false); return xE.isOk(); } private boolean pvFireEventBeforeEdit(EditingMode pEditingMode){ DBSCrudBeanEvent xE = new DBSCrudBeanEvent(this, CRUD_EVENT.BEFORE_EDIT, pEditingMode); setValueChanged(false); try{ pvBroadcastEvent(xE, false, true, false); return xE.isOk(); } catch (Exception e) { xE.setOk(false); wLogger.error("EventBeforeEdit",e); } return xE.isOk(); } private boolean pvFireEventAfterEdit(EditingMode pEditingMode){ DBSCrudBeanEvent xE = new DBSCrudBeanEvent(this, CRUD_EVENT.AFTER_EDIT, pEditingMode); try{ pvBroadcastEvent(xE, false, false, true); } catch (Exception e) { xE.setOk(false); wLogger.error("EventAfterEdir",e); } return xE.isOk(); } private boolean pvFireEventBeforeRefresh(){ DBSCrudBeanEvent xE = new DBSCrudBeanEvent(this, CRUD_EVENT.BEFORE_REFRESH, getEditingMode()); try{ pvBroadcastEvent(xE, true, true, true); } catch (Exception e) { xE.setOk(false); wLogger.error("EventBeforeRefresh",e); } return xE.isOk(); } private void pvFireEventAfterRefresh(){ DBSCrudBeanEvent xE = new DBSCrudBeanEvent(this, CRUD_EVENT.AFTER_REFRESH, getEditingMode()); try{ pvBroadcastEvent(xE, true, true, true); } catch (Exception e) { xE.setOk(false); wLogger.error("EventInitialize",e); } } private boolean pvFireEventBeforeIgnore(){ DBSCrudBeanEvent xE = new DBSCrudBeanEvent(this, CRUD_EVENT.BEFORE_IGNORE, getEditingMode()); try{ pvBroadcastEvent(xE, false, false, false); } catch (Exception e) { xE.setOk(false); wLogger.error("EventBeforeIgnore",e); } return xE.isOk(); } private void pvFireEventAfterIgnore(){ DBSCrudBeanEvent xE = new DBSCrudBeanEvent(this, CRUD_EVENT.AFTER_IGNORE, getEditingMode()); try{ pvBroadcastEvent(xE, false, false, false); } catch (Exception e) { xE.setOk(false); wLogger.error("EventAfterIgnore",e); } } private boolean pvFireEventBeforeValidate(){ DBSCrudBeanEvent xE = new DBSCrudBeanEvent(this, CRUD_EVENT.BEFORE_VALIDATE, getEditingMode()); try{ if (getIsApprovingOrReproving() || wFormStyle == FormStyle.TABLE){ if (getHasSelected()){ wDAO.setCurrentRowIndex(-1); for (Integer xRowIndex : wSelectedRowsIndexes){ wDAO.setCurrentRowIndex(xRowIndex); pvBroadcastEvent(xE, false, false, false); } }else{ xE.setOk(false); addMessage("erroselecao", MESSAGE_TYPE.ERROR,"Não há registro selecionado."); } }else{ pvBroadcastEvent(xE, false, false, false); } } catch (Exception e) { xE.setOk(false); wLogger.error("EventBeforeValidate",e); } return xE.isOk(); } private boolean pvFireEventValidate(){ DBSCrudBeanEvent xE = new DBSCrudBeanEvent(this, CRUD_EVENT.VALIDATE, getEditingMode()); try{ if (getIsApprovingOrReproving() || wFormStyle == FormStyle.TABLE){ if (getHasSelected()){ wDAO.setCurrentRowIndex(-1); for (Integer xRowIndex : wSelectedRowsIndexes){ wDAO.setCurrentRowIndex(xRowIndex); pvBroadcastEvent(xE, false, false, false); if (!xE.isOk()){ if (getIsApprovingOrReproving()){ addMessage("erroassinatura", MESSAGE_TYPE.ERROR,"Não foi possível efetuar a edição de todos os itens selecionados. Procure efetuar a edição individualmente para identificar o registro com problema."); break; }else{ addMessage("erroselecao", MESSAGE_TYPE.ERROR,"Não foi possível efetuar a edição de todos os itens selecionados. Procure efetuar a edição individualmente para identificar o registro com problema."); break; } } } }else{ xE.setOk(false); addMessage("erroselecao", MESSAGE_TYPE.ERROR,"Não há registro selecionado."); } }else{ pvBroadcastEvent(xE, false, false, false); } } catch (Exception e) { xE.setOk(false); wLogger.error("EventValidate",e); } return xE.isOk(); } private boolean pvFireEventBeforeCommit(){ DBSCrudBeanEvent xE = new DBSCrudBeanEvent(this, CRUD_EVENT.BEFORE_COMMIT, getEditingMode()); String xErrorMsg = null; //Chame o metodo(evento) local para quando esta classe for extendida try { //Zera a quantidade de registros afetados xE.setCommittedRowCount(0); if (wConnection != null){ wDAO.setConnection(wConnection); //Se for o crud principal if (wParentCrudBean == null){ DBSIO.beginTrans(wConnection); } } if (getIsApprovingOrReproving() || wFormStyle == FormStyle.TABLE){ if (getHasSelected()){ int xCount = 0; wDAO.setCurrentRowIndex(-1); for (Integer xRowIndex : wSelectedRowsIndexes){ wDAO.setCurrentRowIndex(xRowIndex); if (wFormStyle == FormStyle.TABLE){ wDAO.setExecuteOnlyChangedValues(false); } pvBroadcastEvent(xE, false, false, false); xCount += xE.getCommittedRowCount(); if (!xE.isOk()){ break; } } //Ignora assinatura caso quantidade todal de registros afetados seja inferior a quantidade de itens selectionados if (xCount < wSelectedRowsIndexes.size()){ xE.setCommittedRowCount(0); xE.setOk(false); addMessage("erroassinatura", MESSAGE_TYPE.ERROR,"Não foi possível efetuar a assinatura de todos os itens selecionados. Procure efetuar a assinatura individualmente para identificar o registro com problema."); }else{ xE.setCommittedRowCount(xCount); } } }else{ pvBroadcastEvent(xE, false, false, false); } if (!wDialogMessages.hasMessages() && (!xE.isOk() || (wConnection != null && xE.getCommittedRowCount().equals(0)))){ xE.setOk(false); addMessage(wMessageNoRowComitted); } //Se for o crud principal if (wConnection != null){ if (wParentCrudBean == null){ DBSIO.endTrans(wConnection, xE.isOk()); } } } catch (Exception e) { xE.setOk(false); try { //Se for o crud principal if (wConnection != null){ if (wParentCrudBean == null){ DBSIO.endTrans(wConnection, false); } } if (e instanceof DBSIOException){ DBSIOException xDBException = (DBSIOException) e; xErrorMsg = e.getMessage(); if (xDBException.isIntegrityConstraint()){ clearMessages(); // addMessage("integridate", MESSAGE_TYPE.ERROR, xDBException.getLocalizedMessage()); }else{ wLogger.error("EventBeforeCommit", e); } wMessageError.setMessageText(xDBException.getLocalizedMessage()); wMessageError.setMessageTooltip(xErrorMsg); addMessage(wMessageError); }else{ wMessageError.setMessageText("Entre em contato com o suporte!"); wMessageError.setMessageTooltip(e.getLocalizedMessage()); addMessage(wMessageError); } } catch (DBSIOException e1) { xErrorMsg = e1.getMessage(); } wMessageNoRowComitted.setMessageTooltip(xErrorMsg); addMessage(wMessageNoRowComitted); } return xE.isOk(); } private void pvFireEventAfterCommit(){ DBSCrudBeanEvent xE = new DBSCrudBeanEvent(this, CRUD_EVENT.AFTER_COMMIT, getEditingMode()); try{ pvBroadcastEvent(xE, false, false, false); if (wParentCrudBean!=null){ wParentCrudBean.setValueChanged(true); } } catch (Exception e) { xE.setOk(false); wLogger.error("EventAfterCommit",e); } } private boolean pvFireEventBeforeSelect(){ DBSCrudBeanEvent xE = new DBSCrudBeanEvent(this, CRUD_EVENT.BEFORE_SELECT, getEditingMode()); try{ pvBroadcastEvent(xE, false, true, true); } catch (Exception e) { xE.setOk(false); wLogger.error("EventBeforeIgnore",e); } return xE.isOk(); } private void pvFireEventAfterSelect(){ DBSCrudBeanEvent xE = new DBSCrudBeanEvent(this, CRUD_EVENT.AFTER_SELECT, getEditingMode()); try{ pvBroadcastEvent(xE, false, true, true); } catch (Exception e) { xE.setOk(false); wLogger.error("EventAfterIgnore",e); } } private void pvFireEventAfterCopy(){ DBSCrudBeanEvent xE = new DBSCrudBeanEvent(this, CRUD_EVENT.AFTER_COPY, getEditingMode()); try{ pvBroadcastEvent(xE, false, true, true); } catch (Exception e) { xE.setOk(false); wLogger.error("EventAfterCopy",e); } } /** * Disparado antes do paste. * @return */ private boolean pvFireEventBeforePaste(){ DBSCrudBeanEvent xE = new DBSCrudBeanEvent(this, CRUD_EVENT.BEFORE_PASTE, getEditingMode()); try{ pvBroadcastEvent(xE, false, true, true); } catch (Exception e) { xE.setOk(false); wLogger.error("EventBeforePaste",e); } return xE.isOk(); } private void pvBroadcastEvent(DBSCrudBeanEvent pEvent, boolean pInvokeChildren, boolean pOpenConnection, boolean pCloseConnection) throws Exception { try{ if (pOpenConnection){ openConnection(); } wBrodcastingEvent = true; pvFireEventLocal(pEvent); if (pInvokeChildren){ pvFireEventChildren(pEvent); } pvFireEventListeners(pEvent); }catch(DBSIOException e){ wMessageError.setMessageText(e.getLocalizedMessage()); wMessageError.setMessageTooltip(e.getOriginalException().getLocalizedMessage()); if (!DBSObject.isEmpty(e.getCause())){ wMessageError.setMessageTooltip(e.getCause().getMessage() + "<br/>" + e.getMessage()); } addMessage(wMessageError); pEvent.setOk(false); // wLogger.error(pEvent.getEvent().toString(), e); }catch(Exception e){ String xStr = pEvent.getEvent().toString() + ":" + DBSObject.getNotNull(this.getDialogCaption(),"") + ":"; if (e.getLocalizedMessage()!=null){ xStr = xStr + e.getLocalizedMessage(); }else{ xStr = xStr + e.getClass(); } wMessageError.setMessageTextParameters(xStr); addMessage(wMessageError); pEvent.setOk(false); wLogger.error(pEvent.getEvent().toString(), e); throw e; }finally{ wBrodcastingEvent = false; if (pCloseConnection || !pEvent.isOk()){ closeConnection(); } } } private void pvFireEventLocal(DBSCrudBeanEvent pEvent) throws DBSIOException{ if (pEvent.isOk()){ switch (pEvent.getEvent()) { case INITIALIZE: initialize(pEvent); break; case FINALIZE: finalize(pEvent); break; case BEFORE_CLOSE: beforeClose(pEvent); break; case BEFORE_VIEW: beforeView(pEvent); break; case AFTER_VIEW: afterView(pEvent); break; case BEFORE_INSERT: beforeInsert(pEvent); break; case BEFORE_REFRESH: pvCurrentRowSave(); beforeRefresh(pEvent); pvCurrentRowRestore(); break; case AFTER_REFRESH: afterRefresh(pEvent); break; case BEFORE_COMMIT: beforeCommit(pEvent); break; case AFTER_COMMIT: afterCommit(pEvent); break; case BEFORE_IGNORE: beforeIgnore(pEvent); break; case AFTER_IGNORE: afterIgnore(pEvent); break; case BEFORE_EDIT: beforeEdit(pEvent); break; case AFTER_EDIT: afterEdit(pEvent); break; case BEFORE_SELECT: beforeSelect(pEvent); break; case AFTER_SELECT: afterSelect(pEvent); break; case BEFORE_VALIDATE: beforeValidate(pEvent); break; case VALIDATE: validate(pEvent); break; case AFTER_COPY: afterCopy(pEvent); break; case BEFORE_PASTE: beforePaste(pEvent); break; default: break; } } } /** * Dispara o evento nos beans vinculados a este bean * @param pEvent * @throws DBSIOException */ private void pvFireEventChildren(DBSCrudBeanEvent pEvent) throws DBSIOException{ if (pEvent.isOk()){ //Busca por beans vinculados e este bean for (DBSCrudBean xBean:wChildrenCrudBean){ if (pEvent.getEvent() == CRUD_EVENT.BEFORE_VIEW || pEvent.getEvent() == CRUD_EVENT.BEFORE_INSERT){ xBean.searchList(); } switch (pEvent.getEvent()) { case INITIALIZE: xBean.initialize(pEvent); break; case FINALIZE: xBean.finalize(pEvent); break; case BEFORE_CLOSE: xBean.beforeClose(pEvent); break; case BEFORE_VIEW: xBean.beforeView(pEvent); break; case AFTER_VIEW: xBean.afterView(pEvent); break; case BEFORE_INSERT: xBean.beforeInsert(pEvent); break; case BEFORE_REFRESH: xBean.beforeRefresh(pEvent); break; case AFTER_REFRESH: xBean.afterRefresh(pEvent); break; case BEFORE_COMMIT: xBean.beforeCommit(pEvent); break; case AFTER_COMMIT: xBean.afterCommit(pEvent); break; case BEFORE_IGNORE: xBean.beforeIgnore(pEvent); break; case AFTER_IGNORE: xBean.afterIgnore(pEvent); break; case BEFORE_EDIT: xBean.beforeEdit(pEvent); break; case AFTER_EDIT: xBean.afterEdit(pEvent); break; case BEFORE_SELECT: xBean.beforeSelect(pEvent); break; case AFTER_SELECT: xBean.afterSelect(pEvent); break; case BEFORE_VALIDATE: xBean.beforeValidate(pEvent); break; case VALIDATE: xBean.validate(pEvent); break; case AFTER_COPY: xBean.afterCopy(pEvent); break; case BEFORE_PASTE: xBean.beforePaste(pEvent); break; default: break; } if (!pEvent.isOk()){ break; } } } } private void pvFireEventListeners(DBSCrudBeanEvent pEvent) throws DBSIOException{ if (pEvent.isOk()){ for (int xX=0; xX<wEventListeners.size(); xX++){ switch (pEvent.getEvent()) { case INITIALIZE: wEventListeners.get(xX).initialize(pEvent); break; case FINALIZE: wEventListeners.get(xX).finalize(pEvent); break; case BEFORE_CLOSE: wEventListeners.get(xX).beforeClose(pEvent); break; case BEFORE_VIEW: wEventListeners.get(xX).beforeView(pEvent); break; case AFTER_VIEW: wEventListeners.get(xX).afterView(pEvent); break; case BEFORE_REFRESH: wEventListeners.get(xX).beforeRefresh(pEvent); break; case BEFORE_INSERT: wEventListeners.get(xX).beforeInsert(pEvent); break; case AFTER_REFRESH: wEventListeners.get(xX).afterRefresh(pEvent); break; case BEFORE_COMMIT: wEventListeners.get(xX).beforeCommit(pEvent); break; case AFTER_COMMIT: wEventListeners.get(xX).afterCommit(pEvent); break; case BEFORE_IGNORE: wEventListeners.get(xX).beforeIgnore(pEvent); break; case AFTER_IGNORE: wEventListeners.get(xX).afterIgnore(pEvent); break; case BEFORE_EDIT: wEventListeners.get(xX).beforeEdit(pEvent); break; case AFTER_EDIT: wEventListeners.get(xX).afterEdit(pEvent); break; case BEFORE_SELECT: wEventListeners.get(xX).beforeSelect(pEvent); break; case AFTER_SELECT: wEventListeners.get(xX).afterSelect(pEvent); break; case BEFORE_VALIDATE: wEventListeners.get(xX).beforeValidate(pEvent); break; case VALIDATE: wEventListeners.get(xX).validate(pEvent); break; case AFTER_COPY: wEventListeners.get(xX).afterCopy(pEvent); break; case BEFORE_PASTE: wEventListeners.get(xX).beforePaste(pEvent); break; default: break; } //Sa do loop se encontrar erro if (!pEvent.isOk()){ break; } } } } }
package com.afrozaar.wordpress.wpapi.v2; import com.afrozaar.wordpress.wpapi.v2.exception.PageNotFoundException; import com.afrozaar.wordpress.wpapi.v2.exception.ParsedRestException; import com.afrozaar.wordpress.wpapi.v2.exception.PostCreateException; import com.afrozaar.wordpress.wpapi.v2.exception.TermNotFoundException; import com.afrozaar.wordpress.wpapi.v2.exception.WpApiParsedException; import com.afrozaar.wordpress.wpapi.v2.model.Link; import com.afrozaar.wordpress.wpapi.v2.model.Media; import com.afrozaar.wordpress.wpapi.v2.model.Page; import com.afrozaar.wordpress.wpapi.v2.model.Post; import com.afrozaar.wordpress.wpapi.v2.model.PostMeta; import com.afrozaar.wordpress.wpapi.v2.model.PostStatus; import com.afrozaar.wordpress.wpapi.v2.model.Taxonomy; import com.afrozaar.wordpress.wpapi.v2.model.Term; import com.afrozaar.wordpress.wpapi.v2.request.Request; import com.afrozaar.wordpress.wpapi.v2.request.SearchRequest; import com.afrozaar.wordpress.wpapi.v2.response.PagedResponse; import com.afrozaar.wordpress.wpapi.v2.util.AuthUtil; import com.afrozaar.wordpress.wpapi.v2.util.Two; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableMap; import org.springframework.core.io.Resource; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; import org.springframework.http.RequestEntity; import org.springframework.http.ResponseEntity; import org.springframework.util.LinkedMultiValueMap; import org.springframework.util.MultiValueMap; import org.springframework.web.client.HttpClientErrorException; import org.springframework.web.client.HttpServerErrorException; import org.springframework.web.client.HttpStatusCodeException; import org.springframework.web.client.RestTemplate; import org.springframework.web.util.UriComponents; import org.springframework.web.util.UriComponentsBuilder; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.net.URI; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.function.BiConsumer; import java.util.function.Function; import java.util.function.Predicate; import java.util.stream.Collectors; public class Client implements Wordpress { private static final Logger LOG = LoggerFactory.getLogger(Client.class); private RestTemplate restTemplate = new RestTemplate(); private final Predicate<Link> next = link -> Strings.NEXT.equals(link.getRel()); private final Predicate<Link> previous = link -> Strings.PREV.equals(link.getRel()); public final String baseUrl; final private String username; final private String password; final private boolean debug; public Client(String baseUrl, String username, String password, boolean debug) { this.baseUrl = baseUrl; this.username = username; this.password = password; this.debug = debug; } @Override public Post createPost(final Map<String, Object> postFields, PostStatus status) throws PostCreateException { final ImmutableMap<String, Object> post = new ImmutableMap.Builder<String, Object>() .putAll(postFields) .put("status", status.value) .build(); try { return doExchange1(Request.POSTS, HttpMethod.POST, Post.class, forExpand(), null, post).getBody(); } catch (HttpClientErrorException e) { throw new PostCreateException(e); } } @Override public Post createPost(Post post, PostStatus status) throws PostCreateException { return createPost(fieldsFrom(post), status); } @Override public Post getPost(Long id) { final ResponseEntity<Post> exchange = doExchange1(Request.POST, HttpMethod.GET, Post.class, forExpand(id), null, null); return exchange.getBody(); } @Override public Post updatePost(Post post) { // update post is not as straight forward :( // the fields need to be checked for being empty (not null) and should not be included final ResponseEntity<Post> exchange = doExchange1(Request.POST, HttpMethod.PUT, Post.class, forExpand(post.getId()), ImmutableMap.of(), fieldsFrom(post)); return exchange.getBody(); } @Override public Post deletePost(Post post) { final ResponseEntity<Post> exchange = doExchange1(Request.POST, HttpMethod.DELETE, Post.class, forExpand(post.getId()), null, null);// Deletion of a post returns the post's data before removing it. Preconditions.checkArgument(exchange.getStatusCode().is2xxSuccessful()); return exchange.getBody(); } @Override public PagedResponse<Post> fetchPosts(SearchRequest<Post> search) { final URI uri = search.forHost(baseUrl, CONTEXT).build().toUri(); final ResponseEntity<Post[]> exchange = doExchange(HttpMethod.GET, uri, Post[].class, null); final HttpHeaders headers = exchange.getHeaders(); final List<Link> links = parseLinks(headers); final List<Post> posts = Arrays.asList(exchange.getBody()); LOG.trace("{} returned {} posts.", uri, posts.size()); return PagedResponse.Builder.aPagedResponse(Post.class) .withPages(headers) .withPosts(posts) .withSelf(uri.toASCIIString()) .withNext(link(links, next)) .withPrevious(link(links, previous)) .build(); } @Override public Media createMedia(Media media, Resource resource) throws WpApiParsedException { try { final MultiValueMap<String, Object> uploadMap = new LinkedMultiValueMap<>(); BiConsumer<String, Object> p = (index, value) -> Optional.ofNullable(value).ifPresent(v -> uploadMap.add(index, v)); p.accept("title", media.getTitle().getRendered()); p.accept("post", media.getPost()); p.accept("alt_text", media.getAltText()); p.accept("caption", media.getCaption()); p.accept("description", media.getDescription()); uploadMap.add("file", resource); return doExchange1(Request.MEDIAS, HttpMethod.POST, Media.class, forExpand(), null, uploadMap).getBody(); } catch (HttpClientErrorException | HttpServerErrorException e) { throw WpApiParsedException.of(e); } } @Override public Post setFeaturedImage(Media media) { Post post = this.getPost(media.getPost()); if ("image".equals(media.getMediaType())) { post.setFeaturedImage(media.getId()); } return updatePost(post); } @Override public List<Media> getMedia() { List<Media> collected = new ArrayList<>(); PagedResponse<Media> pagedResponse = this.getPagedResponse(Request.MEDIAS, Media.class); collected.addAll(pagedResponse.getList()); while (pagedResponse.hasNext()) { pagedResponse = this.traverse(pagedResponse, PagedResponse.NEXT); collected.addAll(pagedResponse.getList()); } return collected; } @Override public Media getMedia(Long id) { return doExchange1(Request.MEDIA, HttpMethod.GET, Media.class, forExpand(id), null, null).getBody(); } @Override public Media updateMedia(Media media) { ImmutableMap.Builder<String, Object> builder = new ImmutableMap.Builder<>(); BiConsumer<String, Object> p = (key, value) -> Optional.ofNullable(value).ifPresent(v -> builder.put(key, v)); p.accept("title", media.getTitle().getRendered()); p.accept("post", media.getPost()); p.accept("alt_text", media.getAltText()); p.accept("caption", media.getCaption()); p.accept("description", media.getDescription()); ResponseEntity<Media> exchange = doExchange1(Request.MEDIA, HttpMethod.POST, Media.class, forExpand(media.getId()), null, builder.build()); return exchange.getBody(); } @Override public boolean deleteMedia(Media media, boolean force) { final ResponseEntity<Media> exchange = doExchange1(Request.MEDIA, HttpMethod.DELETE, Media.class, forExpand(media.getId()), ImmutableMap.of("force", force), null); return exchange.getStatusCode().is2xxSuccessful(); } @Override public boolean deleteMedia(Media media) { final ResponseEntity<Media> exchange = doExchange1(Request.MEDIA, HttpMethod.DELETE, Media.class, forExpand(media.getId()), null, null); return exchange.getStatusCode().is2xxSuccessful(); } @Override public PostMeta createMeta(Long postId, String key, String value) { final ImmutableMap<String, String> body = ImmutableMap.of("key", key, "value", value); final ResponseEntity<PostMeta> exchange = doExchange1(Request.METAS, HttpMethod.POST, PostMeta.class, forExpand(postId), null, body); return exchange.getBody(); } @Override public List<PostMeta> getPostMetas(Long postId) { final ResponseEntity<PostMeta[]> exchange = doExchange1(Request.METAS, HttpMethod.GET, PostMeta[].class, forExpand(postId), null, null); return Arrays.asList(exchange.getBody()); } @Override public PostMeta getPostMeta(Long postId, Long metaId) { final ResponseEntity<PostMeta> exchange = doExchange1(Request.META, HttpMethod.GET, PostMeta.class, forExpand(postId, metaId), null, null); return exchange.getBody(); } @Override public PostMeta updatePostMetaValue(Long postId, Long metaId, String value) { return updatePostMeta(postId, metaId, null, value); } @Override public PostMeta updatePostMeta(Long postId, Long metaId, String key, String value) { ImmutableMap.Builder<String, Object> builder = new ImmutableMap.Builder<>(); BiConsumer<String, Object> biConsumer = (key1, value1) -> Optional.ofNullable(value1).ifPresent(v -> builder.put(key1, v)); biConsumer.accept("key", key); biConsumer.accept("value", value); final ResponseEntity<PostMeta> exchange = doExchange1(Request.META, HttpMethod.POST, PostMeta.class, forExpand(postId, metaId), null, builder.build()); return exchange.getBody(); } @Override public boolean deletePostMeta(Long postId, Long metaId) { final ResponseEntity<Map> exchange = doExchange1(Request.META, HttpMethod.DELETE, Map.class, forExpand(postId, metaId), null, null); Preconditions.checkArgument(exchange.getStatusCode().is2xxSuccessful(), String.format("Expected success on post meta delete request: /posts/%s/meta/%s", postId, metaId)); return exchange.getStatusCode().is2xxSuccessful(); } @Override public boolean deletePostMeta(Long postId, Long metaId, boolean force) { final ResponseEntity<Map> exchange = doExchange1(Request.META, HttpMethod.DELETE, Map.class, forExpand(postId, metaId), ImmutableMap.of("force", force), null); Preconditions.checkArgument(exchange.getStatusCode().is2xxSuccessful(), String.format("Expected success on post meta delete request: /posts/%s/meta/%s", postId, metaId)); return exchange.getStatusCode().is2xxSuccessful(); } @Override public List<Taxonomy> getTaxonomies() { final ResponseEntity<Taxonomy[]> exchange = doExchange1(Request.TAXONOMIES, HttpMethod.GET, Taxonomy[].class, forExpand(), null, null); return Arrays.asList(exchange.getBody()); } @Override public Taxonomy getTaxonomy(String slug) { return doExchange1(Request.TAXONOMY, HttpMethod.GET, Taxonomy.class, forExpand(slug), null, null).getBody(); } @Override public Term createTerm(String taxonomy, Term term) throws WpApiParsedException { try { return doExchange1(Request.TERMS, HttpMethod.POST, Term.class, forExpand(taxonomy), null, term.asMap()).getBody(); } catch (HttpClientErrorException | HttpServerErrorException e) { final WpApiParsedException exception = WpApiParsedException.of(e); LOG.error("Could not create {} term '{}'. {} ", taxonomy, term.getName(), exception.getMessage(), exception); throw exception; } } @Override public List<Term> getTerms(String taxonomy) { List<Term> collected = new ArrayList<>(); PagedResponse<Term> pagedResponse = this.getPagedResponse(Request.TERMS, Term.class, taxonomy); collected.addAll(pagedResponse.getList()); while (pagedResponse.hasNext()) { pagedResponse = this.traverse(pagedResponse, PagedResponse.NEXT); collected.addAll(pagedResponse.getList()); } return collected; } @Override public Term getTerm(String taxonomy, Long id) throws TermNotFoundException { try { return doExchange1(Request.TERM, HttpMethod.GET, Term.class, forExpand(taxonomy, id), null, null).getBody(); } catch (HttpClientErrorException e) { if (e.getStatusCode().is4xxClientError() && e.getStatusCode().value() == 404) { throw new TermNotFoundException(e); } else { throw e; } } } @Override public Term updateTerm(String taxonomy, Term term) { return doExchange1(Request.TERM, HttpMethod.POST, Term.class, forExpand(taxonomy, term.getId()), null, term.asMap()).getBody(); } @Override public Term deleteTerm(String taxonomy, Term term) throws TermNotFoundException { try { return doExchange1(Request.TERM, HttpMethod.DELETE, Term.class, forExpand(taxonomy, term.getId()), null, null).getBody(); } catch (HttpClientErrorException e) { if (e.getStatusCode().is4xxClientError() && e.getStatusCode().value() == 404) { throw new TermNotFoundException(e); } else { throw e; } } } @Override public List<Term> deleteTerms(String taxonomy, Term... terms) { List<Term> deletedTerms = new ArrayList<>(terms.length); for (Term term : terms) { try { deletedTerms.add(deleteTerm(taxonomy, term)); } catch (TermNotFoundException e) { LOG.error("Error ", e); } } return deletedTerms; } @Override public Term createPostTerm(Post post, String taxonomy, Term term) throws WpApiParsedException { final Term termToUse = Objects.nonNull(term.getId()) ? term : createTerm(taxonomy, term); return doExchange1(Request.POST_TERM, HttpMethod.POST, Term.class, forExpand(post.getId(), taxonomy, termToUse.getId()), null, null).getBody(); } @Override public Term updatePostTerm(Post post, String taxonomy, Term term) { throw new UnsupportedOperationException("not yet implemented"); } @Override public List<Term> getPostTerms(Post post, String taxonomy) { // TODO: 2015/12/10 For tagging we might need to do paged requests for example if a post has a large number of tags. return Arrays.asList(doExchange1(Request.POST_TERMS, HttpMethod.GET, Term[].class, forExpand(post.getId(), taxonomy), null, null).getBody()); } @Override public Term deletePostTerm(Post post, String taxonomy, Term term) { // This returns 501 Not Implemented from server. Use variant with force parameter. return doExchange1(Request.POST_TERM, HttpMethod.DELETE, Term.class, forExpand(post.getId(), taxonomy, term.getId()), null, null).getBody(); } @Override public Term deletePostTerm(Post post, String taxonomy, Term term, boolean force) { return doExchange1(Request.POST_TERM, HttpMethod.DELETE, Term.class, forExpand(post.getId(), taxonomy, term.getId()), ImmutableMap.of("force", force), null).getBody(); } @Override public Term getPostTerm(Post post, String taxonomy, Term term) throws WpApiParsedException { try { return doExchange1(Request.POST_TERM, HttpMethod.GET, Term.class, forExpand(post.getId(), taxonomy, term.getId()), null, null).getBody(); } catch (HttpStatusCodeException e) { throw new WpApiParsedException(ParsedRestException.of(e)); } } @Override public Page createPage(Page page, PostStatus status) { final Map<String, Object> map = page.asMap(); final ImmutableMap<String, Object> pageFields = new ImmutableMap.Builder<String, Object>() .putAll(map) .put("status", status.value) .build(); return doExchange1(Request.PAGES, HttpMethod.POST, Page.class, forExpand(), null, pageFields).getBody(); } @Override public Page getPage(Long pageId) throws PageNotFoundException { try { return getPage(pageId, "view"); } catch (HttpClientErrorException e) { throw new PageNotFoundException(e); } } @Override public Page getPage(Long pageId, String context) { return doExchange1(Request.PAGE, HttpMethod.GET, Page.class, forExpand(pageId), ImmutableMap.of("context", context), null).getBody(); } @Override public Page updatePage(Page page) { return doExchange1(Request.PAGE, HttpMethod.POST, Page.class, forExpand(page.getId()), null, page.asMap()).getBody(); } @Override public Page deletePage(Page page) { return doExchange1(Request.PAGE, HttpMethod.DELETE, Page.class, forExpand(page.getId()), null, null).getBody(); } @Override public Page deletePage(Page page, boolean force) { return doExchange1(Request.PAGE, HttpMethod.DELETE, Page.class, forExpand(page.getId()), ImmutableMap.of("force", force), null).getBody(); } @SuppressWarnings("unchecked") @Override public <T> PagedResponse<T> getPagedResponse(String context, Class<T> typeRef, String... expandParams) { final URI uri = Request.of(context).usingClient(this).buildAndExpand(expandParams).toUri(); return getPagedResponse(uri, typeRef); } @SuppressWarnings("unchecked") @Override public <T> PagedResponse<T> getPagedResponse(final URI uri, Class<T> typeRef) { try { final ResponseEntity<T[]> exchange = doExchange0(HttpMethod.GET, uri, (Class<T[]>) Class.forName("[L" + typeRef.getName() + ";"), null); final HttpHeaders headers = exchange.getHeaders(); final List<Link> links = parseLinks(headers); final List<T> body = Arrays.asList((T[]) exchange.getBody()); // Ugly... but the only way to get the generic stuff working return PagedResponse.Builder.aPagedResponse(typeRef) .withPages(headers) .withPosts(body) .withSelf(uri.toASCIIString()) .withNext(link(links, next)) .withPrevious(link(links, previous)) .build(); } catch (ClassNotFoundException e) { throw new RuntimeException(e); } } @SuppressWarnings("unchecked") @Override public <T> PagedResponse<T> traverse(PagedResponse<T> response, Function<PagedResponse<?>, String> direction) { final URI uri = response.getUri(direction); return getPagedResponse(uri, response.getClazz()); } public List<Link> parseLinks(HttpHeaders headers) { Optional<List<String>> linkHeader = Optional.ofNullable(headers.get(Strings.HEADER_LINK)); if (linkHeader.isPresent()) { final String rawResponse = linkHeader.get().get(0); final String[] links = rawResponse.split(", "); return Arrays.stream(links).map(link -> { String[] linkData = link.split("; "); final String href = linkData[0].replace("<", "").replace(">", ""); final String rel = linkData[1].substring(4).replace("\"", ""); return Link.of(href, rel); }).collect(Collectors.toList()); } else { return Collections.emptyList(); } } @Override public PagedResponse<Post> get(PagedResponse<Post> postPagedResponse, Function<PagedResponse<Post>, String> previousOrNext) { return fetchPosts(fromPagedResponse(postPagedResponse, previousOrNext)); } @Override public SearchRequest<Post> fromPagedResponse(PagedResponse<Post> response, Function<PagedResponse<Post>, String> previousOrNext) { return Request.fromLink(previousOrNext.apply(response), CONTEXT); } private Map<String, Object> fieldsFrom(Post post) { ImmutableMap.Builder<String, Object> builder = new ImmutableMap.Builder<>(); BiConsumer<String, Object> biConsumer = (key, value) -> Optional.ofNullable(value).ifPresent(v -> builder.put(key, v)); biConsumer.accept("date", post.getDate()); biConsumer.accept("modified_gmt", post.getModified()); // biConsumer.accept("slug", post.getSlug()); // biConsumer.accept("status",post.getStatus()); biConsumer.accept("title", post.getTitle().getRendered()); biConsumer.accept("content", post.getContent().getRendered()); biConsumer.accept("author", post.getAuthor()); biConsumer.accept("excerpt", post.getExcerpt().getRendered()); biConsumer.accept("comment_status", post.getCommentStatus()); biConsumer.accept("ping_status", post.getPingStatus()); biConsumer.accept("format", post.getFormat()); biConsumer.accept("sticky", post.getSticky()); biConsumer.accept("featured_image", post.getFeaturedImage()); return builder.build(); } private <T> ResponseEntity<T> doExchange(HttpMethod method, URI uri, Class<T> typeRef, T body) { return doExchange0(method, uri, typeRef, body); } private <T, B> ResponseEntity<T> doExchange0(HttpMethod method, URI uri, Class<T> typeRef, B body) { final Two<String, String> authTuple = AuthUtil.authTuple(username, password); final RequestEntity<B> entity = RequestEntity.method(method, uri).header(authTuple.a, authTuple.b).body(body); debugRequest(entity); final ResponseEntity<T> exchange = restTemplate.exchange(entity, typeRef); debugHeaders(exchange.getHeaders()); return exchange; } private <T, B> ResponseEntity<T> doExchange0(HttpMethod method, UriComponents uriComponents, Class<T> typeRef, B body) { return doExchange0(method, uriComponents.toUri(), typeRef, body); } private <T, B> ResponseEntity<T> doExchange1(String context, HttpMethod method, Class<T> typeRef, Object[] buildAndExpand, Map<String, Object> queryParams, B body) { final UriComponentsBuilder builder = Request.of(context).usingClient(this); if (queryParams != null) { queryParams.forEach(builder::queryParam); } return doExchange0(method, builder.buildAndExpand(buildAndExpand), typeRef, body); } private Optional<String> link(List<Link> links, Predicate<? super Link> linkPredicate) { return links.stream() .filter(linkPredicate) .map(Link::getHref) .findFirst(); } private void debugRequest(RequestEntity<?> entity) { if (debug) { LOG.debug("Request Entity: {}", entity); } } private void debugHeaders(HttpHeaders headers) { if (debug) { LOG.debug("Response Headers:"); headers.entrySet().stream().forEach(entry -> LOG.debug("{} -> {}", entry.getKey(), entry.getValue())); } } private Object[] forExpand(Object... values) { return values; } }
package com.alibaba.fastjson.support.geo; import com.alibaba.fastjson.annotation.JSONField; import com.alibaba.fastjson.annotation.JSONType; /** * @since 1.2.68 */ @JSONType(typeName = "Point", orders = {"type", "bbox", "coordinates"}) public class Point extends Geometry { private double longitude; private double latitude; public Point() { super("Point"); } public double[] getCoordinates() { return new double[] {longitude, latitude}; } public void setCoordinates(double[] coordinates) { if (coordinates == null || coordinates.length == 0) { this.longitude = 0; this.latitude = 0; return; } if (coordinates.length == 1) { this.longitude = coordinates[0]; return; } this.longitude = coordinates[0]; this.latitude = coordinates[1]; } @JSONField(serialize = false) public double getLongitude() { return longitude; } @JSONField(serialize = false) public double getLatitude() { return latitude; } @JSONField(deserialize = false) public void setLongitude(double longitude) { this.longitude = longitude; } @JSONField(deserialize = false) public void setLatitude(double latitude) { this.latitude = latitude; } }
package com.amihaiemil.eoyaml; import java.util.Collection; import java.util.Iterator; /** * Base YamlSequence which all implementations should extend. * It implementing toString(), equals, hashcode and compareTo methods. * <br><br> * These methods should be default methods on the interface, * but we are not allowed to have default implementations of java.lang.Object * methods.<br><br> * This class also offers the package-protected indent(...) method, which * returns the indented value of the sequence, used in printing YAML. This * method should NOT be visible to users. * @author Mihai Andronache (amihaiemil@gmail.com) * @version $Id$ * @since 4.0.0 */ abstract class BaseYamlSequence extends BaseYamlNode implements YamlSequence { @Override public int hashCode() { int hash = 0; for(final YamlNode node : this.values()) { hash += node.hashCode(); } return hash; } /** * Equals method for YamlSequence. It returns true if the compareTo(...) * method returns 0. * @param other The YamlSequence to which this is compared. * @return True or false */ @Override public boolean equals(final Object other) { final boolean result; if (other == null || !(other instanceof YamlSequence)) { result = false; } else if (this == other) { result = true; } else { result = this.compareTo((YamlSequence) other) == 0; } return result; } /** * Compare this Sequence to another node.<br><br> * * A Sequence is always considered greater than a Scalar and less than * a Mapping.<br> * * If other is a Sequence, their integer lengths are compared - the one with * the greater length is considered greater. If the lengths are equal, * then the 2 Sequences are equal if all elements are equal. If the * elements are not identical, the comparison of the first unequal * elements is returned. * * @param other The other YamlNode. * @checkstyle NestedIfDepth (100 lines) * @checkstyle LineLength (100 lines) * @return * a value &lt; 0 if this &lt; other <br> * 0 if this == other or <br> * a value &gt; 0 if this &gt; other */ @Override public int compareTo(final YamlNode other) { int result = 0; if (other == null || other instanceof Scalar) { result = 1; } else if (other instanceof YamlMapping) { result = -1; } else if (this != other) { final Collection<YamlNode> nodes = this.values(); final Collection<YamlNode> others = ((YamlSequence) other).values(); if(nodes.size() > others.size()) { result = 1; } else if (nodes.size() < others.size()) { result = -1; } else { final Iterator<YamlNode> iterator = others.iterator(); final Iterator<YamlNode> here = nodes.iterator(); while(iterator.hasNext()) { result = here.next().compareTo(iterator.next()); if(result != 0) { break; } } } } return result; } /** * Indent this YamlSequence. This is a base method since indentation * logic should be identical for any kind of YamlSequence, regardless of * its implementation. * * Keep this method package-protected, it should NOT be visible to users. * * @param indentation Indentation to start with. Usually, it's 0, since we * don't want to have spaces at the beginning. But in the case of nested * YamlNodes, this value may be greater than 0. * @return String indented YamlSequence, by the specified indentation. */ final String indent(final int indentation) { if(indentation < 0) { throw new IllegalArgumentException( "Indentation level has to be >=0" ); } final String newLine = System.lineSeparator(); final StringBuilder print = new StringBuilder(); int spaces = indentation; final StringBuilder alignment = new StringBuilder(); while (spaces > 0) { alignment.append(" "); spaces } for (final YamlNode node : this.values()) { final BaseYamlNode indentable = (BaseYamlNode) node; print .append(alignment) .append("- "); if (indentable instanceof Scalar) { print.append(indentable.indent(0)).append(newLine); } else { print .append(newLine) .append(indentable.indent(indentation + 2)) .append(newLine); } } String printed = print.toString(); if(printed.length() > 0) { printed = printed.substring(0, printed.length() - 1); } return printed; } /** * When printing a YamlSequence, just call this.indent(0), no need for * other wrappers. * @return This printed YamlSequence. */ @Override public final String toString() { return this.indent(0); } }
package com.anthonynsimon.url; import com.anthonynsimon.url.exceptions.MalformedURLException; /** * A default URL parser implementation. */ final class DefaultURLParser implements URLParser { /** * Returns a the URL with the new values after parsing the provided URL string. */ public URL parse(String rawUrl) throws MalformedURLException { if (rawUrl == null || rawUrl.isEmpty()) { throw new MalformedURLException("raw url string is empty"); } URLBuilder builder = new URLBuilder(); String remaining = rawUrl; int index = remaining.lastIndexOf(' if (index >= 0) { String frag = remaining.substring(index + 1, remaining.length()); builder.setFragment(frag.isEmpty() ? null : frag); remaining = remaining.substring(0, index); } if (remaining.isEmpty()) { return builder.build(); } if ("*".equals(remaining)) { builder.setPath("*"); return builder.build(); } index = remaining.indexOf('?'); if (index > 0) { String query = remaining.substring(index + 1, remaining.length()); if (query.isEmpty()) { builder.setQuery("?"); } else { builder.setQuery(query); } remaining = remaining.substring(0, index); } PartialParseResult parsedScheme = parseScheme(remaining); String scheme = parsedScheme.result; boolean hasScheme = scheme != null && !scheme.isEmpty(); builder.setScheme(scheme); remaining = parsedScheme.remaining; if (hasScheme && remaining.charAt(0) != '/') { builder.setOpaque(remaining); return builder.build(); } if ((hasScheme || !remaining.startsWith("///")) && remaining.startsWith("//")) { remaining = remaining.substring(2, remaining.length()); String authority = remaining; int i = remaining.indexOf('/'); if (i >= 0) { authority = remaining.substring(0, i); remaining = remaining.substring(i, remaining.length()); } else { remaining = ""; } if (!authority.isEmpty()) { UserInfoResult userInfoResult = parseUserInfo(authority); builder.setUsername(userInfoResult.user); builder.setPassword(userInfoResult.password); authority = userInfoResult.remaining; } PartialParseResult hostResult = parseHost(authority); builder.setHost(hostResult.result); } if (!remaining.isEmpty()) { builder.setPath(PercentEncoder.decode(remaining)); builder.setRawPath(remaining); } return builder.build(); } /** * Parses the scheme from the provided string. * * * @throws MalformedURLException if there was a problem parsing the input string. */ private PartialParseResult parseScheme(String remaining) throws MalformedURLException { int indexColon = remaining.indexOf(':'); if (indexColon == 0) { throw new MalformedURLException("missing scheme"); } if (indexColon < 0) { return new PartialParseResult("", remaining); } // if first char is special then its not a scheme char first = remaining.charAt(0); if ('0' <= first && first <= '9' || first == '+' || first == '-' || first == '.') { return new PartialParseResult("", remaining); } String scheme = remaining.substring(0, indexColon).toLowerCase(); String rest = remaining.substring(indexColon + 1, remaining.length()); return new PartialParseResult(scheme, rest); } /** * Parses the authority (user:password@host:port) from the provided string. * * @throws MalformedURLException if there was a problem parsing the input string. */ private UserInfoResult parseUserInfo(String str) throws MalformedURLException { int i = str.lastIndexOf('@'); String username = null; String password = null; String rest = str; if (i >= 0) { String credentials = str.substring(0, i); if (credentials.indexOf(':') >= 0) { String[] parts = credentials.split(":", 2); username = PercentEncoder.decode(parts[0]); password = PercentEncoder.decode(parts[1]); } else { username = PercentEncoder.decode(credentials); } rest = str.substring(i + 1, str.length()); } return new UserInfoResult(username, password, rest); } /** * Parses the host from the provided string. The port is considered part of the host and * will be checked to ensure that it's a numeric value. * * @throws MalformedURLException if there was a problem parsing the input string. */ private PartialParseResult parseHost(String str) throws MalformedURLException { if (str.length() == 0) { return new PartialParseResult("", ""); } if (str.charAt(0) == '[') { int i = str.lastIndexOf(']'); if (i < 0) { throw new MalformedURLException("IPv6 detected, but missing closing ']' token"); } String portPart = str.substring(i + 1, str.length()); if (!isPortValid(portPart)) { throw new MalformedURLException("invalid port"); } } else { if (str.indexOf(':') != -1) { String[] parts = str.split(":", -1); if (parts.length > 2) { throw new MalformedURLException("invalid host in: " + str); } if (parts.length == 2) { try { Integer.valueOf(parts[1]); } catch (NumberFormatException e) { throw new MalformedURLException("invalid port"); } } } } return new PartialParseResult(PercentEncoder.decode(str.toLowerCase()), ""); } /** * Returns true if the provided port string contains a valid port number. * Note that an empty string is a valid port number since it's optional. * <p> * For example: * <p> * '' => TRUE * null => TRUE * ':8080' => TRUE * ':ab80' => FALSE * ':abc' => FALSE */ protected boolean isPortValid(String portStr) { if (portStr == null || portStr.isEmpty()) { return true; } int i = portStr.indexOf(':'); // Port format must be ':8080' if (i != 0) { return false; } String segment = portStr.substring(i + 1, portStr.length()); try { Integer.valueOf(segment); } catch (NumberFormatException e) { return false; } return true; } private class PartialParseResult { public final String result; public final String remaining; public PartialParseResult(String result, String remaining) { this.result = result; this.remaining = remaining; } } private class UserInfoResult { public final String user; public final String password; public final String remaining; public UserInfoResult(String user, String password, String remaining) { this.user = user; this.password = password; this.remaining = remaining; } } }
package com.hanks.rxsearch; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; import com.google.gson.Gson; import com.jakewharton.rxbinding.widget.RxTextView; import java.util.ArrayList; import java.util.concurrent.TimeUnit; import butterknife.Bind; import butterknife.ButterKnife; import retrofit.RestAdapter; import retrofit.converter.GsonConverter; import retrofit.http.GET; import retrofit.http.Query; import rx.Observable; import rx.android.schedulers.AndroidSchedulers; import rx.functions.Action1; import rx.functions.Func1; import rx.schedulers.Schedulers; public class MainActivity extends AppCompatActivity { @Bind(R.id.et_keyword) EditText et_keyword; @Bind(R.id.tv_result) TextView tv_result; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ButterKnife.bind(this); RestAdapter retrofit = new RestAdapter.Builder().setEndpoint("https://suggest.taobao.com") .setLogLevel(RestAdapter.LogLevel.FULL) .setConverter(new GsonConverter(new Gson())) .build(); final SearchService service = retrofit.create(SearchService.class); RxTextView.textChanges(et_keyword) // tv_result .subscribeOn(AndroidSchedulers.mainThread()) .debounce(1000, TimeUnit.MILLISECONDS, AndroidSchedulers.mainThread()) .filter(new Func1<CharSequence, Boolean>() { @Override public Boolean call(CharSequence charSequence) { tv_result.setText(""); // EditText 0 return charSequence.length() > 0; } }) .switchMap(new Func1<CharSequence, Observable<Data>>() { @Override public Observable<Data> call(CharSequence charSequence) { return service.searchProdcut("utf-8", charSequence.toString()); } }) .subscribeOn(Schedulers.io()) // data ArrayList<ArrayList<String>> .map(new Func1<Data, ArrayList<ArrayList<String>>>() { @Override public ArrayList<ArrayList<String>> call(Data data) { return data.result; } }) // ArrayList<ArrayList<String>> ArrayList<String> .flatMap(new Func1<ArrayList<ArrayList<String>>, Observable<ArrayList<String>>>() { @Override public Observable<ArrayList<String>> call(ArrayList<ArrayList<String>> arrayLists) { return Observable.from(arrayLists); } }) .filter(new Func1<ArrayList<String>, Boolean>() { @Override public Boolean call(ArrayList<String> strings) { return strings.size() >= 2; } }) .map(new Func1<ArrayList<String>, String>() { @Override public String call(ArrayList<String> strings) { return "[:" + strings.get(0) + ", ID:" + strings.get(1) + "]\n"; } }) // onError onErrorResumeNext .onErrorResumeNext(new Func1<Throwable, Observable<? extends String>>() { @Override public Observable<? extends String> call(Throwable throwable) { return Observable.just("error result"); } }) .observeOn(AndroidSchedulers.mainThread()) .subscribe(new Action1<String>() { @Override public void call(String charSequence) { showpop(charSequence); } }, new Action1<Throwable>() { @Override public void call(Throwable throwable) { Toast.makeText(MainActivity.this, "error", Toast.LENGTH_SHORT).show(); } }); } private void showpop(String result) { tv_result.append(result); } interface SearchService { @GET("/sug") Observable<Data> searchProdcut(@Query("code") String code, @Query("q") String keyword); } class Data { public ArrayList<ArrayList<String>> result; } }
package org.redcross.openmapkit; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.content.SharedPreferences; import android.widget.Toast; import com.mapbox.mapboxsdk.tileprovider.tilesource.MBTilesLayer; import com.mapbox.mapboxsdk.tileprovider.tilesource.WebSourceTileLayer; import com.mapbox.mapboxsdk.views.MapView; import java.io.File; import java.util.ArrayList; import java.util.List; public class Basemap { private static final String ONLINE = "Online Humanitarian OpenStreetMap"; private static final String PREVIOUS_BASEMAP = "org.redcross.openmapkit.PREVIOUS_BASEMAP"; private MapActivity mapActivity; private MapView mapView; private Context context; private static String selectedBasemap; public Basemap(MapActivity mapActivity) { this.mapActivity = mapActivity; this.mapView = mapActivity.getMapView(); this.context = mapActivity.getApplicationContext(); final SharedPreferences sharedPreferences = mapActivity.getPreferences(Context.MODE_PRIVATE); selectedBasemap = sharedPreferences.getString(PREVIOUS_BASEMAP, null); if (selectedBasemap != null) { // was online basemap if (selectedBasemap.equals(ONLINE)) { selectOnlineBasemap(); } else { selectMBTilesBasemap(selectedBasemap); } } else { presentBasemapsOptions(); } } private void selectOnlineBasemap() { //create OSM tile layer String defaultTilePID = mapActivity.getString(R.string.defaultTileLayerPID); String defaultTileURL = mapActivity.getString(R.string.defaultTileLayerURL); String defaultTileName = mapActivity.getString(R.string.defaultTileLayerName); String defaultTileAttribution = mapActivity.getString(R.string.defaultTileLayerAttribution); WebSourceTileLayer ws = new WebSourceTileLayer(defaultTilePID, defaultTileURL); ws.setName(defaultTileName).setAttribution(defaultTileAttribution); setSelectedBasemap(ONLINE); //add OSM tile layer to map mapView.setTileSource(ws); } public void presentBasemapsOptions() { //shared preferences private to mapActivity final SharedPreferences sharedPreferences = mapActivity.getPreferences(Context.MODE_PRIVATE); String previousBasemap = sharedPreferences.getString(PREVIOUS_BASEMAP, null); //create an array of all mbtile options final List<String> basemaps = new ArrayList<>(); //when device is connected, HOT OSM Basemap is the first option if(Connectivity.isConnected(context)) { basemaps.add(ONLINE); } //add mbtiles names from external storage File[] mbtiles = ExternalStorage.fetchMBTilesFiles(); if (mbtiles.length > 0) { for (File file : mbtiles) { String filePath = file.getAbsolutePath(); basemaps.add(filePath); } } if (basemaps.size() == 0) { Toast prompt = Toast.makeText(context, "Device is offline. Please add .mbtiles file to " + ExternalStorage.getMBTilesDir() + " or check out a deployment.", Toast.LENGTH_LONG); prompt.show(); return; } //create dialog of mbtiles choices AlertDialog.Builder builder = new AlertDialog.Builder(mapActivity); builder.setTitle(mapActivity.getString(R.string.mbtilesChooserDialogTitle)); int len = basemaps.size(); String[] names = new String[len]; for (int i = 0; i < len; ++i) { String basemap = basemaps.get(i); if (basemap.equals(ONLINE)) { names[i] = basemap; } else { names[i] = new File(basemap).getName(); } } //default mbtiles option is based on previous selections (persisted in shared preferences) or connectivity state of device int defaultRadioButtonIndex = 0; if(previousBasemap == null) { //if user DID NOT previously choose an mbtiles option... if(Connectivity.isConnected(context)) { //the first radio button (for HOT OSM) will be selected by default defaultRadioButtonIndex = 0; //the default selected option is HOT OSM selectedBasemap = basemaps.get(0); //default choice } else { defaultRadioButtonIndex = -1; //no selected radio button by default } } else { //if user previously chose an mbtiles option ... for(int i = 0; i < basemaps.size(); ++i) { String filePath = basemaps.get(i); if(filePath.equals(previousBasemap)) { defaultRadioButtonIndex = i; selectedBasemap = filePath; } } if (selectedBasemap == null) { selectedBasemap = basemaps.get(0); } } //add choices to dialog builder.setSingleChoiceItems(names, defaultRadioButtonIndex, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { setSelectedBasemap(basemaps.get(which)); } }); //handle OK tap event of dialog builder.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int id) { //user clicked OK if(selectedBasemap.equals(ONLINE)) { selectOnlineBasemap(); } else { selectMBTilesBasemap(selectedBasemap); } } }); //handle cancel button tap event of dialog builder.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int id) { //user clicked cancel } }); //present dialog to user builder.show(); } private void selectMBTilesBasemap(String mbtilesPath) { File mbtilesFile = new File(mbtilesPath); if(!mbtilesFile.exists()) { AlertDialog.Builder builder = new AlertDialog.Builder(mapActivity); builder.setTitle("Offline Basemap Not Found"); builder.setMessage("Please add MBTiles to " + ExternalStorage.getMBTilesDir()); builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { //placeholder } }); AlertDialog dialog = builder.create(); dialog.show(); return; } //add mbtiles to map mapView.setTileSource(new MBTilesLayer(mbtilesFile)); setSelectedBasemap(mbtilesPath); } private void setSelectedBasemap(String basemap) { selectedBasemap = basemap; SharedPreferences sharedPreferences = mapActivity.getPreferences(Context.MODE_PRIVATE); SharedPreferences.Editor editor = sharedPreferences.edit(); editor.putString(PREVIOUS_BASEMAP, selectedBasemap); editor.apply(); } }
package ph.pakete.view; import android.app.AlertDialog; import android.app.ProgressDialog; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.content.res.Resources; import android.databinding.DataBindingUtil; import android.net.Uri; import android.os.Bundle; import android.support.v4.content.LocalBroadcastManager; import android.support.v7.app.ActionBar; import android.support.v7.app.AppCompatActivity; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.RelativeLayout; import android.widget.TextView; import android.widget.Toast; import com.facebook.share.model.ShareLinkContent; import com.facebook.share.widget.ShareDialog; import com.twitter.sdk.android.tweetcomposer.TweetComposer; import java.util.ArrayList; import java.util.List; import java.util.Locale; import hotchemi.android.rate.AppRate; import io.smooch.ui.ConversationActivity; import ph.pakete.BackHandledFragment; import ph.pakete.BuildConfig; import ph.pakete.R; import ph.pakete.databinding.FragmentSettingsBinding; import ph.pakete.helpers.MixpanelHelper; import ph.pakete.model.Token; import ph.pakete.util.IabHelper; import ph.pakete.util.SkuDetails; import ph.pakete.viewmodel.PackagesViewModel; public class SettingsFragment extends BackHandledFragment { private PackagesViewModel viewModel; private FragmentSettingsBinding binding; private IabHelper inAppBillingHelper; private static final String SKU_REMOVE_ADS = "ph.pakete.iap.removeads"; private static final int REMOVE_ADS_PURCHASE_CODE = 10001; public static SettingsFragment newInstance(PackagesViewModel viewModel) { final SettingsFragment fragment = new SettingsFragment(); fragment.viewModel = viewModel; return fragment; } public SettingsFragment() { } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setHasOptionsMenu(true); } @Override public void onPrepareOptionsMenu(Menu menu) { super.onPrepareOptionsMenu(menu); MenuItem menuItem = menu.findItem(R.id.action_settings); menuItem.setVisible(false); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment binding = DataBindingUtil.inflate(inflater, R.layout.fragment_settings, container, false); AppCompatActivity activity = (AppCompatActivity) getActivity(); activity.setSupportActionBar(binding.toolbar); ActionBar actionBar = activity.getSupportActionBar(); if (actionBar != null) { actionBar.setTitle("Settings"); // add back button actionBar.setDisplayHomeAsUpEnabled(true); actionBar.setDisplayShowHomeEnabled(true); } binding.toolbar.setNavigationOnClickListener(v -> onBackPressed()); binding.buttonRemoveAds.setOnClickListener(v -> onClickRemoveAdsButton()); binding.buttonRatePakete.setOnClickListener(v -> onClickWriteAReviewButton()); binding.buttonContactThePaketeTeam.setOnClickListener(v -> onClickContactPaketeTeamButton()); binding.buttonTweet.setOnClickListener(v -> onClickTweetAboutPakete()); binding.buttonFb.setOnClickListener(v -> onClickTellYourFriendsAboutPakete()); binding.textSortBy.setText(viewModel.packagesSortBy().toString()); binding.buttonSortBy.setOnClickListener(v -> onClickSortByButton()); binding.buttonGroupByDelivered.setOnClickListener(v -> binding.switchGroupByDelivered.setChecked(!binding.switchGroupByDelivered.isChecked())); binding.switchGroupByDelivered.setChecked(viewModel.packagesGroupByDelivered()); binding.switchGroupByDelivered.setOnCheckedChangeListener((buttonView, isChecked) -> viewModel.groupByDelivered(isChecked)); // listen to sort by change viewModel.packagesSortByReplySubject.subscribe(sortBy -> binding.textSortBy.setText(viewModel.packagesSortBy().toString())); // set version String version = String.format(Locale.getDefault(), "%s (%d)", BuildConfig.VERSION_NAME, BuildConfig.VERSION_CODE); TextView versionText = binding.textVersion; if (versionText != null) { versionText.setText(version); } // track mixpanel MixpanelHelper.getMixpanel(getActivity()).track("Settings View"); // fetch sku details if needed if (alreadyPurchasedRemoveAds() == false) { fetchRemoveAdsSkuDetails(); } return binding.getRoot(); } @Override public void onDestroy() { super.onDestroy(); try { if (inAppBillingHelper != null) inAppBillingHelper.dispose(); } catch (Exception e) { e.printStackTrace(); } inAppBillingHelper = null; } @Override public boolean onBackPressed() { if (getFragmentManager() != null) { getFragmentManager().popBackStack(); // show fab ((MainActivity) getActivity()).showFAB(); return true; } return false; } @Override public void onViewCreated(View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { if (inAppBillingHelper == null) return; // Pass on the activity result to the helper for handling if (!inAppBillingHelper.handleActivityResult(requestCode, resultCode, data)) { // not handled, so handle it ourselves (here's where you'd // perform any handling of activity results not related to in-app // billing... super.onActivityResult(requestCode, resultCode, data); } } private void onClickRemoveAdsButton() { AlertDialog.Builder removeAdsDialogBuilder = new AlertDialog.Builder(getActivity()); removeAdsDialogBuilder.setTitle("Hate Ads?"); removeAdsDialogBuilder.setItems(new CharSequence[]{"Pay to Remove Ads", "Cancel"}, (dialog, which) -> { // The 'which' argument contains the index position // of the selected item switch (which) { case 0: // Pay to Remove Ads purchaseRemoveAds(); break; } }); removeAdsDialogBuilder.create().show(); } private void onClickSortByButton() { final SortByFragment sortByFragment = SortByFragment.newInstance(viewModel); getActivity().getSupportFragmentManager() .beginTransaction() .setCustomAnimations(android.R.anim.fade_in, android.R.anim.fade_out, android.R.anim.fade_in, android.R.anim.fade_out) .add(R.id.root_layout, sortByFragment) .addToBackStack(null) .commit(); } private void onClickWriteAReviewButton() { AppRate.with(getActivity()).showRateDialog(getActivity()); } private void onClickContactPaketeTeamButton() { //ConversationActivity.show(getActivity()); Intent Email = new Intent(Intent.ACTION_SEND); Email.setType("text/email"); Email.putExtra(Intent.EXTRA_EMAIL, new String[] { "support@pakete.ph" }); Email.putExtra(Intent.EXTRA_SUBJECT, "Feedback"); try { startActivity(Intent.createChooser(Email, "Send Feedback:")); } catch (android.content.ActivityNotFoundException ex) { Toast.makeText(getActivity(), "There are no email clients installed.", Toast.LENGTH_SHORT).show(); } } private void onClickTweetAboutPakete() { String tweet = getResources().getString(R.string.share_message) + " " + getResources().getString(R.string.app_url); TweetComposer.Builder builder = new TweetComposer.Builder(getActivity()) .text(tweet); builder.show(); } private void onClickTellYourFriendsAboutPakete() { ShareLinkContent content = new ShareLinkContent.Builder() .setContentUrl(Uri.parse(getResources().getString(R.string.app_url))) .build(); ShareDialog.show(this, content); } private void purchaseRemoveAds() { // purchase listener IabHelper.OnIabPurchaseFinishedListener purchaseFinishedListener = (result, purchase) -> { if (purchase != null) { if (purchase.getSku().equals(SKU_REMOVE_ADS)) { broadcastRemoveAds(); } } }; try { inAppBillingHelper.launchPurchaseFlow(getActivity(), SKU_REMOVE_ADS, REMOVE_ADS_PURCHASE_CODE, purchaseFinishedListener, Token.getUniqueID()); } catch (Exception e) { e.printStackTrace(); } } private void fetchRemoveAdsSkuDetails() { // show progress dialog ProgressDialog dialog = ProgressDialog.show(getActivity(), null, null); String base64EncodedPublicKey = getResources().getString(R.string.license_key); // compute your public key and store it in base64EncodedPublicKey inAppBillingHelper = new IabHelper(getActivity(), base64EncodedPublicKey); inAppBillingHelper.enableDebugLogging(true); // Listener that's called when we finish querying the items and // subscriptions we own IabHelper.QueryInventoryFinishedListener queryInventoryFinishedListener = (result, inventory) -> { dialog.dismiss(); // Have we been disposed of in the meantime? If so, quit. if (inAppBillingHelper == null) { return; } if (result.isSuccess() && inventory != null) { SkuDetails removeAdsSkuDetails = inventory.getSkuDetails(SKU_REMOVE_ADS); if (removeAdsSkuDetails != null) { Resources res = getResources(); String text = String.format(res.getString(R.string.header_text_remove_ads), removeAdsSkuDetails.getPrice()); TextView headerRemoveAdsText = binding.headerText; if (headerRemoveAdsText != null) { headerRemoveAdsText.setText(text); } // show remove ads layout RelativeLayout removeAdsLayout = binding.removeAdsLayout; removeAdsLayout.setVisibility(View.VISIBLE); } } }; inAppBillingHelper.startSetup(result -> { if (result.isSuccess()) { // fetch remove ads sku details try { List additionalSkuList = new ArrayList(); additionalSkuList.add(SKU_REMOVE_ADS); inAppBillingHelper.queryInventoryAsync(true, additionalSkuList, queryInventoryFinishedListener); } catch (Exception e) { e.printStackTrace(); } } else { dialog.dismiss(); } }); } private void broadcastRemoveAds() { // save to preferences SharedPreferences preferences = getActivity().getSharedPreferences("ph.pakete.preferences", Context.MODE_PRIVATE); SharedPreferences.Editor editor = preferences.edit(); editor.putBoolean("removedAds", true); editor.apply(); // broadcast remove ads Intent intent = new Intent("removeAds"); LocalBroadcastManager.getInstance(getActivity()).sendBroadcast(intent); // remove ads layout RelativeLayout removeAdsLayout = binding.removeAdsLayout; removeAdsLayout.setVisibility(View.GONE); } private Boolean alreadyPurchasedRemoveAds() { SharedPreferences preferences = getActivity().getSharedPreferences("ph.pakete.preferences", Context.MODE_PRIVATE); return preferences.getBoolean("removedAds", false); } }
package teammemes.tritonbudget; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.support.design.widget.NavigationView; import android.support.v4.view.GravityCompat; import android.support.v4.widget.DrawerLayout; import android.support.v7.app.ActionBarDrawerToggle; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.text.Editable; import android.text.InputFilter; import android.text.TextWatcher; import android.view.LayoutInflater; import android.view.MenuItem; import android.view.View; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.List; import java.util.Random; import teammemes.tritonbudget.db.HistoryDataSource; import teammemes.tritonbudget.db.TranHistory; public class Settings extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener { final Context context = this; //Nav Drawers private DrawerLayout mDrawerLayout; private ActionBarDrawerToggle mToggle; private Toolbar mToolbar; private User usr; private HistoryDataSource database; private TextView usrName; SimpleDateFormat dateFormat; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.drawer_settings); usr = User.getInstance(getApplicationContext()); database = new HistoryDataSource(this); dateFormat = new SimpleDateFormat("MM/dd/yyyy"); //Creates the toolbar to the one defined in nav_action mToolbar = (Toolbar) findViewById(R.id.nav_action); setSupportActionBar(mToolbar); getSupportActionBar().setDisplayHomeAsUpEnabled(true); getSupportActionBar().setTitle("Settings"); //Create the Drawer layout and the toggle mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_settings); mToggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.string.open, R.string.close); mDrawerLayout.addDrawerListener(mToggle); mToggle.syncState(); //Create the navigationView and add a listener to listen for menu selections NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view); navigationView.setNavigationItemSelectedListener(this); View navHeaderView= navigationView.getHeaderView(0); usrName = (TextView) navHeaderView.findViewById(R.id.header_name); usrName.setText(usr.getName()); //Settings Options TextView changeName = (TextView) findViewById(R.id.settings_changeName); TextView changeBalance = (TextView) findViewById(R.id.settings_changeBalance); TextView addDD = (TextView) findViewById(R.id.settings_addDD); TextView test_load = (TextView) findViewById(R.id.settings_test_load); TextView credits = (TextView) findViewById(R.id.settings_credits); TextView enterDays = (TextView) findViewById(R.id.settings_enterDays); TextView buyandsell = (TextView) findViewById(R.id.settings_buyandsell); //Listeners changeName.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { AlertDialog.Builder builder = new AlertDialog.Builder(context); builder.setTitle("What's Your Name?"); LayoutInflater viewInflated = LayoutInflater.from(context); View deductView = viewInflated.inflate(R.layout.dialog_change_name,null); // Set up the input // Specify the type of input expected; this, for example, sets the input as a password, and will mask the text builder.setView(deductView); final EditText input = (EditText) deductView.findViewById(R.id.changeName_input); // Set up the buttons builder.setPositiveButton("Confirm", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { String value= input.getText().toString(); if (value.length() == 0 || value.length() > 25) { Toast.makeText(Settings.this, "Please up to 25 characters.\nName not saved.", Toast.LENGTH_LONG).show(); } else { usr.setName(value); usrName.setText(usr.getName()); Toast.makeText(Settings.this, "Changed Name to " + value, Toast.LENGTH_LONG).show(); } } }); builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.cancel(); } }); builder.show(); } }); changeBalance.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { AlertDialog.Builder builder = new AlertDialog.Builder(context); builder.setTitle("What's Your Balance?"); LayoutInflater viewInflated = LayoutInflater.from(context); View deductView = viewInflated.inflate(R.layout.dialog_deduction,null); // Set up the input // Specify the type of input expected; this, for example, sets the input as a password, and will mask the text builder.setView(deductView); final EditText input = (EditText) deductView.findViewById(R.id.deduct_input); final int LENGTH = 7; InputFilter[] FilterArray = new InputFilter[1]; FilterArray[0] = new InputFilter.LengthFilter(LENGTH); input.setFilters(FilterArray); //This TextChangedListener is used to stop the user from inputing more than two decimal points input.addTextChangedListener(new TextWatcher() { //Two methods needed to create new TextWatcher public void onTextChanged(CharSequence s, int start, int before, int count) {} public void beforeTextChanged(CharSequence s, int start, int count, int after) {} //After the text is changed this method removes the extra characters if any public void afterTextChanged(Editable s) { String temp = s.toString(); int posDot = temp.indexOf("."); if (posDot <= 0) { return; } if (temp.length() - posDot - 1 > 2) { s.delete(posDot + 3, posDot + 4); } } }); // Set up the buttons builder.setPositiveButton("Confirm", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { double value = Double.parseDouble(input.getText().toString()); if (value > 9999.99 || value < 0) { Toast.makeText(Settings.this, "Please enter an amount $[0, 9999.99].\nBalance was not changed.", Toast.LENGTH_LONG).show(); } else { usr.setBalance(value); Toast.makeText(Settings.this, "Changed Balance to $" + value, Toast.LENGTH_LONG).show(); } } }); builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.cancel(); } }); builder.show(); } }); addDD.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { AlertDialog.Builder builder = new AlertDialog.Builder(context); builder.setTitle("How Much Dining Dollars?"); LayoutInflater viewInflated = LayoutInflater.from(context); View deductView = viewInflated.inflate(R.layout.dialog_deduction,null); // Set up the input // Specify the type of input expected; this, for example, sets the input as a password, and will mask the text builder.setView(deductView); final EditText input = (EditText) deductView.findViewById(R.id.deduct_input); final int LENGTH = 7; InputFilter[] FilterArray = new InputFilter[1]; FilterArray[0] = new InputFilter.LengthFilter(LENGTH); input.setFilters(FilterArray); //This TextChangedListener is used to stop the user from inputing more than two decimal points input.addTextChangedListener(new TextWatcher() { //Two methods needed to create new TextWatcher public void onTextChanged(CharSequence s, int start, int before, int count) {} public void beforeTextChanged(CharSequence s, int start, int count, int after) {} //After the text is changed this method removes the extra characters if any public void afterTextChanged(Editable s) { String temp = s.toString(); int posDot = temp.indexOf("."); if (posDot <= 0) { return; } if (temp.length() - posDot - 1 > 2) { s.delete(posDot + 3, posDot + 4); } } }); // Set up the buttons builder.setPositiveButton("Confirm", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { double value = Double.parseDouble(input.getText().toString()); usr.setBalance(usr.getBalance() + value); TranHistory transaction = new TranHistory(1,"Added Dining Dollars",1,new Date(), 0 - value); database.createTransaction(transaction); Toast.makeText(Settings.this, "Added $" + value + " Dining Dollars", Toast.LENGTH_LONG).show(); } }); builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.cancel(); } }); builder.show(); } }); enterDays.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startActivity(new Intent(Settings.this, NonTrackingDays.class)); } }); buyandsell.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //startActivity(new Intent(Settings.this, NonTrackingDays.class)); try { Intent intent = new Intent(Intent.ACTION_VIEW,Uri.parse("http: startActivity(intent); } catch(Exception e) { startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("http: } } }); test_load.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // Set up the input List<TranHistory> trans = database.getAllTransaction(); for (int i = 0; i < trans.size(); i++){ database.deleteTransaction(trans.get(i).getId()); } Calendar start = Calendar.getInstance(); Calendar today = (Calendar) start.clone(); start.set(2017,0,1); Random rand = new Random(); int count = 0; do{ if (start.get(Calendar.DAY_OF_WEEK) == Calendar.SATURDAY){ start.add(Calendar.DATE, 2); } if (start.after(today)){ break; } if (count < 3){ double cost = rand.nextDouble(); cost = Math.round(cost*1000)/100; TranHistory tran = new TranHistory(1, "Test Item",1,start.getTime(), cost); database.createTransaction(tran); count++; } else{ count = 0; start.add(Calendar.DATE, 1); } }while (true); Toast.makeText(context,"Loaded in test Data", Toast.LENGTH_LONG); } }); credits.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { AlertDialog.Builder builder = new AlertDialog.Builder(context); builder.setTitle("Credits"); LayoutInflater viewInflated = LayoutInflater.from(context); View deductView = viewInflated.inflate(R.layout.dialog_credits,null); // Set up the input // Specify the type of input expected; this, for example, sets the input as a password, and will mask the text builder.setView(deductView); builder.setNegativeButton("Exit", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.cancel(); } }); builder.show(); } }); } //This method is used to listen for the user clicking the menu button, and opens //the drawer up @Override public boolean onOptionsItemSelected(MenuItem item) { if (mToggle.onOptionsItemSelected(item)) { return true; } return super.onOptionsItemSelected(item); } //This method is used to see if the back button was pressed while the drawer was open. //If it is open and the back button is pressed, then close the drawer. @Override public void onBackPressed() { if (mDrawerLayout.isDrawerOpen(GravityCompat.START)) { mDrawerLayout.closeDrawer(GravityCompat.START); } else { super.onBackPressed(); } } // This method is used to react when the user presses one of the options in the drawer @Override public boolean onNavigationItemSelected(MenuItem item) { // Gets the id of the item that was selected int id = item.getItemId(); Intent nextScreen; //Reacts to the item selected depending on which was pressed //Creates a new Intent for the new page and starts that activity switch (id) { case R.id.nav_home: mDrawerLayout.closeDrawer(GravityCompat.START); nextScreen = new Intent(this, HomeScreen.class); nextScreen.putExtra("FROM", "Settings"); startActivity(nextScreen); return true; case R.id.nav_history: mDrawerLayout.closeDrawer(GravityCompat.START); nextScreen = new Intent(this, History.class); nextScreen.putExtra("FROM", "Settings"); startActivity(nextScreen); return true; case R.id.nav_statistics: mDrawerLayout.closeDrawer(GravityCompat.START); nextScreen = new Intent(this, Statistics.class); nextScreen.putExtra("FROM", "Settings"); startActivity(nextScreen); return true; case R.id.nav_menus: mDrawerLayout.closeDrawer(GravityCompat.START); nextScreen = new Intent(this, DiningHallSelection.class); nextScreen.putExtra("FROM", "Settings"); startActivity(nextScreen); return true; case R.id.nav_settings: mDrawerLayout.closeDrawer(GravityCompat.START); return true; case R.id.nav_help: mDrawerLayout.closeDrawer(GravityCompat.START); nextScreen = new Intent(this, Help.class); nextScreen.putExtra("FROM", "Settings"); startActivity(nextScreen); return true; default: mDrawerLayout.closeDrawer(GravityCompat.START); return false; } } }
package x1125io.initdlight; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; public class MainActivity extends AppCompatActivity { EditText appText; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); this.appText = (EditText)findViewById(R.id.appText); final Button testButton = (Button)findViewById(R.id.testButton); addAppText("Target directory for scripts:"); addAppText(this.getFilesDir().toString()); addAppText("\nCurrent scripts:"); for (String file: this.getFilesDir().list()) { addAppText(file); } addAppText("\nRoot access check:"); ProcessRunner pr = new ProcessRunner(); int exitCode = pr.Run(new String[] { "su", "-c", "whoami"}); if (exitCode == 0 && pr.getStdout().equals("root\n")) { addAppText("OK"); testButton.setEnabled(true); } else { addAppText("Error: " + pr.getStderr()); } testButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { addAppText("\nRunning Tests:"); for (String file: v.getContext().getFilesDir().list()) { ProcessRunner pr = new ProcessRunner(); String fullFilePath = v.getContext().getFilesDir().toString() + "/" + file; int exitCode = pr.Run(new String[] { "su", "-c", fullFilePath }); addAppText(String.format( "%s, exit: %d, stdout: %s, stderr: %s", fullFilePath, exitCode, pr.getStdout(), pr.getStderr() )); } } }); } void addAppText(String str) { appText.setText(appText.getText() + str + "\n"); } }
package com.torodb.d2r; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import com.google.common.collect.HashBasedTable; import com.google.common.collect.ImmutableList; import com.google.common.collect.Table; import com.torodb.core.TableRef; import com.torodb.core.d2r.DocPartResult; import com.torodb.core.d2r.DocPartResults; import com.torodb.core.d2r.InternalFields; import com.torodb.core.d2r.R2DBackendTranslator; import com.torodb.core.d2r.R2DTranslator; import com.torodb.core.document.ToroDocument; import com.torodb.core.transaction.metainf.FieldType; import com.torodb.core.transaction.metainf.MetaDocPart; import com.torodb.core.transaction.metainf.MetaField; import com.torodb.core.transaction.metainf.MetaScalar; import com.torodb.kvdocument.values.KVBoolean; import com.torodb.kvdocument.values.KVDocument; import com.torodb.kvdocument.values.KVValue; import com.torodb.kvdocument.values.heap.ListKVArray; public class R2DBackedTranslator<Result extends AutoCloseable, BackendInternalFields extends InternalFields> implements R2DTranslator<Result> { private final R2DBackendTranslator<Result, BackendInternalFields> backendTranslator; public R2DBackedTranslator(R2DBackendTranslator<Result, BackendInternalFields> backendTranslator) { this.backendTranslator = backendTranslator; } @Override public Collection<ToroDocument> translate(DocPartResults<Result> docPartResults) { ImmutableList.Builder<ToroDocument> readedDocuments = ImmutableList.builder(); Table<TableRef, Integer, Map<String, List<KVValue<?>>>> currentFieldDocPartTable = HashBasedTable.<TableRef, Integer, Map<String, List<KVValue<?>>>>create(); Table<TableRef, Integer, Map<String, List<KVValue<?>>>> childFieldDocPartTable = HashBasedTable.<TableRef, Integer, Map<String, List<KVValue<?>>>>create(); int previousDepth = -1; Iterator<DocPartResult<Result>> docPartResultIterator = docPartResults.iterator(); while(docPartResultIterator.hasNext()) { DocPartResult<Result> docPartResultSet = docPartResultIterator.next(); MetaDocPart metaDocPart = docPartResultSet.getMetaDocPart(); TableRef tableRef = metaDocPart.getTableRef(); if (previousDepth != -1 && previousDepth != tableRef.getDepth()) { Table<TableRef, Integer, Map<String, List<KVValue<?>>>> previousFieldChildDocPartTable = childFieldDocPartTable; childFieldDocPartTable = currentFieldDocPartTable; currentFieldDocPartTable = previousFieldChildDocPartTable; if (!tableRef.isRoot()) { currentFieldDocPartTable.clear(); } } previousDepth = tableRef.getDepth(); Map<Integer, Map<String, List<KVValue<?>>>> childFieldDocPartRow = childFieldDocPartTable.row(tableRef); Map<Integer, Map<String, List<KVValue<?>>>> currentFieldDocPartRow; if (tableRef.isRoot()) { currentFieldDocPartRow = null; } else { currentFieldDocPartRow = currentFieldDocPartTable.row(tableRef.getParent().get()); } Result result = docPartResultSet.getResult(); readResult(metaDocPart, tableRef, result, currentFieldDocPartRow, childFieldDocPartRow, readedDocuments); } return readedDocuments.build(); } private void readResult(MetaDocPart metaDocPart, TableRef tableRef, Result result, Map<Integer, Map<String, List<KVValue<?>>>> currentFieldDocPartRow, Map<Integer, Map<String, List<KVValue<?>>>> childFieldDocPartRow, ImmutableList.Builder<ToroDocument> readedDocuments) { while (backendTranslator.next(result)) { KVDocument.Builder documentBuilder = new KVDocument.Builder(); BackendInternalFields internalFields = backendTranslator.readInternalFields(metaDocPart, result); Integer did = internalFields.getDid(); Integer rid = internalFields.getRid(); Integer pid = internalFields.getPid(); Integer seq = internalFields.getSeq(); Map<String, List<KVValue<?>>> childFieldDocPartCell = childFieldDocPartRow.get(rid); //TODO: ensure MetaField order using ResultSet meta data Iterator<? extends MetaScalar> metaScalarIterator = metaDocPart .streamScalars().iterator(); boolean wasScalar = false; int fieldIndex = 0; while (metaScalarIterator.hasNext() && !wasScalar) { assert seq != null : "found scalar value outside of an array"; MetaScalar metaScalar = metaScalarIterator.next(); KVValue<?> value = backendTranslator.getValue(metaScalar.getType(), result, internalFields, fieldIndex); fieldIndex++; if (value != null) { if (metaScalar.getType() == FieldType.CHILD) { value = getChildValue(value, getDocPartCellName(tableRef), childFieldDocPartCell); } addValueToDocPartRow(currentFieldDocPartRow, tableRef, pid, seq, value); wasScalar = true; } } if (wasScalar) { continue; } Iterator<? extends MetaField> metaFieldIterator = metaDocPart .streamFields().iterator(); while (metaFieldIterator.hasNext()) { MetaField metaField = metaFieldIterator.next(); KVValue<?> value = backendTranslator.getValue(metaField.getType(), result, internalFields, fieldIndex); fieldIndex++; if (value != null) { if (metaField.getType() == FieldType.CHILD) { value = getChildValue(value, metaField.getName(), childFieldDocPartCell); } documentBuilder.putValue(metaField.getName(), value); } } if (tableRef.isRoot()) { readedDocuments.add(new ToroDocument(did, documentBuilder.build())); } else { addValueToDocPartRow(currentFieldDocPartRow, tableRef, pid, seq, documentBuilder.build()); } } } private static final Boolean IS_ARRAY = true; private KVValue<?> getChildValue(KVValue<?> value, String key, Map<String, List<KVValue<?>>> childDocPartCell) { KVBoolean child = (KVBoolean) value; if (child.getValue() == IS_ARRAY) { List<KVValue<?>> elements; if (childDocPartCell == null || (elements = childDocPartCell.get(key)) == null) { value = new ListKVArray(ImmutableList.of()); } else { value = new ListKVArray(elements); } } else { value = childDocPartCell.get(key).get(0); } return value; } private void addValueToDocPartRow(Map<Integer, Map<String, List<KVValue<?>>>> currentDocPartRow, TableRef tableRef, Integer pid, Integer seq, KVValue<?> value) { if (seq == null) { setDocPartRowValue(currentDocPartRow, tableRef, pid, seq, ImmutableList.of(value)); } else { addToDocPartRow(currentDocPartRow, tableRef, pid, seq, value); } } private void setDocPartRowValue( Map<Integer, Map<String, List<KVValue<?>>>> docPartRow, TableRef tableRef, Integer pid, Integer seq, ImmutableList<KVValue<?>> elements) { Map<String, List<KVValue<?>>> docPartCell = getDocPartCell(docPartRow, pid); String name = getDocPartCellName(tableRef); docPartCell.put(name, elements); } private void addToDocPartRow( Map<Integer, Map<String, List<KVValue<?>>>> docPartRow, TableRef tableRef, Integer pid, Integer seq, KVValue<?> value) { String name = getDocPartCellName(tableRef); Map<String, List<KVValue<?>>> docPartCell = getDocPartCell(docPartRow, pid); List<KVValue<?>> elements = docPartCell.computeIfAbsent(name, n-> new ArrayList<KVValue<?>>()); final int size = elements.size(); if (seq < size) { elements.set(seq, value); } else { for (int i=elements.size(); i<seq; i++) { elements.add(null); } elements.add(value); } } private String getDocPartCellName(TableRef tableRef) { while (tableRef.isInArray()) { tableRef = tableRef.getParent().get(); } return tableRef.getName(); } private Map<String, List<KVValue<?>>> getDocPartCell(Map<Integer, Map<String, List<KVValue<?>>>> docPartRow, Integer pid) { return docPartRow.computeIfAbsent(pid, p-> new HashMap<String, List<KVValue<?>>>()); } }
package controllers; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.nio.charset.Charset; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.*; import javax.mail.*; import javax.mail.internet.*; import com.avaje.ebean.Ebean; import com.avaje.ebean.Expr; import com.avaje.ebean.Expression; import com.avaje.ebean.FetchConfig; import com.avaje.ebean.RawSql; import com.avaje.ebean.RawSqlBuilder; import com.avaje.ebean.SqlUpdate; import com.csvreader.CsvWriter; import com.ecwid.mailchimp.*; import com.ecwid.mailchimp.method.v2_0.lists.ListMethodResult; import com.feth.play.module.pa.PlayAuthenticate; import models.*; import play.*; import play.data.*; import play.libs.Json; import play.mvc.*; import play.mvc.Http.Context; @With(DumpOnError.class) @Secured.Auth(UserRole.ROLE_ALL_ACCESS) public class CRM extends Controller { static Form<Person> personForm = Form.form(Person.class); static Form<Comment> commentForm = Form.form(Comment.class); static Form<Donation> donationForm = Form.form(Donation.class); public static final String CACHE_RECENT_COMMENTS = "CRM-recentComments-"; public static Result recentComments() { return ok(views.html.cached_page.render( new CachedPage(CACHE_RECENT_COMMENTS, "All people", "crm", "recent_comments") { @Override String render() { List<Comment> recent_comments = Comment.find .fetch("person") .fetch("completed_tasks", new FetchConfig().query()) .fetch("completed_tasks.task", new FetchConfig().query()) .where().eq("person.organization", Organization.getByHost()) .orderBy("created DESC").setMaxRows(20).findList(); return views.html.people_index.render(recent_comments).toString(); } })); } public static Result person(Integer id) { Person the_person = Person.findById(id); List<Person> family_members = Person.find.where().isNotNull("family").eq("family", the_person.family). ne("person_id", the_person.person_id).findList(); Set<Integer> family_ids = new HashSet<Integer>(); family_ids.add(the_person.person_id); for (Person family : family_members) { family_ids.add(family.person_id); } List<Comment> all_comments = Comment.find.where().in("person_id", family_ids). order("created DESC").findList(); List<Donation> all_donations = Donation.find.where().in("person_id", family_ids). order("date DESC").findList(); String comment_destination = "<No email set>"; boolean first = true; for (NotificationRule rule : NotificationRule.findByType(NotificationRule.TYPE_COMMENT)) { if (first) { comment_destination = rule.email; first = false; } else { comment_destination += ", " + rule.email; } } return ok(views.html.family.render( the_person, family_members, all_comments, comment_destination, all_donations)); } public static Result jsonPeople(String query) { Expression search_expr = null; HashSet<Person> selected_people = new HashSet<Person>(); boolean first_time = true; for (String term : query.split(" ")) { List<Person> people_matched_this_round; Expression this_expr = Expr.or(Expr.ilike("last_name", "%" + term + "%"), Expr.ilike("first_name", "%" + term + "%")); this_expr = Expr.or(this_expr, Expr.ilike("address", "%" + term + "%")); this_expr = Expr.or(this_expr, Expr.ilike("email", "%" + term + "%")); people_matched_this_round = Person.find.where().add(this_expr) .eq("organization", Organization.getByHost()) .eq("is_family", false) .findList(); List<PhoneNumber> phone_numbers = PhoneNumber.find.where().ilike("number", "%" + term + "%") .eq("owner.organization", Organization.getByHost()) .findList(); for (PhoneNumber pn : phone_numbers) { people_matched_this_round.add(pn.owner); } if (first_time) { selected_people.addAll(people_matched_this_round); } else { selected_people.retainAll(people_matched_this_round); } first_time = false; } List<Map<String, String> > result = new ArrayList<Map<String, String> > (); for (Person p : selected_people) { HashMap<String, String> values = new HashMap<String, String>(); String label = p.first_name; if (p.last_name != null) { label = label + " " + p.last_name; } values.put("label", label); values.put("id", "" + p.person_id); result.add(values); } return ok(Json.stringify(Json.toJson(result))); } // personId should be -1 if the client doesn't care about a particular // person, but just wants a list of available tags. In that case, // the "create new tag" functionality is also disabled. public static Result jsonTags(String term, Integer personId) { String like_arg = "%" + term + "%"; List<Tag> selected_tags = Tag.find.where() .eq("organization", Organization.getByHost()) .ilike("title", "%" + term + "%").findList(); List<Tag> existing_tags = null; if (personId >= 0) { Person p = Person.findById(personId); if (p != null) { existing_tags = p.tags; } } List<Map<String, String> > result = new ArrayList<Map<String, String> > (); for (Tag t : selected_tags) { if (existing_tags == null || !existing_tags.contains(t)) { HashMap<String, String> values = new HashMap<String, String>(); values.put("label", t.title); values.put("id", "" + t.id); result.add(values); } } boolean tag_already_exists = false; for (Tag t : selected_tags) { if (t.title.toLowerCase().equals(term.toLowerCase())) { tag_already_exists = true; } } if (personId >= 0 && !tag_already_exists) { HashMap<String, String> values = new HashMap<String, String>(); values.put("label", "Create new tag: " + term); values.put("id", "-1"); result.add(values); } return ok(Json.stringify(Json.toJson(result))); } public static Collection<Person> getTagMembers(Integer tagId, String familyMode) { List<Person> people = Tag.findById(tagId).people; Set<Person> selected_people = new HashSet<Person>(); selected_people.addAll(people); if (!familyMode.equals("just_tags")) { for (Person p : people) { if (p.family != null) { selected_people.addAll(p.family.family_members); } } } if (familyMode.equals("family_no_kids")) { Set<Person> no_kids = new HashSet<Person>(); for (Person p2 : selected_people) { if (p2.dob == null || CRM.calcAge(p2) > 18) { no_kids.add(p2); } } selected_people = no_kids; } return selected_people; } public static Result renderTagMembers(Integer tagId, String familyMode) { Tag the_tag = Tag.findById(tagId); return ok(views.html.to_address_fragment.render(the_tag.title, getTagMembers(tagId, familyMode))); } public static Result addTag(Integer tagId, String title, Integer personId) { Person p = Person.findById(personId); if (p == null) { return badRequest(); } Tag the_tag; if (tagId == null) { the_tag = Tag.create(title); } else { the_tag = Tag.find.ref(tagId); } PersonTag pt = PersonTag.create(the_tag, p); PersonTagChange ptc = PersonTagChange.create( the_tag, p, Application.getCurrentUser(), true); p.tags.add(the_tag); notifyAboutTag(the_tag, p, true); return ok(views.html.tag_fragment.render(the_tag, p)); } public static Result removeTag(Integer person_id, Integer tag_id) { Tag t = Tag.findById(tag_id); Person p = Person.findById(person_id); if (Ebean.createSqlUpdate("DELETE from person_tag where person_id=" + person_id + " AND tag_id=" + tag_id).execute() == 1) { PersonTagChange ptc = PersonTagChange.create( t, p, Application.getCurrentUser(), false); } notifyAboutTag(t, p, false); return ok(); } public static void notifyAboutTag(Tag t, Person p, boolean was_add) { for (NotificationRule rule : t.notification_rules) { play.libs.mailer.Email mail = new play.libs.mailer.Email(); if (was_add) { mail.setSubject(getInitials(p) + " added to tag " + t.title); } else { mail.setSubject(getInitials(p) + " removed from tag " + t.title); } mail.addTo(rule.email); mail.setFrom("DemSchoolTools <noreply@demschooltools.com>"); mail.setBodyHtml(views.html.tag_email.render(t, p, was_add).toString()); play.libs.mailer.MailerPlugin.send(mail); } } public static Result allPeople() { return ok(views.html.all_people.render(Person.all())); } public static Result viewTag(Integer id) { Tag the_tag = Tag.find .fetch("people") .fetch("people.phone_numbers", new FetchConfig().query()) .where().eq("organization", Organization.getByHost()) .eq("id", id).findUnique(); List<Person> people = the_tag.people; Set<Person> people_with_family = new HashSet<Person>(); for (Person p : people) { if (p.family != null) { people_with_family.addAll(p.family.family_members); } } return ok(views.html.tag.render( the_tag, people, people_with_family, the_tag.use_student_display)); } public static Result downloadTag(Integer id) throws IOException { Tag the_tag = Tag.find .fetch("people") .fetch("people.phone_numbers", new FetchConfig().query()) .where().eq("organization", Organization.getByHost()) .eq("id", id).findUnique(); response().setHeader("Content-Type", "text/csv; charset=utf-8"); response().setHeader("Content-Disposition", "attachment; filename=" + the_tag.title + ".csv"); List<Person> people = the_tag.people; ByteArrayOutputStream baos = new ByteArrayOutputStream(); Charset charset = Charset.forName("UTF-8"); CsvWriter writer = new CsvWriter(baos, ',', charset); writer.write("First name"); writer.write("Last name"); writer.write("Display (JC) name"); writer.write("Gender"); writer.write("DOB"); writer.write("Email"); writer.write("Phone 1"); writer.write("Phone 1 comment"); writer.write("Phone 2"); writer.write("Phone 2 comment"); writer.write("Phone 3"); writer.write("Phone 3 comment"); writer.write("Neighborhood"); writer.write("Street"); writer.write("City"); writer.write("State"); writer.write("ZIP"); writer.write("Notes"); writer.write("Previous school"); writer.write("School district"); writer.write("Grade"); writer.endRecord(); for (Person p : people) { writer.write(p.first_name); writer.write(p.last_name); writer.write(p.getDisplayName()); writer.write(p.gender); if (p.dob != null) { writer.write(Application.yymmddDate(p.dob)); } else { writer.write(""); } writer.write(p.email); for (int i = 0; i < 3; i++) { if (i < p.phone_numbers.size()) { writer.write(p.phone_numbers.get(i).number); writer.write(p.phone_numbers.get(i).comment); } else { writer.write(""); writer.write(""); } } writer.write(p.neighborhood); writer.write(p.address); writer.write(p.city); writer.write(p.state); writer.write(p.zip); writer.write(p.notes); writer.write(p.previous_school); writer.write(p.school_district); writer.write(p.grade); writer.endRecord(); } writer.close(); // Adding the BOM here causes Excel 2010 on Windows to realize // that the file is Unicode-encoded. return ok("\ufeff" + new String(baos.toByteArray(), charset)); } public static Result newPerson() { return ok(views.html.new_person.render(personForm)); } public static Result makeNewPerson() { Form<Person> filledForm = personForm.bindFromRequest(); if(filledForm.hasErrors()) { return badRequest( views.html.new_person.render(filledForm) ); } else { Person new_person = Person.create(filledForm); return redirect(routes.CRM.person(new_person.person_id)); } } static Email getPendingEmail() { return Email.find.where() .eq("organization", Organization.getByHost()) .eq("deleted", false).eq("sent", false).orderBy("id ASC").setMaxRows(1).findUnique(); } public static boolean hasPendingEmail() { return getPendingEmail() != null; } public static Result viewPendingEmail() { Email e = getPendingEmail(); if (e == null) { return redirect(routes.CRM.recentComments()); } Tag staff_tag = Tag.find.where() .eq("organization", Organization.getByHost()) .eq("title", "Staff").findUnique(); List<Person> people = staff_tag.people; ArrayList<String> test_addresses = new ArrayList<String>(); for (Person p : people) { test_addresses.add(p.email); } test_addresses.add("staff@threeriversvillageschool.org"); ArrayList<String> from_addresses = new ArrayList<String>(); from_addresses.add("office@threeriversvillageschool.org"); from_addresses.add("evan@threeriversvillageschool.org"); from_addresses.add("jmp@threeriversvillageschool.org"); from_addresses.add("jancey@threeriversvillageschool.org"); from_addresses.add("info@threeriversvillageschool.org"); from_addresses.add("staff@threeriversvillageschool.org"); e.parseMessage(); return ok(views.html.view_pending_email.render(e, test_addresses, from_addresses)); } public static Result sendTestEmail() { final Map<String, String[]> values = request().body().asFormUrlEncoded(); Email e = Email.findById(Integer.parseInt(values.get("id")[0])); e.parseMessage(); try { MimeMessage to_send = new MimeMessage(e.parsedMessage); to_send.addRecipient(Message.RecipientType.TO, new InternetAddress(values.get("dest_email")[0])); to_send.setFrom(new InternetAddress("Papal DB <noreply@threeriversvillageschool.org>")); Transport.send(to_send); } catch (MessagingException ex) { ex.printStackTrace(); } return ok(); } public static Result sendEmail() { final Map<String, String[]> values = request().body().asFormUrlEncoded(); Email e = Email.findById(Integer.parseInt(values.get("id")[0])); e.parseMessage(); int tagId = Integer.parseInt(values.get("tagId")[0]); Tag theTag = Tag.findById(tagId); String familyMode = values.get("familyMode")[0]; Collection<Person> recipients = getTagMembers(tagId, familyMode); boolean hadErrors = false; for (Person p : recipients) { if (p.email != null && !p.email.equals("")) { try { MimeMessage to_send = new MimeMessage(e.parsedMessage); to_send.addRecipient(Message.RecipientType.TO, new InternetAddress(p.email, p.first_name + " " + p.last_name)); to_send.setFrom(new InternetAddress(values.get("from")[0])); Transport.send(to_send); } catch (MessagingException ex) { ex.printStackTrace(); hadErrors = true; } catch (UnsupportedEncodingException ex) { ex.printStackTrace(); hadErrors = true; } } } // Send confirmation email try { MimeMessage to_send = new MimeMessage(e.parsedMessage); to_send.addRecipient(Message.RecipientType.TO, new InternetAddress("Staff <staff@threeriversvillageschool.org>")); String subject = "(Sent to " + theTag.title + " " + familyMode + ") " + to_send.getSubject(); if (hadErrors) { subject = "***ERRORS*** " + subject; } to_send.setSubject(subject); to_send.setFrom(new InternetAddress(values.get("from")[0])); Transport.send(to_send); } catch (MessagingException ex) { ex.printStackTrace(); } e.delete(); return ok(); } public static Result deleteEmail() { final Map<String, String[]> values = request().body().asFormUrlEncoded(); Email e = Email.findById(Integer.parseInt(values.get("id")[0])); e.delete(); return ok(); } public static Result deletePerson(Integer id) { Person.delete(id); return redirect(routes.CRM.recentComments()); } public static Result editPerson(Integer id) { return ok(views.html.edit_person.render(Person.findById(id).fillForm())); } public static Result savePersonEdits() { Form<Person> filledForm = personForm.bindFromRequest(); if(filledForm.hasErrors()) { return badRequest( views.html.edit_person.render(filledForm) ); } return redirect(routes.CRM.person(Person.updateFromForm(filledForm).person_id)); } public static String getInitials(Person p) { String result = ""; if (p.first_name != null && p.first_name.length() > 0) { result += p.first_name.charAt(0); } if (p.last_name != null && p.last_name.length() > 0) { result += p.last_name.charAt(0); } return result; } public static Result addComment() { CachedPage.remove(CACHE_RECENT_COMMENTS); Form<Comment> filledForm = commentForm.bindFromRequest(); Comment new_comment = new Comment(); new_comment.person = Person.findById(Integer.parseInt(filledForm.field("person").value())); new_comment.user = Application.getCurrentUser(); new_comment.message = filledForm.field("message").value(); String task_id_string = filledForm.field("comment_task_ids").value(); if (task_id_string.length() > 0 || new_comment.message.length() > 0) { new_comment.save(); String[] task_ids = task_id_string.split(","); for (String id_string : task_ids) { if (!id_string.isEmpty()) { int id = Integer.parseInt(id_string); if (id >= 1) { CompletedTask.create(Task.findById(id), new_comment); } } } if (filledForm.field("send_email").value() != null) { for (NotificationRule rule : NotificationRule.findByType(NotificationRule.TYPE_COMMENT)) { play.libs.mailer.Email mail = new play.libs.mailer.Email(); mail.setSubject("DemSchoolTools comment: " + new_comment.user.name + " & " + getInitials(new_comment.person)); mail.addTo(rule.email); mail.setFrom("DemSchoolTools <noreply@demschooltools.com>"); mail.setBodyHtml(views.html.comment_email.render(Comment.find.byId(new_comment.id)).toString()); play.libs.mailer.MailerPlugin.send(mail); } } return ok(views.html.comment_fragment.render(Comment.find.byId(new_comment.id), false)); } else { return ok(); } } public static Result addDonation() { Form<Donation> filledForm = donationForm.bindFromRequest(); Donation new_donation = new Donation(); new_donation.person = Person.findById(Integer.parseInt(filledForm.field("person").value())); new_donation.description = filledForm.field("description").value(); String dollar_value = filledForm.field("dollar_value").value(); if (dollar_value.charAt(0) == '$') { dollar_value = dollar_value.substring(1); } new_donation.dollar_value = Float.parseFloat(dollar_value); try { new_donation.date = new SimpleDateFormat("yyyy-MM-dd").parse(filledForm.field("date").value()); // Set time to 12 noon so that time zone issues won't bump us to the wrong day. new_donation.date.setHours(12); } catch (ParseException e) { new_donation.date = new Date(); } new_donation.is_cash = filledForm.field("donation_type").value().equals("Cash"); if (filledForm.field("needs_thank_you").value() != null) { new_donation.thanked = !filledForm.field("needs_thank_you").value().equals("on"); } else { new_donation.thanked = true; } if (filledForm.field("needs_indiegogo_reward").value() != null) { new_donation.indiegogo_reward_given = !filledForm.field("needs_indiegogo_reward").value().equals("on"); } else { new_donation.indiegogo_reward_given = true; } new_donation.save(); for (NotificationRule rule : NotificationRule.findByType(NotificationRule.TYPE_DONATION)) { play.libs.mailer.Email mail = new play.libs.mailer.Email(); mail.setSubject("Donation recorded from " + new_donation.person.first_name + " " + new_donation.person.last_name); mail.addTo(rule.email); mail.setFrom("DemSchoolTools <noreply@demschooltools.com>"); mail.setBodyHtml(views.html.donation_email.render(new_donation).toString()); play.libs.mailer.MailerPlugin.send(mail); } return ok(views.html.donation_fragment.render(Donation.find.byId(new_donation.id))); } public static Result donationThankYou(int id) { Donation d = Donation.find.byId(id); d.thanked = true; d.thanked_by_user = Application.getCurrentUser(); d.thanked_time = new Date(); d.save(); return ok(); } public static Result donationIndiegogoReward(int id) { Donation d = Donation.findById(id); d.indiegogo_reward_given = true; d.indiegogo_reward_by_user = Application.getCurrentUser(); d.indiegogo_reward_given_time = new Date(); d.save(); return ok(); } public static Result donationsNeedingThankYou() { List<Donation> donations = Donation.find .fetch("person") .where() .eq("person.organization", Organization.getByHost()) .eq("thanked", false).orderBy("date DESC").findList(); return ok(views.html.donation_list.render("Donations needing thank you", donations)); } public static Result donationsNeedingIndiegogo() { List<Donation> donations = Donation.find .fetch("person") .where() .eq("person.organization", Organization.getByHost()) .eq("indiegogo_reward_given", false).orderBy("date DESC").findList(); return ok(views.html.donation_list.render("Donations needing Indiegogo reward", donations)); } public static Result donations() { return ok(views.html.donation_list.render("All donations", Donation.find .fetch("person") .where() .eq("person.organization", Organization.getByHost()) .orderBy("date DESC").findList())); } public static int calcAge(Person p) { return (int)((new Date().getTime() - p.dob.getTime()) / 1000 / 60 / 60 / 24 / 365.25); } public static int calcAgeAtBeginningOfSchool(Person p) { if (p.dob == null) { return -1; } return (int)((new Date(114, 7, 25).getTime() - p.dob.getTime()) / 1000 / 60 / 60 / 24 / 365.25); } public static String formatDob(Date d) { if (d == null) { return " } return new SimpleDateFormat("MM/dd/yy").format(d); } public static String formatDate(Date d) { d = new Date(d.getTime() + (Application.getConfiguration().getInt("time_zone_offset") * 1000L * 60 * 60)); Date now = new Date(); long diffHours = (now.getTime() - d.getTime()) / 1000 / 60 / 60; // String format = "EEE MMMM d, h:mm a"; String format; if (diffHours < 24) { format = "h:mm a"; } else if (diffHours < 24 * 7) { format = "EEEE, MMMM d"; } else { format = "MM/d/yy"; } return new SimpleDateFormat(format).format(d); } public static Result viewTaskList(Integer id) { TaskList list = TaskList.findById(id); List<Person> people = list.tag.people; return ok(views.html.task_list.render(list, people)); } public static Result viewMailchimpSettings() { MailChimpClient mailChimpClient = new MailChimpClient(); Organization org = OrgConfig.get().org; Map<String, ListMethodResult.Data> mc_list_map = Public.getMailChimpLists(mailChimpClient, org.mailchimp_api_key); return ok(views.html.view_mailchimp_settings.render( Form.form(Organization.class), org, MailchimpSync.find.where().eq("tag.organization", OrgConfig.get().org).findList(), mc_list_map)); } public static Result saveMailchimpSettings() { final Map<String, String[]> values = request().body().asFormUrlEncoded(); if (values.containsKey("mailchimp_api_key")) { OrgConfig.get().org.setMailChimpApiKey(values.get("mailchimp_api_key")[0]); } if (values.containsKey("mailchimp_updates_email")) { OrgConfig.get().org.setMailChimpUpdatesEmail(values.get("mailchimp_updates_email")[0]); } if (values.containsKey("sync_type")) { for (String tag_id : values.get("tag_id")) { Tag t = Tag.findById(Integer.parseInt(tag_id)); MailchimpSync sync = MailchimpSync.create(t, values.get("mailchimp_list_id")[0], values.get("sync_type")[0].equals("local_add"), values.get("sync_type")[0].equals("local_remove")); } } if (values.containsKey("remove_sync_id")) { MailchimpSync sync = MailchimpSync.find.byId(Integer.parseInt( values.get("remove_sync_id")[0])); sync.delete(); } return redirect(routes.CRM.viewMailchimpSettings()); } }
package nl.mpi.kinnate.svg; import java.awt.Point; import nl.mpi.kinnate.kindata.EntityData; import java.util.ArrayList; import nl.mpi.kinnate.kindata.DataTypes; import nl.mpi.kinnate.kindata.EntityRelation; import nl.mpi.kinnate.uniqueidentifiers.UniqueIdentifier; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.Text; import org.w3c.dom.svg.SVGDocument; public class RelationSvg { private void addUseNode(SVGDocument doc, String svgNameSpace, Element targetGroup, String targetDefId) { String useNodeId = targetDefId + "use"; Node useNodeOld = doc.getElementById(useNodeId); if (useNodeOld != null) { useNodeOld.getParentNode().removeChild(useNodeOld); } Element useNode = doc.createElementNS(svgNameSpace, "use"); useNode.setAttributeNS("http://www.w3.org/1999/xlink", "xlink:href", "#" + targetDefId); // the xlink: of "xlink:href" is required for some svg viewers to render correctly // useNode.setAttribute("href", "#" + lineIdString); useNode.setAttribute("id", useNodeId); targetGroup.appendChild(useNode); } private void updateLabelNode(SVGDocument doc, String svgNameSpace, String lineIdString, String targetRelationId) { // remove and readd the text on path label so that it updates with the new path String labelNodeId = targetRelationId + "label"; Node useNodeOld = doc.getElementById(labelNodeId); if (useNodeOld != null) { Node textParentNode = useNodeOld.getParentNode(); String labelText = useNodeOld.getTextContent(); useNodeOld.getParentNode().removeChild(useNodeOld); Element textPath = doc.createElementNS(svgNameSpace, "textPath"); textPath.setAttributeNS("http://www.w3.org/1999/xlink", "xlink:href", "#" + lineIdString); // the xlink: of "xlink:href" is required for some svg viewers to render correctly textPath.setAttribute("startOffset", "50%"); textPath.setAttribute("id", labelNodeId); Text textNode = doc.createTextNode(labelText); textPath.appendChild(textNode); textParentNode.appendChild(textPath); } } protected void setPolylinePointsAttribute(LineLookUpTable lineLookUpTable, String lineIdString, Element targetNode, DataTypes.RelationType relationType, float vSpacing, float egoX, float egoY, float alterX, float alterY) { float midY = (egoY + alterY) / 2; // todo: Ticket #1064 when an entity is above one that it should be below the line should make a zigzag to indicate it switch (relationType) { case affiliation: break; case ancestor: midY = alterY + vSpacing / 2; break; case descendant: midY = egoY + vSpacing / 2; break; case none: break; case sibling: // if (commonParentMaxY != null) { // midY = commonParentMaxY + vSpacing / 2; // } else { midY = (egoY < alterY) ? egoY - vSpacing / 2 : alterY - vSpacing / 2; break; case union: midY = (egoY > alterY) ? egoY + vSpacing / 2 : alterY + vSpacing / 2; break; } // if (alterY == egoY) { // // make sure that union lines go below the entities and sibling lines go above // if (relationType == DataTypes.RelationType.sibling) { // midY = alterY - vSpacing / 2; // } else if (relationType == DataTypes.RelationType.union) { // midY = alterY + vSpacing / 2; Point[] initialPointsList = new Point[]{ new Point((int) egoX, (int) egoY), new Point((int) egoX, (int) midY), new Point((int) alterX, (int) midY), new Point((int) alterX, (int) alterY) }; Point[] adjustedPointsList; if (lineLookUpTable != null) { // this version is used when the relations are drawn on the diagram // or when an entity is dragged before the diagram is redrawn in the case of a reloaded from disk diagram (this case is sub optimal in that on first load the loops will not be drawn) adjustedPointsList = lineLookUpTable.adjustLineToObstructions(lineIdString, initialPointsList); } else { // this version is used when the relation drag handles are used adjustedPointsList = initialPointsList; } StringBuilder stringBuilder = new StringBuilder(); for (Point currentPoint : adjustedPointsList) { stringBuilder.append(currentPoint.x); stringBuilder.append(","); stringBuilder.append(currentPoint.y); stringBuilder.append(" "); } targetNode.setAttribute("points", stringBuilder.toString()); } protected void setPathPointsAttribute(Element targetNode, DataTypes.RelationType relationType, DataTypes.RelationLineType relationLineType, float hSpacing, float vSpacing, float egoX, float egoY, float alterX, float alterY) { float fromBezX; float fromBezY; float toBezX; float toBezY; if ((egoX > alterX && egoY < alterY) || (egoX > alterX && egoY > alterY)) { // prevent the label on the line from rendering upside down float tempX = alterX; float tempY = alterY; alterX = egoX; alterY = egoY; egoX = tempX; egoY = tempY; } if (relationLineType == DataTypes.RelationLineType.verticalCurve) { fromBezX = egoX; fromBezY = alterY; toBezX = alterX; toBezY = egoY; // todo: update the bezier positions similar to in the follwing else statement if (1 / (egoY - alterY) < vSpacing) { fromBezX = egoX; fromBezY = alterY - vSpacing / 2; toBezX = alterX; toBezY = egoY - vSpacing / 2; } } else { fromBezX = alterX; fromBezY = egoY; toBezX = egoX; toBezY = alterY; // todo: if the nodes are almost in align then this test fails and it should insted check for proximity not equality // System.out.println(1 / (egoX - alterX)); // if (1 / (egoX - alterX) < vSpacing) { if (egoX > alterX) { if (egoX - alterX < hSpacing / 4) { fromBezX = egoX - hSpacing / 4; toBezX = alterX - hSpacing / 4; } else { fromBezX = (egoX - alterX) / 2 + alterX; toBezX = (egoX - alterX) / 2 + alterX; } } else { if (alterX - egoX < hSpacing / 4) { fromBezX = egoX + hSpacing / 4; toBezX = alterX + hSpacing / 4; } else { fromBezX = (alterX - egoX) / 2 + egoX; toBezX = (alterX - egoX) / 2 + egoX; } } } targetNode.setAttribute("d", "M " + egoX + "," + egoY + " C " + fromBezX + "," + fromBezY + " " + toBezX + "," + toBezY + " " + alterX + "," + alterY); } private boolean hasCommonParent(EntityData currentNode, EntityRelation graphLinkNode) { if (graphLinkNode.relationType == DataTypes.RelationType.sibling) { for (EntityRelation altersRelation : graphLinkNode.getAlterNode().getDistinctRelateNodes()) { if (altersRelation.relationType == DataTypes.RelationType.ancestor) { for (EntityRelation egosRelation : currentNode.getDistinctRelateNodes()) { if (egosRelation.relationType == DataTypes.RelationType.ancestor) { if (altersRelation.alterUniqueIdentifier.equals(egosRelation.alterUniqueIdentifier)) { if (altersRelation.getAlterNode().isVisible) { return true; } } } } } } } return false; } // private Float getCommonParentMaxY(EntitySvg entitySvg, EntityData currentNode, EntityRelation graphLinkNode) { // if (graphLinkNode.relationType == DataTypes.RelationType.sibling) { // Float maxY = null; // ArrayList<Float> commonParentY = new ArrayList<Float>(); // for (EntityRelation altersRelation : graphLinkNode.getAlterNode().getDistinctRelateNodes()) { // if (altersRelation.relationType == DataTypes.RelationType.ancestor) { // for (EntityRelation egosRelation : currentNode.getDistinctRelateNodes()) { // if (egosRelation.relationType == DataTypes.RelationType.ancestor) { // if (altersRelation.alterUniqueIdentifier.equals(egosRelation.alterUniqueIdentifier)) { // float parentY = entitySvg.getEntityLocation(egosRelation.alterUniqueIdentifier)[1]; // maxY = parentY > maxY ? parentY : maxY; // return maxY; // } else { // return null; protected void insertRelation(GraphPanel graphPanel, Element relationGroupNode, EntityData currentNode, EntityRelation graphLinkNode, int hSpacing, int vSpacing) { if (graphLinkNode.relationLineType == DataTypes.RelationLineType.sanguineLine) { if (hasCommonParent(currentNode, graphLinkNode)) { return; // do not draw lines for siblings if the common parent is visible because the ancestor lines will take the place of the sibling lines } } int relationLineIndex = relationGroupNode.getChildNodes().getLength(); Element groupNode = graphPanel.doc.createElementNS(graphPanel.svgNameSpace, "g"); groupNode.setAttribute("id", "relation" + relationLineIndex); Element defsNode = graphPanel.doc.createElementNS(graphPanel.svgNameSpace, "defs"); String lineIdString = "relation" + relationLineIndex + "Line"; new DataStoreSvg().storeRelationParameters(graphPanel.doc, groupNode, graphLinkNode.relationType, graphLinkNode.relationLineType, currentNode.getUniqueIdentifier(), graphLinkNode.getAlterNode().getUniqueIdentifier()); // set the line end points // int[] egoSymbolPoint = graphPanel.dataStoreSvg.graphData.getEntityLocation(currentNode.getUniqueIdentifier()); // int[] alterSymbolPoint = graphPanel.dataStoreSvg.graphData.getEntityLocation(graphLinkNode.getAlterNode().getUniqueIdentifier()); float[] egoSymbolPoint = graphPanel.entitySvg.getEntityLocation(currentNode.getUniqueIdentifier()); float[] alterSymbolPoint = graphPanel.entitySvg.getEntityLocation(graphLinkNode.getAlterNode().getUniqueIdentifier()); // float fromX = (currentNode.getxPos()); // * hSpacing + hSpacing // float fromY = (currentNode.getyPos()); // * vSpacing + vSpacing // float toX = (graphLinkNode.getAlterNode().getxPos()); // * hSpacing + hSpacing // float toY = (graphLinkNode.getAlterNode().getyPos()); // * vSpacing + vSpacing float fromX = (egoSymbolPoint[0]); // * hSpacing + hSpacing float fromY = (egoSymbolPoint[1]); // * vSpacing + vSpacing float toX = (alterSymbolPoint[0]); // * hSpacing + hSpacing float toY = (alterSymbolPoint[1]); // * vSpacing + vSpacing boolean addedRelationLine = false; switch (graphLinkNode.relationLineType) { case kinTermLine: // this case uses the following case case verticalCurve: // todo: groupNode.setAttribute("id", ); // System.out.println("link: " + graphLinkNode.linkedNode.xPos + ":" + graphLinkNode.linkedNode.yPos); //// <line id="_15" transform="translate(146.0,112.0)" x1="0" y1="0" x2="100" y2="100" ="black" stroke-width="1"/> // Element linkLine = doc.createElementNS(svgNS, "line"); // linkLine.setAttribute("x1", Integer.toString(currentNode.xPos * hSpacing + hSpacing)); // linkLine.setAttribute("y1", Integer.toString(currentNode.yPos * vSpacing + vSpacing)); // linkLine.setAttribute("x2", Integer.toString(graphLinkNode.linkedNode.xPos * hSpacing + hSpacing)); // linkLine.setAttribute("y2", Integer.toString(graphLinkNode.linkedNode.yPos * vSpacing + vSpacing)); // linkLine.setAttribute("stroke", "black"); // linkLine.setAttribute("stroke-width", "1"); // // Attach the rectangle to the root 'svg' element. // svgRoot.appendChild(linkLine); //System.out.println("link: " + graphLinkNode.getAlterNode().xPos + ":" + graphLinkNode.getAlterNode().yPos); // <line id="_15" transform="translate(146.0,112.0)" x1="0" y1="0" x2="100" y2="100" ="black" stroke-width="1"/> Element linkLine = graphPanel.doc.createElementNS(graphPanel.svgNameSpace, "path"); setPathPointsAttribute(linkLine, graphLinkNode.relationType, graphLinkNode.relationLineType, hSpacing, vSpacing, fromX, fromY, toX, toY); // linkLine.setAttribute("x1", ); // linkLine.setAttribute("y1", ); // linkLine.setAttribute("x2", ); linkLine.setAttribute("fill", "none"); if (graphLinkNode.lineColour != null) { linkLine.setAttribute("stroke", graphLinkNode.lineColour); } else { linkLine.setAttribute("stroke", "blue"); } linkLine.setAttribute("stroke-width", Integer.toString(EntitySvg.strokeWidth)); linkLine.setAttribute("id", lineIdString); defsNode.appendChild(linkLine); addedRelationLine = true; break; case sanguineLine: // Element squareLinkLine = doc.createElement("line"); // squareLinkLine.setAttribute("x1", Integer.toString(currentNode.xPos * hSpacing + hSpacing)); // squareLinkLine.setAttribute("y1", Integer.toString(currentNode.yPos * vSpacing + vSpacing)); // squareLinkLine.setAttribute("x2", Integer.toString(graphLinkNode.linkedNode.xPos * hSpacing + hSpacing)); // squareLinkLine.setAttribute("y2", Integer.toString(graphLinkNode.linkedNode.yPos * vSpacing + vSpacing)); // squareLinkLine.setAttribute("stroke", "grey"); // squareLinkLine.setAttribute("stroke-width", Integer.toString(strokeWidth)); Element squareLinkLine = graphPanel.doc.createElementNS(graphPanel.svgNameSpace, "polyline"); setPolylinePointsAttribute(graphPanel.lineLookUpTable, lineIdString, squareLinkLine, graphLinkNode.relationType, vSpacing, fromX, fromY, toX, toY); squareLinkLine.setAttribute("fill", "none"); squareLinkLine.setAttribute("stroke", "grey"); squareLinkLine.setAttribute("stroke-width", Integer.toString(EntitySvg.strokeWidth)); squareLinkLine.setAttribute("id", lineIdString); defsNode.appendChild(squareLinkLine); addedRelationLine = true; break; } groupNode.appendChild(defsNode); if (addedRelationLine) { // insert the node that uses the above definition addUseNode(graphPanel.doc, graphPanel.svgNameSpace, groupNode, lineIdString); // add the relation label if (graphLinkNode.labelString != null) { Element labelText = graphPanel.doc.createElementNS(graphPanel.svgNameSpace, "text"); labelText.setAttribute("text-anchor", "middle"); // labelText.setAttribute("x", Integer.toString(labelX)); // labelText.setAttribute("y", Integer.toString(labelY)); if (graphLinkNode.lineColour != null) { labelText.setAttribute("fill", graphLinkNode.lineColour); } else { labelText.setAttribute("fill", "blue"); } labelText.setAttribute("stroke-width", "0"); labelText.setAttribute("font-size", "14"); // labelText.setAttribute("transform", "rotate(45)"); Element textPath = graphPanel.doc.createElementNS(graphPanel.svgNameSpace, "textPath"); textPath.setAttributeNS("http://www.w3.rg/1999/xlink", "xlink:href", "#" + lineIdString); // the xlink: of "xlink:href" is required for some svg viewers to render correctly textPath.setAttribute("startOffset", "50%"); textPath.setAttribute("id", "relation" + relationLineIndex + "label"); Text textNode = graphPanel.doc.createTextNode(graphLinkNode.labelString); textPath.appendChild(textNode); labelText.appendChild(textPath); groupNode.appendChild(labelText); } } relationGroupNode.appendChild(groupNode); } public void updateRelationLines(GraphPanel graphPanel, ArrayList<UniqueIdentifier> draggedNodeIds, int hSpacing, int vSpacing) { // todo: if an entity is above its ancestor then this must be corrected, if the ancestor data is stored in the relationLine attributes then this would be a good place to correct this Element relationGroup = graphPanel.doc.getElementById("RelationGroup"); for (Node currentChild = relationGroup.getFirstChild(); currentChild != null; currentChild = currentChild.getNextSibling()) { if ("g".equals(currentChild.getLocalName())) { Node idAttrubite = currentChild.getAttributes().getNamedItem("id"); //System.out.println("idAttrubite: " + idAttrubite.getNodeValue()); DataStoreSvg.GraphRelationData graphRelationData = new DataStoreSvg().getEntitiesForRelations(currentChild); if (graphRelationData != null) { if (draggedNodeIds.contains(graphRelationData.egoNodeId) || draggedNodeIds.contains(graphRelationData.alterNodeId)) { // todo: update the relation lines //System.out.println("needs update on: " + idAttrubite.getNodeValue()); String lineElementId = idAttrubite.getNodeValue() + "Line"; Element relationLineElement = graphPanel.doc.getElementById(lineElementId); //System.out.println("type: " + relationLineElement.getLocalName()); float[] egoSymbolPoint = graphPanel.entitySvg.getEntityLocation(graphRelationData.egoNodeId); float[] alterSymbolPoint = graphPanel.entitySvg.getEntityLocation(graphRelationData.alterNodeId); // int[] egoSymbolPoint = graphPanel.dataStoreSvg.graphData.getEntityLocation(graphRelationData.egoNodeId); // int[] alterSymbolPoint = graphPanel.dataStoreSvg.graphData.getEntityLocation(graphRelationData.alterNodeId); float egoX = egoSymbolPoint[0]; float egoY = egoSymbolPoint[1]; float alterX = alterSymbolPoint[0]; float alterY = alterSymbolPoint[1]; // SVGRect egoSymbolRect = new EntitySvg().getEntityLocation(doc, graphRelationData.egoNodeId); // SVGRect alterSymbolRect = new EntitySvg().getEntityLocation(doc, graphRelationData.alterNodeId); // float egoX = egoSymbolRect.getX() + egoSymbolRect.getWidth() / 2; // float egoY = egoSymbolRect.getY() + egoSymbolRect.getHeight() / 2; // float alterX = alterSymbolRect.getX() + alterSymbolRect.getWidth() / 2; // float alterY = alterSymbolRect.getY() + alterSymbolRect.getHeight() / 2; if ("polyline".equals(relationLineElement.getLocalName())) { setPolylinePointsAttribute(graphPanel.lineLookUpTable, lineElementId, relationLineElement, graphRelationData.relationType, vSpacing, egoX, egoY, alterX, alterY); } if ("path".equals(relationLineElement.getLocalName())) { setPathPointsAttribute(relationLineElement, graphRelationData.relationType, graphRelationData.relationLineType, hSpacing, vSpacing, egoX, egoY, alterX, alterY); } addUseNode(graphPanel.doc, graphPanel.svgNameSpace, (Element) currentChild, lineElementId); updateLabelNode(graphPanel.doc, graphPanel.svgNameSpace, lineElementId, idAttrubite.getNodeValue()); } } } } } // new RelationSvg().addTestNode(doc, (Element) relationLineElement.getParentNode().getParentNode(), svgNameSpace); // public void addTestNode(SVGDocument doc, Element addTarget, String svgNameSpace) { // Element squareNode = doc.createElementNS(svgNameSpace, "rect"); // squareNode.setAttribute("x", "100"); // squareNode.setAttribute("y", "100"); // squareNode.setAttribute("width", "20"); // squareNode.setAttribute("height", "20"); // squareNode.setAttribute("fill", "green"); // squareNode.setAttribute("stroke", "black"); // squareNode.setAttribute("stroke-width", "2"); // addTarget.appendChild(squareNode); }
package org.reprap.gui.botConsole; import java.text.SimpleDateFormat; import java.util.Date; import java.util.GregorianCalendar; import java.io.File; import javax.swing.JOptionPane; import org.reprap.Extruder; import org.reprap.Main; import org.reprap.Printer; import org.reprap.pcb.PCB; /** * * @author ensab */ public class PrintTabFrame extends javax.swing.JInternalFrame { private static final long serialVersionUID = 1L; private BotConsoleFrame parentBotConsoleFrame = null; // private XYZTabPanel xYZTabPanel = null; private Printer printer; private boolean paused = false; private boolean seenSNAP = false; private boolean seenGCode = false; private long startTime = -1; private int oldLayer = -1; private String loadedFiles = ""; private boolean loadedFilesLong = false; private boolean stlLoaded = false; private boolean gcodeLoaded = false; /** Creates new form PrintTabFrame */ public PrintTabFrame() { initComponents(); String machine = "simulator"; //toSNAPRepRapRadioButton.setSelected(false); try { machine = org.reprap.Preferences.loadGlobalString("RepRap_Machine"); //if(machine.equalsIgnoreCase("SNAPRepRap")) // toSNAPRepRapRadioButton.setSelected(true); // seenSNAP = true; //} else if(machine.equalsIgnoreCase("GCodeRepRap")) // if(org.reprap.Preferences.loadGlobalBool("GCodeUseSerial")) // toGCodeRepRapRadioButton.setSelected(true); // else // gCodeToFileRadioButton.setSelected(true); seenGCode = true; } catch (Exception e) { System.err.println("Failure trying to load 'RepRap_Machine' preference: " + e); return; } printer = org.reprap.Main.gui.getPrinter(); enableSLoad(); } /** * Keep the user amused. If fractionDone is negative, the function * queries the layer statistics. If it is 0 or positive, the function uses * it. * @param fractionDone */ public void updateProgress(double fractionDone, int layer, int layers) { //System.out.println("layer marker: " + fractionDone + ", " + layer + ", " + layers); if(layer >= 0) currentLayerOutOfN.setText("" + layer + "/" + layers); if(layers < 0) { layers = org.reprap.Main.gui.getLayers(); } if(layer < 0) { layer = org.reprap.Main.gui.getLayer(); if(layer >= 0) currentLayerOutOfN.setText("" + layer + "/" + layers); } if(fractionDone < 0) { // Only bother if the layer has just changed if(layer == oldLayer) return; boolean topDown = layer < oldLayer; oldLayer = layer; //currentLayerOutOfN.setText("" + layer + "/" + layers); if(topDown) fractionDone = (double)(layers - layer)/(double)layers; else fractionDone = (double)layer/(double)layers; } progressBar.setMinimum(0); progressBar.setMaximum(100); progressBar.setValue((int)(100*fractionDone)); GregorianCalendar cal = new GregorianCalendar(); SimpleDateFormat dateFormat = new SimpleDateFormat("EE HH:mm:ss Z"); Date d = cal.getTime(); long e = d.getTime(); if(startTime < 0) { startTime = e; return; } //if(layer <= 0) //return; long f = (long)((double)(e - startTime)/fractionDone); int h = (int)(f/60000)/60; int m = (int)(f/60000)%60; if(m > 9) expectedBuildTime.setText("" + h + ":" + m); else expectedBuildTime.setText("" + h + ":0" + m); expectedFinishTime.setText(dateFormat.format(new Date(startTime + f))); } /** * So the BotConsoleFrame can let us know who it is * @param b */ public void setConsoleFrame(BotConsoleFrame b) { parentBotConsoleFrame = b; } /** This method is called from within the constructor to * initialize the form. * WARNING: Do NOT modify this code. The content of this method is * always regenerated by the Form Editor. */ // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { buttonGroup1 = new javax.swing.ButtonGroup(); printButton = new java.awt.Button(); pcbButton = new java.awt.Button(); pauseButton = new java.awt.Button(); stopButton = new java.awt.Button(); exitButton = new java.awt.Button(); layerPauseCheck = new javax.swing.JCheckBox(); layerPause(false); //toSNAPRepRapRadioButton = new javax.swing.JRadioButton(); getWebPage = new javax.swing.JButton(); expectedBuildTimeLabel = new javax.swing.JLabel(); hoursMinutesLabel1 = new javax.swing.JLabel(); expectedBuildTime = new javax.swing.JLabel(); expectedFinishTimeLabel = new javax.swing.JLabel(); expectedFinishTime = new javax.swing.JLabel(); progressLabel = new javax.swing.JLabel(); currentLayerOutOfN = new javax.swing.JLabel(); progressBar = new javax.swing.JProgressBar(); loadSTL = new java.awt.Button(); loadGCode = new java.awt.Button(); gCodeToFileRadioButton = new javax.swing.JRadioButton(); loadRFO = new java.awt.Button(); toGCodeRepRapRadioButton = new javax.swing.JRadioButton(); fileNameBox = new javax.swing.JLabel(); preferencesButton = new java.awt.Button(); saveRFO = new java.awt.Button(); displayPathsCheck = new javax.swing.JCheckBox(); displayPaths(false); printButton.setBackground(new java.awt.Color(51, 204, 0)); printButton.setFont(printButton.getFont()); printButton.setLabel("Print"); // NOI18N printButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { printButtonActionPerformed(evt); } }); pcbButton.setBackground(new java.awt.Color(152, 99, 62)); pcbButton.setFont(pcbButton.getFont()); pcbButton.setLabel("PCB"); // NOI18N pcbButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { pcbButtonActionPerformed(evt); } }); pauseButton.setBackground(new java.awt.Color(255, 204, 0)); pauseButton.setLabel("Pause"); // NOI18N pauseButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { pauseButtonActionPerformed(evt); } }); stopButton.setBackground(new java.awt.Color(255, 0, 0)); stopButton.setFont(new java.awt.Font("Dialog", 1, 12)); stopButton.setLabel("STOP !"); // NOI18N stopButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { stopButtonActionPerformed(evt); } }); exitButton.setLabel("Exit"); exitButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { exitButtonActionPerformed(evt); } }); layerPauseCheck.setText("Pause at end of layer"); // NOI18N layerPauseCheck.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { layerPauseCheckActionPerformed(evt); } }); // buttonGroup1.add(toSNAPRepRapRadioButton); // toSNAPRepRapRadioButton.setText("Print on SNAP RepRap"); // toSNAPRepRapRadioButton.addMouseListener(new java.awt.event.MouseAdapter() { // public void mousePressed(java.awt.event.MouseEvent evt) { // selectorRadioButtonMousePressed(evt); getWebPage.setIcon(new javax.swing.ImageIcon( ClassLoader.getSystemResource("rr-logo-green-url.png"))); // NOI18N getWebPage.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { getWebPageActionPerformed(evt); } }); expectedBuildTimeLabel.setFont(new java.awt.Font("Tahoma", 0, 12)); expectedBuildTimeLabel.setText("Expected build time:"); // NOI18N hoursMinutesLabel1.setFont(new java.awt.Font("Tahoma", 0, 12)); hoursMinutesLabel1.setText("(h:m)"); // NOI18N expectedBuildTime.setFont(new java.awt.Font("Tahoma", 0, 12)); expectedBuildTime.setText("00:00"); // NOI18N expectedFinishTimeLabel.setFont(new java.awt.Font("Tahoma", 0, 12)); expectedFinishTimeLabel.setText("Expected to finish at:"); // NOI18N expectedFinishTime.setFont(new java.awt.Font("Tahoma", 0, 12)); expectedFinishTime.setText(" -"); // NOI18N progressLabel.setFont(new java.awt.Font("Tahoma", 0, 12)); progressLabel.setText("Layer progress:"); // NOI18N currentLayerOutOfN.setFont(new java.awt.Font("Tahoma", 0, 12)); currentLayerOutOfN.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT); currentLayerOutOfN.setText("000/000"); // NOI18N loadSTL.setActionCommand("loadSTL"); loadSTL.setBackground(new java.awt.Color(0, 204, 255)); loadSTL.setLabel("Load STL"); // NOI18N loadSTL.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { loadSTL(evt); } }); loadGCode.setActionCommand("loadGCode"); loadGCode.setBackground(new java.awt.Color(0, 204, 255)); loadGCode.setLabel("Load GCode"); // NOI18N loadGCode.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { LoadGCode(evt); } }); buttonGroup1.add(gCodeToFileRadioButton); gCodeToFileRadioButton.setText("Send GCodes to file"); gCodeToFileRadioButton.addMouseListener(new java.awt.event.MouseAdapter() { public void mousePressed(java.awt.event.MouseEvent evt) { selectorRadioButtonMousePressed(evt); } }); loadRFO.setActionCommand("loadRFO"); loadRFO.setBackground(new java.awt.Color(0, 204, 255)); loadRFO.setLabel("Load RFO"); // NOI18N loadRFO.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { loadRFO(evt); } }); buttonGroup1.add(toGCodeRepRapRadioButton); toGCodeRepRapRadioButton.setText("Print on G-Code RepRap"); toGCodeRepRapRadioButton.addMouseListener(new java.awt.event.MouseAdapter() { public void mousePressed(java.awt.event.MouseEvent evt) { selectorRadioButtonMousePressed(evt); } }); fileNameBox.setFont(new java.awt.Font("Tahoma", 0, 12)); fileNameBox.setText(" - "); preferencesButton.setActionCommand("preferences"); preferencesButton.setBackground(new java.awt.Color(255, 102, 255)); preferencesButton.setLabel("Preferences"); // NOI18N preferencesButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { preferences(evt); } }); saveRFO.setActionCommand("saveRFO"); saveRFO.setBackground(new java.awt.Color(153, 153, 153)); saveRFO.setLabel("Save RFO"); // NOI18N saveRFO.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { saveRFO(evt); } }); displayPathsCheck.setText("Display paths"); displayPathsCheck.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { displayPathsCheckMouseClicked(evt); } }); org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(layout.createSequentialGroup() .addContainerGap() .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(layout.createSequentialGroup() .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING) .add(pcbButton, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 100, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) .add(saveRFO, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 100, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) .add(loadGCode, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 100, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(loadRFO, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 100, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) .add(loadSTL, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 100, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) //.add(toSNAPRepRapRadioButton) .add(toGCodeRepRapRadioButton) .add(gCodeToFileRadioButton) .add(layerPauseCheck) .add(displayPathsCheck)) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING, false) .add(layout.createSequentialGroup() .add(preferencesButton, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .add(getWebPage, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 190, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)) .add(layout.createSequentialGroup() .add(printButton, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 72, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) //.add(pcbButton, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 72, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) //.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(pauseButton, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 78, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(stopButton, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 75, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(exitButton, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 62, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)))) .add(layout.createSequentialGroup() .add(expectedFinishTimeLabel) .add(7, 7, 7) .add(expectedFinishTime)) .add(layout.createSequentialGroup() .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(layout.createSequentialGroup() .add(expectedBuildTimeLabel) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(expectedBuildTime)) .add(layout.createSequentialGroup() .add(progressLabel) .add(7, 7, 7) .add(currentLayerOutOfN))) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING, false) .add(layout.createSequentialGroup() .add(hoursMinutesLabel1) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(fileNameBox, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .add(progressBar, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 430, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)))) .addContainerGap(29, Short.MAX_VALUE)) ); layout.setVerticalGroup( layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(layout.createSequentialGroup() .addContainerGap() .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(layout.createSequentialGroup() .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(getWebPage, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 72, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)) .add(layout.createSequentialGroup() .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(layout.createSequentialGroup() .add(loadGCode, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 41, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(loadSTL, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 41, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) ) .add(layout.createSequentialGroup() //.add(toSNAPRepRapRadioButton) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(toGCodeRepRapRadioButton) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(gCodeToFileRadioButton)) .add(preferencesButton, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 45, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(layout.createSequentialGroup() .add(layerPauseCheck) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(displayPathsCheck)) .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING) .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(pauseButton, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 39, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) .add(printButton, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 39, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) .add(pcbButton, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 39, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) .add(stopButton, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 39, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) .add(exitButton, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 39, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)) .add(layout.createSequentialGroup() .add(loadRFO, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 41, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(saveRFO, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 41, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(pcbButton, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 41, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) ))))) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING) .add(expectedBuildTimeLabel) .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE) .add(expectedBuildTime) .add(hoursMinutesLabel1) .add(fileNameBox))) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING) .add(expectedFinishTimeLabel) .add(expectedFinishTime)) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING) .add(progressLabel) .add(currentLayerOutOfN)) .add(progressBar, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)) .addContainerGap(24, Short.MAX_VALUE)) ); pack(); }// </editor-fold>//GEN-END:initComponents private void printButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_printButtonActionPerformed parentBotConsoleFrame.suspendPolling(); parentBotConsoleFrame.setFractionDone(-1, -1, -1); org.reprap.Main.gui.mouseToWorld(); if(gCodeToFileRadioButton.isSelected()) { int sp = loadedFiles.length(); if(sp <= 0) { JOptionPane.showMessageDialog(null, "There are no STLs/RFOs loaded to print to file."); return; } sp = Math.max(loadedFiles.indexOf(".stl"), Math.max(loadedFiles.indexOf(".STL"), Math.max(loadedFiles.indexOf(".rfo"), loadedFiles.indexOf(".RFO")))); if(sp <= 0) { JOptionPane.showMessageDialog(null, "The loaded file is not an STL or an RFO file."); } printer.setTopDown(true); if(printer.setGCodeFileForOutput(loadedFiles.substring(0, sp)) == null) return; } if(!printer.filePlay()) org.reprap.Main.gui.onProduceB(); //parentBotConsoleFrame.resumePolling(); }//GEN-LAST:event_printButtonActionPerformed private void pcbButtonActionPerformed(java.awt.event.ActionEvent evt) { if(!SLoadOK) return; Extruder pcbp = printer.getExtruder("PCB-pen"); if(pcbp == null) { JOptionPane.showMessageDialog(null, "You have no PCB-pen among your extruders; see http://reprap.org/wiki/Plotting#Using_the_RepRap_Host_Software."); return; } parentBotConsoleFrame.suspendPolling(); File inputGerber = org.reprap.Main.gui.onOpen("PCB Gerber file", new String[] {"top", "bot"}, ""); if(inputGerber == null) { JOptionPane.showMessageDialog(null, "No Gerber file was loaded."); return; } int sp = inputGerber.getAbsolutePath().toLowerCase().indexOf(".top"); String drill; if(sp < 0) { sp = inputGerber.getAbsolutePath().toLowerCase().indexOf(".bot"); drill = ".bdr"; } else { drill = ".tdr"; } String fileRoot = ""; if(sp > 0) fileRoot = inputGerber.getAbsolutePath().substring(0, sp); drill = fileRoot+drill; File inputDrill = new File(drill); if(inputDrill == null) { JOptionPane.showMessageDialog(null, "Drill file " + drill + " not found; drill centres will not be marked"); } File outputGCode = org.reprap.Main.gui.onOpen("G-Code file for PCB printing", new String[] {"gcode"}, fileRoot); if(outputGCode == null) { JOptionPane.showMessageDialog(null, "No G-Code file was chosen."); return; } PCB p = new PCB(); p.pcb(inputGerber, inputDrill, outputGCode, pcbp); parentBotConsoleFrame.resumePolling(); } public void pauseAction() { paused = !paused; if(paused) { pauseButton.setLabel("Pausing..."); org.reprap.Main.gui.pause(); //while(!printer.iAmPaused()); parentBotConsoleFrame.resumePolling(); parentBotConsoleFrame.getPosition(); //parentBotConsoleFrame.getXYZTabPanel().recordCurrentPosition(); pauseButton.setLabel("Resume"); } else { org.reprap.Main.gui.resume(); parentBotConsoleFrame.suspendPolling(); pauseButton.setLabel("Pause"); } } private void pauseButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_pauseButtonActionPerformed pauseAction(); }//GEN-LAST:event_pauseButtonActionPerformed private void stopButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_stopButtonActionPerformed //org.reprap.Main.gui.clickCancel(); pauseAction(); //FIXME - best we can do at the moment }//GEN-LAST:event_stopButtonActionPerformed private void exitButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_exitButtonActionPerformed Main.ftd.killThem(); printer.dispose(); System.exit(0); }//GEN-LAST:event_exitButtonActionPerformed private void layerPause(boolean p) { org.reprap.Main.gui.setLayerPause(p); } private void layerPauseCheckActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_layerPauseCheckActionPerformed org.reprap.Main.gui.setLayerPause(layerPauseCheck.isSelected()); }//GEN-LAST:event_layerPauseCheckActionPerformed private void selectorRadioButtonMousePressed(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_selectorRadioButtonMousePressed @SuppressWarnings("unused") String machine = "simulator"; boolean closeMessage = false; try { machine = org.reprap.Preferences.loadGlobalString("RepRap_Machine"); // if(evt.getSource() == toSNAPRepRapRadioButton) // org.reprap.Preferences.setGlobalString("RepRap_Machine", "SNAPRepRap"); // if(seenGCode) // closeMessage = true; // seenSNAP = true; // } else if(evt.getSource() == toGCodeRepRapRadioButton) { enableGLoad(); if(seenSNAP) closeMessage = true; seenGCode = true; } else if(evt.getSource() == gCodeToFileRadioButton) { enableSLoad(); if(seenSNAP) closeMessage = true; seenGCode = true; } org.reprap.Preferences.saveGlobal(); printer.refreshPreferences(); if(!closeMessage) return; JOptionPane.showMessageDialog(null, "As you have changed the type of RepRap machine you are using,\nyou will have to exit this program and run it again."); } catch (Exception ex) { JOptionPane.showMessageDialog(null, "Could not get preference 'RepRap_Machine'"); } }//GEN-LAST:event_selectorRadioButtonMousePressed private void getWebPageActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_getWebPageActionPerformed try {