answer
stringlengths
17
10.2M
package org.jfree.data.statistics; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.List; import org.jfree.chart.util.ParamChecks; /** * A utility class that calculates the mean, median, quartiles Q1 and Q3, plus * a list of outlier values...all from an arbitrary list of * <code>Number</code> objects. */ public abstract class BoxAndWhiskerCalculator { /** * Calculates the statistics required for a {@link BoxAndWhiskerItem} * from a list of <code>Number</code> objects. Any items in the list * that are <code>null</code>, not an instance of <code>Number</code>, or * equivalent to <code>Double.NaN</code>, will be ignored. * * @param values a list of numbers (a <code>null</code> list is not * permitted). * * @return A box-and-whisker item. */ public static BoxAndWhiskerItem calculateBoxAndWhiskerStatistics( List values) { return calculateBoxAndWhiskerStatistics(values, true); } /** * Calculates the statistics required for a {@link BoxAndWhiskerItem} * from a list of <code>Number</code> objects. Any items in the list * that are <code>null</code>, not an instance of <code>Number</code>, or * equivalent to <code>Double.NaN</code>, will be ignored. * * @param values a list of numbers (a <code>null</code> list is not * permitted). * @param stripNullAndNaNItems a flag that controls the handling of null * and NaN items. * * @return A box-and-whisker item. * * @since 1.0.3 */ public static BoxAndWhiskerItem calculateBoxAndWhiskerStatistics( List values, boolean stripNullAndNaNItems) { ParamChecks.nullNotPermitted(values, "values"); List vlist; if (stripNullAndNaNItems) { vlist = new ArrayList(values.size()); Iterator iterator = values.listIterator(); while (iterator.hasNext()) { Object obj = iterator.next(); if (obj instanceof Number) { Number n = (Number) obj; double v = n.doubleValue(); if (!Double.isNaN(v)) { vlist.add(n); } } } } else { vlist = values; } Collections.sort(vlist); double mean = Statistics.calculateMean(vlist, false); double median = Statistics.calculateMedian(vlist, false); double q1 = calculateQ1(vlist); double q3 = calculateQ3(vlist); double interQuartileRange = q3 - q1; double upperOutlierThreshold = q3 + (interQuartileRange * 1.5); double lowerOutlierThreshold = q1 - (interQuartileRange * 1.5); double upperFaroutThreshold = q3 + (interQuartileRange * 2.0); double lowerFaroutThreshold = q1 - (interQuartileRange * 2.0); double minRegularValue = Double.POSITIVE_INFINITY; double maxRegularValue = Double.NEGATIVE_INFINITY; double minOutlier = Double.POSITIVE_INFINITY; double maxOutlier = Double.NEGATIVE_INFINITY; List outliers = new ArrayList(); Iterator iterator = vlist.iterator(); while (iterator.hasNext()) { Number number = (Number) iterator.next(); double value = number.doubleValue(); if (value > upperOutlierThreshold) { outliers.add(number); if (value > maxOutlier && value <= upperFaroutThreshold) { maxOutlier = value; } } else if (value < lowerOutlierThreshold) { outliers.add(number); if (value < minOutlier && value >= lowerFaroutThreshold) { minOutlier = value; } } else { minRegularValue = Math.min(minRegularValue, value); maxRegularValue = Math.max(maxRegularValue, value); } minOutlier = Math.min(minOutlier, minRegularValue); maxOutlier = Math.max(maxOutlier, maxRegularValue); } return new BoxAndWhiskerItem(new Double(mean), new Double(median), new Double(q1), new Double(q3), new Double(minRegularValue), new Double(maxRegularValue), new Double(minOutlier), new Double(maxOutlier), outliers); } /** * Calculates the first quartile for a list of numbers in ascending order. * If the items in the list are not in ascending order, the result is * unspecified. If the list contains items that are <code>null</code>, not * an instance of <code>Number</code>, or equivalent to * <code>Double.NaN</code>, the result is unspecified. * * @param values the numbers in ascending order (<code>null</code> not * permitted). * * @return The first quartile. */ public static double calculateQ1(List values) { ParamChecks.nullNotPermitted(values, "values"); double result = Double.NaN; int count = values.size(); if (count > 0) { if (count % 2 == 1) { if (count > 1) { result = Statistics.calculateMedian(values, 0, count / 2); } else { result = Statistics.calculateMedian(values, 0, 0); } } else { result = Statistics.calculateMedian(values, 0, count / 2 - 1); } } return result; } /** * Calculates the third quartile for a list of numbers in ascending order. * If the items in the list are not in ascending order, the result is * unspecified. If the list contains items that are <code>null</code>, not * an instance of <code>Number</code>, or equivalent to * <code>Double.NaN</code>, the result is unspecified. * * @param values the list of values (<code>null</code> not permitted). * * @return The third quartile. */ public static double calculateQ3(List values) { ParamChecks.nullNotPermitted(values, "values"); double result = Double.NaN; int count = values.size(); if (count > 0) { if (count % 2 == 1) { if (count > 1) { result = Statistics.calculateMedian(values, count / 2, count - 1); } else { result = Statistics.calculateMedian(values, 0, 0); } } else { result = Statistics.calculateMedian(values, count / 2, count - 1); } } return result; } }
package edu.conncoll.cas.jdbc; import java.io.FileWriter; import java.io.IOException; import java.util.Map; import java.util.Date; import java.util.List; import java.util.ArrayList; import java.lang.Character; import java.lang.Integer; import java.sql.Types; import java.sql.ResultSet; import java.sql.SQLException; import java.util.HashMap; import javax.mail.Address; import javax.mail.Message; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.MimeMessage; import javax.mail.internet.InternetAddress; import javax.naming.InitialContext; import javax.naming.Context; import javax.naming.directory.BasicAttribute; import javax.naming.directory.DirContext; import javax.naming.directory.ModificationItem; import javax.sql.DataSource; import javax.validation.constraints.NotNull; import org.springframework.dao.DataAccessException; import org.springframework.jdbc.core.simple.SimpleJdbcTemplate; import org.springframework.jdbc.core.namedparam.SqlParameterSource; import org.springframework.jdbc.core.namedparam.MapSqlParameterSource; import org.springframework.jdbc.core.SqlReturnResultSet; import org.springframework.jdbc.core.SqlParameter; import org.springframework.jdbc.core.SqlOutParameter; import org.springframework.jdbc.object.StoredProcedure; import org.springframework.jdbc.core.RowMapper; import org.springframework.ldap.core.support.AbstractContextMapper; import org.springframework.ldap.core.LdapTemplate; import org.springframework.ldap.core.DirContextOperations; import org.springframework.webflow.execution.RequestContext; import sample.appsforyourdomain.AppsForYourDomainClient; import com.google.gdata.data.appsforyourdomain.provisioning.UserEntry; import com.google.gdata.data.appsforyourdomain.provisioning.NicknameEntry; import com.google.gdata.data.appsforyourdomain.provisioning.NicknameFeed; import com.google.gdata.data.appsforyourdomain.Nickname; import com.google.gdata.data.appsforyourdomain.Login; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.jasig.cas.authentication.principal.UsernamePasswordCredentials; import org.jasig.cas.util.LdapUtils; import org.jasig.cas.web.support.IntData; public class jdbcCamel { @NotNull private SimpleJdbcTemplate jdbcTemplate; @NotNull private SimpleJdbcTemplate jdbcCensus; @NotNull private DataSource dataSource; @NotNull private DataSource censusSource; @NotNull private LdapTemplate ldapTemplate; @NotNull private String filter; @NotNull private String searchBase; @NotNull private String mainUsername; @NotNull private String mainPassword; @NotNull private String nuVisionPath; /* briley 7/20/2012 - added PIF to list */ public enum Interrupts { AUP, OEM, QNA, ACT, PWD, EMR, AAUP, PIF, CNS, NOVALUE; public static Interrupts toInt(String str) { try { return valueOf(str); } catch (Exception ex) { return NOVALUE; } } } private Log log = LogFactory.getLog(this.getClass()); public void readFlow (final String flag, final RequestContext context, final UsernamePasswordCredentials credentials) throws Exception { String userName = credentials.getUsername(); String SQL = ""; SqlParameterSource namedParameters = new MapSqlParameterSource("user", userName + "@conncoll.edu"); log.debug("readFlow Preparing data for " + flag + " user is " + userName); switch (Interrupts.toInt(flag)) { case AUP: SQL = "select count(*) ct from cc_user where email = :user and active=1"; Map<String,Object> ChkUser = jdbcTemplate.queryForMap(SQL,namedParameters); context.getFlowScope().put("actcheck", ChkUser.get("ct")); break; case OEM: SQL = "select oemail, firstname from cc_user where email = :user and active=1"; try { Map<String,Object> OEMData = jdbcTemplate.queryForMap(SQL,namedParameters); if (OEMData.get("oemail").toString().length() > 0){ Context initCtx = new InitialContext(); Session session = (Session) initCtx.lookup("java:comp/env/mail/Session"); StringBuilder actMsg = new StringBuilder(); actMsg.append("Welcome " + OEMData.get("firstname").toString() + ",\n\n"); actMsg.append("This email is to alert you that your Connecticut College CamelWeb account has been activated.\n\n"); actMsg.append("If you did not activate your account or believe you have otherwise received this email in error"); actMsg.append(" please contact the Connecticut College Help Desk @ (860) 439 - HELP (4357).\n\n"); actMsg.append("We are committed to delivering you quality service that is reliable and highly secure."); actMsg.append(" This email is one of many components designed to ensure your information is safeguarded at all times.\n\n"); actMsg.append("Thank you,\nConnecticut College Information Services Staff"); log.debug("readFlow sending email to " + OEMData.get("oemail").toString()); Message message = new MimeMessage(session); Address address = new InternetAddress("help@conncoll.edu", "Connecticut College Helpdesk"); Address toAddress = new InternetAddress(OEMData.get("oemail").toString()); message.setSentDate(new Date()); message.setFrom(address); message.addRecipient(Message.RecipientType.TO, toAddress); message.setSubject("CamelWeb Account Activation"); message.setContent(actMsg.toString(), "text/plain"); Transport.send(message); context.getFlowScope().put("oemail", OEMData.get("oemail").toString()); } else { context.getFlowScope().put("oemail", ""); } } catch (Exception e) { // No OEM email in cc_user context.getFlowScope().put("oemail", ""); } break; case QNA: SQL = "select question qChoice from cc_user_questions"; List<Map<String,Object>> QNAData = jdbcTemplate.queryForList(SQL); log.debug("readFlow sending questions"); context.getFlowScope().put("questionList", QNAData); break; case ACT: SQL = "select firstname, lastname from cc_user where email = :user and active=1"; Map<String,Object> ACTData = jdbcTemplate.queryForMap(SQL,namedParameters); try { context.getFlowScope().put("firstname", ACTData.get("firstname").toString()); context.getFlowScope().put("lastname", ACTData.get("lastname").toString()); } catch (Exception e) { // No CamelWeb account context.getFlowScope().put("firstname",""); context.getFlowScope().put("lastname",""); } AppsForYourDomainClient googleCTX = new AppsForYourDomainClient ("googleadmin@conncoll.edu","alpdhuez","conncoll.edu"); try { NicknameFeed nickNames = googleCTX.retrieveNicknames(userName); List<NicknameEntry> nameList = nickNames.getEntries(); log.debug("readFlow found " + nameList.size() + " nicknames "); if (nameList.size() > 0){ for (int x=0; x<nameList.size(); x++) { Nickname firstNick = nameList.get(x).getNickname(); if (firstNick.getName().indexOf(".") > 0){ log.debug("readFlow sending nickname " + firstNick.getName()); context.getFlowScope().put("NickName", firstNick.getName()); } } } } catch (Exception e) { // No Google account } context.getFlowScope().put("userName", userName); break; case EMR: SQL = "select Id, ccId from cc_user where email = :user and active=1"; try { Map<String,Object> CWData = jdbcTemplate.queryForMap(SQL,namedParameters); EMRRead emrRead = new EMRRead(this.dataSource); Map<String,Object> readData = emrRead.execute(CWData.get("ccId").toString(),CWData.get("Id"),0); log.debug("proc size" + readData.size()); log.debug("proc retun" + readData.toString()); ArrayList temp = (ArrayList) readData.get("emrData"); context.getFlowScope().put("emrData", (HashMap)temp.get(0)); temp = (ArrayList) readData.get("ccData"); context.getFlowScope().put("ccData", (HashMap)temp.get(0)); temp = (ArrayList) readData.get("Phones"); context.getFlowScope().put("Phones", temp); temp = (ArrayList) readData.get("Relations"); context.getFlowScope().put("Relations", temp); temp = (ArrayList) readData.get("SMSVendors"); context.getFlowScope().put("SMSVendors", temp); context.getFlowScope().put("ValidEmr", 1); } catch (Exception e){ context.getFlowScope().put("ValidEmr", 0); log.warn("Invalid connect-ed data for " + userName); } break; /* briley 7/20/12 - Added User Name to the scope so its available on form */ case PIF: context.getFlowScope().put("cwUserName", userName); break; case CNS: //Find Term Code SQL = "select param_value from cc_gen_census_settings where param_name = 'CURRENT TERM CODE' "; Map<String,Object> termData = jdbcCensus.queryForMap(SQL,namedParameters); log.debug("Termcode returned by query " + termData.get("param_value").toString()); // term code termData.get("param_value").toString() // get banner id from ldap String searchFilter = LdapUtils.getFilterWithValues(this.filter, userName); List DN = this.ldapTemplate.search( this.searchBase, searchFilter, new AbstractContextMapper(){ protected Object doMapFromContext(DirContextOperations ctx) { return ctx.getNameInNamespace(); } } ); DirContextOperations ldapcontext = ldapTemplate.lookupContext(DN.get(0).toString()); String Attrib = ldapcontext.getStringAttribute("extensionAttribute15"); try { SQL = "insert INTO census.cc_gen_census_data (network_id, banner_id, term_code, login_date) values ( :userName, :bannerId, :termCode, SYSDATE) "; log.debug("SQL for insert" + SQL); Map<String, Object> insertParameters = new HashMap<String, Object>(); insertParameters.put("userName", userName); insertParameters.put("bannerId", Attrib.toString()); insertParameters.put("termCode", termData.get("param_value").toString()); log.debug("SQL for insert " + SQL); log.debug("user " + userName); log.debug("banner id " + Attrib.toString()); log.debug("Term Code " + termData.get("param_value").toString()); int check = jdbcCensus.update(SQL, userName, Attrib.toString(), termData.get("param_value").toString()); log.debug("insert rerutn" + Integer.toString(check)); } catch (DataAccessException e){ log.warn("SQL for Census insert failed " + e.getMessage()); } String fileStr = Attrib.toString() + ";;;;;;;;;;;;;;;;;;;;;;;\r\n"; try { FileWriter writer = new FileWriter(nuVisionPath,true); log.info("writing to NuViosn file:" + fileStr); writer.append(fileStr); writer.flush(); writer.close(); } catch(IOException e) { log.error("unable to update nuvision file for id " + Attrib.toString()); } try { FileWriter writer = new FileWriter(nuVisionPath+"_bak",true); Date now = new Date(); fileStr = Attrib.toString() + ";;;;;;;;;;;;;;;;;;;;;;;"+now.toString()+"\r\n"; log.info("writing to NuViosn file:" + fileStr); writer.append(fileStr); writer.flush(); writer.close(); } catch(IOException e) { log.error("unable to update nuvision file for id " + Attrib.toString()); } break; default: break; } } public String writeFlow (final String flag, final RequestContext context, UsernamePasswordCredentials credentials, final IntData intData) throws Exception { String userName = credentials.getUsername(); String SQL = ""; Map<String,Object> namedParameters = new HashMap<String,Object>(); namedParameters.put("user", userName + "@conncoll.edu"); log.info("writeFlow Saving data for " + flag); log.debug("writeFlow got data " +intData.getFields().toString()); context.getFlowScope().put("ErrorMsg", " "); if (flag.equals("QNA")) { SQL = "update cc_user set password_question=:question, password_answer=:answer where email = :user and active=1"; log.debug("QNA question: " + intData.getField(1)); log.debug("QNA answer: " + intData.getField(2)); namedParameters.put("question", intData.getField(1)); namedParameters.put("answer", intData.getField(2)); int check = jdbcTemplate.update(SQL,namedParameters); log.debug("Update result" + check); } if (flag.equals("PWD")) { String searchFilter = LdapUtils.getFilterWithValues(this.filter, userName); List DN = this.ldapTemplate.search( this.searchBase, searchFilter, new AbstractContextMapper(){ protected Object doMapFromContext(DirContextOperations ctx) { return ctx.getNameInNamespace(); } } ); DirContextOperations ldapcontext = ldapTemplate.lookupContext(DN.get(0).toString()); String Attrib = ldapcontext.getStringAttribute("extensionAttribute14"); String domain; if (Attrib.equals("alumni")) { domain = "alumni.conncoll.edu"; } else { domain = "conncoll.edu"; } ModificationItem[] mods = new ModificationItem[1]; String newQuotedPassword = "\"" + intData.getField(1) + "\""; byte[] newUnicodePassword = newQuotedPassword.getBytes("UTF-16LE"); mods[0] = new ModificationItem(DirContext.REPLACE_ATTRIBUTE, new BasicAttribute("unicodePwd", newUnicodePassword)); try { ldapTemplate.modifyAttributes(DN.get(0).toString(),mods); }catch( Exception e){ log.warn("Password reset failed at AD"); context.getFlowScope().put("ErrorMsg", "Password rejected by server, please ensure your password meets all the listed criteria."); return "Failed"; } AppsForYourDomainClient googleCTX = new AppsForYourDomainClient (this.mainUsername,this.mainPassword,domain); try { UserEntry userEntry = googleCTX.retrieveUser(userName); Login userLogin = userEntry.getLogin(); userLogin.setAgreedToTerms(true); userLogin.setChangePasswordAtNextLogin(false); userLogin.setPassword(intData.getField(1)); googleCTX.updateUser(userName,userEntry); } catch (Exception e) { log.info("Password reset failed at google"); // No Google account } SQL = "insert cc_user_password_history (date,uid,ip,adminid) (select getdate() date, id uid, 'CAS Services' ip, id adminid from cc_user where email=:user) "; int check = jdbcTemplate.update(SQL,namedParameters); log.debug("Insert result " + check); credentials.setPassword(intData.getField(1)); } if (flag.equals("EMR")) { log.debug("Opt Out Answer is: " + intData.getField(2)); SQL = "select Id, ccId from cc_user where email = :user and active=1"; Map<String,Object> CWData = jdbcTemplate.queryForMap(SQL,namedParameters); if (intData.getField(2) != null){ SQL = "delete emr_main where bannerid = :bannerId "; namedParameters.put("bannerId", CWData.get("ccId")); int check = jdbcTemplate.update(SQL,namedParameters); log.debug("Delete result " + check); SQL = "Update CC_user set EMR=2 where ccID= :bannerId "; namedParameters.put("bannerId", CWData.get("ccId")); check = jdbcTemplate.update(SQL,namedParameters); return "Saved"; }else{ //Check primary phone length if (intData.getField(6).replace("-","").length() != 7){ //check if primary phone conatins any non-numeric characters if (intData.getField(6).replaceAll("\\d+","").length() > 0) { //Invalid Primary Phone number log.warn("Invalid Primary Phone number"); context.getFlowScope().put("ErrorMsg", "Primary phone is not a valid phone number, please correct and submit again"); return "Failed"; } } FormSave formSave = new FormSave(this.dataSource); Integer smsVend = Integer.parseInt(intData.getField(41)); if (intData.getField(11).length() <7) { smsVend=null; } Map<String,Object> readData = formSave.execute(CWData.get("ccId").toString(),Integer.parseInt(CWData.get("Id").toString()),intData.getField(39), intData.getField(42), intData.getField(40), intData.getField(36), smsVend, intData.getField(38).toCharArray()[0] ); int EMRID = Integer.parseInt(readData.get("EMRID").toString()); log.debug("starting phone save"); PhoneSave phoneSave = new PhoneSave(this.dataSource); int[] PhonePos = {5,10,15,20,25,30}; char PID = ' '; int AreaCode; int Phone; for (int x = 0; x < PhonePos.length;x++) { if (x == 0){ PID = 'P'; } else if (x == 1) { PID = 'C'; } else { PID = Character.forDigit((x - 1), 10); } if (intData.getField(PhonePos[x]).length() == 3) { AreaCode = Integer.parseInt(intData.getField(PhonePos[x])); }else { AreaCode = 860; } if ((intData.getField(PhonePos[x]+1).length() == 7) && (intData.getField(PhonePos[x]+1).replaceAll("\\d+","").length() > 0)){ Phone = Integer.parseInt(intData.getField(PhonePos[x]+1).replace("-","")); log.debug("Executing Phone save with: " + EMRID + "," + PID + "," + AreaCode + "," + Phone + "," + intData.getField(PhonePos[x]+2).toCharArray()[0] + "," + intData.getField(PhonePos[x]+3) + "," + Integer.parseInt(intData.getField(PhonePos[x]+4))); phoneSave.execute(EMRID, PID, AreaCode, Phone, intData.getField(PhonePos[x]+2).toCharArray()[0], intData.getField(PhonePos[x]+3), Integer.parseInt(intData.getField(PhonePos[x]+4))); } } SQL = "Update CC_user set EMR=1 where ccID= :bannerId "; namedParameters.put("bannerId", CWData.get("ccId")); int check = jdbcTemplate.update(SQL,namedParameters); log.debug("Update result " + check); } } return "Saved"; } public final String setPWD(){ return "PWD"; } public final void setDataSource(final DataSource dataSource) { this.jdbcTemplate = new SimpleJdbcTemplate(dataSource); this.dataSource = dataSource; } public final void setCensusSource(final DataSource dataSource) { this.jdbcCensus = new SimpleJdbcTemplate(dataSource); this.censusSource = dataSource; } protected final SimpleJdbcTemplate getJdbcTemplate() { return this.jdbcTemplate; } protected final DataSource getDataSource() { return this.dataSource; } protected final DataSource getCensusSource() { return this.censusSource; } public void setsearchBase (final String searchBase) { this.searchBase = searchBase; } public void setMainUsername (final String mainUsername) { this.mainUsername = mainUsername; } public void setMainPassword (final String mainPassword) { this.mainPassword = mainPassword; } public void setNuVisionPath (final String nuVisionPath) { this.nuVisionPath = nuVisionPath; } public void setldapTemplate(final LdapTemplate ldapTemplate){ this.ldapTemplate=ldapTemplate; } public void setFilter (final String filter) { this.filter = filter; } private class EMRRead extends StoredProcedure{ public EMRRead(DataSource dataSource) { super(dataSource, "EMR_FormRead"); declareParameter(new SqlParameter("BannerID", Types.VARCHAR)); declareParameter(new SqlParameter("CCUserID", Types.INTEGER )); declareParameter(new SqlOutParameter("Admin", Types.BIT)); declareParameter(new SqlReturnResultSet("emrData", new RowMapper() { public Map<String,Object> mapRow(ResultSet rs, int rowNum) throws SQLException { Map<String,Object> emrData = new HashMap<String,Object>(); emrData.put("EmrId",rs.getInt(1)); emrData.put("ContactType",rs.getString(2)); emrData.put("toEmail",rs.getString(3)); emrData.put("AltEmail",rs.getString(4)); emrData.put("Language",rs.getString(5)); emrData.put("SmsVendor",rs.getInt(6)); emrData.put("Tty",rs.getString(7)); // add more mappings here return emrData; } })); declareParameter(new SqlReturnResultSet("ccData", new RowMapper() { public Map<String,Object> mapRow(ResultSet rs, int rowNum) throws SQLException { Map<String,Object> ccData = new HashMap<String,Object>(); ccData.put("FirstName",rs.getString(1)); ccData.put("LastName",rs.getString(2)); ccData.put("CollegePhone",rs.getString(3)); ccData.put("Email",rs.getString(4)); ccData.put("CcId",rs.getString(5)); // add more mappings here return ccData; } })); declareParameter(new SqlReturnResultSet("Phones", new RowMapper() { public Map<String,Object> mapRow(ResultSet rs, int rowNum) throws SQLException { Map<String,Object> Phones = new HashMap<String,Object>(); Phones.put("PhoneCode",rs.getString(1)); Phones.put("AreaCode",rs.getInt(2)); Phones.put("PhoneNum",rs.getString(3)); Phones.put("phoneType",rs.getString(4)); Phones.put("ContactName",rs.getString(5)); Phones.put("ContactRelation",rs.getString(6)); // add more mappings here return Phones; } })); declareParameter(new SqlReturnResultSet("Relations", new RowMapper() { public Map<String,Object> mapRow(ResultSet rs, int rowNum) throws SQLException { Map<String,Object> Relations = new HashMap<String,Object>(); Relations.put("ContactRelation",rs.getInt(1)); Relations.put("Relationship",rs.getString(2)); // add more mappings here return Relations; } })); declareParameter(new SqlReturnResultSet("SMSVendors", new RowMapper() { public Object mapRow(ResultSet rs, int rowNum) throws SQLException { Map<String,Object> SMSVendors = new HashMap<String,Object>(); SMSVendors.put("SMSVendor",rs.getInt(1)); SMSVendors.put("VendorName",rs.getString(2)); // add more mappings here return SMSVendors; } })); declareParameter(new SqlReturnResultSet("ListAddresses", new RowMapper() { public Object mapRow(ResultSet rs, int rowNum) throws SQLException { Map <String,Object>ListAddresses = new HashMap<String,Object>(); ListAddresses.put("emailnum",rs.getInt(1)); ListAddresses.put("emailaddress",rs.getString(2)); // add more mappings here return ListAddresses; } })); compile(); } public Map<String,Object> execute(String bannerId, int ccUserId, int admin) { Map<String,Object> inputs = new HashMap<String,Object>(); inputs.put("BannerID", bannerId); inputs.put("CCUserID", ccUserId); inputs.put("Admin", admin); return super.execute(inputs); } } private class FormSave extends StoredProcedure{ public FormSave(DataSource dataSource) { super(dataSource, "EMR_FormSave"); declareParameter(new SqlParameter("BannerID", Types.VARCHAR)); declareParameter(new SqlParameter("CCUserID", Types.INTEGER )); declareParameter(new SqlParameter("AltEmail", Types.VARCHAR)); declareParameter(new SqlParameter("OEMail", Types.VARCHAR)); declareParameter(new SqlParameter("ContactType", Types.VARCHAR)); declareParameter(new SqlParameter("Language", Types.VARCHAR)); declareParameter(new SqlParameter("SMSVendor", Types.INTEGER)); declareParameter(new SqlParameter("TTY", Types.VARCHAR)); declareParameter(new SqlOutParameter("EMRID", Types.INTEGER)); compile(); } public Map<String,Object> execute(String bannerId, int ccUserId, String AltEmail, String OEMail, String ContactType, String Language, Integer SMSVendor, char TTY) { Map<String,Object> inputs = new HashMap<String,Object>(); inputs.put("BannerID", bannerId); inputs.put("CCUserID", ccUserId); inputs.put("AltEmail", AltEmail); inputs.put("OEMail", OEMail); inputs.put("ContactType", ContactType); inputs.put("Language", Language); inputs.put("SMSVendor", SMSVendor); inputs.put("TTY", TTY); inputs.put("EMRID", 0); return super.execute(inputs); } } private class PhoneSave extends StoredProcedure{ public PhoneSave(DataSource dataSource) { super(dataSource, "EMR_PhoneSave"); declareParameter(new SqlParameter("EMRID", Types.INTEGER)); declareParameter(new SqlParameter("PhoneCode", Types.VARCHAR )); declareParameter(new SqlParameter("AreaCode", Types.INTEGER )); declareParameter(new SqlParameter("PhoneNum", Types.VARCHAR )); declareParameter(new SqlParameter("PhoneType", Types.VARCHAR )); declareParameter(new SqlParameter("ContactName", Types.NVARCHAR )); declareParameter(new SqlParameter("ContactRelation", Types.INTEGER )); compile(); } public Map<String,Object> execute(int EMRID, char PID, int AreaCode, String Phone, char pType, String Name, int Rela) { Map<String,Object> inputs = new HashMap<String,Object>(); inputs.put("EMRID", EMRID); inputs.put("PhoneCode", PID); inputs.put("AreaCode", AreaCode); inputs.put("PhoneNum", Phone); inputs.put("PhoneType", pType); inputs.put("ContactName", Name); inputs.put("ContactRelation", Rela); return super.execute(inputs); } } }
package org.gluu.oxtrust.util; import java.io.Serializable; import org.jboss.seam.annotations.Name; @Name("buildVersion") public class BuildVersion implements Serializable { private static final long serialVersionUID = 3790281266924133197L; private String revisionVersion; private String revisionDate; private String buildDate; private String buildNumber; public String getRevisionVersion() { return revisionVersion; } public void setRevisionVersion(String revisionVersion) { this.revisionVersion = revisionVersion; } public String getRevisionDate() { return revisionDate; } public void setRevisionDate(String revisionDate) { this.revisionDate = revisionDate; } public String getBuildDate() { return buildDate; } public void setBuildDate(String buildDate) { this.buildDate = buildDate; } public String getBuildNumber() { return buildNumber; } public void setBuildNumber(String buildNumber) { this.buildNumber = buildNumber; } }
import java.io.BufferedReader; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStreamReader; import java.net.URL; import java.text.DecimalFormat; import java.text.NumberFormat; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.Map; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.management.MBeanAttributeInfo; import javax.management.MBeanInfo; import javax.management.MBeanServerConnection; import javax.management.ObjectInstance; import javax.management.ObjectName; import javax.management.remote.JMXConnector; import javax.management.remote.JMXConnectorFactory; import javax.management.remote.JMXServiceURL; public class ConfluentPlatform { public static String pluginVersion="1"; private String host="127.0.0.1"; private String port="9990"; private String filePath="metrics.txt"; private static JMXConnector jmxConnector = null; private static MBeanServerConnection connection = null; public static void main(String[] args) { try { ConfluentPlatform cp = new ConfluentPlatform(); if(args.length == 2){ cp.host = args[0]; cp.port = args[1]; } cp.getConnection(cp.host, cp.port); Map<String,Object> metrics = cp.getMetrics(); printMetrics(metrics); } catch(Exception e) { System.out.print("plugin_version:"+pluginVersion+"|heartbeat:true|status:0|msg:Error Occurred"); }finally { try { jmxConnector.close(); } catch (Exception e) { // TODO Auto-generated catch block // e.printStackTrace(); } } } private void getConnection(String host,String port) throws Exception{ String JMX_URL = "service:jmx:rmi:///jndi/rmi://"+host+":"+port+"/jmxrmi"; JMXServiceURL jmxurl = new JMXServiceURL(String.format(JMX_URL, host, port)); Map<String, Object> env = new HashMap<String, Object>(); jmxConnector = JMXConnectorFactory.connect(jmxurl, env); connection = jmxConnector.getMBeanServerConnection(); } private ArrayList<String> getRequiredMBeansList(String filePath) throws Exception{ Object path = this.getClass().getResource(filePath); if(path == null){ throw new FileNotFoundException(filePath); } String filepath = ((URL)path).getFile(); FileInputStream in = new FileInputStream(filepath); BufferedReader reader = new BufferedReader(new InputStreamReader(in)); ArrayList<String> list = new ArrayList<String>(); String line; while ((line = reader.readLine()) != null) { if (!line.startsWith("#") && !line.isEmpty()) { list.add(line); } } in.close(); reader.close(); return list; } private Map<String,Object> getMetrics() throws Exception { ArrayList<String> requiredMbeans = getRequiredMBeansList(filePath); NumberFormat formatter = new DecimalFormat("#0.0000"); Map<String, Object> metrics = new LinkedHashMap<String, Object>(); for(String mbean:requiredMbeans ) { String[] splitline = mbean.split(" "); int len = splitline.length; String mBeanName = splitline[0]; String attributetype = len == 2 ? null : splitline[1]; String label = len == 2 ? splitline[1] : splitline[2]; ObjectName query = new ObjectName(mBeanName); Set<ObjectInstance> mbeans = connection.queryMBeans(query, null); Iterator<ObjectInstance> iterator = mbeans.iterator(); while (iterator.hasNext()) { ObjectInstance instance = iterator.next(); try { String oname1Str = instance.getObjectName().toString(); ObjectName oname1 = new ObjectName(oname1Str); MBeanInfo info = connection.getMBeanInfo(oname1); MBeanAttributeInfo[] attributes = info.getAttributes(); for (MBeanAttributeInfo attribute : attributes) { if (attributetype == null || attribute.getName().matches(attributetype)) { Object obj = connection.getAttribute(oname1,attribute.getName()); String key = replaceTokens(oname1Str, label); if(attributetype ==null) { key = key + ":" +attribute.getName(); } if (obj instanceof Long) { metrics.put(key, formatter.format(obj)); } else if (obj instanceof Double) { Double d = Double.valueOf(obj.toString()); if(!d.isNaN()) { metrics.put(key, formatter.format(obj)); } } else if (obj instanceof String) { metrics.put(key, (String) obj); } else { metrics.put(key, obj); } } } } catch (NullPointerException e) { //e.printStackTrace(); } } } return metrics; } private static void printMetrics(Map<String,Object> metrics) { int i = 0; int limit = 25; int len = metrics.size(); for (String key : metrics.keySet()) { if (i < (limit-1) || i<(len-2)) { System.out.print(key + ":" + metrics.get(key) ); } else { System.out.print("plugin_version:"+pluginVersion+"|heartbeat:true|status:0|msg:No metrics Available"); System.exit(1); } if(!(i == (limit-1) || (i == len-1))){ System.out.print("|"); } i++; } System.out.print("|plugin_version:"+pluginVersion+"|heartbeat:true"); } private static String replaceTokens(String mBeanName, String text) { HashMap<String, String> replacements = new HashMap<String, String>(); int firstColon = mBeanName.indexOf(':'); String[] props = mBeanName.substring(firstColon + 1).split( "(?!\\B\"[^\"]*),(?![^\"]*\"\\B)"); for (int i = 0; i < props.length; i++) { String[] parts = props[i].split("="); replacements.put(parts[0], parts[1]); } Pattern pattern = Pattern.compile("\\<(.+?)\\>"); Matcher matcher = pattern.matcher(text); StringBuilder builder = new StringBuilder(); int i = 0; while (matcher.find()) { String replacement = replacements.get(matcher.group(1)); builder.append(text.substring(i, matcher.start())); if (replacement == null) builder.append(matcher.group(0)); else builder.append(replacement); i = matcher.end(); } builder.append(text.substring(i, text.length())); return builder.toString().replaceAll("\"", "").replaceAll(" ", "-"); } }
package am.userInterface.table; import javax.swing.DefaultCellEditor; import javax.swing.JComboBox; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.table.AbstractTableModel; import javax.swing.table.DefaultTableCellRenderer; import javax.swing.table.TableCellRenderer; import javax.swing.table.TableColumn; import am.Utility; import am.app.Core; import am.app.mappingEngine.AbstractMatcher; import am.app.mappingEngine.MatcherFactory; import am.app.mappingEngine.MatchersRegistry; import am.app.mappingEngine.manualMatcher.UserManualMatcher; import am.userInterface.UI; import java.awt.Component; import java.awt.Dimension; import java.awt.GridLayout; public class MatchersTablePanel extends JPanel { private static final long serialVersionUID = -5579979645883093290L; private MatchersTable table; public MatchersTablePanel() { super(new GridLayout(1,1)); MyTableModel mt = new MyTableModel(); table = new MatchersTable(mt); table.setPreferredScrollableViewportSize(new Dimension(500, 70)); table.setFillsViewportHeight(true); //We need autoresize because when the table is fullscreen it's useful to use all the space //at the same time with autoresize set to ON there is not anymore horizontal scrolling //while we need it when the screen is smaller because we don't want columns to disappear //this is a famous problem that it is fixed with class MatcherTable table.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS); //Create the scroll pane and add the table to it. JScrollPane scrollPane = new JScrollPane(table); DefaultTableCellRenderer renderer = new DefaultTableCellRenderer(); renderer.setToolTipText("Click to modify values"); //Fiddle with the column's cell editors/renderers: THRESHOLD JComboBox comboTh = new JComboBox(Utility.getPercentStringList()); TableColumn thColumn = table.getColumnModel().getColumn(MyTableModel.THRESHOLD); thColumn.setCellEditor(new DefaultCellEditor(comboTh)); thColumn.setCellRenderer(renderer); //Fiddle with the column's cell editors/renderers: NUM RELATIONS FOR SOURCE AND TARGET JComboBox comboNumRelations = new JComboBox(Utility.getNumRelList()); TableColumn SRelColumn = table.getColumnModel().getColumn(MyTableModel.SRELATIONS); SRelColumn.setCellEditor(new DefaultCellEditor(comboNumRelations)); SRelColumn.setCellRenderer(renderer); TableColumn TRelColumn = table.getColumnModel().getColumn(MyTableModel.TRELATIONS); TRelColumn.setCellEditor(new DefaultCellEditor(comboNumRelations)); TRelColumn.setCellRenderer(renderer); TableColumn inputColumn = table.getColumnModel().getColumn(MyTableModel.INPUTMATCHERS); InputMatchersEditor mc = new InputMatchersEditor(); inputColumn.setCellEditor(mc); inputColumn.setCellRenderer(renderer); ColorRenderer cr = new ColorRenderer(true); ColorEditor ce = new ColorEditor(); TableColumn colorColumn = table.getColumnModel().getColumn(MyTableModel.COLOR); colorColumn.setCellEditor(ce); colorColumn.setCellRenderer(cr); //STATICALLY ADD THE FIRST MATCHER THAT IS THE USER MANUAL MATCHER //is important to add this here so that initColumns can assign the best width to columns //This matcher cannot be deleted UserManualMatcher userMatcher = (UserManualMatcher) MatcherFactory.getMatcherInstance(MatchersRegistry.UserManual, 0); addMatcher(userMatcher); setOpaque(true); //content panes must be opaque //Set up column sizes. initColumnSizes(table); //Add the scroll pane to this panel. add(scrollPane); } /* * This method picks good column sizes. * If all column heads are wider than the column's cells' * contents, then you can just use column.sizeWidthToFit(). */ private void initColumnSizes(JTable table) { MyTableModel model = (MyTableModel)table.getModel(); TableColumn column = null; Component comp = null; TableCellRenderer headerRenderer = table.getTableHeader().getDefaultRenderer(); int width = 0; for (int i = 0; i < model.getColumnCount(); i++) { column = table.getColumnModel().getColumn(i); comp = headerRenderer.getTableCellRendererComponent( null, column.getHeaderValue(), false, false, 0, 0); width = 0; if(i == MyTableModel.INPUTMATCHERS || i == MyTableModel.NAME){ width = 175; } else{ column = table.getColumnModel().getColumn(i); comp = headerRenderer.getTableCellRendererComponent( null, column.getHeaderValue(), false, false, 0, 0); width = comp.getPreferredSize().width; } column.setPreferredWidth(width); column.setMinWidth(width); column.setMaxWidth(width); } /* THIS WAS MADE TO SET THE WIDTH AUTOMATICALLY BUT THERE WAS A BUG * MyTableModel model = (MyTableModel)table.getModel(); TableColumn column = null; Component comp = null; int headerWidth = 0; int cellWidth = 0; Object[] longValues = model.defaultValues; TableCellRenderer headerRenderer = table.getTableHeader().getDefaultRenderer(); for (int i = 0; i < model.getColumnCount(); i++) { column = table.getColumnModel().getColumn(i); comp = headerRenderer.getTableCellRendererComponent( null, column.getHeaderValue(), false, false, 0, 0); headerWidth = comp.getPreferredSize().width; if(model.getRowCount() > 0) {//consider also the dimension of the elements rendered in the first row, and then take the max between header and row cells comp = table.getDefaultRenderer(model.getColumnClass(i)). getTableCellRendererComponent( table, longValues[i], false, false, 0, i); cellWidth = comp.getPreferredSize().width; System.out.println("Initializing width of column " + i + ". " + "headerWidth = " + headerWidth + "; cellWidth = " + cellWidth); column.setPreferredWidth(Math.max(headerWidth, cellWidth)); column.setMinWidth(Math.max(headerWidth, cellWidth)); column.setMaxWidth(Math.max(headerWidth, cellWidth)); } else {//Else just consider the header width column.setPreferredWidth(headerWidth); column.setMinWidth(headerWidth); column.setMaxWidth(headerWidth); } } */ } public MatchersTable getTable() { return table; } public void addMatcher(AbstractMatcher a) { Core.getInstance().addMatcherInstance(a); TableColumn inputColumn = table.getColumnModel().getColumn(MyTableModel.INPUTMATCHERS); InputMatchersEditor mc = (InputMatchersEditor)inputColumn.getCellEditor(); mc.addEditor(a); insertedRows(a.getIndex(), a.getIndex()); } public void insertedRows(int firstrow, int lastrow) { ((AbstractTableModel)table.getModel()).fireTableRowsInserted(firstrow, lastrow); } public void updatedRows(int firstrow, int lastrow) { ((AbstractTableModel)table.getModel()).fireTableRowsUpdated(firstrow, lastrow); } public void updatedCell(int row, int col) { ((AbstractTableModel)table.getModel()).fireTableCellUpdated(row, col); } public void deletedRows(int firstrow, int lastrow) { ((AbstractTableModel)table.getModel()).fireTableRowsDeleted(firstrow, lastrow); } public void removeMatcher(AbstractMatcher a) { Core.getInstance().removeMatcher(a); TableColumn inputColumn = table.getColumnModel().getColumn(MyTableModel.INPUTMATCHERS); InputMatchersEditor mc = (InputMatchersEditor)inputColumn.getCellEditor(); mc.removeEditor(a); deletedRows(a.getIndex(), a.getIndex()); } /** * Create the GUI and show it. It s just a debugging method */ private static void createAndShowGUI() { //Create and set up the window. JFrame frame = new JFrame("TableRenderDemo"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //Create and set up the content pane. MatchersTablePanel alignTable = new MatchersTablePanel(); frame.setContentPane(alignTable); //Display the window. frame.pack(); frame.setVisible(true); } public static void main(String[] args) { //Schedule a job for the event-dispatching thread: //creating and showing this application's GUI. javax.swing.SwingUtilities.invokeLater(new Runnable() { public void run() { createAndShowGUI(); } }); } }
//submitted by DominikRafacz import java.util.Random; public class MonteCarlo { public static void main(String[] args) { double piEstimation = monteCarlo(1000); System.out.println("Estimated pi value: " + piEstimation); System.out.printf("Percent error: " + 100 * Math.abs(piEstimation - Math.PI) / Math.PI); } //function to check whether point (x,y) is in unit circle private static boolean inCircle(double x, double y) { return x * x + y * y < 1; } //function to calculate estimation of pi public static double monteCarlo(int samples) { int piCount = 0; Random random = new Random(); for (int i = 0; i < samples; i++) { double x = random.nextDouble(); double y = random.nextDouble(); if (inCircle(x, y)) { piCount++; } } double estimation = 4.0 * piCount / samples; return estimation; } }
package io.quarkus.dev; import java.io.Closeable; import java.io.DataInputStream; import java.io.IOException; import java.io.InputStream; import java.io.ObjectInputStream; import java.net.URL; import java.net.URLClassLoader; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.ServiceLoader; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.locks.LockSupport; import java.util.function.Consumer; import org.jboss.logging.Logger; import io.quarkus.builder.BuildChainBuilder; import io.quarkus.builder.BuildContext; import io.quarkus.builder.BuildStep; import io.quarkus.deployment.builditem.ApplicationClassPredicateBuildItem; import io.quarkus.deployment.builditem.LiveReloadBuildItem; import io.quarkus.deployment.devmode.HotReplacementSetup; import io.quarkus.runner.RuntimeRunner; import io.quarkus.runtime.LaunchMode; import io.quarkus.runtime.Timing; import io.smallrye.config.SmallRyeConfigProviderResolver; /** * The main entry point for the dev mojo execution */ public class DevModeMain implements Closeable { public static final String DEV_MODE_CONTEXT = "META-INF/dev-mode-context.dat"; private static final Logger log = Logger.getLogger(DevModeMain.class); private static volatile ClassLoader currentAppClassLoader; private static volatile URLClassLoader runtimeCl; private final DevModeContext context; private static volatile Closeable runner; static volatile Throwable deploymentProblem; static volatile Throwable compileProblem; static volatile RuntimeUpdatesProcessor runtimeUpdatesProcessor; private List<HotReplacementSetup> hotReplacement = new ArrayList<>(); private final Map<Class<?>, Object> liveReloadContext = new ConcurrentHashMap<>(); public DevModeMain(DevModeContext context) { this.context = context; } public static void main(String... args) throws Exception { Timing.staticInitStarted(); try (InputStream devModeCp = DevModeMain.class.getClassLoader().getResourceAsStream(DEV_MODE_CONTEXT)) { DevModeContext context = (DevModeContext) new ObjectInputStream(new DataInputStream(devModeCp)).readObject(); new DevModeMain(context).start(); LockSupport.park(); } catch (Exception e) { throw new RuntimeException(e); } finally { } } public void start() throws Exception { //propagate system props for (Map.Entry<String, String> i : context.getSystemProperties().entrySet()) { if (!System.getProperties().containsKey(i.getKey())) { System.setProperty(i.getKey(), i.getValue()); } } for (HotReplacementSetup service : ServiceLoader.load(HotReplacementSetup.class)) { hotReplacement.add(service); } runtimeUpdatesProcessor = setupRuntimeCompilation(context); if (runtimeUpdatesProcessor != null) { runtimeUpdatesProcessor.checkForChangedClasses(); } //TODO: we can't handle an exception on startup with hot replacement, as Undertow might not have started doStart(false, Collections.emptySet()); if (deploymentProblem != null || compileProblem != null) { if (context.isAbortOnFailedStart()) { throw new RuntimeException(deploymentProblem == null ? compileProblem : deploymentProblem); } } Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() { @Override public void run() { synchronized (DevModeMain.class) { if (runner != null) { try { runner.close(); } catch (IOException e) { e.printStackTrace(); } } if (runtimeCl != null) { try { runtimeCl.close(); } catch (IOException e) { e.printStackTrace(); } } } } }, "Quarkus Shutdown Thread")); } private synchronized void doStart(boolean liveReload, Set<String> changedResources) { try { final URL[] urls = new URL[context.getClassesRoots().size()]; for (int i = 0; i < context.getClassesRoots().size(); i++) { urls[i] = context.getClassesRoots().get(i).toURI().toURL(); } runtimeCl = new URLClassLoader(urls, ClassLoader.getSystemClassLoader()); currentAppClassLoader = runtimeCl; ClassLoader old = Thread.currentThread().getContextClassLoader(); //we can potentially throw away this class loader, and reload the app try { Thread.currentThread().setContextClassLoader(runtimeCl); RuntimeRunner.Builder builder = RuntimeRunner.builder() .setLaunchMode(LaunchMode.DEVELOPMENT) .setLiveReloadState(new LiveReloadBuildItem(liveReload, changedResources, liveReloadContext)) .setClassLoader(runtimeCl) // just use the first item in classesRoot which is where the actual class files are written .setTarget(context.getClassesRoots().get(0).toPath()) .setTransformerCache(context.getCacheDir().toPath()); if (context.getFrameworkClassesDir() != null) { builder.setFrameworkClassesPath(context.getFrameworkClassesDir().toPath()); } List<Path> addAdditionalHotDeploymentPaths = new ArrayList<>(); for (DevModeContext.ModuleInfo i : context.getModules()) { if (i.getClassesPath() != null) { Path classesPath = Paths.get(i.getClassesPath()); addAdditionalHotDeploymentPaths.add(classesPath); builder.addAdditionalHotDeploymentPath(classesPath); } } // Make it possible to identify wiring classes generated for classes from additional hot deployment paths builder.addChainCustomizer(new Consumer<BuildChainBuilder>() { @Override public void accept(BuildChainBuilder buildChainBuilder) { buildChainBuilder.addBuildStep(new BuildStep() { @Override public void execute(BuildContext context) { context.produce(new ApplicationClassPredicateBuildItem(n -> { return getClassInApplicationClassPaths(n, addAdditionalHotDeploymentPaths) != null; })); } }).produces(ApplicationClassPredicateBuildItem.class).build(); } }); Properties buildSystemProperties = new Properties(); buildSystemProperties.putAll(context.getBuildSystemProperties()); builder.setBuildSystemProperties(buildSystemProperties); RuntimeRunner runner = builder .build(); runner.run(); DevModeMain.runner = runner; deploymentProblem = null; } catch (Throwable t) { deploymentProblem = t; if (context.isAbortOnFailedStart() || liveReload) { log.error("Failed to start quarkus", t); } else { //we need to set this here, while we still have the correct TCCL //this is so the config is still valid, and we can read HTTP config from application.properties log.error("Failed to start Quarkus", t); log.info("Attempting to start hot replacement endpoint to recover from previous Quarkus startup failure"); if (runtimeUpdatesProcessor != null) { runtimeUpdatesProcessor.startupFailed(); } } } finally { Thread.currentThread().setContextClassLoader(old); } } catch (Throwable t) { deploymentProblem = t; log.error("Failed to start quarkus", t); } } public synchronized void restartApp(Set<String> changedResources) { stop(); Timing.restart(); doStart(true, changedResources); } public static ClassLoader getCurrentAppClassLoader() { return currentAppClassLoader; } private static Path getClassInApplicationClassPaths(String name, List<Path> addAdditionalHotDeploymentPaths) { final String fileName = name.replace('.', '/') + ".class"; Path classLocation; for (Path i : addAdditionalHotDeploymentPaths) { classLocation = i.resolve(fileName); if (Files.exists(classLocation)) { return classLocation; } } return null; } private RuntimeUpdatesProcessor setupRuntimeCompilation(DevModeContext context) throws Exception { if (!context.getModules().isEmpty()) { ServiceLoader<CompilationProvider> serviceLoader = ServiceLoader.load(CompilationProvider.class); List<CompilationProvider> compilationProviders = new ArrayList<>(); for (CompilationProvider provider : serviceLoader) { compilationProviders.add(provider); context.getModules().forEach(moduleInfo -> moduleInfo.addSourcePaths(provider.handledSourcePaths())); } ClassLoaderCompiler compiler; try { compiler = new ClassLoaderCompiler(Thread.currentThread().getContextClassLoader(), compilationProviders, context); } catch (Exception e) { log.error("Failed to create compiler, runtime compilation will be unavailable", e); return null; } RuntimeUpdatesProcessor processor = new RuntimeUpdatesProcessor(context, compiler, this); for (HotReplacementSetup service : hotReplacement) { service.setupHotDeployment(processor); processor.addHotReplacementSetup(service); } return processor; } return null; } public void stop() { if (runner != null) { ClassLoader old = Thread.currentThread().getContextClassLoader(); Thread.currentThread().setContextClassLoader(runtimeCl); try { runner.close(); } catch (IOException e) { e.printStackTrace(); } finally { Thread.currentThread().setContextClassLoader(old); } } SmallRyeConfigProviderResolver.instance().releaseConfig(SmallRyeConfigProviderResolver.instance().getConfig()); DevModeMain.runner = null; } public void close() { try { stop(); } finally { for (HotReplacementSetup i : hotReplacement) { i.close(); } } } }
package imagej.legacy; import ij.IJ; import ij.ImagePlus; import ij.WindowManager; import imagej.ImageJ; import imagej.core.options.OptionsMisc; import imagej.data.Dataset; import imagej.data.display.DatasetView; import imagej.data.display.ImageDisplay; import imagej.data.display.ImageDisplayService; import imagej.data.options.OptionsChannels; import imagej.event.EventHandler; import imagej.event.EventService; import imagej.ext.KeyCode; import imagej.ext.display.event.DisplayActivatedEvent; import imagej.ext.display.event.input.KyPressedEvent; import imagej.ext.display.event.input.KyReleasedEvent; import imagej.ext.menu.MenuService; import imagej.ext.plugin.Plugin; import imagej.ext.plugin.PluginInfo; import imagej.ext.plugin.PluginService; import imagej.legacy.plugin.LegacyPlugin; import imagej.legacy.plugin.LegacyPluginFinder; import imagej.log.LogService; import imagej.options.OptionsService; import imagej.options.event.OptionsEvent; import imagej.service.AbstractService; import imagej.service.Service; import imagej.util.ColorRGB; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; /** * Service for working with legacy ImageJ 1.x. * <p> * The legacy service overrides the behavior of various IJ1 methods, inserting * seams so that (e.g.) the modern UI is aware of IJ1 events as they occur. * </p> * <p> * It also maintains an image map between IJ1 {@link ImagePlus} objects and IJ2 * {@link Dataset}s. * </p> * <p> * In this fashion, when a legacy plugin is executed on a {@link Dataset}, the * service transparently translates it into an {@link ImagePlus}, and vice * versa, enabling backward compatibility with legacy plugins. * </p> * * @author Curtis Rueden * @author Barry DeZonia */ @Plugin(type = Service.class) public final class LegacyService extends AbstractService { static { new LegacyInjector().injectHooks(); } private final LogService log; private final EventService eventService; private final PluginService pluginService; private final OptionsService optionsService; private final ImageDisplayService imageDisplayService; private final MenuService menuService; private boolean lastDebugMode; private boolean initialized; /** Mapping between modern and legacy image data structures. */ private LegacyImageMap imageMap; /** Method of synchronizing IJ2 & IJ1 options. */ private OptionsSynchronizer optionsSynchronizer; // -- Constructors -- /** Default contructor (will not run to completion). Provided only to fulfill * an API contract elsewhere. Do not use. */ public LegacyService() { // NB: Required by SezPoz. super(null); throw new UnsupportedOperationException(); } /** Preferred constructor. */ public LegacyService(final ImageJ context, final LogService log, final EventService eventService, final PluginService pluginService, final OptionsService optionsService, final ImageDisplayService imageDisplayService, final MenuService menuService) { super(context); this.log = log; this.eventService = eventService; this.pluginService = pluginService; this.optionsService = optionsService; this.imageDisplayService = imageDisplayService; this.menuService = menuService; imageMap = new LegacyImageMap(context); optionsSynchronizer = new OptionsSynchronizer(optionsService); // initialize legacy ImageJ application try { new ij.ImageJ(ij.ImageJ.NO_SHOW); } catch (final Throwable t) { log.warn("Failed to instantiate IJ1.", t); } // discover legacy plugins final OptionsMisc optsMisc = optionsService.getOptions(OptionsMisc.class); lastDebugMode = optsMisc.isDebugMode(); final boolean enableBlacklist = !optsMisc.isDebugMode(); addLegacyPlugins(enableBlacklist); updateIJ1Settings(); subscribeToEvents(eventService); initialized = true; } // -- LegacyService methods -- /** Returns the EventService associated with this LegacyService */ public EventService getEventService() { return eventService; } /** Returns the PluginService associated with this LegacyService */ public PluginService getPluginService() { return pluginService; } /** Returns the OptionsService associated with this LegacyService */ public OptionsService getOptionsService() { return optionsService; } /** Returns the ImageDisplayService associated with this LegacyService */ public ImageDisplayService getImageDisplayService() { return imageDisplayService; } /** Returns the LegacyImageMap associated with this LegacyService */ public LegacyImageMap getImageMap() { return imageMap; } /** Runs a legacy plugin programmaticaly * * @param ij1ClassName The name of the plugin class you want to run e.g. * "ij.plugin.Clipboard" * @param argument The argument string to pass to the plugin e.g. "copy" */ public void runLegacyPlugin(final String ij1ClassName, final String argument) { final String arg = (argument == null) ? "" : argument; final Map<String, Object> inputMap = new HashMap<String, Object>(); inputMap.put("className", ij1ClassName); inputMap.put("arg", arg); pluginService.run(LegacyPlugin.class, inputMap); } /** * Indicates to the service that the given {@link ImagePlus} has changed as * part of a legacy plugin execution. */ public void legacyImageChanged(final ImagePlus imp) { // CTR FIXME rework static InsideBatchDrawing logic? // BDZ - removal for now. replace if issues arise. Alternative fix outlined // in FunctionsMethods code. This code was for addressing bug #554 // if (FunctionsMethods.InsideBatchDrawing > 0) return; // create a display if it doesn't exist yet. imageMap.registerLegacyImage(imp); // record resultant ImagePlus as a legacy plugin output LegacyOutputTracker.getOutputImps().add(imp); } /** * Ensures that the currently active {@link ImagePlus} matches the currently * active {@link ImageDisplay}. Does not perform any harmonization. */ public void syncActiveImage() { final ImageDisplay activeDisplay = imageDisplayService.getActiveImageDisplay(); final ImagePlus activeImagePlus = imageMap.lookupImagePlus(activeDisplay); // NB - old way - caused probs with 3d Project //WindowManager.setTempCurrentImage(activeImagePlus); // NB - new way - test thoroughly if (activeImagePlus == null) WindowManager.setCurrentWindow(null); else WindowManager.setCurrentWindow(activeImagePlus.getWindow()); } /** Returns true if this LegacyService has been initialized already and false * if not. */ public boolean isInitialized() { return initialized; } // TODO - make private only??? /** Updates ImageJ 1.x option settings from ImageJ 2.x options values. */ public void updateIJ1Settings() { optionsSynchronizer.updateIJ1SettingsFromIJ2(); } // TODO - make private only??? /** Updates ImageJ 2.x option settings from ImageJ 1.x options values. */ public void updateIJ2Settings() { optionsSynchronizer.updateIJ2SettingsFromIJ1(); } /** Sets the foreground and background colors in ImageJ 1.x from the current * view using the current channel values. */ public void syncColors() { DatasetView view = imageDisplayService.getActiveDatasetView(); if (view == null) return; OptionsChannels channels = getChannels(); ColorRGB fgColor = view.getColor(channels.getFgValues()); ColorRGB bgColor = view.getColor(channels.getBgValues()); optionsSynchronizer.colorOptions(fgColor, bgColor); } // -- Event handlers -- /** * Keeps the active legacy {@link ImagePlus} in sync with the active modern * {@link ImageDisplay}. */ @EventHandler protected void onEvent( @SuppressWarnings("unused") final DisplayActivatedEvent event) { syncActiveImage(); } @EventHandler protected void onEvent(final OptionsEvent event) { if (event.getOptions().getClass() == OptionsMisc.class) { final OptionsMisc opts = (OptionsMisc) event.getOptions(); if (opts.isDebugMode() != lastDebugMode) updateMenus(opts); } updateIJ1Settings(); } @EventHandler protected void onEvent(final KyPressedEvent event) { final KeyCode code = event.getCode(); if (code == KeyCode.SPACE) IJ.setKeyDown(KeyCode.SPACE.getCode()); if (code == KeyCode.ALT) IJ.setKeyDown(KeyCode.ALT.getCode()); if (code == KeyCode.SHIFT) IJ.setKeyDown(KeyCode.SHIFT.getCode()); if (code == KeyCode.CONTROL) IJ.setKeyDown(KeyCode.CONTROL.getCode()); if (IJ.isMacintosh() && code == KeyCode.META) { IJ.setKeyDown(KeyCode.CONTROL.getCode()); } } @EventHandler protected void onEvent(final KyReleasedEvent event) { final KeyCode code = event.getCode(); if (code == KeyCode.SPACE) IJ.setKeyUp(KeyCode.SPACE.getCode()); if (code == KeyCode.ALT) IJ.setKeyUp(KeyCode.ALT.getCode()); if (code == KeyCode.SHIFT) IJ.setKeyUp(KeyCode.SHIFT.getCode()); if (code == KeyCode.CONTROL) IJ.setKeyUp(KeyCode.CONTROL.getCode()); if (IJ.isMacintosh() && code == KeyCode.META) { IJ.setKeyUp(KeyCode.CONTROL.getCode()); } } // -- helpers -- private OptionsChannels getChannels() { final OptionsService service = getContext().getService(OptionsService.class); return service.getOptions(OptionsChannels.class); } private void updateMenus(final OptionsMisc optsMisc) { pluginService.reloadPlugins(); final boolean enableBlacklist = !optsMisc.isDebugMode(); addLegacyPlugins(enableBlacklist); lastDebugMode = optsMisc.isDebugMode(); } private void addLegacyPlugins(final boolean enableBlacklist) { final LegacyPluginFinder finder = new LegacyPluginFinder(log, menuService.getMenu(), enableBlacklist); final ArrayList<PluginInfo<?>> plugins = new ArrayList<PluginInfo<?>>(); finder.findPlugins(plugins); pluginService.addPlugins(plugins); } /* 3-1-12 We are no longer going to synchronize colors from IJ1 to IJ2 protected class IJ1EventListener implements IJEventListener { @Override public void eventOccurred(final int eventID) { @SuppressWarnings("synthetic-access") final OptionsChannels colorOpts = optionsService.getOptions(OptionsChannels.class); ColorRGB color; switch (eventID) { case ij.IJEventListener.COLOR_PICKER_CLOSED: color = AWTColors.getColorRGB(Toolbar.getForegroundColor()); colorOpts.setFgColor(color); color = AWTColors.getColorRGB(Toolbar.getBackgroundColor()); colorOpts.setBgColor(color); colorOpts.save(); break; case ij.IJEventListener.FOREGROUND_COLOR_CHANGED: color = AWTColors.getColorRGB(Toolbar.getForegroundColor()); colorOpts.setFgColor(color); colorOpts.save(); break; case ij.IJEventListener.BACKGROUND_COLOR_CHANGED: color = AWTColors.getColorRGB(Toolbar.getBackgroundColor()); colorOpts.setBgColor(color); colorOpts.save(); break; case ij.IJEventListener.LOG_WINDOW_CLOSED: // TODO - do something??? break; case ij.IJEventListener.TOOL_CHANGED: // TODO - do something??? break; default: // unknown event // do nothing break; } } } */ }
package edu.tamu.framework.util; import static org.apache.commons.codec.binary.Base64.decodeBase64; import static org.apache.commons.codec.binary.Base64.encodeBase64URLSafeString; import java.io.UnsupportedEncodingException; import java.security.InvalidKeyException; import java.security.Key; import java.security.NoSuchAlgorithmException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.HashMap; import java.util.Map; import javax.crypto.BadPaddingException; import javax.crypto.Cipher; import javax.crypto.IllegalBlockSizeException; import javax.crypto.Mac; import javax.crypto.NoSuchPaddingException; import javax.crypto.spec.SecretKeySpec; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.core.env.Environment; import org.springframework.security.jwt.Jwt; import org.springframework.security.jwt.JwtHelper; import org.springframework.security.jwt.crypto.sign.MacSigner; import org.springframework.stereotype.Service; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import edu.tamu.framework.exception.JWTException; import edu.tamu.framework.model.jwt.JWT;; /** * JSON Web Token Utility. * * @author <a href="mailto:jmicah@library.tamu.edu">Micah Cooper</a> * @author <a href="mailto:jcreel@library.tamu.edu">James Creel</a> * @author <a href="mailto:huff@library.tamu.edu">Jeremy Huff</a> * @author <a href="mailto:jsavell@library.tamu.edu">Jason Savell</a> * @author <a href="mailto:wwelling@library.tamu.edu">William Welling</a> * */ @Service public class JwtUtility { @Value("${auth.security.jwt.secret-key}") private String secret_key; @Value("${auth.security.jwt-expiration}") private Long expiration; @Value("${shib.keys}") private String[] shibKeys; @Autowired private Environment env; @Autowired public ObjectMapper objectMapper; private final Logger log = LoggerFactory.getLogger(this.getClass()); public JwtUtility() { } /** * Instantiate new token. * * @return */ public JWT craftToken() { try { return new JWT(secret_key, expiration); } catch (InvalidKeyException e) { log.debug(e.getStackTrace().toString()); throw new JWTException("InvalidKeyException", e.getMessage()); } catch (JsonProcessingException e) { log.debug(e.getStackTrace().toString()); throw new JWTException("JsonProcessingException", e.getMessage()); } catch (NoSuchAlgorithmException e) { log.debug(e.getStackTrace().toString()); throw new JWTException("NoSuchAlgorithmException", e.getMessage()); } catch (IllegalStateException e) { log.debug(e.getStackTrace().toString()); throw new JWTException("IllegalStateException", e.getMessage()); } catch (UnsupportedEncodingException e) { log.debug(e.getStackTrace().toString()); throw new JWTException("UnsupportedEncodingException", e.getMessage()); } } /** * Get token as a string. * * @param token * @return */ public String tokenAsString(JWT token) { try { return token.getTokenAsString(); } catch (InvalidKeyException e) { log.debug(e.getStackTrace().toString()); throw new JWTException("InvalidKeyException", e.getMessage()); } catch (JsonProcessingException e) { log.debug(e.getStackTrace().toString()); throw new JWTException("JsonProcessingException", e.getMessage()); } catch (NoSuchAlgorithmException e) { log.debug(e.getStackTrace().toString()); throw new JWTException("NoSuchAlgorithmException", e.getMessage()); } catch (NoSuchPaddingException e) { log.debug(e.getStackTrace().toString()); throw new JWTException("NoSuchPaddingException", e.getMessage()); } catch (IllegalBlockSizeException e) { log.debug(e.getStackTrace().toString()); throw new JWTException("IllegalBlockSizeException", e.getMessage()); } catch (BadPaddingException e) { log.debug(e.getStackTrace().toString()); throw new JWTException("BadPaddingException", e.getMessage()); } } public JWT makeToken(Map<String, String> payload) throws InvalidKeyException, JsonProcessingException, NoSuchAlgorithmException, IllegalStateException, UnsupportedEncodingException { JWT token = craftToken(); for (String k : shibKeys) { String p = payload.get(env.getProperty("shib." + k, "")); token.makeClaim(k, p); // System.out.println("Adding " + k +": " + p + " to JWT."); } return token; } /** * Encodes JSON. * * @param json * String * * @return String * */ public String encodeJSON(String json) { return encodeBase64URLSafeString(json.getBytes()); } /** * Hashes signature with secret and returns it encoded. * * @param sig * String * @param secret * String * * @return String * * @exception NoSuchAlgorithmException * @exception InvalidKeyException * */ public String hashSignature(String sig, String secret) throws NoSuchAlgorithmException, InvalidKeyException { Mac sha256_HMAC = Mac.getInstance("HmacSHA256"); SecretKeySpec secret_key = new SecretKeySpec(secret.getBytes(), "HmacSHA256"); sha256_HMAC.init(secret_key); byte[] signature = sha256_HMAC.doFinal(sig.getBytes()); return encodeBase64URLSafeString(signature); } @SuppressWarnings("unchecked") public Map<String, String> validateJWT(String jwe) { Map<String, String> tokenMap = new HashMap<String, String>(); if (jwe == null) { tokenMap.put("ERROR", "MISSING_JWT"); return tokenMap; } Key key = new SecretKeySpec(secret_key.getBytes(), "AES"); Cipher c = null; byte[] decordedValue = decodeBase64(jwe); byte[] decValue = null; try { c = Cipher.getInstance("AES"); c.init(Cipher.DECRYPT_MODE, key); decValue = c.doFinal(decordedValue); } catch (NoSuchAlgorithmException | NoSuchPaddingException | IllegalBlockSizeException | BadPaddingException | InvalidKeyException e1) { System.out.println("Could not decrypt token!" + e1); tokenMap.put("ERROR", "UNDECRYPTED_JWT"); return tokenMap; } MacSigner hmac = new MacSigner(secret_key); Jwt token = null; try { token = JwtHelper.decodeAndVerify(new String(decValue), hmac); } catch (Exception e) { log.error("Invalid token! Not verified!"); tokenMap.put("ERROR", "INVALID_JWT"); return tokenMap; } try { tokenMap = objectMapper.readValue(token.getClaims(), Map.class); } catch (Exception e) { log.error("Invalid token! Unable to map!"); tokenMap.put("ERROR", "INVALID_JWT"); return tokenMap; } return tokenMap; } /** * Check if token has expired. * * @param tokenMap * Map<String, String> * @return */ public boolean isExpired(Map<String, String> tokenMap) { long currentTime = new Date().getTime(); long expTime = Long.parseLong(tokenMap.get("exp")); if (log.isDebugEnabled()) { SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yy - hh:mm:ss"); log.debug("Token expiration time: " + sdf.format(new Date(expTime))); } if (currentTime >= expTime) { return true; } else { Long remainingTimeInSeconds = (expTime - currentTime) / 1000; if (remainingTimeInSeconds > 60) { log.debug("Token expires in " + remainingTimeInSeconds / 60 + " minutes."); } else { log.debug("Token expires in " + remainingTimeInSeconds + " seconds."); } } return false; } }
package hudson.model; import hudson.ExtensionPoint; import hudson.ExtensionList; import hudson.Extension; import hudson.ExtensionPoint.LegacyInstancesAreScopedToHudson; import hudson.triggers.SCMTrigger; import hudson.triggers.TimerTrigger; import java.util.Set; import java.io.IOException; import org.kohsuke.stapler.StaplerRequest; import org.kohsuke.stapler.StaplerResponse; @LegacyInstancesAreScopedToHudson public abstract class AdministrativeMonitor extends AbstractModelObject implements ExtensionPoint { /** * Human-readable ID of this monitor, which needs to be unique within the system. * * <p> * This ID is used to remember persisted setting for this monitor, * so the ID should remain consistent beyond the Hudson JVM lifespan. */ public final String id; protected AdministrativeMonitor(String id) { this.id = id; } protected AdministrativeMonitor() { this.id = this.getClass().getName(); } /** * Returns the URL of this monitor, relative to the context path, like "administrativeMonitor/foobar". */ public String getUrl() { return "administrativeMonitor/"+id; } public String getDisplayName() { return id; } public final String getSearchUrl() { return getUrl(); } /** * Mark this monitor as disabled, to prevent this from showing up in the UI. */ public void disable(boolean value) throws IOException { Hudson hudson = Hudson.getInstance(); Set<String> set = hudson.disabledAdministrativeMonitors; if(value) set.add(id); else set.remove(id); hudson.save(); } /** * Returns true if this monitor {@link #disable(boolean) isn't disabled} earlier. * * <p> * This flag implements the ability for the admin to say "no thank you" to the monitor that * he wants to ignore. */ public boolean isEnabled() { return !Hudson.getInstance().disabledAdministrativeMonitors.contains(id); } /** * Returns true if this monitor is activated and * wants to produce a warning message. * * <p> * This method is called from the HTML rendering thread, * so it should run efficiently. */ public abstract boolean isActivated(); /** * URL binding to disable this monitor. */ public void doDisable(StaplerRequest req, StaplerResponse rsp) throws IOException { Hudson.getInstance().checkPermission(Hudson.ADMINISTER); disable(true); rsp.sendRedirect2(req.getContextPath()+"/manage"); } /** * All registered {@link AdministrativeMonitor} instances. */ public static ExtensionList<AdministrativeMonitor> all() { return Hudson.getInstance().getExtensionList(AdministrativeMonitor.class); } }
package org.commcare.android.tasks; import android.os.AsyncTask; import android.os.Bundle; import java.io.File; import java.io.IOException; import org.commcare.android.util.TemplatePrinterUtils; /** * Asynchronous task for populating an html document with data. * * @author Richard Lu * @author amstone */ public class TemplatePrinterTask extends AsyncTask<Void, Void, Integer> { /** * The 4 result codes that can be sent back by this task */ public static final int SUCCESS = 0; public static final int IO_ERROR = 1; public static final int VALIDATION_ERROR_MUSTACHE = 2; public static final int VALIDATION_ERROR_CHEVRON = 3; /** * Used to track which type of error (2 or 3 above) was encountered in validateString */ private static int validationErrorType; /** * Used to track the string in the template file where a validation error was encountered */ private String problemString; /** * The template file for this print action */ private final File inputFile; /** * The path where the populated template should be saved to */ private final String outputPath; /** * The mapping from keywords to case property values to be used in populating the template */ private final Bundle values; private final PopulateListener listener; public TemplatePrinterTask(File input, String outputPath, Bundle values, PopulateListener listener) { this.inputFile = input; this.outputPath = outputPath; this.values = values; this.listener = listener; } /** * Attempts to perform population of the template file, and throws the appropriate exception * if encountering an error. */ @Override protected Integer doInBackground(Void... params) { try { populateHtml(inputFile, values); return SUCCESS; } catch (IOException e) { return IO_ERROR; } catch (RuntimeException e) { problemString = e.getMessage(); return validationErrorType; } } /** * Receives the return value from doInBackground and proceeds accordingly */ @Override protected void onPostExecute(Integer result) { listener.onFinished(result, problemString); } /** * Populates an html print template based on the given set of key-value pairings * and save the newly-populated template to a temp location * * @param input the html print template * @param values the mapping of keywords to case property values * @throws IOException */ private void populateHtml(File input, Bundle values) throws IOException { // Read from input file // throws IOException String fileText = TemplatePrinterUtils.docToString(input).toLowerCase(); // Check if <body></body> section of html string is properly formed // throws RuntimeException int startBodyIndex = fileText.indexOf("<body"); String beforeBodySection = fileText.substring(0, startBodyIndex); String bodySection = fileText.substring(startBodyIndex); validateStringOrThrowException(bodySection); // Swap out place-holder keywords for case property values within <body></body> section bodySection = replace(bodySection, values); // Write the new HTML to the desired temp file location // throws IO Exception TemplatePrinterUtils.writeStringToFile(beforeBodySection + bodySection, outputPath); } /** * Populate an input string with attribute keys formatted as {{ attr_key }} * with attribute values. * @param input String input * @param values Bundle of String attribute key-value mappings * @return The populated String */ private static String replace(String input, Bundle values) { // Split input into tokens bounded by {{ and }} String[] tokens = TemplatePrinterUtils.splitKeepDelimiter(input, "\\{{2}", "\\}{2}"); for (int i=0; i<tokens.length; i++) { String token = tokens[i]; // Every 2nd token is a attribute enclosed in {{ }} if (i % 2 == 1) { // Split token into tokenSplits bounded by < and > String[] tokenSplits = TemplatePrinterUtils.splitKeepDelimiter(token, "<|(\\}{2})", ">|(\\{{2})"); // First and last tokenSplits are {{ and }} for (int j=1; j<tokenSplits.length-1; j++) { String tokenSplit = tokenSplits[j]; // tokenSplit is key or whitespace if (!tokenSplit.startsWith("<")) { // Remove whitespace from key String key = TemplatePrinterUtils.remove(tokenSplit, " "); if (values.containsKey(key) && (key = values.getString(key)) != null) { // Populate with value tokenSplits[j] = key; } else { // Empty if not found tokenSplits[j] = ""; } } } // Remove {{ and }} tokenSplits[0] = ""; tokenSplits[tokenSplits.length-1] = ""; // Reconstruct token tokens[i] = TemplatePrinterUtils.join(tokenSplits); } } // Reconstruct input return TemplatePrinterUtils.join(tokens); } /** * Validates the input string for well-formed {{ }} and < > pairs. * If malformed, throws a RuntimeException which will be caught by * doInBackground(), and trigger the appropriate result code to be * sent back to the attached PopulateListener * * @param input String to validate */ private static void validateStringOrThrowException(String input) { boolean isBetweenMustaches = false; boolean isBetweenChevrons = false; StringBuilder recentString = new StringBuilder(); for (int i = 0; i < input.length(); i++) { char c = input.charAt(i); recentString.append(c); if (recentString.length() > 40) { recentString.deleteCharAt(0); } if (c == '{') { if (isBetweenMustaches) { validationErrorType = VALIDATION_ERROR_MUSTACHE; throw new RuntimeException(recentString.toString()); } else { i++; c = input.charAt(i); if (c == '{') { isBetweenMustaches = true; recentString.append(c); } else { isBetweenMustaches = false; } } } else if (c == '}') { if (isBetweenMustaches) { i++; c = input.charAt(i); if (c != '}') { validationErrorType = VALIDATION_ERROR_MUSTACHE; recentString.append(c); throw new RuntimeException(recentString.toString()); } else { isBetweenMustaches = false; } } } else if (c == '<') { if (isBetweenChevrons) { validationErrorType = VALIDATION_ERROR_CHEVRON; throw new RuntimeException(recentString.toString()); } else { isBetweenChevrons = true; } } else if (c == '>') { if (isBetweenChevrons) { isBetweenChevrons = false; } else { validationErrorType = VALIDATION_ERROR_CHEVRON; throw new RuntimeException(recentString.toString()); } } } // If we reach the end of the string and are in between either type, should also throw error if (isBetweenChevrons) { validationErrorType = VALIDATION_ERROR_CHEVRON; throw new RuntimeException(recentString.toString()); } else if (isBetweenMustaches) { validationErrorType = VALIDATION_ERROR_MUSTACHE; throw new RuntimeException(recentString.toString()); } } /** * A listener for this task, implemented by TemplatePrinterActivity */ public interface PopulateListener { void onFinished(int result, String problemString); } }
package nl.b3p.viewer.print; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.StringWriter; import java.net.MalformedURLException; import java.net.URL; import java.util.Date; import java.util.logging.Level; import java.util.logging.Logger; import javax.servlet.http.HttpServletResponse; import javax.xml.bind.JAXBContext; import javax.xml.bind.util.JAXBSource; import javax.xml.transform.Result; import javax.xml.transform.Source; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerFactory; import javax.xml.transform.sax.SAXResult; import javax.xml.transform.stream.StreamSource; import nl.b3p.mail.Mailer; import nl.b3p.viewer.stripes.PrintActionBean; import org.apache.commons.io.output.ByteArrayOutputStream; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.fop.apps.FOUserAgent; import org.apache.fop.apps.Fop; import org.apache.fop.apps.FopFactory; /** * * @author meine */ public class PrintGenerator implements Runnable{ private static final Log log = LogFactory.getLog(PrintGenerator.class); private final PrintInfo info; private final String mimeType; private final File xsl; private final String filename; private final String fromName; private final String fromMail; private final String toMail; public PrintGenerator(PrintInfo info, String mimeType, File xsl, String filename, String fromName, String fromMail, String toMail) { this.info = info; this.mimeType = mimeType; this.xsl = xsl; this.filename = filename; this.fromName = fromName; this.fromMail = fromMail; this.toMail = toMail; } @Override public void run() { try { mailPrint(); } catch (Exception ex) { log.error("Cannot creat print."); try { Mailer.sendMail(fromName, fromMail,toMail, "Fout bij printen", "De print kon niet worden gemaakt. De foutmelding is: " + ex.getLocalizedMessage()); } catch (Exception ex1) { log.error("Cannot send mail for reporting exception"); } } } public void mailPrint() throws Exception{ File temp = File.createTempFile("flamingo", "print"); try { FileOutputStream fos = new FileOutputStream(temp); String path = new File(xsl.getParent()).toURI().toString(); // PrintInfo info, String mimeType, InputStream xslIs, String basePath, OutputStream ou createOutput(info, mimeType, new FileInputStream(xsl), path, fos, filename); Mailer.sendMail(fromName, fromMail,toMail,"Print is klaar", "De print is klaar en staat in de bijlage", temp, filename); } finally { temp.delete(); } } public static void createOutput(PrintInfo info, String mimeType, File xslFile, boolean addJavascript, HttpServletResponse response, String filename) throws MalformedURLException, IOException { String path = new File(xslFile.getParent()).toURI().toString(); createOutput(info, mimeType, new FileInputStream(xslFile), path, addJavascript, response,filename); } public static void createOutput(PrintInfo info, String mimeType, URL xslUrl, boolean addJavascript, HttpServletResponse response, String filename) throws MalformedURLException, IOException { String path = xslUrl.toString().substring(0, xslUrl.toString().lastIndexOf("/")+1); createOutput(info, mimeType, xslUrl.openStream(), path, addJavascript, response,filename); } /** * Create the output pdf. * @param info the print info * @param mimeType mimeType of the result * @param xslIs inputstream for xsl sheet * @param basePath the base path of that sheet * @param addJavascript addJavascript? * @param response the response for the outputstream * @throws MalformedURLException * @throws IOException */ public static void createOutput(PrintInfo info, String mimeType, InputStream xslIs, String basePath, boolean addJavascript, HttpServletResponse response, String filename) throws MalformedURLException, IOException { /* Setup output stream */ ByteArrayOutputStream out = new ByteArrayOutputStream(); createOutput(info, mimeType, xslIs, basePath, out,filename); /* Setup response */ response.setContentType(mimeType); response.setContentLength(out.size()); response.setHeader("Content-Disposition", "attachment; filename=" + filename); //TODO: Postprocess pages to add javascript print /* use postprocessing with itext to add Javascript to output if (addJavascript) { addJsToPdfOutput(out, response); } else { response.getOutputStream().write(out.toByteArray()); }*/ response.getOutputStream().write(out.toByteArray()); response.getOutputStream().flush(); } public static void createOutput(PrintInfo info, String mimeType, InputStream xslIs, String basePath, OutputStream out, String filename) throws MalformedURLException, IOException { /* Setup fopfactory */ FopFactory fopFactory = FopFactory.newInstance(); /* Set BaseUrl so that fop knows paths to images etc... */ fopFactory.setBaseURL(basePath); try { /* Construct fop */ FOUserAgent foUserAgent = fopFactory.newFOUserAgent(); foUserAgent.setCreator("Flamingo"); foUserAgent.setProducer("Flamingo"); Date now = new Date(); foUserAgent.setCreationDate(now); foUserAgent.setTitle("Kaart"); Fop fop = fopFactory.newFop(mimeType, foUserAgent, out); //String s=printInfoToString(info); /* Setup Jaxb */ JAXBContext jc = JAXBContext.newInstance(PrintInfo.class); JAXBSource src = new JAXBSource(jc, info); if (log.isDebugEnabled()) { JAXBContext jaxbContext = JAXBContext.newInstance(PrintInfo.class); StringWriter sw = new StringWriter(); jaxbContext.createMarshaller().marshal(info, sw); log.debug("Print XML:\n" + sw.toString()); } /* Setup xslt */ Source xsltSrc = new StreamSource(xslIs); xsltSrc.setSystemId(basePath); TransformerFactory factory = TransformerFactory.newInstance(); Transformer transformer = factory.newTransformer(xsltSrc); Result res = new SAXResult(fop.getDefaultHandler()); transformer.transform(src, res); } catch (Exception ex) { log.error("Fout tijdens print output: ", ex); } finally { out.close(); } } }
package org.commcare.dalvik.activities; import java.util.Date; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.content.DialogInterface; import android.content.DialogInterface.OnCancelListener; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.telephony.PhoneStateListener; import android.telephony.TelephonyManager; /** * @author ctsims * */ public class CallOutActivity extends Activity { public static final String PHONE_NUMBER = "cos_pn"; public static final String CALL_DURATION = "cos_pd"; public static final String RETURNING = "cos_return"; public static final String INCOMING_ACTION = "cos_inac"; private static final int DIALOG_NUMBER_ACTION = 0; private static final int SMS_RESULT = 0; private static String number; TelephonyManager tManager; CallListener listener; /* * (non-Javadoc) * @see android.app.Activity#onCreate(android.os.Bundle) */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); tManager = (TelephonyManager) this.getSystemService(TELEPHONY_SERVICE); listener = new CallListener(); number = this.getIntent().getStringExtra(PHONE_NUMBER); if(this.getIntent().hasExtra(INCOMING_ACTION)) { dispatchAction(this.getIntent().getStringExtra(INCOMING_ACTION)); } else { this.showDialog(DIALOG_NUMBER_ACTION); } } public void onResume() { super.onResume(); if(listener.isFinished()) { long duration = listener.getCallDuration(); if(duration > 0) { Intent i = new Intent(getIntent()); i.putExtra(CALL_DURATION, duration); setResult(RESULT_OK, i); finish(); return; } else { //TODO: We could also pop up a thing here that said "Phone call in progress" //or something Intent i = new Intent(getIntent()); setResult(RESULT_CANCELED, i); finish(); return; } } } protected Dialog onCreateDialog(int id) { switch (id) { case DIALOG_NUMBER_ACTION: final CharSequence[] items = {"Call", "Send SMS"}; AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle("Select Action"); builder.setItems(items, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int item) { dispatchAction(item == 0 ? Intent.ACTION_CALL : Intent.ACTION_SENDTO); } }); builder.setOnCancelListener(new OnCancelListener() { public void onCancel(DialogInterface dialog) { Intent i = new Intent(getIntent()); setResult(RESULT_CANCELED, i); finish(); return; } }); AlertDialog alert = builder.create(); return alert; } return null; } private void dispatchAction(String action) { // using createChooser to handle any errors gracefully if(Intent.ACTION_CALL.equals(action) ) { tManager.listen(listener, PhoneStateListener.LISTEN_CALL_STATE); Intent call = new Intent(Intent.ACTION_CALL); call.setData(Uri.parse("tel:" + number)); startActivity(Intent.createChooser(call, "Dialing " + number)); } else { Intent sms = new Intent(Intent.ACTION_SENDTO); sms.setData(Uri.parse("smsto:" + number)); startActivityForResult(Intent.createChooser(sms, "Messaging " + number),SMS_RESULT); } } protected void onActivityResult(int requestCode, int resultCode, Intent intent) { super.onActivityResult(requestCode, resultCode, intent); if(requestCode == SMS_RESULT) { //we're done here Intent i = new Intent(getIntent()); setResult(RESULT_CANCELED, i); finish(); } } public class CallListener extends PhoneStateListener { boolean called = false; long started; long duration; boolean finished = false; /* * (non-Javadoc) * @see android.telephony.PhoneStateListener#onCallStateChanged(int, java.lang.String) */ @Override public void onCallStateChanged(int state, String incomingNumber) { super.onCallStateChanged(state, incomingNumber); // Don't fire before the call was made if (state == TelephonyManager.CALL_STATE_OFFHOOK) { called = true; started = new Date().getTime(); } // Call has ended -- now bring the activity back to front if (called && state == TelephonyManager.CALL_STATE_IDLE) { called = false; tManager.listen(this, PhoneStateListener.LISTEN_NONE); duration = new Date().getTime() - started; finished = true; //TODO: Any way to skip the stupid Call Log? if(duration > 0) { Intent i = new Intent(getIntent()); i.putExtra(CALL_DURATION, duration); setResult(RESULT_OK, i); finish(); return; } else { Intent i = new Intent(getIntent()); setResult(RESULT_CANCELED, i); finish(); return; } } } public long getCallDuration() { return duration; } public boolean isFinished() { return finished; } } }
package lucee.commons.digest; import java.util.Arrays; import java.util.HashMap; import java.util.Map; import lucee.commons.io.CharsetUtil; import lucee.runtime.coder.CoderException; public class Base64Encoder { private static final char[] ALPHABET = new char[] { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/' }; private static final char PAD = '='; private static final Map<Character, Integer> REVERSE = new HashMap<Character, Integer>(); static { for (int i = 0; i < 64; i++) { REVERSE.put(ALPHABET[i], i); } REVERSE.put('-', 62); REVERSE.put('_', 63); REVERSE.put(PAD, 0); } public static String encodeFromString(String data) { return encode(data.getBytes(CharsetUtil.UTF8)); } /** * Translates the specified byte array into Base64 string. * * @param data * the byte array (not null) * @return the translated Base64 string (not null) */ public static String encode(byte[] data) { StringBuilder builder = new StringBuilder(); for (int position = 0; position < data.length; position += 3) { builder.append(encodeGroup(data, position)); } return builder.toString(); } //// Helper methods /** * Encode three bytes of data into four characters. */ private static char[] encodeGroup(byte[] data, int position) { final char[] c = new char[] { '=', '=', '=', '=' }; int b1 = 0, b2 = 0, b3 = 0; int length = data.length - position; if(length == 0) return c; if(length >= 1) { b1 = (data[position]) & 0xFF; } if(length >= 2) { b2 = (data[position + 1]) & 0xFF; } if(length >= 3) { b3 = (data[position + 2]) & 0xFF; } c[0] = ALPHABET[b1 >> 2]; c[1] = ALPHABET[(b1 & 3) << 4 | (b2 >> 4)]; if(length == 1) return c; c[2] = ALPHABET[(b2 & 15) << 2 | (b3 >> 6)]; if(length == 2) return c; c[3] = ALPHABET[b3 & 0x3f]; return c; } public static String decodeAsString(String data) throws CoderException { return new String(decode(data), CharsetUtil.UTF8); } /** * Translates the specified Base64 string into a byte array. * * @param data the Base64 string (not null) * @return the byte array (not null) * @throws CoderException */ public static byte[] decode(String data) { return org.apache.commons.codec.binary.Base64.decodeBase64(data); } }
package net.novucs.ftop; import mkremins.fanciful.FancyMessage; import org.apache.commons.lang.math.NumberUtils; import org.bukkit.ChatColor; import org.bukkit.Material; import org.bukkit.command.Command; import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandSender; import org.bukkit.entity.EntityType; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.HandlerList; import org.bukkit.event.Listener; import org.bukkit.event.player.PlayerCommandPreprocessEvent; import org.bukkit.event.server.ServerCommandEvent; import java.util.HashMap; import java.util.List; import java.util.ListIterator; import java.util.Map; import java.util.stream.Collectors; public class FactionsTopCommand implements CommandExecutor, Listener, PluginService { private final FactionsTopPlugin plugin; public FactionsTopCommand(FactionsTopPlugin plugin) { this.plugin = plugin; } @Override public void initialize() { plugin.getServer().getPluginManager().registerEvents(this, plugin); plugin.getServer().getPluginCommand("ftop").setExecutor(this); } @Override public void terminate() { HandlerList.unregisterAll(this); plugin.getServer().getPluginCommand("ftop").setExecutor(null); } @Override public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { if (!sender.hasPermission("factionstop.use")) { sender.sendMessage(plugin.getSettings().getPermissionMessage()); return true; } if (args.length == 0) { sendTop(sender, 0); } else if (args[0].equalsIgnoreCase("reload")) { if (!sender.hasPermission("factionstop.reload")) { sender.sendMessage(plugin.getSettings().getPermissionMessage()); return true; } plugin.loadSettings(); sender.sendMessage(ChatColor.YELLOW + "FactionsTop settings have been successfully reloaded."); sender.sendMessage(ChatColor.YELLOW + "New faction worth values will take a while to register."); } else { sendTop(sender, NumberUtils.toInt(args[0])); } return true; } @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) public void onCommand(PlayerCommandPreprocessEvent event) { event.setMessage("/" + attemptRebind(event.getMessage().substring(1))); } @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) public void onCommand(ServerCommandEvent event) { event.setCommand(attemptRebind(event.getCommand())); } private String attemptRebind(String command) { for (String alias : plugin.getSettings().getCommandAliases()) { if (command.startsWith(alias)) { return command.replaceFirst(alias, "ftop"); } } return command; } private void sendTop(CommandSender sender, int page) { // Do not attempt to send hook worth if page requested is beyond the limit. int entries = plugin.getSettings().getFactionsPerPage(); List<FactionWorth> factions = plugin.getWorthManager().getOrderedFactions(); int maxPage = Math.max((int) Math.ceil((double) factions.size() / entries), 1); page = Math.max(1, Math.min(maxPage, page)); Map<String, String> placeholders = new HashMap<>(); placeholders.put("{page:back}", String.valueOf(page - 1)); placeholders.put("{page:this}", String.valueOf(page)); placeholders.put("{page:next}", String.valueOf(page + 1)); placeholders.put("{page:last}", String.valueOf(maxPage)); ButtonMessage back = plugin.getSettings().getBackButtonMessage(); ButtonMessage next = plugin.getSettings().getNextButtonMessage(); String backMsg = page == 1 ? back.getDisabled() : back.getEnabled(); String backCmd = page == 1 ? null : "/ftop " + (page - 1); List<String> backTooltip = replace(back.getTooltip(), placeholders); String nextMsg = page == maxPage ? next.getDisabled() : next.getEnabled(); String nextCmd = page == maxPage ? null : "/ftop " + (page + 1); List<String> nextTooltip = replace(next.getTooltip(), placeholders); if (!plugin.getSettings().getHeaderMessage().isEmpty()) { String headerString = replace(plugin.getSettings().getHeaderMessage(), placeholders); FancyMessage header = build(headerString, backMsg, backCmd, backTooltip, nextMsg, nextCmd, nextTooltip); header.send(sender); } if (factions.size() == 0) { sender.sendMessage(plugin.getSettings().getNoEntriesMessage()); return; } int spacer = entries * --page; ListIterator<FactionWorth> it = factions.listIterator(spacer); for (int i = 0; i < entries; i++) { if (!it.hasNext()) break; FactionWorth worth = it.next(); int spawnerCount = 0; for (EntityType spawner : worth.getSpawners().keySet()) { spawnerCount += worth.getSpawners().get(spawner); } Map<String, String> worthPlaceholders = new HashMap<>(placeholders); worthPlaceholders.put("{rank}", Integer.toString(i + 1)); worthPlaceholders.put("{relcolor}", "" + ChatColor.COLOR_CHAR + getRelationColor(sender, worth.getFactionId()).getChar()); worthPlaceholders.put("{faction}", worth.getName()); worthPlaceholders.put("{worth:total}", plugin.getSettings().getCurrencyFormat().format(worth.getTotalWorth())); worthPlaceholders.put("{count:total:spawner}", String.valueOf(spawnerCount)); String bodyMessage = insertPlaceholders(worth, replace(plugin.getSettings().getBodyMessage(), worthPlaceholders)); List<String> tooltip = insertPlaceholders(worth, replace(plugin.getSettings().getBodyTooltip(), worthPlaceholders)); FancyMessage message = new FancyMessage(bodyMessage).tooltip(tooltip); message.send(sender); } if (!plugin.getSettings().getFooterMessage().isEmpty()) { String footerString = replace(plugin.getSettings().getFooterMessage(), placeholders); FancyMessage footer = build(footerString, backMsg, backCmd, backTooltip, nextMsg, nextCmd, nextTooltip); footer.send(sender); } } private String insertPlaceholders(Replacer replacer, String key, String message) { int index = message.indexOf('{' + key + ':'); if (index < 0) { return message; } String first = message.substring(0, index); String next = message.substring(index + key.length() + 2); index = next.indexOf('}'); if (index < 0) { return first + insertPlaceholders(replacer, key, next); } return first + replacer.replace(next.substring(0, index)) + insertPlaceholders(replacer, key, next.substring(index + 1)); } private String insertPlaceholders(FactionWorth worth, String message) { message = insertPlaceholders((s) -> { double value = worth.getWorth(StringUtils.parseEnum(WorthType.class, s).orElse(null)); return plugin.getSettings().getCurrencyFormat().format(value); }, "worth", message); message = insertPlaceholders((s) -> { int count = worth.getSpawners().getOrDefault(StringUtils.parseEnum(EntityType.class, s).orElse(null), 0); return plugin.getSettings().getCountFormat().format(count); }, "count:spawner", message); message = insertPlaceholders((s) -> { int count = worth.getMaterials().getOrDefault(StringUtils.parseEnum(Material.class, s).orElse(null), 0); return plugin.getSettings().getCountFormat().format(count); }, "count:material", message); return message; } private List<String> insertPlaceholders(FactionWorth worth, List<String> messages) { return messages.stream() .map(message -> insertPlaceholders(worth, message)) .collect(Collectors.toList()); } private String replace(String message, Map<String, String> placeholders) { for (Map.Entry<String, String> entry : placeholders.entrySet()) { message = message.replace(entry.getKey(), entry.getValue()); } return message; } private List<String> replace(List<String> messages, Map<String, String> placeholders) { return messages.stream() .map(message -> replace(message, placeholders)) .collect(Collectors.toList()); } private FancyMessage build(String message, String backText, String backCmd, List<String> backTooltip, String nextText, String nextCmd, List<String> nextTooltip) { FancyMessage fancyMessage = new FancyMessage(""); while (!message.isEmpty()) { int backIndex = message.indexOf("{button:back}"); int nextIndex = message.indexOf("{button:next}"); backIndex = backIndex == -1 ? Integer.MAX_VALUE : backIndex; nextIndex = nextIndex == -1 ? Integer.MAX_VALUE : nextIndex; if (backIndex < nextIndex && backIndex != Integer.MAX_VALUE) { fancyMessage.then(message.substring(0, backIndex)).then(backText); if (backCmd != null) { fancyMessage.command(backCmd).tooltip(backTooltip); } message = message.substring(backIndex + 13); } else if (nextIndex < backIndex && nextIndex != Integer.MAX_VALUE) { fancyMessage.then(message.substring(0, nextIndex)).then(nextText); if (nextCmd != null) { fancyMessage.command(nextCmd).tooltip(nextTooltip); } message = message.substring(nextIndex + 13); } else { fancyMessage.then(message); break; } } return fancyMessage; } private ChatColor getRelationColor(CommandSender sender, String factionId) { return sender instanceof Player ? plugin.getFactionsHook().getRelation((Player) sender, factionId) : ChatColor.WHITE; } }
package com.oneandone.snmpman; import com.oneandone.snmpman.exception.InitializationException; import org.mockito.Mockito; import org.snmp4j.agent.BaseAgent; import org.snmp4j.smi.OID; import org.snmp4j.util.TableEvent; import org.testng.annotations.Test; import java.util.Collections; import java.util.List; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertNotEquals; import static org.testng.Assert.assertTrue; public class SnmpmanTest extends AbstractSnmpmanTest { @Test public void testSnmpGetBulk() throws Exception { assertEquals(snmpman.getAgents().size(), 11); List<TableEvent> responses = getResponse(new OID("1.3.6.1.2.1"), 10000); assertEquals(responses.size(), 19); responses = getResponse(new OID("1.3.6.1.2.1.31"), 10000); assertEquals(responses.size(), 10); responses = getResponse(new OID(".1.3.6.1.2.1.2"), 10000); assertEquals(responses.size(), 7); responses = getResponse(new OID(".1.3"), 10010); assertEquals(responses.size(), 30); responses = getResponse(new OID(".1.0"), 10010); assertEquals(responses.size(), 8); } @Test public void testWithCommunityIndex() throws Exception { assertEquals(snmpman.getAgents().size(), 11); final String oid = "1.3.6.1.2.1.17.2.4"; List<TableEvent> responses1 = getResponse(new OID(oid), PORT, "public@42"); assertEquals(responses1.size(), 1); assertTrue(containsColumn(responses1, oid, "150")); List<TableEvent> responses2 = getResponse(new OID(oid), PORT, "public@9"); assertEquals(responses2.size(), 1); assertTrue(containsColumn(responses2, oid, "120")); List<TableEvent> responses3 = getResponse(new OID(oid), PORT, COMMUNITY); assertEquals(responses3.size(), 1); assertTrue(containsColumn(responses3, oid, "0")); } @Test(expectedExceptions = InitializationException.class) public void startWithAlreadyStoppedAgent() { final SnmpmanAgent mock = Mockito.mock(SnmpmanAgent.class); Mockito.when(mock.getAgentState()).thenReturn(BaseAgent.STATE_STOPPED); final List<SnmpmanAgent> snmpmanAgents = Collections.singletonList(mock); Snmpman.start(snmpmanAgents); } @Test public void testModifier() throws Exception { final String oid = "1.3.6.1.2.1.2.2.1.13"; List<TableEvent> responses1 = SnmpmanTest.getResponse(new OID(oid), PORT, COMMUNITY); List<TableEvent> responses2 = SnmpmanTest.getResponse(new OID(oid), PORT, COMMUNITY); assertNotEquals(responses1.get(0).getColumns(), responses2.get(0).getColumns(), "repeated call should return a different result"); } }
// Triple Play - utilities for use in PlayN-based games package tripleplay.ui.bgs; import pythagoras.f.IDimension; import playn.core.Image; import playn.core.ImmediateLayer; import playn.core.PlayN; import playn.core.Surface; import playn.core.Tint; import tripleplay.ui.Background; /** * A background constructed by scaling the parts of a source image to fit the target width and * height. First the source image is divided into a 3x3 grid. Of the resulting 9 parts, the corners * are drawn without scaling to the destination, the top and bottom center pieces are copied with * horizontal scaling, the left and right center pieces are copied with vertical scaling, and the * center piece is copied with both horizontal and vertical scaling. * * <p>By using {@link #xaxis} and {@link #yaxis}, the partitioning of the image can be * controlled directly. For example, if the horizontal middle of an image is a single pixel: * <pre>{@code * Scale9Background bkg = ...; * bkg.xaxis.resize(1, 1); * }</pre></p> */ public class Scale9Background extends Background { /** A horizontal or vertical axis, broken up into 3 chunks. */ public static class Axis3 { /** Creates a new axis equally splitting the given length. */ public Axis3 (float length) { float d = length / 3; _lengths = new float[] {d, length - 2 * d, d}; _offsets = new float[] {0, _lengths[0], _lengths[0] + _lengths[1]}; } /** Creates a new axis with the given total length and 0th and 2nd lengths copied from a * source axis. */ public Axis3 (float length, Axis3 src) { _lengths = new float[] {src.size(0), length - src.size(0) - src.size(2), src.size(2)}; _offsets = new float[] {0, _lengths[0], _lengths[0] + _lengths[1]}; } /** Returns the coordinate of the given chunk, 0 - 2. */ public float coord (int idx) { return _offsets[idx]; } /** Returns the size of the given chunk, 0 - 2. */ public float size (int idx) { return _lengths[idx]; } /** Sets the size and location of the given chunk, 0 - 2. */ public Axis3 set (int idx, float coord, float size) { _offsets[idx] = coord; _lengths[idx] = size; return this; } /** Sets the size of the given chunk, shifting neighbors. */ public Axis3 resize (int idx, float size) { float excess = _lengths[idx] - size; _lengths[idx] = size; switch (idx) { case 0: _offsets[1] -= excess; _lengths[1] += excess; break; case 1: float half = excess * .5f; _lengths[0] += half; _lengths[2] += half; _offsets[1] += half; _offsets[2] -= half; break; case 2: _offsets[2] -= excess; _lengths[1] += excess; break; } return this; } /** The positions of the 3 chunks. */ protected final float[] _offsets; /** The lengths of the 3 chunks. */ protected final float[] _lengths; } /** * Will ensure that the Axis3 passed in does not exceed the length given. An equal chunk will * be removed from the outer chunks if it is too long. The given Axis3 is modified and returned. */ public static Axis3 clamp (Axis3 axis, float length) { float left = axis.size(0); float middle = axis.size(1); float right = axis.size(2); if (left + middle + right > length && middle > 0 && left + right < length) { // the special case where for some reason the total is too wide, but the middle is non // zero, and it can absorb the extra all on its own. axis.set(1, left, length - left - right); axis.set(2, length - right, right); } else if (left + right > length) { // eat equal chunks out of each end so that we don't end up overlapping float remove = (left + right - length) / 2; axis.set(0, 0, left - remove); axis.set(1, left - remove, 0); axis.set(2, left - remove, right - remove); } return axis; } /** The axes of our source image. */ public final Axis3 xaxis, yaxis; /** Creates a new background using the given image. The subdivision of the image into a 3x3 * grid is automatic. * * <p>NOTE: the image must be preloaded since we need to determine the stretching factor. * If this cannot be arranged using the application resource strategy, callers may consider * setting the background style from the images callback.</p> */ public Scale9Background (Image image) { if (!image.isReady()) { // complain about this, we don't support asynch images PlayN.log().warn("Scale9 image not preloaded: " + image); } _image = image; xaxis = new Axis3(image.width()); yaxis = new Axis3(image.height()); } @Override protected Instance instantiate (final IDimension size) { return new LayerInstance(size, new ImmediateLayer.Renderer() { // The axes of our destination surface. Axis3 dx = clamp(new Axis3(size.width(), xaxis), size.width()); Axis3 dy = clamp(new Axis3(size.height(), yaxis), size.height()); public void render (Surface surf) { surf.save(); if (alpha != null) surf.setAlpha(alpha); if (_tint != Tint.NOOP_TINT) surf.setTint(_tint); // issue the 9 draw calls for (int yy = 0; yy < 3; ++yy) for (int xx = 0; xx < 3; ++xx) { drawPart(surf, xx, yy); } if (alpha != null) surf.setAlpha(1); // alpha is not part of save/restore surf.restore(); } protected void drawPart (Surface surf, int x, int y) { if (dx.size(x) ==0 || dy.size(y) == 0) return; surf.drawImage(_image, dx.coord(x), dy.coord(y), dx.size(x), dy.size(y), xaxis.coord(x), yaxis.coord(y), xaxis.size(x), yaxis.size(y)); } }); } /** * Sets the tint for this background, as {@code ARGB}. * * <p> <em>NOTE:</em> this will overwrite any value configured via {@link #alpha}. Either * include your desired alpha in the high bits of {@code tint} or set {@link #alpha} after * calling this method. </p> * * <p> <em>NOTE:</em> the RGB components of a layer's tint only work on GL-based backends. It is * not possible to tint layers using the HTML5 canvas and Flash backends. </p> */ public Scale9Background setTint (int tint) { _tint = tint; this.alpha = ((tint >> 24) & 0xFF) / 255f; return this; } protected Image _image; protected int _tint = Tint.NOOP_TINT; }
package boilerplate.steamapi.item; import java.util.ArrayList; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; import net.minecraft.world.World; /** * @author warlordjones * */ public interface IArmorModule { // 0 is helmet, 1 is plate, 2 is legs and 3 is boots. Return -1 for any piece public int getApplicablePiece(); //Localized Name public String getName(); //Unlocalized Name public String getModuleId(); //The Effect this module has public boolean applyArmorEffect(World world, EntityPlayer player, ItemStack stack); //The type of effect (see below) public EnumArmorEffectType getArmorEffectType(); //NYI public ArrayList<IArmorModule> getListOfIncompatibleModules(); public static enum EnumArmorEffectType { ONTICK, /*DEFENSIVE,*/ HUD } /** Whenever applyArmorEffect returns true, this amount of steam will be consumed from canisters in the player's inventory. * The effect will not be run if the player does not have enough steam. */ public int getSteamConsumedOnEffect(); //NYI public int getEnergyConsumedOnEffect(); }
package br.com.entelgy.selenium; import io.github.bonigarcia.wdm.ChromeDriverManager; import io.github.bonigarcia.wdm.PhantomJsDriverManager; import org.openqa.selenium.Dimension; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.firefox.FirefoxDriver; import org.openqa.selenium.firefox.FirefoxProfile; import org.openqa.selenium.phantomjs.PhantomJSDriver; import org.openqa.selenium.phantomjs.PhantomJSDriverService; import org.openqa.selenium.remote.CapabilityType; import org.openqa.selenium.remote.DesiredCapabilities; import java.util.ArrayList; import java.util.concurrent.TimeUnit; public class SeleniumDriver { private static WebDriver driver; private static final long TIMEOUT = 20; private static final long TIMEOUT_PAGE_LOAD = 60; @Deprecated public static WebDriver getInstance() { return getInstance(DriverEnum.FIREFOX, null); } /** * Use getDriver(DriverEnum driverEnum) for automatically resolves binary driver path * @param driverEnum * @param driverPath * @return */ @Deprecated public static WebDriver getInstance(DriverEnum driverEnum, String driverPath) { if (driver == null) { switch (driverEnum) { case CHROME: driver = createChromeDriver(driverPath); break; case FIREFOX: driver = createFireFoxDriver(); break; case PHANTOMJS: default: driver = createPhantomJSDriver(driverPath); break; } driver.manage().timeouts().implicitlyWait(TIMEOUT, TimeUnit.SECONDS); driver.manage().timeouts().pageLoadTimeout(TIMEOUT_PAGE_LOAD, TimeUnit.SECONDS); driver.manage().window().setSize(new Dimension(1200, 800)); } return driver; } public static WebDriver getDriver(DriverEnum driverEnum) { if (driver == null) { switch (driverEnum) { case CHROME: ChromeDriverManager.getInstance().setup(); driver = new ChromeDriver(); break; case FIREFOX: driver = new FirefoxDriver(); break; case PHANTOMJS: default: PhantomJsDriverManager.getInstance().setup(); driver = new PhantomJSDriver(); break; } driver.manage().timeouts().implicitlyWait(TIMEOUT, TimeUnit.SECONDS); driver.manage().timeouts().pageLoadTimeout(TIMEOUT_PAGE_LOAD, TimeUnit.SECONDS); driver.manage().window().setSize(new Dimension(1200, 800)); } return driver; } private static WebDriver createChromeDriver(String driverPath) { System.setProperty("webdriver.chrome.driver", driverPath); return new ChromeDriver(); } private static WebDriver createFireFoxDriver() { FirefoxProfile firefoxProfile = new FirefoxProfile(); firefoxProfile.setEnableNativeEvents(false); firefoxProfile.setAcceptUntrustedCertificates(true); firefoxProfile.setPreference("layers.acceleration.disabled", true); DesiredCapabilities desiredCapabilities = DesiredCapabilities.firefox(); desiredCapabilities.setCapability(FirefoxDriver.PROFILE, firefoxProfile); return new FirefoxDriver(desiredCapabilities); } private static WebDriver createPhantomJSDriver(String driverPath) { DesiredCapabilities desiredCapabilities = DesiredCapabilities.phantomjs(); desiredCapabilities.setCapability(PhantomJSDriverService.PHANTOMJS_EXECUTABLE_PATH_PROPERTY, driverPath); desiredCapabilities.setCapability(CapabilityType.ELEMENT_SCROLL_BEHAVIOR, true); desiredCapabilities.setCapability(CapabilityType.TAKES_SCREENSHOT, true); desiredCapabilities.setCapability(CapabilityType.ENABLE_PROFILING_CAPABILITY, true); desiredCapabilities.setCapability(CapabilityType.HAS_NATIVE_EVENTS, true); desiredCapabilities.setJavascriptEnabled(true); ArrayList<String> cliArgs = new ArrayList<String>(); cliArgs.add("--web-security=true"); cliArgs.add("--ignore-ssl-errors=true"); desiredCapabilities.setCapability(PhantomJSDriverService.PHANTOMJS_CLI_ARGS, cliArgs); return new PhantomJSDriver(desiredCapabilities); } }
package ch.tkuhn.nanopub.monitor; import java.io.InputStream; import java.util.Random; import net.trustyuri.TrustyUriUtils; import org.apache.commons.lang.time.StopWatch; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.config.RequestConfig; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.wicket.util.thread.ICode; import org.apache.wicket.util.thread.Task; import org.apache.wicket.util.time.Duration; import org.nanopub.Nanopub; import org.nanopub.NanopubImpl; import org.nanopub.extra.server.NanopubServerUtils; import org.nanopub.extra.server.ServerInfo; import org.nanopub.trusty.TrustyNanopubUtils; import org.openrdf.rio.RDFFormat; import org.slf4j.Logger; public class ServerScanner implements ICode { private static ServerScanner singleton; private static Random random = new Random(); private Logger logger; public static void initDaemon() { if (singleton != null) return; Task scanTask = new Task("server-scanner"); scanTask.setDaemon(true); singleton = new ServerScanner(); scanTask.run(Duration.seconds(MonitorConf.get().getScanFreq()), singleton); } private ServerScanner() { } @Override public void run(Logger logger) { this.logger = logger; logger.info("Scan servers..."); ServerList.get().refresh(); testServers(); } private void testServers() { RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(10 * 1000).build(); HttpClient c = HttpClientBuilder.create().setDefaultRequestConfig(requestConfig).build(); for (ServerData d : ServerList.get().getServerData()) { logger.info("Testing server " + d.getServerInfo().getPublicUrl() + "..."); ServerInfo i = d.getServerInfo(); if (i.getNextNanopubNo() == 0) continue; try { long npNo = (long) (random.nextDouble() * (i.getNextNanopubNo())); logger.info("Trying to retrieve nanopub number " + npNo); int pageNo = (int) (npNo / i.getPageSize()) + 1; int rowNo = (int) (npNo % i.getPageSize()); int r = 0; for (String nanopubUri : NanopubServerUtils.loadNanopubUriList(i, pageNo)) { if (rowNo < r) { r++; continue; } String ac = TrustyUriUtils.getArtifactCode(nanopubUri); HttpGet get = new HttpGet(i.getPublicUrl() + ac); get.setHeader("Accept", "application/trig"); StopWatch watch = new StopWatch(); watch.start(); HttpResponse resp = c.execute(get); watch.stop(); if (!wasSuccessful(resp)) { logger.info("Test failed. HTTP code " + resp.getStatusLine().getStatusCode()); d.reportTestFailure("INACCESSIBLE"); } else { InputStream in = resp.getEntity().getContent(); Nanopub np = new NanopubImpl(in, RDFFormat.TRIG); if (TrustyNanopubUtils.isValidTrustyNanopub(np)) { d.reportTestSuccess(watch.getTime()); } else { logger.info("Test failed. Not a trusty nanopub: " + np.getUri()); d.reportTestFailure("BROKEN"); } } break; } } catch (Exception ex) { ex.printStackTrace(); d.reportTestFailure("INACCESSIBLE"); } } } private boolean wasSuccessful(HttpResponse resp) { int c = resp.getStatusLine().getStatusCode(); return c >= 200 && c < 300; } }
package ch.tkuhn.nanopub.monitor; import java.io.InputStream; import java.time.Duration; import java.util.Random; import net.trustyuri.TrustyUriUtils; import org.apache.commons.lang.time.StopWatch; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.config.RequestConfig; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.wicket.util.thread.ICode; import org.apache.wicket.util.thread.Task; import org.nanopub.Nanopub; import org.nanopub.NanopubImpl; import org.nanopub.extra.server.NanopubServerUtils; import org.nanopub.extra.server.ServerInfo; import org.nanopub.trusty.TrustyNanopubUtils; import org.eclipse.rdf4j.rio.RDFFormat; import org.slf4j.Logger; public class ServerScanner implements ICode { private static ServerScanner singleton; private static Task scanTask; private static Random random = new Random(); public static void initDaemon() { if (singleton != null) { if (singleton.aliveAtTime + 10 * 60 * 1000 < System.currentTimeMillis()) { singleton.logger.info("No sign of life of the daemon for 10 minutes. Starting new one."); singleton = null; scanTask.interrupt(); } else { return; } } scanTask = new Task("server-scanner"); scanTask.setDaemon(true); singleton = new ServerScanner(); scanTask.run(Duration.ofSeconds(MonitorConf.get().getScanFreq()), singleton); } private Logger logger; private long aliveAtTime; private ServerScanner() { stillAlive(); } @Override public void run(Logger logger) { this.logger = logger; logger.info("Scan servers..."); ServerList.get().refresh(); stillAlive(); testServers(); } private void testServers() { RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(10 * 1000).build(); HttpClient c = HttpClientBuilder.create().setDefaultRequestConfig(requestConfig).build(); for (ServerData d : ServerList.get().getServerData()) { logger.info("Testing server " + d.getServiceId() + "..."); stillAlive(); if (d.getServerInfo() instanceof ServerInfo) { ServerInfo i = (ServerInfo) d.getServerInfo(); if (i.getNextNanopubNo() == 0) continue; try { long npNo = (long) (random.nextDouble() * (i.getNextNanopubNo())); logger.info("Trying to retrieve nanopub number " + npNo); int pageNo = (int) (npNo / i.getPageSize()) + 1; int rowNo = (int) (npNo % i.getPageSize()); int r = 0; for (String nanopubUri : NanopubServerUtils.loadNanopubUriList(i, pageNo)) { if (rowNo < r) { r++; continue; } String ac = TrustyUriUtils.getArtifactCode(nanopubUri); HttpGet get = new HttpGet(i.getPublicUrl() + ac); get.setHeader("Accept", "application/trig"); StopWatch watch = new StopWatch(); watch.start(); HttpResponse resp = c.execute(get); watch.stop(); if (!wasSuccessful(resp)) { logger.info("Test failed. HTTP code " + resp.getStatusLine().getStatusCode()); d.reportTestFailure("DOWN"); } else { InputStream in = resp.getEntity().getContent(); Nanopub np = new NanopubImpl(in, RDFFormat.TRIG); if (TrustyNanopubUtils.isValidTrustyNanopub(np)) { d.reportTestSuccess(watch.getTime()); } else { logger.info("Test failed. Not a trusty nanopub: " + np.getUri()); d.reportTestFailure("BROKEN"); } } break; } } catch (Exception ex) { ex.printStackTrace(); d.reportTestFailure("INACCESSIBLE"); } } else { logger.info("Trying to access " + d.getServiceId() + "..."); try { HttpGet get = new HttpGet(d.getServiceId()); StopWatch watch = new StopWatch(); watch.start(); HttpResponse resp = c.execute(get); watch.stop(); if (!wasSuccessful(resp)) { logger.info("Test failed. HTTP code " + resp.getStatusLine().getStatusCode()); d.reportTestFailure("DOWN"); } else { d.reportTestSuccess(watch.getTime()); } } catch (Exception ex) { ex.printStackTrace(); d.reportTestFailure("INACCESSIBLE"); } } } } private boolean wasSuccessful(HttpResponse resp) { int c = resp.getStatusLine().getStatusCode(); return c >= 200 && c < 300; } private void stillAlive() { aliveAtTime = System.currentTimeMillis(); } }
package co.uniandes.KM.logicPuzzles.UI; import java.awt.BorderLayout; import java.awt.ComponentOrientation; import java.awt.Dimension; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.TextArea; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.ArrayList; import javax.swing.BorderFactory; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.SwingConstants; import javax.swing.border.BevelBorder; import com.sun.org.apache.bcel.internal.generic.DMUL; import co.uniandes.KM.logicPuzzles.Configuration; import co.uniandes.KM.logicPuzzles.mundo.LogicDimension; import co.uniandes.KM.logicPuzzles.mundo.LogicPuzzle; public class Tablero extends JFrame implements ActionListener { /** * Generated serial version ID */ private static final long serialVersionUID = 96492363195714367L; private static final int LABEL_TITLE_SIZE = 1; private JLabel nombreHorizontal, nombreVertical; private JButton fila1A, fila2A, fila3A, fila4A, fila1B, fila2B, fila3B, fila4B, fila1C, fila2C, fila3C, fila4C; private LogicPuzzle logicPuzzle; private JPanel board; private JPanel factList; public Tablero() { DimensionDataInput dDI = new DimensionDataInput(this); dDI.setVisible(true); } /** * @param dimensions */ public void initialize(LogicDimension[] dimensions) { this.logicPuzzle = new LogicPuzzle(dimensions); BorderLayout borderLayout = new BorderLayout(); setLayout(borderLayout); board = new JPanel(); board.setLayout(null); factList = new JPanel(); factList.setLayout(null); TextArea txt = new TextArea("adsf"); txt.setSize(50, 300); factList.add(txt); factList.setSize(50, 300); // int posX = 30; // String[] etiquetas = new String[Configuration.DIMENSION_AMOUNT*Configuration.ITEM_PER_DIMENSION_AMOUNT]; // for (int i = 0; i < dimensions.length; i++) { // LogicDimension currentDimension = dimensions[i]; // String[] currentDimensionItems = currentDimension.getItems(); // for (int j = 0; j < currentDimensionItems.length; j++) { // etiquetas[i*currentDimensionItems.length + j] =currentDimensionItems[j]; // String botones[] = { "a1", "a2", "a3", "a4", "a5", "a6", "a7", "a8", "a9", "a10", "a11", "a12", "a13", "a14", "a15", "a16" }; // JButton filas[] = { fila1A, fila2A, fila3A, fila4A, fila1B, fila2B, fila3B, fila4B, fila1C, fila2C, fila3C, fila4C }; // /* para construir cuadrante a */ // for (int ia = 0; ia < 4; ia++) { // nombreHorizontal = new JLabel(etiquetas[ia]); // nombreHorizontal.setBounds(25 + posX, 20, 200, 30); // board.add(nombreHorizontal); // nombreVertical = new JLabel(etiquetas[ia + 8]); // nombreVertical.setBounds(10, posX + 25, 200, 30); // board.add(nombreVertical); // for (int ja = 0; ja < 4; ja++) { // filas[ja] = new JButton(botones[ia]); // filas[ja].setBounds(posX, 50 + (50 * ja), 50, 50); // board.add(filas[ja]); // posX += 50; // /* para construir cuadrante b */ // for (int ib = 4; ib < 8; ib++) { // nombreHorizontal = new JLabel(etiquetas[ib]); // nombreHorizontal.setBounds(posX + 35, 20, 200, 30); // board.add(nombreHorizontal); // for (int jb = 4; jb < 8; jb++) { // filas[jb] = new JButton(botones[jb]); // filas[jb].setBounds(posX + 10, (50 * (jb - 3)), 50, 50); // board.add(filas[jb]); // posX += 50; // /* para construir cuadrante c */ // for (int ic = 8; ic < 12; ic++) { // nombreHorizontal = new JLabel(etiquetas[ic - 4]); // nombreHorizontal.setBounds(10, posX - 160, 200, 30); // board.add(nombreHorizontal); // for (int jc = 8; jc < 12; jc++) { // filas[jc] = new JButton(botones[jc]); // filas[jc].setBounds(posX - 400, 10 + (50 * (jc - 3)), 50, 50); // board.add(filas[jc]); // posX += 50; // add(board,BorderLayout.CENTER); // //add(factList,FlowLayout.LEFT); add(createBoard(dimensions)); setBounds(10, 10, 960, 580); setVisible(true); setResizable(true); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } private JPanel createBoard(LogicDimension[] dimensions){ GridBagLayout gBL = new GridBagLayout(); JPanel board = new JPanel(); board.setComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT); board.setLayout(gBL); GridBagConstraints singleCellConstraint = new GridBagConstraints(); singleCellConstraint.gridheight = 1; singleCellConstraint.gridwidth = 1; singleCellConstraint.ipadx = 15; singleCellConstraint.ipady = 15 ; singleCellConstraint.fill = GridBagConstraints.BOTH; GridBagConstraints dimensionHorizontalLabel = new GridBagConstraints(); dimensionHorizontalLabel.gridwidth = Configuration.ITEM_PER_DIMENSION_AMOUNT; dimensionHorizontalLabel.gridheight = LABEL_TITLE_SIZE; GridBagConstraints dimensionVerticalLabel = new GridBagConstraints(); dimensionVerticalLabel.gridwidth = LABEL_TITLE_SIZE; dimensionVerticalLabel.gridheight = Configuration.ITEM_PER_DIMENSION_AMOUNT; // Drawing help int horizontalThreshold = Configuration.DIMENSION_AMOUNT - 1; int currentRow = 0; int currentColumn = 0; boolean[][] haveIAlreadyDrawnThisParticularSide = new boolean[Configuration.DIMENSION_AMOUNT][Configuration.DIMENSION_AMOUNT]; LogicDimension currentDimension; String[] currentItems; RotatedLabel dimensionLabel; // Safety all-false initialization of boolean matrix because reasons for (int i = 0; i < haveIAlreadyDrawnThisParticularSide.length; i++) { for (int j = 0; j < haveIAlreadyDrawnThisParticularSide.length; j++) { haveIAlreadyDrawnThisParticularSide[i][j] = false; } } for (int i = 0; i < dimensions.length; i++) { if( (currentColumn + 1) > horizontalThreshold ) { horizontalThreshold currentRow++; currentColumn = 0; } int xOffset = currentColumn * Configuration.ITEM_PER_DIMENSION_AMOUNT; int yOffset = currentRow * Configuration.ITEM_PER_DIMENSION_AMOUNT; //I only need to draw the labels when either currentRow or currentColumn is 0 if(currentRow == 0 && currentColumn == 0) { currentDimension = dimensions[i]; currentItems = currentDimension.getItems(); dimensionLabel = new RotatedLabel(currentDimension.getName()); //Upwards title label dimensionHorizontalLabel.gridx = xOffset + LABEL_TITLE_SIZE *2; dimensionHorizontalLabel.gridy = yOffset; board.add(dimensionLabel, dimensionHorizontalLabel); //Upwards item title labels for (int j = 0; j < currentItems.length; j++) { RotatedLabel itemTitleLabel = new RotatedLabel(currentItems[j]); itemTitleLabel.setHorizontalAlignment(SwingConstants.LEFT); itemTitleLabel.setDirection(RotatedLabel.Direction.VERTICAL_UP); singleCellConstraint.gridx = xOffset + LABEL_TITLE_SIZE + j + 1; singleCellConstraint.gridy = yOffset + LABEL_TITLE_SIZE ; singleCellConstraint.ipady = 45; board.add(itemTitleLabel,singleCellConstraint); singleCellConstraint.ipady = 15; } currentDimension = dimensions[i+1]; currentItems = currentDimension.getItems(); dimensionLabel = new RotatedLabel(currentDimension.getName()); dimensionVerticalLabel.gridx = currentColumn + xOffset; dimensionVerticalLabel.gridy = currentRow + 2; dimensionVerticalLabel.ipady = 60; dimensionLabel.setHorizontalAlignment(SwingConstants.CENTER); dimensionLabel.setDirection(RotatedLabel.Direction.VERTICAL_UP); board.add(dimensionLabel, dimensionVerticalLabel); //Item title labels for (int j = 0; j < currentItems.length; j++) { JLabel itemTitleLabel = new JLabel(currentItems[j]); itemTitleLabel.setHorizontalAlignment(SwingConstants.RIGHT); singleCellConstraint.gridx = xOffset + LABEL_TITLE_SIZE; singleCellConstraint.gridy = yOffset + LABEL_TITLE_SIZE + j + 1 ; board.add(itemTitleLabel,singleCellConstraint); } } else if(currentRow == 0) { currentDimension = dimensions[dimensions.length-1]; currentItems = currentDimension.getItems(); dimensionLabel = new RotatedLabel(currentDimension.getName()); //Dimension title label dimensionHorizontalLabel.gridx = xOffset + LABEL_TITLE_SIZE *2; dimensionHorizontalLabel.gridy = yOffset; board.add(dimensionLabel, dimensionHorizontalLabel); //Item title labels for (int j = 0; j < currentItems.length; j++) { RotatedLabel itemTitleLabel = new RotatedLabel(currentItems[j]); itemTitleLabel.setHorizontalAlignment(SwingConstants.LEFT); itemTitleLabel.setDirection(RotatedLabel.Direction.VERTICAL_UP); singleCellConstraint.gridx = xOffset + LABEL_TITLE_SIZE + j + 1; singleCellConstraint.gridy = yOffset + LABEL_TITLE_SIZE ; singleCellConstraint.ipady = 45; board.add(itemTitleLabel,singleCellConstraint); singleCellConstraint.ipady = 15; } } else if (currentColumn == 0) { currentDimension = dimensions[dimensions.length-1]; currentItems = currentDimension.getItems(); dimensionLabel = new RotatedLabel(currentDimension.getName()); dimensionVerticalLabel.gridx = currentColumn + xOffset; dimensionVerticalLabel.gridy = currentRow + yOffset ; dimensionVerticalLabel.ipady = 60; dimensionLabel.setHorizontalAlignment(SwingConstants.LEFT); dimensionLabel.setDirection(RotatedLabel.Direction.VERTICAL_UP); board.add(dimensionLabel, dimensionVerticalLabel); //Item title labels for (int j = 0; j < currentItems.length; j++) { JLabel itemTitleLabel = new JLabel(currentItems[j]); itemTitleLabel.setHorizontalAlignment(SwingConstants.RIGHT); singleCellConstraint.gridx = xOffset + LABEL_TITLE_SIZE; singleCellConstraint.gridy = yOffset + LABEL_TITLE_SIZE + j + 1 ; board.add(itemTitleLabel,singleCellConstraint); } } // If i haven't already drawn this particular side, then i should draw it if(!haveIAlreadyDrawnThisParticularSide[currentColumn][currentRow]) { for (int j = 0; j < Configuration.ITEM_PER_DIMENSION_AMOUNT; j++) { for (int k = 0; k < Configuration.ITEM_PER_DIMENSION_AMOUNT; k++) { JLabel cellLabel = new JLabel("?"); cellLabel.setHorizontalAlignment(SwingConstants.CENTER); // The x position is 'j' plus the amount of items already drawn plus the space for both the dimension and items labels. // ditto for the y position singleCellConstraint.gridx = j + xOffset + LABEL_TITLE_SIZE*2; singleCellConstraint.gridy = k + yOffset + LABEL_TITLE_SIZE*2; board.add(cellLabel,singleCellConstraint); } } haveIAlreadyDrawnThisParticularSide[currentColumn][currentRow] = true; } currentColumn++; } board.setPreferredSize(new Dimension(500,500)); board.setSize(new Dimension(500,500)); return board; } @Override public void actionPerformed(ActionEvent e) { // TODO Auto-generated method stub } public LogicPuzzle getLogicPuzzle() { return logicPuzzle; } public void setLogicPuzzle(LogicPuzzle logicPuzzle) { this.logicPuzzle = logicPuzzle; } }
package com.akiban.server.api; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingDeque; import java.util.concurrent.atomic.AtomicLong; import com.akiban.ais.model.Column; import com.akiban.ais.model.HKey; import com.akiban.ais.model.HKeyColumn; import com.akiban.ais.model.HKeySegment; import com.akiban.ais.model.Index; import com.akiban.ais.model.IndexColumn; import com.akiban.ais.model.Join; import com.akiban.ais.model.Table; import com.akiban.ais.model.UserTable; import com.akiban.server.AkServerUtil; import com.akiban.server.IndexDef; import com.akiban.server.InvalidOperationException; import com.akiban.server.RowData; import com.akiban.server.RowDef; import com.akiban.server.TableStatistics; import com.akiban.server.api.common.NoSuchTableException; import com.akiban.server.api.dml.*; import com.akiban.server.api.dml.scan.BufferFullException; import com.akiban.server.api.dml.scan.ColumnSet; import com.akiban.server.api.dml.scan.ConcurrentScanAndUpdateException; import com.akiban.server.api.dml.scan.Cursor; import com.akiban.server.api.dml.scan.CursorId; import com.akiban.server.api.dml.scan.CursorIsFinishedException; import com.akiban.server.api.dml.scan.CursorIsUnknownException; import com.akiban.server.api.dml.scan.CursorState; import com.akiban.server.api.dml.scan.LegacyOutputConverter; import com.akiban.server.api.dml.scan.BufferedLegacyOutputRouter; import com.akiban.server.api.dml.scan.LegacyRowOutput; import com.akiban.server.api.dml.scan.LegacyRowWrapper; import com.akiban.server.api.dml.scan.NewRow; import com.akiban.server.api.dml.scan.NiceRow; import com.akiban.server.api.dml.scan.RowDataLegacyOutputRouter; import com.akiban.server.api.dml.scan.RowOutput; import com.akiban.server.api.dml.scan.RowOutputException; import com.akiban.server.api.dml.scan.ScanAllRequest; import com.akiban.server.api.dml.scan.ScanLimit; import com.akiban.server.api.dml.scan.ScanRequest; import com.akiban.server.encoding.EncodingException; import com.akiban.server.service.session.Session; import com.akiban.server.store.RowCollector; import com.akiban.server.util.RowDefNotFoundException; import com.akiban.util.ArgumentValidation; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class DMLFunctionsImpl extends ClientAPIBase implements DMLFunctions { private static final ColumnSelector ALL_COLUMNS_SELECTOR = new ColumnSelector() { @Override public boolean includesColumn(int columnPosition) { return true; } }; private static final Class<?> MODULE_NAME = DMLFunctionsImpl.class; private static final AtomicLong cursorsCount = new AtomicLong(); private static final String OPEN_CURSORS_MAP = "OPEN_CURSORS_MAP"; private final static Logger logger = LoggerFactory.getLogger(DMLFunctionsImpl.class); private final DDLFunctions ddlFunctions; private final Scanner scanner; public DMLFunctionsImpl(DDLFunctions ddlFunctions) { this(ddlFunctions, NONE); } DMLFunctionsImpl(DDLFunctions ddlFunctions, ScanHooks scanHooks) { this.ddlFunctions = ddlFunctions; this.scanner = new Scanner(scanHooks); } interface ScanHooks { void loopStartHook(); void preWroteRowHook(); } private static final ScanHooks NONE = new ScanHooks() { @Override public void loopStartHook() { } @Override public void preWroteRowHook() { } }; @Override public TableStatistics getTableStatistics(Session session, int tableId, boolean updateFirst) throws NoSuchTableException, GenericInvalidOperationException { logger.trace("stats for {} updating: {}", tableId, updateFirst); try { if (updateFirst) { store().analyzeTable(session, tableId); } return store().getTableStatistics(session, tableId); } catch (Exception e) { InvalidOperationException ioe = launder(e); throwIfInstanceOf(NoSuchTableException.class, ioe); throw new GenericInvalidOperationException(e); } } private static final class ScanData { private final Cursor cursor; private final byte[] scanColumns; private final boolean scanAll; private Set<Integer> scanColumnsUnpacked; ScanData(ScanRequest request, Cursor cursor) { scanColumns = request.getColumnBitMap(); scanAll = request.scanAllColumns(); this.cursor = cursor; } public Set<Integer> getScanColumns() { if (scanColumnsUnpacked == null) { scanColumnsUnpacked = ColumnSet.unpackFromLegacy(scanColumns); } return scanColumnsUnpacked; } public Cursor getCursor() { return cursor; } public boolean scanAll() { return scanAll; } @Override public String toString() { return String.format("ScanData[cursor=%s, columns=%s]", cursor, getScanColumns()); } } @Override public CursorId openCursor(Session session, ScanRequest request) throws NoSuchTableException, NoSuchColumnException, NoSuchIndexException, GenericInvalidOperationException { logger.trace("opening scan: {} -> {}", System.identityHashCode(request), request); if (request.scanAllColumns()) { request = scanAllColumns(session, request); } final RowCollector rc = getRowCollector(session, request); final CursorId cursorId = newUniqueCursor(rc.getTableId()); final Cursor cursor = new Cursor(rc, request.getScanLimit()); Object old = session.put(MODULE_NAME, cursorId, new ScanData(request, cursor)); assert old == null : old; Map<CursorId,Cursor> cursors = session.get(MODULE_NAME, OPEN_CURSORS_MAP); if (cursors == null) { cursors = new HashMap<CursorId,Cursor>(); session.put(MODULE_NAME, OPEN_CURSORS_MAP, cursors); } Cursor oldCursor = cursors.put(cursorId, cursor); assert oldCursor == null : String.format("%s -> %s conflicted with %s", cursor, cursors, oldCursor); logger.trace("cursor for scan: {} -> {}", System.identityHashCode(request), cursorId); return cursorId; } private ScanRequest scanAllColumns(final Session session, final ScanRequest request) throws NoSuchTableException { Table table = ddlFunctions.getAIS(session).getTable( ddlFunctions.getTableName(session, request.getTableId()) ); final int colsCount = table.getColumns().size(); Set<Integer> allColumns = new HashSet<Integer>(colsCount); for (int i = 0; i < colsCount; ++i) { allColumns.add(i); } final byte[] allColumnsBytes = ColumnSet.packToLegacy(allColumns); return new ScanRequest() { @Override public int getIndexId() { return request.getIndexId(); } @Override public int getScanFlags() { return request.getScanFlags(); } @Override public RowData getStart() throws NoSuchTableException { return request.getStart(); } @Override public RowData getEnd() throws NoSuchTableException { return request.getEnd(); } @Override public byte[] getColumnBitMap() { return allColumnsBytes; } @Override public int getTableId() throws NoSuchTableException { return request.getTableId(); } @Override public ScanLimit getScanLimit() { return ScanLimit.NONE; } @Override public boolean scanAllColumns() { return true; } }; } protected RowCollector getRowCollector(Session session, ScanRequest request) throws NoSuchTableException, NoSuchColumnException, NoSuchIndexException, GenericInvalidOperationException { try { return store().newRowCollector(session, request.getTableId(), request.getIndexId(), request.getScanFlags(), request.getStart(), request.getEnd(), request.getColumnBitMap()); } catch (RowDefNotFoundException e) { throw new NoSuchTableException(request.getTableId(), e); } catch (Exception e) { throw new GenericInvalidOperationException(e); } } protected CursorId newUniqueCursor(int tableId) { return new CursorId(cursorsCount.incrementAndGet(), tableId); } @Override public CursorState getCursorState(Session session, CursorId cursorId) { final ScanData extraData = session.get(MODULE_NAME, cursorId); if (extraData == null || extraData.getCursor() == null) { return CursorState.UNKNOWN_CURSOR; } return extraData.getCursor().getState(); } @Override public boolean scanSome(Session session, CursorId cursorId, LegacyRowOutput output) throws CursorIsFinishedException, CursorIsUnknownException, RowOutputException, BufferFullException, ConcurrentScanAndUpdateException, GenericInvalidOperationException { logger.trace("scanning from {}", cursorId); ArgumentValidation.notNull("cursor", cursorId); ArgumentValidation.notNull("output", output); final Cursor cursor = session.<ScanData> get(MODULE_NAME, cursorId).getCursor(); if (cursor == null) { throw new CursorIsUnknownException(cursorId); } if (CursorState.CONCURRENT_MODIFICATION.equals(cursor.getState())) { throw new ConcurrentScanAndUpdateException("for cursor " + cursorId); } if (cursor.isFinished()) { throw new CursorIsFinishedException(cursorId); } return scanner.doScan(cursor, cursorId, output); } private static class PooledConverter { private final LegacyOutputConverter converter; private final BufferedLegacyOutputRouter router; public PooledConverter(DMLFunctions dmlFunctions) { router = new BufferedLegacyOutputRouter(1024 * 1024, true); converter = new LegacyOutputConverter(dmlFunctions); router.addHandler(converter); } public LegacyRowOutput getLegacyOutput() { return router; } public void setConverter(RowOutput output, Set<Integer> columns) throws NoSuchTableException { converter.setOutput(output); converter.setColumnsToScan(columns); } } private final BlockingQueue<PooledConverter> convertersPool = new LinkedBlockingDeque<PooledConverter>(); private PooledConverter getPooledConverter(RowOutput output, Set<Integer> columns) throws NoSuchTableException { PooledConverter converter = convertersPool.poll(); if (converter == null) { logger.debug("Allocating new PooledConverter"); converter = new PooledConverter(this); } try { converter.setConverter(output, columns); } catch (NoSuchTableException e) { releasePooledConverter(converter); throw e; } catch (RuntimeException e) { releasePooledConverter(converter); throw e; } return converter; } private void releasePooledConverter(PooledConverter which) { if (!convertersPool.offer(which)) { logger.warn("Failed to release PooledConverter " + which + " to pool. " + "This could result in superfluous allocations, and may happen because too many pools are being " + "released at the same time."); } } @Override public boolean scanSome(Session session, CursorId cursorId, RowOutput output) throws CursorIsFinishedException, CursorIsUnknownException, RowOutputException, NoSuchTableException, ConcurrentScanAndUpdateException, GenericInvalidOperationException { logger.trace("scanning from {}", cursorId); final ScanData scanData = session.get(MODULE_NAME, cursorId); assert scanData != null; Set<Integer> scanColumns = scanData.scanAll() ? null : scanData.getScanColumns(); final PooledConverter converter = getPooledConverter(output, scanColumns); try { return scanSome(session, cursorId, converter.getLegacyOutput()); } catch (BufferFullException e) { throw new RowOutputException(e); } finally { releasePooledConverter(converter); } } static class Scanner { private final ScanHooks scanHooks; Scanner() { this(NONE); } Scanner(ScanHooks scanHooks) { this.scanHooks = scanHooks; } /** * Do the actual scan. Refactored out of scanSome for ease of unit testing. * * @param cursor * the cursor itself; used to check status and get a row * collector * @param cursorId * the cursor id; used only to report errors * @param output * the output; see * {@link #scanSome(Session, CursorId, LegacyRowOutput)} * @return whether more rows remain to be scanned; see * {@link #scanSome(Session, CursorId, LegacyRowOutput)} * @throws CursorIsFinishedException * see * {@link #scanSome(Session, CursorId, LegacyRowOutput)} * @throws RowOutputException * see * {@link #scanSome(Session, CursorId, LegacyRowOutput)} * @throws GenericInvalidOperationException * see * {@link #scanSome(Session, CursorId, LegacyRowOutput)} * @throws BufferFullException * see * {@link #scanSome(Session, CursorId, LegacyRowOutput)} * @see #scanSome(Session, CursorId, LegacyRowOutput) */ protected boolean doScan(Cursor cursor, CursorId cursorId, LegacyRowOutput output) throws CursorIsFinishedException, RowOutputException, GenericInvalidOperationException, BufferFullException { assert cursor != null; assert cursorId != null; assert output != null; if (cursor.isClosed()) { logger.error("Shouldn't have gotten a closed cursor. id = {} state = {}", cursorId, cursor.getState()); throw new CursorIsFinishedException(cursorId); } final RowCollector rc = cursor.getRowCollector(); final ScanLimit limit = cursor.getLimit(); try { if (!rc.hasMore()) { cursor.setFinished(); return false; } cursor.setScanning(); if (output.getOutputToMessage()) { collectRowsIntoBuffer(cursor, output, limit); } else { collectRows(cursor, output, limit); } return !cursor.isFinished(); } catch (BufferFullException e) { throw e; // Don't want this to be handled as an Exception } catch (Exception e) { cursor.setFinished(); throw new GenericInvalidOperationException(e); } } // Returns true if cursor ran out of rows before reaching the limit, false otherwise. private void collectRowsIntoBuffer(Cursor cursor, LegacyRowOutput output, ScanLimit limit) throws Exception { RowCollector rc = cursor.getRowCollector(); rc.outputToMessage(true); ByteBuffer buffer = output.getOutputBuffer(); if (!buffer.hasArray()) { throw new IllegalArgumentException("buffer must have array"); } boolean limitReached = false; while (!limitReached && !cursor.isFinished()) { scanHooks.loopStartHook(); int bufferLastPos = buffer.position(); if (!rc.collectNextRow(buffer)) { if (rc.hasMore()) { throw new BufferFullException(); } cursor.setFinished(); } else { int bufferPos = buffer.position(); assert bufferPos > bufferLastPos : String.format("false: %d >= %d", bufferPos, bufferLastPos); RowData rowData = getRowData(buffer.array(), bufferLastPos, bufferPos - bufferLastPos); limitReached = limit.limitReached(rowData); scanHooks.preWroteRowHook(); output.wroteRow(limitReached); if (limitReached || !rc.hasMore()) { cursor.setFinished(); } } } } protected RowData getRowData(byte[] bytes, int offset, int length) { RowData rowData = new RowData(bytes, offset, length); rowData.prepareRow(offset); return rowData; } // Returns true if cursor ran out of rows before reaching the limit, false otherwise. private void collectRows(Cursor cursor, LegacyRowOutput output, ScanLimit limit) throws Exception { RowCollector rc = cursor.getRowCollector(); rc.outputToMessage(false); while (!cursor.isFinished()) { scanHooks.loopStartHook(); RowData rowData = rc.collectNextRow(); if (rowData == null || limit.limitReached(rowData)) { cursor.setFinished(); } else { output.addRow(rowData); } } } } @Override public void closeCursor(Session session, CursorId cursorId) throws CursorIsUnknownException { logger.trace("closing cursor {}", cursorId); ArgumentValidation.notNull("cursor ID", cursorId); final ScanData scanData = session.remove(MODULE_NAME, cursorId); if (scanData == null) { throw new CursorIsUnknownException(cursorId); } Map<CursorId,Cursor> cursors = session.get(MODULE_NAME, OPEN_CURSORS_MAP); // cursors should not be null, since the cursor isn't null and creating // it guarantees a Set<Cursor> Cursor removedCursor = cursors.remove(cursorId); removedCursor.getRowCollector().close(); } @Override public Set<CursorId> getCursors(Session session) { Map<CursorId,Cursor> cursors = session.get(MODULE_NAME, OPEN_CURSORS_MAP); if (cursors == null) { return Collections.emptySet(); } return Collections.unmodifiableSet(cursors.keySet()); } @Override public RowData convertNewRow(NewRow row) throws NoSuchTableException { logger.trace("converting to RowData: {}", row); return row.toRowData(); } @Override public NewRow convertRowData(RowData rowData) throws NoSuchTableException { logger.trace("converting to NewRow: {}", rowData); RowDef rowDef = ddlFunctions.getRowDef(rowData.getRowDefId()); return NiceRow.fromRowData(rowData, rowDef); } @Override public List<NewRow> convertRowDatas(List<RowData> rowDatas) throws NoSuchTableException { logger.trace("converting {} RowData(s) to NewRow", rowDatas.size()); if (rowDatas.isEmpty()) { return Collections.emptyList(); } List<NewRow> converted = new ArrayList<NewRow>(rowDatas.size()); int lastRowDefId = -1; RowDef rowDef = null; for (RowData rowData : rowDatas) { int currRowDefId = rowData.getRowDefId(); if ((rowDef == null) || (currRowDefId != lastRowDefId)) { lastRowDefId = currRowDefId; rowDef = ddlFunctions.getRowDef(currRowDefId); } converted.add(NiceRow.fromRowData(rowData, rowDef)); } return converted; } @Override public Long writeRow(Session session, NewRow row) throws NoSuchTableException, UnsupportedModificationException, TableDefinitionMismatchException, DuplicateKeyException, GenericInvalidOperationException { logger.trace("writing a row"); final RowData rowData = niceRowToRowData(row); try { store().writeRow(session, rowData); return null; } catch (Exception e) { InvalidOperationException ioe = launder(e); throwIfInstanceOf(DuplicateKeyException.class, ioe); throw new GenericInvalidOperationException(e); } } @Override public void deleteRow(Session session, NewRow row) throws NoSuchTableException, UnsupportedModificationException, ForeignKeyConstraintDMLException, NoSuchRowException, TableDefinitionMismatchException, GenericInvalidOperationException { logger.trace("deleting a row"); final RowData rowData = niceRowToRowData(row); try { store().deleteRow(session, rowData); } catch (Exception e) { InvalidOperationException ioe = launder(e); throwIfInstanceOf(NoSuchRowException.class, ioe); throw new GenericInvalidOperationException(e); } } private RowData niceRowToRowData(NewRow row) throws NoSuchTableException, TableDefinitionMismatchException { try { return row.toRowData(); } catch (EncodingException e) { throw new TableDefinitionMismatchException(e); } } @Override public void updateRow(Session session, NewRow oldRow, NewRow newRow, ColumnSelector columnSelector) throws NoSuchTableException, DuplicateKeyException, TableDefinitionMismatchException, UnsupportedModificationException, ForeignKeyConstraintDMLException, NoSuchRowException, GenericInvalidOperationException { logger.trace("updating a row"); final RowData oldData = niceRowToRowData(oldRow); final RowData newData = niceRowToRowData(newRow); final int tableId = LegacyUtils.matchRowDatas(oldData, newData); checkForModifiedCursors( session, oldRow, newRow, columnSelector == null ? ALL_COLUMNS_SELECTOR : columnSelector, tableId ); try { store().updateRow(session, oldData, newData, columnSelector); } catch (Exception e) { final InvalidOperationException ioe = launder(e); throwIfInstanceOf(NoSuchRowException.class, ioe); throwIfInstanceOf(DuplicateKeyException.class, ioe); throw new GenericInvalidOperationException(ioe); } } private void checkForModifiedCursors( Session session, NewRow oldRow, NewRow newRow, ColumnSelector columnSelector, int tableId) throws NoSuchTableException { boolean hKeyIsModified = isHKeyModified(session, oldRow, newRow, columnSelector, tableId); Map<CursorId,Cursor> cursorsMap = session.get(MODULE_NAME, OPEN_CURSORS_MAP); if (cursorsMap == null) { return; } for (Cursor cursor : cursorsMap.values()) { if (cursor.isClosed()) { continue; } RowCollector rc = cursor.getRowCollector(); if (hKeyIsModified) { // check whether the update is on this scan or its ancestors int scanTableId = rc.getTableId(); while (scanTableId > 0) { if (scanTableId == tableId) { cursor.setScanModified(); break; } scanTableId = ddlFunctions.getRowDef(scanTableId).getParentRowDefId(); } } else { IndexDef indexDef = rc.getIndexDef(); if (indexDef == null) { indexDef = ddlFunctions.getRowDef(rc.getTableId()).getPKIndexDef(); } if (indexDef != null) { for (int field : indexDef.getFields()) { if (columnSelector.includesColumn(field) && !AkServerUtil.equals(oldRow.get(field), newRow.get(field))) { cursor.setScanModified(); break; } } } } } } private boolean isHKeyModified(Session session, NewRow oldRow, NewRow newRow, ColumnSelector columns, int tableId) { UserTable userTable = ddlFunctions.getAIS(session).getUserTable(tableId); HKey hKey = userTable.hKey(); for (HKeySegment segment : hKey.segments()) { for (HKeyColumn hKeyColumn : segment.columns()) { Column column = hKeyColumn.column(); if (column.getTable() != userTable) { continue; } int pos = column.getPosition(); if (columns.includesColumn(pos) && !AkServerUtil.equals(oldRow.get(pos), newRow.get(pos))) { return true; } } } return false; } /** * Determine if a UserTable can be truncated 'quickly' through the Store interface. * This is possible if the entire group can be truncated. Specifically, all other * tables in the group must have no rows. * @param session Session to operation on * @param userTable UserTable to determine if a fast truncate is possible on * @return true if store.truncateGroup() used, false otherwise */ private boolean canFastTruncate(Session session, UserTable userTable) throws GenericInvalidOperationException, NoSuchTableException { UserTable rootTable = userTable.getGroup().getGroupTable().getRoot(); for(Join join : rootTable.getChildJoins()) { UserTable childTable = join.getChild(); if(!childTable.equals(userTable)) { TableStatistics stats = getTableStatistics(session, childTable.getTableId(), false); if(stats.getRowCount() > 0) { return false; } } } // Only iterated over children, also check root table return rootTable.equals(userTable) || getTableStatistics(session, rootTable.getTableId(), false).getRowCount() == 0; } @Override public void truncateTable(final Session session, final int tableId) throws NoSuchTableException, UnsupportedModificationException, ForeignKeyConstraintDMLException, GenericInvalidOperationException { logger.trace("truncating tableId={}", tableId); final Table table = ddlFunctions.getTable(session, tableId); final UserTable utable = table.isUserTable() ? (UserTable)table : null; if(utable == null || canFastTruncate(session, utable)) { final RowDef rowDef = ddlFunctions.getRowDef(table.getTableId()); try { store().truncateGroup(session, rowDef.getRowDefId()); return; } catch(Exception e) { throw new GenericInvalidOperationException(e); } } // We can't do a "fast truncate" for whatever reason, so we have to delete row by row // (one reason is orphan row maintenance). Do so with a full table scan. // Store.deleteRow() requires all index columns to be in the passed RowData to properly clean everything up Set<Integer> keyColumns = new HashSet<Integer>(); for(Index index : utable.getIndexesIncludingInternal()) { for(IndexColumn col : index.getColumns()) { int pos = col.getColumn().getPosition(); keyColumns.add(pos); } } RowDataLegacyOutputRouter output = new RowDataLegacyOutputRouter(); output.addHandler(new RowDataLegacyOutputRouter.Handler() { private LegacyRowWrapper rowWrapper = new LegacyRowWrapper(); @Override public void handleRow(RowData rowData) throws RowOutputException { try { rowWrapper.setRowData(rowData); deleteRow(session, rowWrapper); } catch (InvalidOperationException e) { throw new RowOutputException(e); } } }); final CursorId cursorId; try { ScanRequest all = new ScanAllRequest(tableId, keyColumns); cursorId = openCursor(session, all); } catch (InvalidOperationException e) { throw new RuntimeException("Internal error", e); } InvalidOperationException thrown = null; try { while (scanSome(session, cursorId, output)) { } } catch (InvalidOperationException e) { throw new RuntimeException("Internal error", e); } catch (BufferFullException e) { throw new RuntimeException("Internal error, buffer full: " + e); } finally { try { closeCursor(session, cursorId); } catch (CursorIsUnknownException e) { thrown = e; } } if (thrown != null) { throw new RuntimeException("Internal error", thrown); } } }
package com.baloise.repocleaner; import static java.lang.String.format; import java.awt.Desktop; import java.io.File; import java.io.IOException; import java.net.URL; import java.nio.file.Files; import java.nio.file.Path; import java.util.ArrayList; import java.util.List; import com.beust.jcommander.JCommander; import com.beust.jcommander.Parameter; public class RepoCleanerCLI { @Parameter(description = "<the git URLs to clone and clean including credentials. file:// URLs will not be cloned>") private List<URL> repoURLs = new ArrayList<>(); @Parameter(names = { "--help", "-help", "-h" }, description = "display usage", help = true) private boolean help; @Parameter(names = { "-files", "-f" }, description = "comma seperated file or directory names to remove") private String files = ".classpath,.cvsignore,.project,.settings,*.iml,.fbwarnings,bin,classes,target"; static RepoCleanerCLI cli = new RepoCleanerCLI(); public static void main(String[] args) { JCommander jCommander = new JCommander(cli, args); jCommander.setProgramName("repoCleaner"); if (cli.help || cli.repoURLs.isEmpty()) { jCommander.usage(); return; } cli.repoURLs.stream().forEach(RepoCleanerCLI::clean); } private static void clean(URL repo) { try { Path local = repo.getProtocol().equalsIgnoreCase("file") ? new File(repo.getPath()).toPath() : Files.createTempDirectory("repoCleaner"+repo.getPath().toString().replaceAll("\\W+", "-")); GitHelper gitHelper = new GitHelper(local); gitHelper.cloneReop(repo); List<String> branches = gitHelper.getUnmergedBranches(); List<String> done = new ArrayList<>(branches.size()); branches.stream().forEach((branch) -> { try { done.add(branch); if(branch.contains("->")) { LOG.info("skipping " +branch); return; } LOG.info(format("switching to %s. (%s/%s)",branch, done.size(), branches.size())); gitHelper.switchBranch(branch.replaceFirst("origin/", "")); LOG.info("cleaning "+branch); new RepoCleaner(local).clean(cli.files.split(",")); LOG.info("committing "+branch); gitHelper.commit("CLEAN "+cli.files); } catch (IOException e) { LOG.exception("cleaning", local, e); } }); if(branches.contains("origin/master")) { gitHelper.switchBranch("master"); } Desktop.getDesktop().open(local.toFile()); } catch (Exception e) { e.printStackTrace(); } } }
package com.blogspot.activeactive.kata; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class BankOcr { public static void main(final String[] args) throws Exception { String inputFile = null; String outputFile = null; if (args == null || args.length == 0) { throw new IllegalArgumentException("You must provide one or two" + " arguments. The first argument is the input file, the second" + " argument is the output file. If an output file is not provided" + " program output will go into './output.txt'."); } else if (args.length == 1) { inputFile = args[0]; outputFile = "output.txt"; } else { inputFile = args[0]; outputFile = args[1]; } new BankOcr().parseAndWrite(inputFile, outputFile); } public void parseAndWrite(final String inputFilename, final String outputFilename) throws IOException { writeToFile(parseFile(inputFilename), outputFilename); } protected void writeToFile(final List<String> lines, final String filename) throws IOException { final File f = new File(filename); f.createNewFile(); final FileWriter fw = new FileWriter(f); final BufferedWriter w = new BufferedWriter(fw); for (int i = 0; i < lines.size(); i++) { if (i != 0) { w.newLine(); } w.write(lines.get(i)); } w.flush(); w.close(); } protected List<String> readFile(final String filename) throws IOException { final BufferedReader br = createReader(filename); final List<String> results = new ArrayList<String>(); String line = br.readLine(); while (line != null) { results.add(line); line = br.readLine(); } return results; } public List<Entry> readEntries(final List<String> contents) { validateContents(contents); final List<Entry> result = new ArrayList<Entry>(); Entry entry = new Entry(); for (final String line : contents) { entry.addLine(line); if (entry.isFull()) { result.add(entry); entry = new Entry(); } } return result; } public List<String> parseFile(final String filename) throws IOException { final List<String> contents = readFile(filename); final List<Entry> entries = readEntries(contents); final List<String> result = new ArrayList<String>(); for (final Entry entry : entries) { result.add(entry.toString()); } return result; } private BufferedReader createReader(final String filename) throws IOException { validateFilename(filename); final File f = new File(filename.trim()); validateFile(f); /* * Ideally, in a language other than java, I could find a way to * mock an un-readable file in the tests to exercise this line, but * I cannot easily do that here. */ final FileReader fr = new FileReader(f); return new BufferedReader(fr); } private void validateFile(final File file) { if (! file.exists()) { throw new IllegalArgumentException("The filename parameter is required" + " but refers to a file which does not exist."); } } private void validateFilename(final String filename) { if (filename == null || "".equals(filename.trim())) { throw new IllegalArgumentException("The filename parameter is required" + " and must not be null-valued, empty, or contain only whitespace."); } } private void validateContents(final List<String> contents) { if (contents == null || contents.isEmpty()) { throw new IllegalArgumentException("The contents parameter is required and" + " must not be null-valued or empty."); } if ((contents.size() % 4) != 0) { throw new IllegalArgumentException("Each valid entry in the contents" + " parameter must contain exactly four lines. The contents parameter" + " does not contain a whole number of valid account number entries."); } } }
package com.censoredsoftware.demigods; import com.censoredsoftware.demigods.ability.Ability; import com.censoredsoftware.demigods.command.DevelopmentCommands; import com.censoredsoftware.demigods.command.GeneralCommands; import com.censoredsoftware.demigods.command.MainCommand; import com.censoredsoftware.demigods.conversation.Prayer; import com.censoredsoftware.demigods.deity.Deity; import com.censoredsoftware.demigods.deity.god.Hades; import com.censoredsoftware.demigods.deity.god.Poseidon; import com.censoredsoftware.demigods.deity.god.Zeus; import com.censoredsoftware.demigods.deity.titan.Iapetus; import com.censoredsoftware.demigods.deity.titan.Oceanus; import com.censoredsoftware.demigods.deity.titan.Prometheus; import com.censoredsoftware.demigods.helper.QuitReasonHandler; import com.censoredsoftware.demigods.helper.WrappedCommand; import com.censoredsoftware.demigods.helper.WrappedConversation; import com.censoredsoftware.demigods.language.Translation; import com.censoredsoftware.demigods.listener.*; import com.censoredsoftware.demigods.player.DCharacter; import com.censoredsoftware.demigods.structure.Altar; import com.censoredsoftware.demigods.structure.Obelisk; import com.censoredsoftware.demigods.structure.Shrine; import com.censoredsoftware.demigods.structure.Structure; import com.censoredsoftware.demigods.util.Messages; import com.censoredsoftware.errornoise.ErrorNoise; import com.google.common.base.Function; import com.google.common.base.Predicate; import com.google.common.collect.Collections2; import com.google.common.collect.Sets; import com.sk89q.worldguard.bukkit.WorldGuardPlugin; import org.bukkit.Bukkit; import org.bukkit.Location; import org.bukkit.World; import org.bukkit.conversations.ConversationContext; import org.bukkit.conversations.ConversationFactory; import org.bukkit.conversations.Prompt; import org.bukkit.event.Listener; import org.bukkit.plugin.Plugin; import org.bukkit.plugin.PluginManager; import org.mcstats.MetricsLite; import java.util.Set; public class Demigods { // Constants public static String SAVE_PATH; // Public Static Access public static DemigodsPlugin PLUGIN; public static ConversationFactory CONVERSATION_FACTORY; // Public Dependency Plugins public static WorldGuardPlugin WORLD_GUARD; public static boolean ERROR_NOISE; // Disabled Worlds protected static Set<String> DISABLED_WORLDS; protected static Set<String> COMMANDS; // The LANGUAGE public static Translation LANGUAGE; // Start the PLUGIN static { // Allow static access. CONVERSATION_FACTORY = new ConversationFactory(PLUGIN); // Initialize metrics try { (new MetricsLite(PLUGIN)).start(); } catch(Exception ignored) {} // Start the data SAVE_PATH = "plugins/Demigods/data/"; // Don't change this. // Finish loading the PLUGIN based on the game data loadDepends(); loadListeners(); loadCommands(); if(MiscUtil.isRunningSpigot()) Messages.info(("Spigot found, will use extra API features.")); } private static boolean loadWorlds() { DISABLED_WORLDS = Sets.newHashSet(); for(String world : Collections2.filter(PLUGIN.getConfig().getStringList("restrictions.disabled_worlds"), new Predicate<String>() { @Override public boolean apply(String world) { return PLUGIN.getServer().getWorld(world) != null; } })) if(PLUGIN.getServer().getWorld(world) != null) DISABLED_WORLDS.add(world); if(PLUGIN.getServer().getWorlds().size() == DISABLED_WORLDS.size()) return false; return true; } private static void loadListeners() { PluginManager register = PLUGIN.getServer().getPluginManager(); // Engine for(ListedListener listener : ListedListener.values()) register.registerEvents(listener.getListener(), PLUGIN); // Disabled worlds if(!DISABLED_WORLDS.isEmpty()) register.registerEvents(new DisabledWorldListener(), PLUGIN); // Deities for(ListedDeity deity : ListedDeity.values()) { if(deity.getDeity().getAbilities() == null) continue; for(Ability ability : Sets.filter(deity.getDeity().getAbilities(), new Predicate<Ability>() { @Override public boolean apply(Ability ability) { return ability.getListener() != null; } })) register.registerEvents(ability.getListener(), PLUGIN); } // Structures for(ListedStructure structure : Sets.filter(Sets.newHashSet(ListedStructure.values()), new Predicate<ListedStructure>() { @Override public boolean apply(ListedStructure structure) { return structure.getStructure().getUniqueListener() != null; } })) register.registerEvents(structure.getStructure().getUniqueListener(), PLUGIN); // Conversations for(WrappedConversation conversation : Collections2.filter(Collections2.transform(Sets.newHashSet(ListedConversation.values()), new Function<ListedConversation, WrappedConversation>() { @Override public WrappedConversation apply(ListedConversation conversation) { return conversation.getConversation(); } }), new Predicate<WrappedConversation>() { @Override public boolean apply(WrappedConversation conversation) { return conversation.getUniqueListener() != null; } })) register.registerEvents(conversation.getUniqueListener(), PLUGIN); // Quit reason. PLUGIN.getServer().getLogger().addHandler(new QuitReasonHandler()); } private static void loadCommands() { COMMANDS = Sets.newHashSet(); for(ListedCommand command : ListedCommand.values()) COMMANDS.addAll(command.getCommand().getCommands()); COMMANDS.add("dg"); COMMANDS.add("demigod"); } private static void loadDepends() { // WorldGuard Plugin depend = PLUGIN.getServer().getPluginManager().getPlugin("WorldGuard"); if(depend instanceof WorldGuardPlugin) WORLD_GUARD = (WorldGuardPlugin) depend; ERROR_NOISE = PLUGIN.getServer().getPluginManager().getPlugin("ErrorNoise") instanceof ErrorNoise; } static { // Update usable characters DCharacter.Util.updateUsableCharacters(); // Check if there are no enabled worlds if(!loadWorlds()) { Messages.severe("Demigods was unable to load any worlds."); Messages.severe("Please configure at least 1 world for "); PLUGIN.getServer().getPluginManager().disablePlugin(PLUGIN); } } public static class MiscUtil { public static boolean isRunningSpigot() { try { Bukkit.getServer().getWorlds().get(0).spigot(); return true; } catch(Throwable ignored) {} return false; } public static boolean isDisabledWorld(Location location) { return DISABLED_WORLDS.contains(location.getWorld().getName()); } public static boolean isDisabledWorld(World world) { return DISABLED_WORLDS.contains(world.getName()); } public static boolean isDemigodsCommand(String command) { return COMMANDS.contains(command); } } // Deities public static enum ListedDeity { // GODS ZEUS("Zeus", new Zeus()), POSEIDON("Poseidon", new Poseidon()), HADES("Hades", new Hades()), // TITANS IAPETUS("Iapetus", new Iapetus()), OCEANUS("Oceanus", new Oceanus()), PROMETHEUS("Prometheus", new Prometheus()); // DONATORS // DISCO("DrD1sco", new DrD1sco()), OMEGA("OmegaX17", new OmegaX17()); private final String name; private final Deity deity; private ListedDeity(String name, Deity deity) { this.name = name; this.deity = deity; } public String getName() { return name; } public Deity getDeity() { return deity; } public static Deity get(String name) { for(ListedDeity deity : values()) if(deity.getName().equalsIgnoreCase(name)) return deity.getDeity(); return null; } } // Structures public static enum ListedStructure { ALTAR(new Altar()), SHRINE(new Shrine()), OBELISK(new Obelisk()); private final Structure structure; private ListedStructure(Structure structure) { this.structure = structure; } public Structure getStructure() { return structure; } } // Conversations public enum ListedConversation { PRAYER(new Prayer()); private final WrappedConversation conversationInfo; private ListedConversation(WrappedConversation conversationInfo) { this.conversationInfo = conversationInfo; } public WrappedConversation getConversation() { return this.conversationInfo; } // Can't touch this. Naaaaaa na-na-na.. Ba-dum, ba-dum. public static interface Category extends Prompt { public String getChatName(); public boolean canUse(ConversationContext context); } } // Listeners public enum ListedListener { BATTLE(new BattleListener()), CHAT(new ChatListener()), ENTITY(new EntityListener()), FLAG(new FlagListener()), GRIEF(new GriefListener()), PLAYER(new PlayerListener()), TRIBUTE(new TributeListener()); private Listener listener; private ListedListener(Listener listener) { this.listener = listener; } public Listener getListener() { return listener; } } // Commands public enum ListedCommand { MAIN(new MainCommand()), GENERAL(new GeneralCommands()), DEVELOPMENT(new DevelopmentCommands()); private WrappedCommand command; private ListedCommand(WrappedCommand command) { this.command = command; } public WrappedCommand getCommand() { return command; } } }
import java.util.*; import java.io.*; public class Scanner { public static final String DATA_FILE = "input.txt"; public static void main (String[] args) { boolean verify = false; boolean debug = false; for (int i = 0; i < args.length; i++) { if ("-help".equals(args[i])) { System.out.println("Usage: [-debug] [-verify] [-help]"); System.exit(0); } if ("-debug".equals(args[i])) debug = true; if ("-verify".equals(args[i])) verify = true; } if (verify) { Verifier v = new Verifier(debug); if (v.verify()) System.out.println("Verified ok."); else System.out.println("Verify failed!"); System.exit(0); } /* * Open the data file and read it in. */ BufferedReader reader = null; Plane thePlane = new Plane(debug); try { reader = new BufferedReader(new FileReader(DATA_FILE)); String line = null; while ((line = reader.readLine()) != null) { Barcode b = new Barcode(line, debug); if (debug) System.out.println("Loaded: "+b); thePlane.addSeat(b.getSeat()); } } catch (Throwable ex) { ex.printStackTrace(); } finally { try { reader.close(); } catch (Throwable ex) { } } Vector<Seat> emptySeats = thePlane.emptySeats(); Enumeration<Seat> iter = emptySeats.elements(); int row = -1; Seat theSeat = null; while (iter.hasMoreElements()) { Seat s = iter.nextElement(); if (debug) System.out.println("Empty seat: "+s); /* * The seat will have a unique row as it's the last one * on the plane. */ if (s.getRow() == row) { row = -1; theSeat = null; } else { row = s.getRow(); theSeat = s; } } System.out.println("Seat: "+theSeat); } }
package com.custardsource.parfait.dxm; import java.io.IOException; import java.nio.ByteBuffer; interface ByteBufferFactory { ByteBuffer build(int length) throws IOException; }
package org.sbolstandard.core2; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.Writer; import java.util.ArrayList; import java.net.URI; //import java.util.Collection; import java.util.List; import uk.ac.ncl.intbio.core.datatree.DocumentRoot; import uk.ac.ncl.intbio.core.datatree.NamedProperty; import uk.ac.ncl.intbio.core.datatree.TopLevelDocument; import uk.ac.ncl.intbio.core.io.rdf.RdfIo; import static uk.ac.ncl.intbio.core.datatree.Datatree.*; import javanet.staxutils.IndentingXMLStreamWriter; import javax.xml.namespace.QName; import javax.xml.stream.XMLOutputFactory; import javax.xml.stream.XMLStreamWriter; /** * @author Zhen Zhang and Tramy Nguyen * @version 2.0 * */ public class SBOLWriter { /* * Note: * all checks for != null will be change to isSet() * All getIdentity were removed. * * TODO: * make contract headers for PUBLIC methods only * make various types of write() with diff. params. * */ /** * Serializes a given SBOLDocument and outputs the data from the serialization to the given output stream * @param doc * @param out */ public static void write(SBOLDocument doc, OutputStream out) { List<TopLevelDocument<QName>> topLevelDoc = new ArrayList<TopLevelDocument<QName>>(); formatCollections(doc.getCollections(), topLevelDoc); formatModules(doc.getModules(), topLevelDoc); formatModels(doc.getModels(), topLevelDoc); formatComponents(doc.getComponents(), topLevelDoc); formatStructures(doc.getStructures(), topLevelDoc); //TODO: add formatTopLevels(); try { write(new OutputStreamWriter(out), DocumentRoot(TopLevelDocuments(topLevelDoc))); } catch(Exception e) { e.printStackTrace();} } private static void write(Writer stream, DocumentRoot<QName> document) throws Exception { XMLStreamWriter xmlWriter = new IndentingXMLStreamWriter(XMLOutputFactory.newInstance().createXMLStreamWriter(stream)); RdfIo rdfIo = new RdfIo(); rdfIo.createIoWriter(xmlWriter).write(document); xmlWriter.flush(); xmlWriter.close(); } private static void formatCollections (List<Collection> collections, List<TopLevelDocument<QName>> topLevelDoc) { for(Collection c : collections) { List<NamedProperty<QName>> list = new ArrayList<NamedProperty<QName>>(); if(c.getIdentity() != null) list.add(NamedProperty(Sbol2Terms.Identified.identity, c.getIdentity())); if(c.getPersistentIdentity() != null) list.add(NamedProperty(Sbol2Terms.Documented.persistentIdentity, c.getPersistentIdentity())); if(c.getVersion() != null) list.add(NamedProperty(Sbol2Terms.Documented.version, c.getVersion())); if(c.getDisplayId() != null) list.add(NamedProperty(Sbol2Terms.Documented.displayId, c.getDisplayId())); if(c.getName() != null) list.add(NamedProperty(Sbol2Terms.Documented.name, c.getName())); if(c.getDescription() != null) list.add(NamedProperty(Sbol2Terms.Documented.description, c.getDescription())); topLevelDoc.add(TopLevelDocument(Sbol2Terms.Collection.Collection, c.getIdentity(), NamedProperties(list))); } } private static void formatComponents (List<Component> components, List<TopLevelDocument<QName>> topLevelDoc) { for(Component c : components) { List<NamedProperty<QName>> list = new ArrayList<NamedProperty<QName>>(); if(c.getIdentity() != null) list.add(NamedProperty(Sbol2Terms.Identified.identity, c.getIdentity())); if(c.getPersistentIdentity() != null) list.add(NamedProperty(Sbol2Terms.Documented.persistentIdentity, c.getPersistentIdentity())); if(c.getVersion() != null) list.add(NamedProperty(Sbol2Terms.Documented.version, c.getVersion())); if(c.getDisplayId() != null) list.add(NamedProperty(Sbol2Terms.Documented.displayId, c.getDisplayId())); if(c.getName() != null) list.add(NamedProperty(Sbol2Terms.Documented.name, c.getName())); if(c.getDescription() != null) list.add(NamedProperty(Sbol2Terms.Documented.description, c.getDescription())); if(c.getRoles() != null) list.add(NamedProperty(Sbol2Terms.Component.roles, c.getRoles().toString())); //TODO: iterate through each roles and types if(c.getType() != null) list.add(NamedProperty(Sbol2Terms.Component.types, c.getType().toString())); getStructuralInstantiations(c.getStructuralInstantiations(),list); getStructuralAnnotations(c.getStructuralAnnotations(),list); getStructuralConstraints(c.getStructuralConstraints(),list); if(c.getStructure() != null) getStructure(c.getStructure(), list); topLevelDoc.add(TopLevelDocument(Sbol2Terms.Component.Component, c.getIdentity(), NamedProperties(list))); } } /** * getModel for Module * @param model * @param properties */ private static void formatModels (List<Model> models, List<TopLevelDocument<QName>> topLevelDoc) { for(Model m : models) { List<NamedProperty<QName>> list = new ArrayList<NamedProperty<QName>>(); if(m.getIdentity() != null) list.add(NamedProperty(Sbol2Terms.Identified.identity, m.getIdentity())); if(m.getPersistentIdentity() != null) list.add(NamedProperty(Sbol2Terms.Documented.persistentIdentity, m.getPersistentIdentity())); if(m.getVersion() != null) list.add(NamedProperty(Sbol2Terms.Documented.version, m.getVersion())); if(m.getDisplayId() != null) list.add(NamedProperty(Sbol2Terms.Documented.displayId, m.getDisplayId())); if(m.getName() != null) list.add(NamedProperty(Sbol2Terms.Documented.name, m.getName())); if(m.getDescription() != null) list.add(NamedProperty(Sbol2Terms.Documented.description, m.getDescription())); if(m.getSource() != null) list.add(NamedProperty(Sbol2Terms.Model.source, m.getSource())); if(m.getLanguage() != null) list.add(NamedProperty(Sbol2Terms.Model.language, m.getLanguage())); if(m.getFramework() != null) list.add(NamedProperty(Sbol2Terms.Model.framework, m.getFramework())); topLevelDoc.add(TopLevelDocument(Sbol2Terms.Model.Model, m.getIdentity(), NamedProperties(list))); } } private static void formatModules(List<Module> module, List<TopLevelDocument<QName>> topLevelDoc) { for (Module m : module) { List<NamedProperty<QName>> list = new ArrayList<NamedProperty<QName>>(); if(m.getIdentity() != null) list.add(NamedProperty(Sbol2Terms.Identified.identity, m.getIdentity())); if(m.getPersistentIdentity() != null) list.add(NamedProperty(Sbol2Terms.Documented.persistentIdentity, m.getPersistentIdentity())); if(m.getVersion() != null) list.add(NamedProperty(Sbol2Terms.Documented.version, m.getVersion())); if(m.getDisplayId() != null) list.add(NamedProperty(Sbol2Terms.Documented.displayId, m.getDisplayId())); if(m.getName() != null) list.add(NamedProperty(Sbol2Terms.Documented.name, m.getName())); if(m.getDescription() != null) list.add(NamedProperty(Sbol2Terms.Documented.description, m.getDescription())); if(m.getRoles() != null) { for (URI roles : m.getRoles()) { list.add(NamedProperty(Sbol2Terms.Module.roles, roles.toString())); } } getFunctionalInstantiations(m.getFunctionalInstantiations(),list); getInteractions(m.getInteractions(),list); getModels(m.getModels(),list); //TODO: iterate through Models to obtain URI getModuleInstantiation(m.getModuleInstantiations(),list); topLevelDoc.add(TopLevelDocument(Sbol2Terms.Module.Module, m.getIdentity(), NamedProperties(list))); } } private static void formatStructures (List<Structure> structures, List<TopLevelDocument<QName>> topLevelDoc) { for(Structure s : structures) { List<NamedProperty<QName>> list = new ArrayList<NamedProperty<QName>>(); if(s.getIdentity() != null) list.add(NamedProperty(Sbol2Terms.Identified.identity, s.getIdentity())); if(s.getPersistentIdentity() != null) list.add(NamedProperty(Sbol2Terms.Documented.persistentIdentity, s.getPersistentIdentity())); if(s.getVersion() != null) list.add(NamedProperty(Sbol2Terms.Documented.version, s.getVersion())); if(s.getDisplayId() != null) list.add(NamedProperty(Sbol2Terms.Documented.displayId, s.getDisplayId())); if(s.getName() != null) list.add(NamedProperty(Sbol2Terms.Documented.name, s.getName())); if(s.getDescription() != null) list.add(NamedProperty(Sbol2Terms.Documented.description, s.getDescription())); if(s.getElements() != null) list.add(NamedProperty(Sbol2Terms.Structure.elements, s.getElements())); if(s.getEncoding() != null) list.add(NamedProperty(Sbol2Terms.Structure.encoding, s.getEncoding())); topLevelDoc.add(TopLevelDocument(Sbol2Terms.Structure.Structure, s.getIdentity(), NamedProperties(list))); } } /** * getFunctionalInstantiations for Module * @param functionalInstantiation * @param properties */ private static void getFunctionalInstantiations(List<FunctionalInstantiation> functionalInstantiation, List<NamedProperty<QName>> properties) { for(FunctionalInstantiation f : functionalInstantiation) { List<NamedProperty<QName>> list = new ArrayList<NamedProperty<QName>>(); if(f.getIdentity() != null) list.add(NamedProperty(Sbol2Terms.Identified.identity, f.getIdentity())); if(f.getPersistentIdentity() != null) list.add(NamedProperty(Sbol2Terms.Documented.persistentIdentity, f.getPersistentIdentity())); if(f.getVersion() != null) list.add(NamedProperty(Sbol2Terms.Documented.version, f.getVersion())); if(f.getDisplayId() != null) list.add(NamedProperty(Sbol2Terms.Documented.displayId, f.getDisplayId())); if(f.getName() != null) list.add(NamedProperty(Sbol2Terms.Documented.name, f.getName())); if(f.getDescription() != null) list.add(NamedProperty(Sbol2Terms.Documented.description, f.getDescription())); if(f.getTimeStamp() != null) list.add(NamedProperty(Sbol2Terms.Documented.timeStamp, f.getTimeStamp().toString())); // if(f.getInstantiatedComponent() != null) //TODO: Why does creating an object of FunctionalInstantiation requires a component identity? //how to retrieve List<URI> type? in mainTester, you need to create a List<URI> type but there is no //method to retrieve this data. properties.add(NamedProperty(Sbol2Terms.Module.hasfunctionalInstantiations, NestedDocument( Sbol2Terms.FunctionalInstantiation.FunctionalInstantiation, f.getIdentity(), NamedProperties(list)))); } } /** * getInteractions for Module * @param interactions * @param properties */ private static void getInteractions (List<Interaction> interactions, List<NamedProperty<QName>> properties) { for(Interaction i : interactions) { List<NamedProperty<QName>> list = new ArrayList<NamedProperty<QName>>(); if(i.getIdentity() != null) list.add(NamedProperty(Sbol2Terms.Identified.identity, i.getIdentity())); if(i.getPersistentIdentity() != null) list.add(NamedProperty(Sbol2Terms.Documented.persistentIdentity, i.getPersistentIdentity())); if(i.getVersion() != null) list.add(NamedProperty(Sbol2Terms.Documented.version, i.getVersion())); if(i.getDisplayId() != null) list.add(NamedProperty(Sbol2Terms.Documented.displayId, i.getDisplayId())); if(i.getName() != null) list.add(NamedProperty(Sbol2Terms.Documented.name, i.getName())); if(i.getDescription() != null) list.add(NamedProperty(Sbol2Terms.Documented.description, i.getDescription())); if (i.getParticipations() != null) list.add(NamedProperty(Sbol2Terms.Interaction.type, i.getParticipations().toString())); //TODO: is getParticipation() == getType() because Interaction does not have a getType(). //in mainTester, a List<URI> type must be declared to create an Interaction. properties.add(NamedProperty(Sbol2Terms.Module.hasInteractions, NestedDocument( Sbol2Terms.Interaction.Interaction, i.getIdentity(), NamedProperties(list)))); } } private static void getModels(List<URI> models, List<NamedProperty<QName>> list) { for(URI m : models) { list.add(NamedProperty(Sbol2Terms.Module.hasModels, m)); } } /** * getModuleInstantiation for Module * @param moduleInstantiation * @param properties */ private static void getModuleInstantiation (List<ModuleInstantiation> moduleInstantiation, List<NamedProperty<QName>> properties) { for(ModuleInstantiation m : moduleInstantiation) { List<NamedProperty<QName>> list = new ArrayList<NamedProperty<QName>>(); if(m.getIdentity() != null) list.add(NamedProperty(Sbol2Terms.Identified.identity, m.getIdentity())); if(m.getPersistentIdentity() != null) list.add(NamedProperty(Sbol2Terms.Documented.persistentIdentity, m.getPersistentIdentity())); if(m.getVersion() != null) list.add(NamedProperty(Sbol2Terms.Documented.version, m.getVersion())); if(m.getDisplayId() != null) list.add(NamedProperty(Sbol2Terms.Documented.displayId, m.getDisplayId())); if(m.getName() != null) list.add(NamedProperty(Sbol2Terms.Documented.name, m.getName())); if(m.getDescription() != null) list.add(NamedProperty(Sbol2Terms.Documented.description, m.getDescription())); // if(m.getInstantiatedModule() != null) //TODO properties.add(NamedProperty(Sbol2Terms.Module.hasModuleInstantiations, NestedDocument( Sbol2Terms.ModuleInstantiation.ModuleInstantiation, m.getIdentity(), NamedProperties(list)))); } } private static void getStructure(URI structure, List<NamedProperty<QName>> list) { // for(URI s : structures) list.add(NamedProperty(Sbol2Terms.Component.hasStructure, structure)); } private static void getStructuralAnnotations(List<StructuralAnnotation> structuralAnnotations, List<NamedProperty<QName>> properties) { for(StructuralAnnotation s : structuralAnnotations) { List<NamedProperty<QName>> list = new ArrayList<NamedProperty<QName>>(); if(s.getIdentity() != null) list.add(NamedProperty(Sbol2Terms.Identified.identity, s.getIdentity())); if(s.getPersistentIdentity() != null) list.add(NamedProperty(Sbol2Terms.Documented.persistentIdentity, s.getPersistentIdentity())); if(s.getVersion() != null) list.add(NamedProperty(Sbol2Terms.Documented.version, s.getVersion())); if(s.getDisplayId() != null) list.add(NamedProperty(Sbol2Terms.Documented.displayId, s.getDisplayId())); if(s.getName() != null) list.add(NamedProperty(Sbol2Terms.Documented.name, s.getName())); if(s.getDescription() != null) list.add(NamedProperty(Sbol2Terms.Documented.description, s.getDescription())); properties.add(NamedProperty(Sbol2Terms.Component.hasStructuralAnnotations, NestedDocument( Sbol2Terms.StructuralAnnotation.StructuralAnnotation, s.getIdentity(), NamedProperties(list)))); } } private static void getStructuralConstraints(List<StructuralConstraint> structuralConstraint, List<NamedProperty<QName>> properties) { for(StructuralConstraint s : structuralConstraint) { List<NamedProperty<QName>> list = new ArrayList<NamedProperty<QName>>(); if(s.getIdentity() != null) list.add(NamedProperty(Sbol2Terms.Documented.identity, s.getIdentity())); if(s.getPersistentIdentity() != null) list.add(NamedProperty(Sbol2Terms.Documented.persistentIdentity, s.getPersistentIdentity())); if(s.getVersion() != null) list.add(NamedProperty(Sbol2Terms.Identified.identity, s.getVersion())); properties.add(NamedProperty(Sbol2Terms.Component.hasStructuralConstraints, NestedDocument( Sbol2Terms.StructuralConstraint.StructuralConstraint, s.getIdentity(), NamedProperties(list)))); } } private static void getStructuralInstantiations(List<StructuralInstantiation> structuralInstantiations, List<NamedProperty<QName>> properties) { for(StructuralInstantiation s : structuralInstantiations) { List<NamedProperty<QName>> list = new ArrayList<NamedProperty<QName>>(); if(s.getIdentity() != null) list.add(NamedProperty(Sbol2Terms.Identified.identity, s.getIdentity())); if(s.getPersistentIdentity() != null) list.add(NamedProperty(Sbol2Terms.Documented.persistentIdentity, s.getPersistentIdentity())); if(s.getVersion() != null) list.add(NamedProperty(Sbol2Terms.Documented.version, s.getVersion())); if(s.getDisplayId() != null) list.add(NamedProperty(Sbol2Terms.Documented.displayId, s.getDisplayId())); if(s.getName() != null) list.add(NamedProperty(Sbol2Terms.Documented.name, s.getName())); if(s.getDescription() != null) list.add(NamedProperty(Sbol2Terms.Documented.description, s.getDescription())); properties.add(NamedProperty(Sbol2Terms.Component.hasStructuralInstantiations, NestedDocument( Sbol2Terms.StructuralInstantiation.StructuralInstantiation, s.getIdentity(), NamedProperties(list)))); } } }
package fr.ece.pfe_project.panel; import fr.ece.pfe_project.database.DatabaseHelper; import fr.ece.pfe_project.editor.CameraCellEditor; import fr.ece.pfe_project.interfaces.ToolbarActionsListener; import fr.ece.pfe_project.interfaces.ToolbarEntityListener; import fr.ece.pfe_project.interfaces.ToolbarEntityListener.ENTITY; import static fr.ece.pfe_project.interfaces.ToolbarEntityListener.ENTITY.CAMERA; import static fr.ece.pfe_project.interfaces.ToolbarEntityListener.ENTITY.CARNETADRESSE; import static fr.ece.pfe_project.interfaces.ToolbarEntityListener.ENTITY.EXCELROW; import static fr.ece.pfe_project.interfaces.ToolbarEntityListener.ENTITY.LISTINGVOLS; import static fr.ece.pfe_project.interfaces.ToolbarEntityListener.ENTITY.NONE; import fr.ece.pfe_project.model.Camera; import fr.ece.pfe_project.model.CarnetAdresses; import fr.ece.pfe_project.model.FrequentationJournaliere; import fr.ece.pfe_project.model.ListingVols; import fr.ece.pfe_project.panel.MainPanel.FaceDetectorListener; import fr.ece.pfe_project.panel.MainPanel.ToolbarsListener; import static fr.ece.pfe_project.panel.ParametersDialog.msgbox; import fr.ece.pfe_project.renderer.CameraCellRenderer; import fr.ece.pfe_project.tablemodel.MyTableModel; import fr.ece.pfe_project.utils.ExcelUtils; import fr.ece.pfe_project.utils.GlobalVariableUtils; import fr.ece.pfe_project.widget.CameraCellComponent; import fr.ece.pfe_project.widget.CameraSaisieDialog; import fr.ece.pfe_project.widget.CarnetAdressesDialog; import fr.ece.pfe_project.widget.ExcelSaisieDialog; import fr.ece.pfe_project.widget.PlanPanel; import fr.ece.pfe_project.widget.ProgressDialog; import java.awt.CardLayout; import java.awt.Color; import java.awt.Component; import java.awt.Font; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.ComponentEvent; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.awt.event.MouseMotionListener; import java.io.IOException; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.text.DateFormatSymbols; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Collections; import java.util.Date; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.DefaultCellEditor; import javax.swing.DefaultComboBoxModel; import javax.swing.JFormattedTextField; import javax.swing.JFrame; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JTable; import javax.swing.table.DefaultTableCellRenderer; import org.jdatepicker.ComponentManager; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import real_time_image_processing.FaceDetectorThread; /** * * @author pierreghazal */ public class ListPanel extends JPanel implements FaceDetectorThread.FaceDetectorInterface, ToolbarEntityListener, ToolbarActionsListener, MouseMotionListener, MouseListener, ActionListener { SimpleDateFormat f = new SimpleDateFormat("dd/MM/yyyy"); public class DateEditor extends DefaultCellEditor { private final JFormattedTextField textField; public DateEditor() { super(new JFormattedTextField(f)); textField = (JFormattedTextField) super.getComponent(); textField.setFont(new Font(textField.getFont().getName(), Font.PLAIN, 11)); } @Override public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) { if (value instanceof Date) { String strDate = f.format((Date) value); this.textField.setText(strDate); } return this.textField; } @Override public Object getCellEditorValue() { try { if (textField.getText().trim().length() == 0) { throw new ParseException("", 0); } java.util.Date utilDate = f.parse(textField.getText().trim()); return utilDate; } catch (ParseException e) { msgbox("Format date invalide. Format accepté : jj/mm/aaaa"); return textField.getText(); } } } public class DateRenderer extends DefaultTableCellRenderer { @Override public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int col) { super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, col); if (value instanceof Date) { String strDate = f.format((Date) value); this.setText(strDate); } this.setBackground(row % 2 == 0 ? Color.LIGHT_GRAY : Color.WHITE); if (isSelected) { this.setBackground(Color.BLUE); this.setForeground(Color.WHITE); } else { this.setForeground(Color.BLACK); } return this; } } public class MyDefaultRenderer extends DefaultTableCellRenderer { @Override public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { final Component c = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column); c.setBackground(row % 2 == 0 ? Color.LIGHT_GRAY : Color.WHITE); if (isSelected) { c.setBackground(Color.BLUE); c.setForeground(Color.WHITE); } else { c.setForeground(Color.BLACK); } return c; } } private final ArrayList<Camera> cameras; private final ArrayList<CarnetAdresses> carnetAdresses; private boolean isCameraActive; MyTableModel model; FaceDetectorListener faceDetectorListener; ToolbarsListener toolbarsListener; private PlanPanel planPanel; /** * Creates new form DrawingPanel * * @param faceListener * @param toolbarsListener */ public ListPanel(FaceDetectorListener faceListener, ToolbarsListener toolbarsListener) { initComponents(); planPanel = new PlanPanel(); planPanel.addComponentListener(new java.awt.event.ComponentAdapter() { @Override public void componentResized(java.awt.event.ComponentEvent evt) { planPanelComponentResized(evt); } }); this.scrollPanePlans.setViewportView(planPanel); this.faceDetectorListener = faceListener; this.toolbarsListener = toolbarsListener; // Listener addMouseListener(this); addMouseMotionListener(this); //Initialisation du carnet d'adresses carnetAdresses = new ArrayList<CarnetAdresses>(); carnetAdresses.add(new CarnetAdresses("Air France", 3, "AIR FRANCE", "0 970 808 816")); carnetAdresses.add(new CarnetAdresses("Brussels Airlines", 2, "AVIAPARTNER", "03 88 64 73 11")); setExcelButtonVisibility(false); setMonthComboboxItems(); setYearComboboxItems(); setVisibilityRefresh(false); setCameraButtonVisibility(false); cameras = new ArrayList<Camera>(); cameras.add(new Camera(1)); //cameras[1].setState(Camera.CAMERA_STATE.ALERT); // SET THE 2ND CAMERA AS DECTECTING CROWD isCameraActive = false; refreshButton.addActionListener(this); //Ajout des listerner sur les boutons de la page carnet d'adresses cameraButton.addActionListener(this); this.itemsTable.setModel(new MyTableModel()); itemsTable.setDefaultRenderer(Integer.class, new MyDefaultRenderer()); itemsTable.setDefaultRenderer(String.class, new MyDefaultRenderer()); itemsTable.setDefaultRenderer(Long.class, new MyDefaultRenderer()); itemsTable.setDefaultRenderer(Date.class, new DateRenderer()); itemsTable.setDefaultRenderer(Camera.class, new CameraCellRenderer()); itemsTable.setDefaultEditor(Camera.class, new CameraCellEditor()); itemsTable.setDefaultEditor(Date.class, new DateEditor()); } private void planPanelComponentResized(ComponentEvent evt) { planPanel.repaint(); } @Override public void performAction(int action) { final ENTITY entity = model.getEntity(); switch (action) { case ACTION_ADD: switch (entity) { case CAMERA: CameraSaisieDialog csd = new CameraSaisieDialog(null, true); csd.setVisible(true); Camera cameraToAdd = csd.getCamera(); if (cameraToAdd == null) { System.err.println("Camera NULL"); // Ne rien ajouter } else { System.out.println("Camera : " + cameraToAdd.getId()); cameras.add(cameraToAdd); model.setData(cameras, true); } break; case CARNETADRESSE: CarnetAdressesDialog cad = new CarnetAdressesDialog(null, true); cad.setVisible(true); CarnetAdresses carnetToAdd = cad.getCa(); if (carnetToAdd == null) { System.err.println("Excel NULL"); } else{ System.out.println("Carnet d'adresses : " + carnetToAdd.getCompagnieca()); carnetAdresses.add(carnetToAdd); model.setData(carnetAdresses, true); } break; case EXCELROW: ExcelSaisieDialog esd = new ExcelSaisieDialog(null, true); esd.setVisible(true); FrequentationJournaliere excelToAdd = esd.getFj(); if (excelToAdd == null) { System.err.println("Excel NULL"); } else { System.out.println("Frequentation journaliere de " + excelToAdd.getFrequentation() + " Pour le " + excelToAdd.getDate()); //model.setData(esd, true); } break; default: break; } break; case ACTION_DELETE: switch (entity) { case CAMERA: if (itemsTable.getSelectedRowCount() > 0) { Camera selectedCamera = (Camera) model.getDataAtRow(itemsTable.getSelectedRow()); if (selectedCamera != null) { cameras.remove(selectedCamera); model.setData(cameras, true); } } else { JOptionPane.showMessageDialog(this, "Aucun élément sélectionné dans la liste", "Erreur", JOptionPane.INFORMATION_MESSAGE); } break; case CARNETADRESSE: if (itemsTable.getSelectedRowCount() > 0) { CarnetAdresses selectedCarnet = (CarnetAdresses) model.getDataAtRow(itemsTable.getSelectedRow()); if (selectedCarnet != null) { carnetAdresses.remove(selectedCarnet); model.setData(carnetAdresses, true); } } else { JOptionPane.showMessageDialog(this, "Aucun élément sélectionné dans la liste", "Erreur", JOptionPane.INFORMATION_MESSAGE); } break; case EXCELROW: if (itemsTable.getSelectedRowCount() > 0) { FrequentationJournaliere selectedFj = (FrequentationJournaliere) model.getDataAtRow(itemsTable.getSelectedRow()); if (selectedFj != null) { } } else { JOptionPane.showMessageDialog(this, "Aucun élément sélectionné dans la liste", "Erreur", JOptionPane.INFORMATION_MESSAGE); } break; default: break; } break; case ACTION_EDIT: switch (entity) { case CAMERA: if (itemsTable.getSelectedRowCount() > 0) { Camera selectedCamera = (Camera) model.getDataAtRow(itemsTable.getSelectedRow()); if (selectedCamera != null) { CameraSaisieDialog csd = new CameraSaisieDialog(null, true); csd.setCamera(selectedCamera); csd.setVisible(true); selectedCamera = csd.getCamera(); cameras.set(itemsTable.getSelectedRow(), selectedCamera); model.setData(cameras, true); } } else { JOptionPane.showMessageDialog(this, "Aucun élément sélectionné dans la liste", "Erreur", JOptionPane.INFORMATION_MESSAGE); } break; case CARNETADRESSE: if (itemsTable.getSelectedRowCount() > 0) { CarnetAdresses selectedCarnet = (CarnetAdresses) model.getDataAtRow(itemsTable.getSelectedRow()); if (selectedCarnet != null) { CarnetAdressesDialog cad = new CarnetAdressesDialog(null, true); cad.setCa(selectedCarnet); cad.setVisible(true); selectedCarnet = cad.getCa(); carnetAdresses.set(itemsTable.getSelectedRow(), selectedCarnet); model.setData(carnetAdresses, true); } } else { JOptionPane.showMessageDialog(this, "Aucun élément sélectionné dans la liste", "Erreur", JOptionPane.INFORMATION_MESSAGE); } break; case EXCELROW: break; default: break; } break; default: break; } } @Override public void entityHasChange(ENTITY typeEntity) { System.out.println("List entityHasChange : " + typeEntity.toString()); model = (MyTableModel) this.itemsTable.getModel(); model.setEntity(typeEntity); final CardLayout cl = (CardLayout) (cardPanel.getLayout()); switch (typeEntity) { case CAMERA: setVisibilityRefresh(false); setExcelButtonVisibility(false); setCameraButtonVisibility(true); itemsTable.setRowHeight(new CameraCellComponent().getPreferredSize().height); model.setData(cameras, false); cl.show(cardPanel, "table"); break; case EXCELROW: setVisibilityRefresh(false); setExcelButtonVisibility(true); setCameraButtonVisibility(false); itemsTable.setRowHeight(16); model.setData((ArrayList) ExcelUtils.sortedListFromMap(GlobalVariableUtils.getExcelMap()), false); cl.show(cardPanel, "table"); break; case LISTINGVOLS: Runnable r = new Runnable() { @Override public void run() { if (!testConnexion()) { model.setData(listingVolsRecup(), false); setExcelButtonVisibility(false); setCameraButtonVisibility(false); setVisibilityRefresh(true); itemsTable.setRowHeight(16); cl.show(cardPanel, "table"); } else { JOptionPane.showMessageDialog(ListPanel.this, "Pas de connexion internet :\n" + "Veuillez vérifier votre connexion.", "Warning", JOptionPane.WARNING_MESSAGE); } } }; ProgressDialog progressDialog = new ProgressDialog(new JFrame(), r, "Récupération des données en cours..."); progressDialog.setVisible(true); break; case CARNETADRESSE: setVisibilityRefresh(false); setExcelButtonVisibility(false); setCameraButtonVisibility(false); itemsTable.setRowHeight(16); model.setData(carnetAdresses, false); cl.show(cardPanel, "table"); break; case PLAN: setVisibilityRefresh(false); setExcelButtonVisibility(false); setCameraButtonVisibility(false); cl.show(cardPanel, "plans"); break; case NONE: setExcelButtonVisibility(false); setVisibilityRefresh(false); setCameraButtonVisibility(false); break; default: break; } model.fireTableStructureChanged(); } private void setExcelButtonVisibility(boolean bool) { if (bool == false) { jLabel1.setVisible(false); monthComboBox.setVisible(false); yearComboBox.setVisible(false); } else { jLabel1.setVisible(true); monthComboBox.setVisible(true); yearComboBox.setVisible(true); } } private void setCameraButtonVisibility(boolean bool) { if (bool == false) { cameraButton.setVisible(false); } else { cameraButton.setVisible(true); cameraButton.setOpaque(false); cameraButton.setContentAreaFilled(false); cameraButton.setBorderPainted(false); } } @Override public void actionPerformed(ActionEvent e) { if (e.getSource() == cameraButton) { if (isCameraActive == true) { cameraInterface(!isCameraActive); cameraButton.setIcon(ComponentManager.getInstance().getComponentIconDefaults().getgreenCameraIcon()); toolbarsListener.changeCameraStatus(isCameraActive); } else { cameraInterface(!isCameraActive); toolbarsListener.changeCameraStatus(isCameraActive); cameraButton.setIcon(ComponentManager.getInstance().getComponentIconDefaults().getredCameraIcon()); } } if (e.getSource() == refreshButton) { System.out.println("Button Refresh clicked"); Runnable r = new Runnable() { @Override public void run() { if (!testConnexion()) { model.setData(listingVolsRecup(), false); } else { JOptionPane.showMessageDialog(ListPanel.this, "Pas de connexion internet :\n" + "Veuillez vérifier votre connexion.", "Warning", JOptionPane.WARNING_MESSAGE); } } }; ProgressDialog progressDialog = new ProgressDialog(new JFrame(), r, "Récupération des données en cours..."); progressDialog.setVisible(true); } } private void setMonthComboboxItems() { DateFormatSymbols symbols = new DateFormatSymbols(); String[] monthNames = symbols.getMonths(); this.monthComboBox.setModel(new DefaultComboBoxModel(monthNames)); } private void setYearComboboxItems() { ArrayList<Integer> listYears = DatabaseHelper.getYearsCompletePlusActual(); Collections.sort(listYears); Integer[] years = listYears.toArray(new Integer[0]); yearComboBox.setModel(new DefaultComboBoxModel(years)); } public boolean testConnexion() { boolean internet = false; URL url; try { url = new URL("http: HttpURLConnection urlConn; urlConn = (HttpURLConnection) url.openConnection(); urlConn.connect(); internet = false; } catch (MalformedURLException ex) { Logger.getLogger(ListPanel.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { internet = true; Logger.getLogger(ListPanel.class.getName()).log(Level.SEVERE, null, ex); } return internet; } private void cameraInterface(final boolean on) { isCameraActive = !isCameraActive; Runnable r = new Runnable() { @Override public void run() { // On souhaite lancer l'activation des cameras if (on) { for (int i = 0; i < cameras.size(); i++) { Camera cam = cameras.get(i); if (cam != null && cam.getFaceDetectorThread() != null && !cam.getFaceDetectorThread().isActive()) { cam.getFaceDetectorThread().launch(0); } else if (cam == null) { cam = new Camera(i); cam.setFaceDetectorThread(new FaceDetectorThread(faceDetectorListener)); cam.getFaceDetectorThread().launch(0); } else if (cam.getFaceDetectorThread() == null) { cam.setFaceDetectorThread(new FaceDetectorThread(faceDetectorListener)); cam.getFaceDetectorThread().launch(0); } else if (cam.getFaceDetectorThread() != null && cam.getFaceDetectorThread().isActive()) { // do nothing } } } // Extinction du systeme de detection else { for (int i = 0; i < cameras.size(); i++) { Camera cam = cameras.get(i); if (cam != null && cam.getFaceDetectorThread() != null && !cam.getFaceDetectorThread().isActive()) { // do nothing } else if (cam == null) { // do nothing } else if (cam.getFaceDetectorThread() == null) { // do nothing } else if (cam.getFaceDetectorThread() != null && cam.getFaceDetectorThread().isActive()) { cam.getFaceDetectorThread().stopFaceDetection(); cam.setFaceDetectorThread(null); } } } } }; ProgressDialog progressDialog = new ProgressDialog(new JFrame(), r, "Traitement en cours..."); if (on) { progressDialog.setMessage("Activation des caméras en cours..."); } else { progressDialog.setMessage("Désactivation des caméras en cours..."); } progressDialog.setVisible(true); } @Override public void getCountFaceDetected(int number_of_faces) { System.out.println("List Panel NB FACES : " + number_of_faces); } //Fonction pour rendre le bouton refresh visible private void setVisibilityRefresh(boolean bool) { if (bool == false) { refreshButton.setVisible(false); } else { refreshButton.setVisible(true); } } private ArrayList<ListingVols> listingVolsRecup() { //isRefreshBoutonActive = !isRefreshBoutonActive; try { //On se connecte au site et on charge le document html Document doc = Jsoup.connect("http: int el = doc.select("td").size(); int nb = 0; String[] tab = new String[6]; ArrayList<ListingVols> ensembleDesVols = new ArrayList<ListingVols>(); ListingVols listingVols = null; for (int i = 3; i < el; i++) { listingVols = new ListingVols(); Element element = doc.select("td").get(i); String element1 = element.text(); tab[nb] = element1; nb++; if (nb == 6) { for (int j = 0; j < 6; j++) { switch (j) { case 0: listingVols.setDate1(tab[j]); break; case 1: listingVols.setHeure(tab[j]); break; case 2: listingVols.setDestination(tab[j]); break; case 3: listingVols.setNumeroVol(tab[j]); break; case 4: listingVols.setCompagnie(tab[j]); break; case 5: listingVols.setObservation(tab[j]); default: break; } } nb = 0; ensembleDesVols.add(listingVols); } } return ensembleDesVols; } catch (MalformedURLException | NumberFormatException | java.lang.ArrayIndexOutOfBoundsException e) { System.out.println(e); } catch (IOException ex) { System.out.println(ex); } return null; } /** * 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. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jSpinnerPanel = new javax.swing.JPanel(); jLabel1 = new javax.swing.JLabel(); cameraButton = new javax.swing.JButton(); monthComboBox = new javax.swing.JComboBox(); yearComboBox = new javax.swing.JComboBox(); refreshButton = new javax.swing.JButton(); cardPanel = new javax.swing.JPanel(); scrollPaneTable = new javax.swing.JScrollPane(); itemsTable = new javax.swing.JTable(); scrollPanePlans = new javax.swing.JScrollPane(); setLayout(new java.awt.BorderLayout()); jSpinnerPanel.setPreferredSize(new java.awt.Dimension(40, 40)); jLabel1.setText("Sélectionner date :"); jSpinnerPanel.add(jLabel1); cameraButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/nomoreline/img/greencamera.png"))); // NOI18N cameraButton.setPreferredSize(new java.awt.Dimension(35, 35)); jSpinnerPanel.add(cameraButton); monthComboBox.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" })); jSpinnerPanel.add(monthComboBox); yearComboBox.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" })); jSpinnerPanel.add(yearComboBox); refreshButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/nomoreline/img/refresh.png"))); // NOI18N refreshButton.setBorderPainted(false); refreshButton.setContentAreaFilled(false); refreshButton.setMaximumSize(new java.awt.Dimension(35, 35)); refreshButton.setMinimumSize(new java.awt.Dimension(35, 35)); refreshButton.setPreferredSize(new java.awt.Dimension(35, 35)); jSpinnerPanel.add(refreshButton); add(jSpinnerPanel, java.awt.BorderLayout.PAGE_START); cardPanel.setLayout(new java.awt.CardLayout()); itemsTable.setAutoCreateRowSorter(true); itemsTable.setModel(new MyTableModel()); itemsTable.setFillsViewportHeight(true); itemsTable.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION); itemsTable.setShowHorizontalLines(false); itemsTable.setShowVerticalLines(false); itemsTable.getTableHeader().setReorderingAllowed(false); scrollPaneTable.setViewportView(itemsTable); cardPanel.add(scrollPaneTable, "table"); cardPanel.add(scrollPanePlans, "plans"); add(cardPanel, java.awt.BorderLayout.CENTER); }// </editor-fold>//GEN-END:initComponents // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton cameraButton; private javax.swing.JPanel cardPanel; private javax.swing.JTable itemsTable; private javax.swing.JLabel jLabel1; private javax.swing.JPanel jSpinnerPanel; private javax.swing.JComboBox monthComboBox; private javax.swing.JButton refreshButton; private javax.swing.JScrollPane scrollPanePlans; private javax.swing.JScrollPane scrollPaneTable; private javax.swing.JComboBox yearComboBox; // End of variables declaration//GEN-END:variables @Override public void mouseDragged(MouseEvent e) { } @Override public void mouseMoved(MouseEvent e) { } @Override public void mouseClicked(MouseEvent e) { } @Override public void mousePressed(MouseEvent e) { } @Override public void mouseReleased(MouseEvent e) { } @Override public void mouseEntered(MouseEvent e) { } @Override public void mouseExited(MouseEvent e) { } }
package com.cluttered.cryptocurrency.ann; import ch.obermuhlner.math.big.BigFloat; import com.cluttered.cryptocurrency.ann.neuron.Neuron; import java.util.ArrayList; import java.util.List; /** * @author cluttered.code@gmail.com */ public class Layer { private final List<Neuron> neurons; public Layer(final List<Neuron> neurons) { this.neurons = neurons; } public List<BigFloat> fire(final List<BigFloat> inputs) { // TODO: parallelize and profile speed // Stream was untestable by JMockit final List<BigFloat> results = new ArrayList<>(neurons.size()); for(final Neuron neuron : neurons) { results.add(neuron.fire(inputs)); } return results; } }
package de.otto.edison.about.spec; import de.otto.edison.annotations.Beta; /** * Non-functional requirements regarding the performance of something this service is depending on. * */ @Beta public enum Performance { /** * Depending on your overall requirements, this might be something like &lt; 20ms in the 99 percentile: */ HIGH, /** * Depending on your overall requirements, this might be something like &lt; 200ms in the 99 percentile: */ MEDIUM, /** * Depending on your overall requirements, this might be something like &lt; 2000ms in the 99 percentile: */ LOW, /** Default value if no performance requirements where specified. */ NOT_SPECIFIED }
package arez.processor; import java.util.Arrays; import java.util.Collections; import javax.annotation.Nonnull; import javax.tools.JavaFileObject; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; public class ArezProcessorTest extends AbstractArezProcessorTest { @DataProvider( name = "successfulCompiles" ) public Object[][] successfulCompiles() { return new Object[][] { new Object[]{ "com.example.SubpackageModel", false, false, false, false }, new Object[]{ "com.example.action.ActionTypeParametersModel", false, false, false, false }, new Object[]{ "com.example.action.NewTypeParametersModel", false, false, false, false }, new Object[]{ "com.example.action.NoReportParametersModel", false, false, false, false }, new Object[]{ "com.example.action.FunctionActionThrowsRuntimeExceptionModel", false, false, false, false }, new Object[]{ "com.example.action.FunctionActionThrowsThrowableModel", false, false, false, false }, new Object[]{ "com.example.action.MultiThrowAction", false, false, false, false }, new Object[]{ "com.example.action.NonStandardNameActionModel", false, false, false, false }, new Object[]{ "com.example.action.UnsafeSpecificFunctionActionModel", false, false, false, false }, new Object[]{ "com.example.action.UnsafeSpecificProcedureActionModel", false, false, false, false }, new Object[]{ "com.example.action.UnsafeFunctionActionModel", false, false, false, false }, new Object[]{ "com.example.action.UnsafeProcedureActionModel", false, false, false, false }, new Object[]{ "com.example.action.NoReportResultActionModel", false, false, false, false }, new Object[]{ "com.example.action.NoVerifyActionModel", false, false, false, false }, new Object[]{ "com.example.action.ReadOnlyActionModel", false, false, false, false }, new Object[]{ "com.example.action.RequiresNewTxTypeActionModel", false, false, false, false }, new Object[]{ "com.example.action.RequiresTxTypeActionModel", false, false, false, false }, new Object[]{ "com.example.action.BasicFunctionActionModel", false, false, false, false }, new Object[]{ "com.example.action.BasicActionModel", false, false, false, false }, new Object[]{ "com.example.cascade_dispose.ComponentCascadeDisposeModel", false, false, false, false }, new Object[]{ "com.example.cascade_dispose.ComponentCascadeDisposeMethodModel", false, false, false, false }, new Object[]{ "com.example.cascade_dispose.DisposableCascadeDisposeModel", false, false, false, false }, new Object[]{ "com.example.cascade_dispose.DisposableCascadeDisposeMethodModel", false, false, false, false }, new Object[]{ "com.example.cascade_dispose.NonStandardNameCascadeDisposeMethodModel", false, false, false, false }, new Object[]{ "com.example.cascade_dispose.NonStandardNameDisposableCascadeDisposeModel", false, false, false, false }, new Object[]{ "com.example.component.AnnotatedConcreteModel", false, false, false, false }, new Object[]{ "com.example.component.PublicCtorNonPublicModel", false, false, false, false }, new Object[]{ "com.example.collections.AbstractCollectionObservableModel", false, false, false, false }, new Object[]{ "com.example.collections.AbstractListObservableModel", false, false, false, false }, new Object[]{ "com.example.collections.AbstractMapObservableModel", false, false, false, false }, new Object[]{ "com.example.collections.AbstractNonnullCollectionObservableModel", false, false, false, false }, new Object[]{ "com.example.collections.AbstractNonnullListObservableModel", false, false, false, false }, new Object[]{ "com.example.collections.AbstractNonnullMapObservableModel", false, false, false, false }, new Object[]{ "com.example.collections.AbstractNonnullSetObservableModel", false, false, false, false }, new Object[]{ "com.example.collections.AbstractSetObservableModel", false, false, false, false }, new Object[]{ "com.example.collections.MemoizeCollectionModel", false, false, false, false }, new Object[]{ "com.example.collections.MemoizeCollectionWithHooksModel", false, false, false, false }, new Object[]{ "com.example.collections.MemoizeKeepAliveListModel", false, false, false, false }, new Object[]{ "com.example.collections.MemoizeListModel", false, false, false, false }, new Object[]{ "com.example.collections.MemoizeMapModel", false, false, false, false }, new Object[]{ "com.example.collections.MemoizeNonnullCollectionModel", false, false, false, false }, new Object[]{ "com.example.collections.MemoizeNonnullListModel", false, false, false, false }, new Object[]{ "com.example.collections.MemoizeNonnullMapModel", false, false, false, false }, new Object[]{ "com.example.collections.MemoizeNonnullSetModel", false, false, false, false }, new Object[]{ "com.example.collections.MemoizeSetModel", false, false, false, false }, new Object[]{ "com.example.collections.ObservableCollectionModel", false, false, false, false }, new Object[]{ "com.example.collections.ObservableListModel", false, false, false, false }, new Object[]{ "com.example.collections.ObservableMapModel", false, false, false, false }, new Object[]{ "com.example.collections.ObservableNonnullCollectionModel", false, false, false, false }, new Object[]{ "com.example.collections.ObservableNonnullListModel", false, false, false, false }, new Object[]{ "com.example.collections.ObservableNonnullMapModel", false, false, false, false }, new Object[]{ "com.example.collections.ObservableNonnullSetModel", false, false, false, false }, new Object[]{ "com.example.collections.ObservableNoSettersModel", false, false, false, false }, new Object[]{ "com.example.collections.ObservableSetModel", false, false, false, false }, new Object[]{ "com.example.component.DisposeOnDeactivateModel", false, false, false, false }, new Object[]{ "com.example.component.GeneratedNonEmptyComponent", false, false, false, false }, new Object[]{ "com.example.component.NoRequireEqualsModel", false, false, false, false }, new Object[]{ "com.example.component.NotObservableModel", false, false, false, false }, new Object[]{ "com.example.component.ObservableModel", false, false, false, false }, new Object[]{ "com.example.component_id.BooleanComponentId", false, false, false, false }, new Object[]{ "com.example.component_id.BooleanComponentIdRequireEquals", false, false, false, false }, new Object[]{ "com.example.component_id.ByteComponentId", false, false, false, false }, new Object[]{ "com.example.component_id.ByteComponentIdRequireEquals", false, false, false, false }, new Object[]{ "com.example.component_id.CharComponentId", false, false, false, false }, new Object[]{ "com.example.component_id.CharComponentIdRequireEquals", false, false, false, false }, new Object[]{ "com.example.component_id.ComponentIdOnModel", false, false, false, false }, new Object[]{ "com.example.component_id.DoubleComponentId", false, false, false, false }, new Object[]{ "com.example.component_id.DoubleComponentIdRequireEquals", false, false, false, false }, new Object[]{ "com.example.component_id.FloatComponentId", false, false, false, false }, new Object[]{ "com.example.component_id.FloatComponentIdRequireEquals", false, false, false, false }, new Object[]{ "com.example.component_id.IntComponentId", false, false, false, false }, new Object[]{ "com.example.component_id.IntComponentIdRequireEquals", false, false, false, false }, new Object[]{ "com.example.component_id.LongComponentId", false, false, false, false }, new Object[]{ "com.example.component_id.LongComponentIdRequireEquals", false, false, false, false }, new Object[]{ "com.example.component_id.NonStandardNameComponentId", false, false, false, false }, new Object[]{ "com.example.component_id.ObjectComponentId", false, false, false, false }, new Object[]{ "com.example.component_id.ObjectComponentIdRequireEquals", false, false, false, false }, new Object[]{ "com.example.component_id.ShortComponentId", false, false, false, false }, new Object[]{ "com.example.component_id.ShortComponentIdRequireEquals", false, false, false, false }, new Object[]{ "com.example.component_id.ComponentIdOnSingletonModel", false, false, false, false }, new Object[]{ "com.example.component_id_ref.BasicModel", false, false, false, false }, new Object[]{ "com.example.component_id_ref.CombinedWithComponentIdModel", false, false, false, false }, new Object[]{ "com.example.component_id_ref.NonIntTypeModel", false, false, false, false }, new Object[]{ "com.example.component_id_ref.NonStandardNameModel", false, false, false, false }, new Object[]{ "com.example.component_name_ref.ComponentNameModel", false, false, false, false }, new Object[]{ "com.example.component_name_ref.ComponentTypeNameModel", false, false, false, false }, new Object[]{ "com.example.component_name_ref.ComponentTypeNameAloneOnSingletonModel", false, false, false, false }, new Object[]{ "com.example.component_name_ref.ComponentNameOnSingletonModel", false, false, false, false }, new Object[]{ "com.example.component_name_ref.NonStandardNameComponentTypeNameModel", false, false, false, false }, new Object[]{ "com.example.component_name_ref.NonStandardNameModel", false, false, false, false }, new Object[]{ "com.example.component_ref.AnnotatedComponent", false, false, false, false }, new Object[]{ "com.example.component_ref.NonStandardNameComponent", false, false, false, false }, new Object[]{ "com.example.component_ref.SimpleComponent", false, false, false, false }, new Object[]{ "com.example.component_ref.ProtectedAccessComponent", false, false, false, false }, new Object[]{ "com.example.memoize.ArezOrNoneDependenciesModel", false, false, false, false }, new Object[]{ "com.example.memoize.NameVariationsModel", false, false, false, false }, new Object[]{ "com.example.memoize.HighestPriorityModel", false, false, false, false }, new Object[]{ "com.example.memoize.HighPriorityModel", false, false, false, false }, new Object[]{ "com.example.memoize.NormalPriorityModel", false, false, false, false }, new Object[]{ "com.example.memoize.LowestPriorityModel", false, false, false, false }, new Object[]{ "com.example.memoize.LowPriorityModel", false, false, false, false }, new Object[]{ "com.example.memoize.NonArezDependenciesModel", false, false, false, false }, new Object[]{ "com.example.memoize.NoReportResultModel", false, false, false, false }, new Object[]{ "com.example.memoize.WithHooksModel", false, false, false, false }, new Object[]{ "com.example.memoize.KeepAliveModel", false, false, false, false }, new Object[]{ "com.example.memoize.ObserveLowerPriorityModel", false, false, false, false }, new Object[]{ "com.example.memoize.OnActivateModel", false, false, false, false }, new Object[]{ "com.example.memoize.OnDeactivateModel", false, false, false, false }, new Object[]{ "com.example.memoize.OnStaleModel", false, false, false, false }, new Object[]{ "com.example.memoize.ReadOutsideTransactionModel", false, false, false, false }, new Object[]{ "com.example.memoize.ScheduleDeferredKeepAliveModel", false, false, false, false }, new Object[]{ "com.example.memoize.TypeParametersModel", false, false, false, false }, new Object[]{ "com.example.computable_value_ref.DefaultRefNameModel", false, false, false, false }, new Object[]{ "com.example.computable_value_ref.NonStandardName2Model", false, false, false, false }, new Object[]{ "com.example.computable_value_ref.NonStandardNameModel", false, false, false, false }, new Object[]{ "com.example.computable_value_ref.ParametersComputableValueModel", false, false, false, false }, new Object[]{ "com.example.computable_value_ref.RawComputableValueModel", false, false, false, false }, new Object[]{ "com.example.context_ref.AnnotatedComponent", false, false, false, false }, new Object[]{ "com.example.context_ref.NonStandardNameComponent", false, false, false, false }, new Object[]{ "com.example.context_ref.SimpleComponent", false, false, false, false }, new Object[]{ "com.example.context_ref.ProtectedAccessComponent", false, false, false, false }, new Object[]{ "com.example.component_dependency.AbstractObservableDependency", false, false, false, false }, new Object[]{ "com.example.component_dependency.BasicDependencyModel", false, false, false, false }, new Object[]{ "com.example.component_dependency.BasicFieldDependencyModel", false, false, false, false }, new Object[]{ "com.example.component_dependency.CascadeDependencyModel", false, false, false, false }, new Object[]{ "com.example.component_dependency.CascadeFieldDependencyModel", false, false, false, false }, new Object[]{ "com.example.component_dependency.ComplexDependencyModel", false, false, false, false }, new Object[]{ "com.example.component_dependency.ComplexDependencyWithCustomNameMethodModel", false, false, false, false }, new Object[]{ "com.example.component_dependency.ComponentDependencyModel", false, false, false, false }, new Object[]{ "com.example.component_dependency.ComponentFieldDependencyModel", false, false, false, false }, new Object[]{ "com.example.component_dependency.ConcreteObservablePairWithInitializerDependency", false, false, false, false }, new Object[]{ "com.example.component_dependency.NonCascadeObservableDependency", false, false, false, false }, new Object[]{ "com.example.component_dependency.NonnullAbstractObservableDependency", false, false, false, false }, new Object[]{ "com.example.component_dependency.NonnullFieldDependencyModel", false, false, false, false }, new Object[]{ "com.example.component_dependency.NonnullObservableDependency", false, false, false, false }, new Object[]{ "com.example.component_dependency.NonStandardNameDependencyModel", false, false, false, false }, new Object[]{ "com.example.component_dependency.NonStandardNameFieldDependencyModel", false, false, false, false }, new Object[]{ "com.example.component_dependency.ObservableDependency", false, false, false, false }, new Object[]{ "com.example.component_dependency.ObservablePairWithInitializerDependency", false, false, false, false }, new Object[]{ "com.example.component_dependency.ObservablePairAnnotatedDependency", false, false, false, false }, new Object[]{ "com.example.component_dependency.ScheduleDeferredDependencyModel", false, false, false, false }, new Object[]{ "com.example.component_dependency.SetNullObservableDependency", false, false, false, false }, new Object[]{ "com.example.deprecated.DeprecatedActionModel", false, false, false, false }, new Object[]{ "com.example.deprecated.DeprecatedObserveModel", false, false, false, false }, new Object[]{ "com.example.deprecated.DeprecatedMemoizeModel1", false, false, false, false }, new Object[]{ "com.example.deprecated.DeprecatedMemoizeModel2", false, false, false, false }, new Object[]{ "com.example.deprecated.DeprecatedMemoizeModel3", false, false, false, false }, new Object[]{ "com.example.deprecated.DeprecatedMemoizeModel4", false, false, false, false }, new Object[]{ "com.example.deprecated.DeprecatedMemoize5Model", false, false, false, false }, new Object[]{ "com.example.deprecated.DeprecatedObservableModel1", false, false, false, false }, new Object[]{ "com.example.deprecated.DeprecatedObservableModel2", false, false, false, false }, new Object[]{ "com.example.deprecated.DeprecatedPostConstructModel", false, false, false, false }, new Object[]{ "com.example.deprecated.DeprecatedObserveModel1", false, false, false, false }, new Object[]{ "com.example.deprecated.DeprecatedObserveModel2", false, false, false, false }, new Object[]{ "com.example.deprecated.DeprecatedObserveModel3", false, false, false, false }, new Object[]{ "com.example.deprecated.DeprecatedObserveModel4", false, false, false, false }, new Object[]{ "com.example.dispose_notifier.DisposeNotifierModel", false, false, false, false }, new Object[]{ "com.example.dispose_notifier.NoDisposeNotifierModel", false, false, false, false }, new Object[]{ "com.example.id.ComponentIdExample", false, false, false, false }, new Object[]{ "com.example.id.NonStandardNameModel", false, false, false, false }, new Object[]{ "com.example.id.RepositoryExample", false, false, true, true }, new Object[]{ "com.example.id.RequireIdDisable", false, false, false, false }, new Object[]{ "com.example.id.RequireIdEnable", false, false, false, false }, new Object[]{ "com.example.inject.BasicInjectModel", false, false, false, false }, new Object[]{ "com.example.inject.ConsumeInjectViaAnnotationWithPostConstructModel", false, true, false, false }, new Object[]{ "com.example.inject.CtorInjectModel", false, false, false, false }, new Object[]{ "com.example.inject.CtorInjectWithFactoryModel", false, false, false, false }, new Object[]{ "com.example.inject.CtorInjectWithObserveAndFactoryModel", false, false, false, false }, new Object[]{ "com.example.inject.CtorInjectWithObserveModel", false, false, false, false }, new Object[]{ "com.example.inject.CtorInjectWithPostConstructAndFactoryModel", false, false, false, false }, new Object[]{ "com.example.inject.CtorInjectWithPostConstructModel", false, false, false, false }, new Object[]{ "com.example.inject.CtorInjectWithTrackingObserveAndFactoryModel", false, false, false, false }, new Object[]{ "com.example.inject.CtorInjectWithTrackingObserveModel", false, false, false, false }, new Object[]{ "com.example.inject.DefaultCtorModel", false, false, false, false }, new Object[]{ "com.example.inject.FactoryConsumer1Model", false, true, false, false }, new Object[]{ "com.example.inject.FactoryConsumer2Model", false, true, false, false }, new Object[]{ "com.example.inject.FactoryConsumer3Model", false, true, false, false }, new Object[]{ "com.example.inject.FactoryConsumer4Model", false, true, false, false }, new Object[]{ "com.example.inject.FactoryConsumer5Model", false, true, false, false }, new Object[]{ "com.example.inject.FactoryConsumer6Model", false, true, false, false }, new Object[]{ "com.example.inject.FactoryConsumer7Model", false, true, false, false }, new Object[]{ "com.example.inject.InjectViaAnnotationModel", false, false, false, false }, new Object[]{ "com.example.inject.InjectViaAnnotationWithPostConstructModel", false, true, false, false }, new Object[]{ "com.example.inject.MultipleArgsModel", false, false, false, false }, new Object[]{ "com.example.inject.NoInjectModel", false, false, false, false }, new Object[]{ "com.example.inject.NonPublicConsumeInjectViaAnnotationWithPostConstructModel", false, true, false, false }, new Object[]{ "com.example.inject.ProvideInjectViaAnnotationWithPostConstructModel", false, true, false, false }, new Object[]{ "com.example.inject.ScopedButNoDaggerModel", false, false, false, false }, new Object[]{ "com.example.inject.ScopedInjectModel", true, false, false, false }, new Object[]{ "com.example.inverse.CustomNamesInverseModel", false, false, false, false }, new Object[]{ "com.example.inverse.DefaultMultiplicityInverseModel", false, false, false, false }, new Object[]{ "com.example.inverse.DisableInverseModel", false, false, false, false }, new Object[]{ "com.example.inverse.NonGetterInverseModel", false, false, false, false }, new Object[]{ "com.example.inverse.NonObservableCollectionInverseModel", false, false, false, false }, new Object[]{ "com.example.inverse.NonObservableNullableManyReferenceModel", false, false, false, false }, new Object[]{ "com.example.inverse.NonObservableNullableOneReferenceModel", false, false, false, false }, new Object[]{ "com.example.inverse.NonObservableNullableZeroOrOneReferenceModel", false, false, false, false }, new Object[]{ "com.example.inverse.NonStandardNameModel", false, false, false, false }, new Object[]{ "com.example.inverse.ObservableCollectionInverseModel", false, false, false, false }, new Object[]{ "com.example.inverse.ObservableListInverseModel", false, false, false, false }, new Object[]{ "com.example.inverse.ObservableManyReferenceModel", false, false, false, false }, new Object[]{ "com.example.inverse.ObservableOneReferenceModel", false, false, false, false }, new Object[]{ "com.example.inverse.ObservableReferenceInverseModel", false, false, false, false }, new Object[]{ "com.example.inverse.ObservableSetInverseModel", false, false, false, false }, new Object[]{ "com.example.inverse.ObservableZeroOrOneReferenceModel", false, false, false, false }, new Object[]{ "com.example.inverse.OneMultiplicityInverseModel", false, false, false, false }, new Object[]{ "com.example.inverse.ZeroOrOneMultiplicityInverseModel", false, false, false, false }, new Object[]{ "com.example.memoize.BasicModel", false, false, false, false }, new Object[]{ "com.example.memoize.CustomDepTypeModel", false, false, false, false }, new Object[]{ "com.example.memoize.CustomPriorityModel", false, false, false, false }, new Object[]{ "com.example.memoize.LocalTypeParamModel", false, false, false, false }, new Object[]{ "com.example.memoize.NonStandardNameModel", false, false, false, false }, new Object[]{ "com.example.memoize.TypeParamModel", false, false, false, false }, new Object[]{ "com.example.observable.AbstractNonPrimitiveObservablesModel", false, false, false, false }, new Object[]{ "com.example.observable.AbstractObservablesModel", false, false, false, false }, new Object[]{ "com.example.observable.GenericObservableModel", false, false, false, false }, new Object[]{ "com.example.observable.InitializerAndConstructorParamNameCollisionModel", false, false, false, false }, new Object[]{ "com.example.observable.NonStandardNameModel", false, false, false, false }, new Object[]{ "com.example.observable.NullableInitializerModel", false, false, false, false }, new Object[]{ "com.example.observable.ObservableWithNoSetter", false, false, false, false }, new Object[]{ "com.example.observable.ReadOutsideTransactionObservableModel", false, false, false, false }, new Object[]{ "com.example.observable.SetterAlwaysMutatesFalseObjectValue", false, false, false, false }, new Object[]{ "com.example.observable.SetterAlwaysMutatesFalsePrimitiveValue", false, false, false, false }, new Object[]{ "com.example.observable.WildcardGenericObservableModel", false, false, false, false }, new Object[]{ "com.example.observable.WriteOutsideTransactionObservablesModel", false, false, false, false }, new Object[]{ "com.example.observable.WriteOutsideTransactionThrowingObservablesModel", false, false, false, false }, new Object[]{ "com.example.observable.AbstractNonPrimitiveNonnullObservablesModel", false, false, false, false }, new Object[]{ "com.example.observable.AbstractPrimitiveObservablesWithInitializerModel", false, false, false, false }, new Object[]{ "com.example.observable_value_ref.DefaultRefNameModel", false, false, false, false }, new Object[]{ "com.example.observable_value_ref.GenericObservableRefModel", false, false, false, false }, new Object[]{ "com.example.observable_value_ref.NonStandardName2Model", false, false, false, false }, new Object[]{ "com.example.observable_value_ref.NonStandardNameModel", false, false, false, false }, new Object[]{ "com.example.observable_value_ref.RawObservableModel", false, false, false, false }, new Object[]{ "com.example.observe.BasicObserveModel", false, false, false, false }, new Object[]{ "com.example.observe.NestedActionsAllowedObserveModel", false, false, false, false }, new Object[]{ "com.example.observe.HighestPriorityObserveModel", false, false, false, false }, new Object[]{ "com.example.observe.HighPriorityObserveModel", false, false, false, false }, new Object[]{ "com.example.observe.LowestPriorityObserveModel", false, false, false, false }, new Object[]{ "com.example.observe.LowPriorityObserveModel", false, false, false, false }, new Object[]{ "com.example.observe.NormalPriorityObserveModel", false, false, false, false }, new Object[]{ "com.example.observe.ObserveLowerPriorityObserveModel", false, false, false, false }, new Object[]{ "com.example.observe.ReadWriteObserveModel", false, false, false, false }, new Object[]{ "com.example.observe.ScheduleAfterConstructedModel", false, false, false, false }, new Object[]{ "com.example.observe.ScheduleDeferredModel", false, false, false, false }, new Object[]{ "com.example.observe.ArezOrNoneDependenciesModel", false, false, false, false }, new Object[]{ "com.example.observe.BasicTrackedModel", false, false, false, false }, new Object[]{ "com.example.observe.BasicTrackedWithExceptionsModel", false, false, false, false }, new Object[]{ "com.example.observe.NestedActionsAllowedTrackedModel", false, false, false, false }, new Object[]{ "com.example.observe.NonArezDependenciesModel", false, false, false, false }, new Object[]{ "com.example.observe.NonStandardNameTrackedModel", false, false, false, false }, new Object[]{ "com.example.observe.DeriveFinalOnDepsChangeModel", false, false, false, false }, new Object[]{ "com.example.observe.DeriveOnDepsChangeModel", false, false, false, false }, new Object[]{ "com.example.observe.DeriveTrackedModel", false, false, false, false }, new Object[]{ "com.example.observe.HighestPriorityTrackedModel", false, false, false, false }, new Object[]{ "com.example.observe.HighPriorityTrackedModel", false, false, false, false }, new Object[]{ "com.example.observe.NormalPriorityTrackedModel", false, false, false, false }, new Object[]{ "com.example.observe.LowestPriorityTrackedModel", false, false, false, false }, new Object[]{ "com.example.observe.LowPriorityTrackedModel", false, false, false, false }, new Object[]{ "com.example.observe.NoReportParametersModel", false, false, false, false }, new Object[]{ "com.example.observe.NoReportResultModel", false, false, false, false }, new Object[]{ "com.example.observe.ObserveLowerPriorityTrackedModel", false, false, false, false }, new Object[]{ "com.example.observe.ProtectedAccessTrackedModel", false, false, false, false }, new Object[]{ "com.example.observe.TrackedAllTypesModel", false, false, false, false }, new Object[]{ "com.example.observe.TrackedAndSchedulableModel", false, false, false, false }, new Object[]{ "com.example.observe.TrackedNoOtherSchedulableModel", false, false, false, false }, new Object[]{ "com.example.observer_ref.CustomNameRefOnObserveModel1", false, false, false, false }, new Object[]{ "com.example.observer_ref.CustomNameRefOnObserveModel2", false, false, false, false }, new Object[]{ "com.example.observer_ref.CustomNameRefOnObserveModel3", false, false, false, false }, new Object[]{ "com.example.observer_ref.RefOnObserveModel1", false, false, false, false }, new Object[]{ "com.example.observer_ref.RefOnBothModel", false, false, false, false }, new Object[]{ "com.example.observer_ref.RefOnObserveModel2", false, false, false, false }, new Object[]{ "com.example.overloaded_names.OverloadedActions", false, false, false, false }, new Object[]{ "com.example.post_construct.NonStandardNamePostConstructModel", false, false, false, false }, new Object[]{ "com.example.post_construct.PostConstructModel", false, false, false, false }, new Object[]{ "com.example.post_dispose.PostDisposeModel", false, false, false, false }, new Object[]{ "com.example.post_dispose.PostDisposeWithDisabledDisposeNotifierModel", false, false, false, false }, new Object[]{ "com.example.priority_override.CustomNameModel", false, false, false, false }, new Object[]{ "com.example.priority_override.MemoizeModel", false, false, false, false }, new Object[]{ "com.example.priority_override.ObserveModel", false, false, false, false }, new Object[]{ "com.example.priority_override.ParameterForDefaultMemoizeModel", false, false, false, false }, new Object[]{ "com.example.priority_override.ParameterForDefaultObserveModel", false, false, false, false }, new Object[]{ "com.example.reference.CustomNameReferenceModel2", false, false, false, false }, new Object[]{ "com.example.reference.CustomNameReferenceModel", false, false, false, false }, new Object[]{ "com.example.reference.EagerLoadNulableObservableReferenceModel", false, false, false, false }, new Object[]{ "com.example.reference.EagerLoadObservableReferenceModel", false, false, false, false }, new Object[]{ "com.example.reference.EagerLoadReferenceModel", false, false, false, false }, new Object[]{ "com.example.reference.EagerObservableReadOutsideTransactionReferenceModel", false, false, false, false }, new Object[]{ "com.example.reference.ExplicitLoadObservableReferenceModel", false, false, false, false }, new Object[]{ "com.example.reference.ExplicitLoadReferenceModel", false, false, false, false }, new Object[]{ "com.example.reference.LazyLoadObservableReferenceModel", false, false, false, false }, new Object[]{ "com.example.reference.LazyLoadReferenceModel", false, false, false, false }, new Object[]{ "com.example.reference.LazyObservableReadOutsideTransactionReferenceModel", false, false, false, false }, new Object[]{ "com.example.reference.NonJavabeanNameReferenceModel", false, false, false, false }, new Object[]{ "com.example.reference.NonnullLazyLoadReferenceModel", false, false, false, false }, new Object[]{ "com.example.reference.NonObservableReferenceModel", false, false, false, false }, new Object[]{ "com.example.reference.NullableLazyLoadReferenceModel", false, false, false, false }, new Object[]{ "com.example.reference.ObservableReferenceModel", false, false, false, false }, new Object[]{ "com.example.repository.DaggerDisabledRepository", false, false, true, false }, new Object[]{ "com.example.repository.DaggerEnabledRepository", false, false, true, true }, new Object[]{ "com.example.repository.InjectEnabledRepository", false, false, true, true }, new Object[]{ "com.example.repository.InjectDisabledRepository", false, false, false, false }, new Object[]{ "com.example.repository.RepositoryWithAttachOnly", false, false, true, true }, new Object[]{ "com.example.repository.RepositoryWithCreateOnly", false, false, true, true }, new Object[]{ "com.example.repository.RepositoryWithCreateOrAttach", false, false, true, true }, new Object[]{ "com.example.repository.RepositoryPreDisposeHook", false, false, true, true }, new Object[]{ "com.example.repository.RepositoryWithDestroyAndDetach", false, false, true, true }, new Object[]{ "com.example.repository.RepositoryWithDetachNone", false, false, true, true }, new Object[]{ "com.example.repository.RepositoryWithDetachOnly", false, false, true, true }, new Object[]{ "com.example.repository.RepositoryWithExplicitId", false, false, true, true }, new Object[]{ "com.example.repository.RepositoryWithExplicitNonStandardId", false, false, true, true }, new Object[]{ "com.example.repository.RepositoryWithImplicitId", false, false, true, true }, new Object[]{ "com.example.repository.RepositoryWithInitializerModel", false, false, true, true }, new Object[]{ "com.example.repository.RepositoryWithInitializerNameCollisionModel", false, false, true, true }, new Object[]{ "com.example.repository.RepositoryWithMultipleCtors", false, false, true, true }, new Object[]{ "com.example.repository.RepositoryWithMultipleInitializersModel", false, false, true, true }, new Object[]{ "com.example.repository.RepositoryWithProtectedConstructor", false, false, true, true }, new Object[]{ "com.example.repository.RepositoryWithSingleton", false, false, true, true }, new Object[]{ "com.example.reserved_names.NonReservedNameModel", false, false, false, false }, new Object[]{ "com.example.to_string.NoToStringPresent", false, false, false, false }, new Object[]{ "com.example.to_string.ToStringPresent", false, false, false, false }, new Object[]{ "com.example.type_access_levels.ReduceAccessLevelModel", false, false, false, false }, new Object[]{ "com.example.verifiable.DisableVerifyModel", false, false, false, false }, new Object[]{ "com.example.verifiable.EnableVerifyModel", false, false, false, false }, new Object[]{ "DisposingModel", false, false, false, false }, new Object[]{ "ObservableTypeParametersModel", false, false, false, false }, new Object[]{ "TypeParametersOnModel", false, false, false, false }, new Object[]{ "ObservableGuessingModel", false, false, false, false }, new Object[]{ "AnnotationsOnModel", false, false, false, false }, new Object[]{ "ObservableWithAnnotatedCtorModel", false, false, false, false }, new Object[]{ "ObservableModelWithUnconventionalNames", false, false, false, false }, new Object[]{ "DifferentObservableTypesModel", false, false, false, false }, new Object[]{ "ObservableWithExceptingCtorModel", false, false, false, false }, new Object[]{ "OverrideNamesInModel", false, false, false, false }, new Object[]{ "ImplicitSingletonModel", true, false, false, false }, new Object[]{ "SingletonModel", false, false, false, false }, new Object[]{ "SingletonWithIdModel", true, false, false, false }, new Object[]{ "EmptyModel", false, false, false, false }, new Object[]{ "BasicModelWithDifferentAccessLevels", false, false, false, false }, new Object[]{ "ObservableWithCtorModel", false, false, false, false }, new Object[]{ "ObservableWithSpecificExceptionModel", false, false, false, false }, new Object[]{ "ObservableWithExceptionModel", false, false, false, false }, new Object[]{ "BasicObservableModel", false, false, false, false } }; } @Test( dataProvider = "successfulCompiles" ) public void processSuccessfulCompile( @Nonnull final String classname, final boolean componentDaggerEnabled, final boolean daggerComponentExtensionExpected, final boolean repositoryEnabled, final boolean repositoryDaggerEnabled ) throws Exception { assertSuccessfulCompile( classname, componentDaggerEnabled, daggerComponentExtensionExpected, repositoryEnabled, repositoryDaggerEnabled ); } @Test public void processSuccessfulMultipleInverseWithSameTarget() throws Exception { final JavaFileObject source1 = fixture( "input/com/example/inverse/MultipleReferenceWithInverseWithSameTarget.java" ); final String output1 = "expected/com/example/inverse/MultipleReferenceWithInverseWithSameTarget_Arez_RoleType.java"; final String output2 = "expected/com/example/inverse/MultipleReferenceWithInverseWithSameTarget_Arez_RoleTypeGeneralisation.java"; assertSuccessfulCompile( Collections.singletonList( source1 ), Arrays.asList( output1, output2 ) ); } @Test public void processSuccessfulRepositoryIncludingExtension() throws Exception { final JavaFileObject source1 = fixture( "input/com/example/repository/CompleteRepositoryExample.java" ); final JavaFileObject source2 = fixture( "input/com/example/repository/CompleteRepositoryExampleRepositoryExtension.java" ); final String output1 = "expected/com/example/repository/Arez_CompleteRepositoryExample.java"; final String output2 = "expected/com/example/repository/Arez_CompleteRepositoryExampleRepository.java"; final String output3 = "expected/com/example/repository/CompleteRepositoryExampleRepository.java"; final String output4 = "expected/com/example/repository/CompleteRepositoryExampleRepositoryDaggerModule.java"; assertSuccessfulCompile( Arrays.asList( source1, source2 ), Arrays.asList( output1, output2, output3, output4 ) ); } @Test public void processSuccessfulPackageAccessRepositoryIncludingExtension() throws Exception { final JavaFileObject source1 = fixture( "input/com/example/repository/PackageAccessRepositoryExample.java" ); final JavaFileObject source2 = fixture( "input/com/example/repository/PackageAccessRepositoryExampleRepositoryExtension.java" ); final String output1 = "expected/com/example/repository/Arez_PackageAccessRepositoryExample.java"; final String output2 = "expected/com/example/repository/Arez_PackageAccessRepositoryExampleRepository.java"; final String output3 = "expected/com/example/repository/PackageAccessRepositoryExampleRepository.java"; final String output4 = "expected/com/example/repository/PackageAccessRepositoryExampleRepositoryDaggerModule.java"; assertSuccessfulCompile( Arrays.asList( source1, source2 ), Arrays.asList( output1, output2, output3, output4 ) ); } @Test public void processSuccessfulInheritedProtectedAccessInDifferentPackage() throws Exception { final JavaFileObject source1 = fixture( "input/com/example/observe/InheritProtectedAccessTrackedModel.java" ); final JavaFileObject source2 = fixture( "input/com/example/observe/other/BaseModelProtectedAccess.java" ); final String output = "expected/com/example/observe/Arez_InheritProtectedAccessTrackedModel.java"; assertSuccessfulCompile( Arrays.asList( source1, source2 ), Collections.singletonList( output ) ); } @Test public void processSuccessfulDependencyThatIsTransitivelyDisposeTrackable() throws Exception { final JavaFileObject source1 = fixture( "input/com/example/component_dependency/TransitivelyDisposeTrackableDependencyModel.java" ); final JavaFileObject source2 = fixture( "input/com/example/component_dependency/MyDependentValue.java" ); final String output = "expected/com/example/component_dependency/Arez_TransitivelyDisposeTrackableDependencyModel.java"; assertSuccessfulCompile( Arrays.asList( source1, source2 ), Collections.singletonList( output ) ); } @Test public void processSuccessfulBaseInterfaceInDifferentPackage() throws Exception { final JavaFileObject source1 = fixture( "input/com/example/inheritance/CompleteInterfaceModel.java" ); final JavaFileObject source2 = fixture( "input/com/example/inheritance/other/BaseCompleteInterfaceModel.java" ); final JavaFileObject source3 = fixture( "input/com/example/inheritance/other/OtherElement.java" ); final String output = "expected/com/example/inheritance/Arez_CompleteInterfaceModel.java"; assertSuccessfulCompile( Arrays.asList( source1, source2, source3 ), Collections.singletonList( output ) ); } @Test public void processSuccessfulBaseClassInDifferentPackage() throws Exception { final JavaFileObject source1 = fixture( "input/com/example/inheritance/CompleteModel.java" ); final JavaFileObject source2 = fixture( "input/com/example/inheritance/other/BaseCompleteModel.java" ); final JavaFileObject source3 = fixture( "input/com/example/inheritance/other/Element.java" ); final String output = "expected/com/example/inheritance/Arez_CompleteModel.java"; assertSuccessfulCompile( Arrays.asList( source1, source2, source3 ), Collections.singletonList( output ) ); } @Test public void processSuccessfulReactArezGenericsScenario() throws Exception { final JavaFileObject source1 = fixture( "input/com/example/override_generics/BaseReactComponent.java" ); final JavaFileObject source2 = fixture( "input/com/example/override_generics/ArezReactComponent.java" ); final JavaFileObject source3 = fixture( "input/com/example/override_generics/MyArezReactComponent.java" ); final JavaFileObject source4 = fixture( "input/com/example/override_generics/MyArezReactComponent_.java" ); final String output = "expected/com/example/override_generics/Arez_MyArezReactComponent_.java"; assertSuccessfulCompile( Arrays.asList( source1, source2, source3, source4 ), Collections.singletonList( output ) ); } @Test public void processSuccessfulWhereAbstractMethodWithGenericParameterIsRefinedInMiddleComponent() throws Exception { final JavaFileObject source1 = fixture( "input/com/example/override_generics/BaseModel.java" ); final JavaFileObject source2 = fixture( "input/com/example/override_generics/MiddleModel.java" ); final JavaFileObject source3 = fixture( "input/com/example/override_generics/LeafModel.java" ); final String output = "expected/com/example/override_generics/Arez_LeafModel.java"; assertSuccessfulCompile( Arrays.asList( source1, source2, source3 ), Collections.singletonList( output ) ); } @Test public void processSuccessfulNestedCompileWithRepositories() throws Exception { assertSuccessfulCompile( "input/com/example/repository/NestedModel.java", "expected/com/example/repository/NestedModel_Arez_BasicActionModel.java", "expected/com/example/repository/NestedModel_BasicActionModelRepositoryDaggerModule.java", "expected/com/example/repository/NestedModel_BasicActionModelRepository.java", "expected/com/example/repository/Arez_NestedModel_BasicActionModelRepository.java" ); } @Test public void processSuccessfulInverseInDifferentPackage() throws Exception { final JavaFileObject source1 = fixture( "input/com/example/inverse/PackageAccessWithDifferentPackageInverseModel.java" ); final JavaFileObject source2 = fixture( "input/com/example/inverse/other/Element.java" ); final String output = "expected/com/example/inverse/Arez_PackageAccessWithDifferentPackageInverseModel.java"; assertSuccessfulCompile( Arrays.asList( source1, source2 ), Collections.singletonList( output ) ); } @Test public void processSuccessfulToStringInPresent() throws Exception { final JavaFileObject source1 = fixture( "input/com/example/to_string/ToStringPresentInParent.java" ); final JavaFileObject source2 = fixture( "input/com/example/to_string/ParentType.java" ); final String output = "expected/com/example/to_string/Arez_ToStringPresentInParent.java"; assertSuccessfulCompile( Arrays.asList( source1, source2 ), Collections.singletonList( output ) ); } @Test public void processSuccessfulNestedCompile() throws Exception { assertSuccessfulCompile( "input/NestedModel.java", "expected/NestedModel_Arez_BasicActionModel.java" ); } @Test public void processSuccessfulNestedNestedCompile() throws Exception { assertSuccessfulCompile( "input/NestedNestedModel.java", "expected/NestedNestedModel_Something_Arez_BasicActionModel.java" ); } @Test public void processSuccessfulWhereAnnotationsSourcedFromInterface() throws Exception { final JavaFileObject source1 = fixture( "input/DefaultMethodsModel.java" ); final JavaFileObject source2 = fixture( "input/MyAnnotatedInterface.java" ); final String output1 = "expected/Arez_DefaultMethodsModel.java"; assertSuccessfulCompile( Arrays.asList( source1, source2 ), Collections.singletonList( output1 ) ); } @Test public void processSuccessfulWhereTypeResolvedInInheritanceHierarchy() throws Exception { final JavaFileObject source1 = fixture( "input/com/example/type_params/AbstractModel.java" ); final JavaFileObject source2 = fixture( "input/com/example/type_params/MiddleModel.java" ); final JavaFileObject source3 = fixture( "input/com/example/type_params/ConcreteModel.java" ); final String output1 = "expected/com/example/type_params/Arez_ConcreteModel.java"; assertSuccessfulCompile( Arrays.asList( source1, source2, source3 ), Collections.singletonList( output1 ) ); } @Test public void processResolvedParameterizedType() throws Exception { final JavaFileObject source1 = fixture( "input/com/example/parameterized_type/ParentModel.java" ); final JavaFileObject source2 = fixture( "input/com/example/parameterized_type/ResolvedModel.java" ); final String output1 = "expected/com/example/parameterized_type/Arez_ResolvedModel.java"; assertSuccessfulCompile( Arrays.asList( source1, source2 ), Collections.singletonList( output1 ) ); } @Test public void processUnresolvedParameterizedType() throws Exception { final JavaFileObject source1 = fixture( "input/com/example/parameterized_type/ParentModel.java" ); final JavaFileObject source2 = fixture( "input/com/example/parameterized_type/UnresolvedModel.java" ); final String output1 = "expected/com/example/parameterized_type/Arez_UnresolvedModel.java"; assertSuccessfulCompile( Arrays.asList( source1, source2 ), Collections.singletonList( output1 ) ); } @Test public void processSuccessfulWhereGenericsRefinedAndActionsOverriddenHierarchy() throws Exception { final JavaFileObject source1 = fixture( "input/com/example/override_generics/GenericsBaseModel.java" ); final JavaFileObject source2 = fixture( "input/com/example/override_generics/GenericsMiddleModel.java" ); final JavaFileObject source3 = fixture( "input/com/example/override_generics/GenericsModel.java" ); final String output1 = "expected/com/example/override_generics/Arez_GenericsModel.java"; assertSuccessfulCompile( Arrays.asList( source1, source2, source3 ), Collections.singletonList( output1 ) ); } @Test public void processSuccessfulWhereTraceInheritanceChain() throws Exception { final JavaFileObject source1 = fixture( "input/com/example/inheritance/BaseModel.java" ); final JavaFileObject source2 = fixture( "input/com/example/inheritance/ParentModel.java" ); final JavaFileObject source3 = fixture( "input/com/example/inheritance/MyModel.java" ); final JavaFileObject source4 = fixture( "input/com/example/inheritance/MyInterface1.java" ); final JavaFileObject source5 = fixture( "input/com/example/inheritance/MyInterface2.java" ); final String output1 = "expected/com/example/inheritance/Arez_MyModel.java"; assertSuccessfulCompile( Arrays.asList( source1, source2, source3, source4, source5 ), Collections.singletonList( output1 ) ); } @Test public void processSuccessfulWithInjectViaInheritance() throws Exception { final JavaFileObject source1 = fixture( "input/com/example/inject/inheritance/other/BaseInjectModel.java" ); final JavaFileObject source2 = fixture( "input/com/example/inject/inheritance/EnhancerNeededForConsumerModel.java" ); final String output1 = "expected/com/example/inject/inheritance/Arez_EnhancerNeededForConsumerModel.java"; final String output2 = "expected/com/example/inject/inheritance/EnhancerNeededForConsumerModelDaggerComponentExtension.java"; assertSuccessfulCompile( Arrays.asList( source1, source2 ), Arrays.asList( output1, output2 ) ); } @DataProvider( name = "failedCompiles" ) public Object[][] failedCompiles() { return new Object[][] { new Object[]{ "com.example.reserved_names.DataPrefixReservedNameModel", "Method defined on a class annotated by @ArezComponent uses a name with a prefix reserved by Arez" }, new Object[]{ "com.example.reserved_names.DisposeReservedNameModel", "Method defined on a class annotated by @ArezComponent uses a name reserved by Arez" }, new Object[]{ "com.example.reserved_names.FieldPrefixReservedNameModel", "Method defined on a class annotated by @ArezComponent uses a name with a prefix reserved by Arez" }, new Object[]{ "com.example.reserved_names.FrameworkPrefixReservedNameModel", "Method defined on a class annotated by @ArezComponent uses a name with a prefix reserved by Arez" }, new Object[]{ "com.example.reserved_names.GetArezIdReservedNameModel", "Method defined on a class annotated by @ArezComponent uses a name reserved by Arez" }, new Object[]{ "com.example.reserved_names.IsDisposedReservedNameModel", "Method defined on a class annotated by @ArezComponent uses a name reserved by Arez" }, new Object[]{ "com.example.reserved_names.ObserveReservedNameModel", "Method defined on a class annotated by @ArezComponent uses a name reserved by Arez" }, new Object[]{ "com.example.action.AbstractActionModel", "@Action target must not be abstract" }, new Object[]{ "com.example.action.BadActionName2Model", "@Action target specified an invalid name 'ace-'. The name must be a valid java identifier." }, new Object[]{ "com.example.action.BadActionNameModel", "@Action target specified an invalid name 'assert'. The name must not be a java keyword." }, new Object[]{ "com.example.action.DuplicateActionModel", "Method annotated with @Action specified name ace that duplicates @Action defined by method setField" }, new Object[]{ "com.example.action.PrivateActionModel", "@Action target must not be private" }, new Object[]{ "com.example.action.StaticActionModel", "@Action target must not be static" }, new Object[]{ "com.example.observe.ApplicationExecutorButNoOnDepsChangeModel", "@Observe target defined parameter executor=EXTERNAL but does not specify an @OnDepsChange method." }, new Object[]{ "com.example.observe.ArezExecutorOnDepsChangeButNoObserverRefModel", "@Observe target with parameter executor=INTERNAL defined an @OnDepsChange method but has not defined an @ObserverRef method and thus can neverschedule observer." }, new Object[]{ "com.example.observe.NonArezDependenciesButNoObserverRefModel", "@Observe target with parameter depType=AREZ_OR_EXTERNAL has not defined an @ObserverRef method and thus can not invoke reportStale()." }, new Object[]{ "com.example.observe.ObserveAbstractModel", "@Observe target must not be abstract" }, new Object[]{ "com.example.observe.ObserveBadNameModel", "@Observe target specified an invalid name '-ace'. The name must be a valid java identifier." }, new Object[]{ "com.example.observe.ObserveBadNameModel2", "@Observe target specified an invalid name 'float'. The name must not be a java keyword." }, new Object[]{ "com.example.observe.ObserveDuplicateModel", "@Observe target duplicates existing method named foo" }, new Object[]{ "com.example.observe.ObserveDuplicateModel2", "Method annotated with @Memoize specified name doStuff that duplicates @Observe defined by method foo" }, new Object[]{ "com.example.observe.ObserveFinalModel", "@Observe target must not be final" }, new Object[]{ "com.example.observe.ObserveParametersModel", "@Observe target must not have any parameters" }, new Object[]{ "com.example.observe.ObservePrivateModel", "@Observe target must not be private" }, new Object[]{ "com.example.observe.ObservePublicModel", "@Observe target must not be public" }, new Object[]{ "com.example.observe.ObserveReturnsValueModel", "@Observe target must not return a value" }, new Object[]{ "com.example.observe.ObserveStaticModel", "@Observe target must not be static" }, new Object[]{ "com.example.observe.ObserveThrowsExceptionModel", "@Observe target must not throw any exceptions" }, new Object[]{ "com.example.observe.ReportResultArezExecutorModel", "@Observe target must not specify reportResult parameter when executor=INTERNAL" }, new Object[]{ "com.example.observe.ReportParametersArezExecutorModel", "@Observe target must not specify reportParameters parameter when executor=INTERNAL" }, new Object[]{ "com.example.cascade_dispose.AbstractMethodComponent", "@CascadeDispose target must not be abstract" }, new Object[]{ "com.example.cascade_dispose.BadType1Component", "@CascadeDispose target must be assignable to arez.Disposable or a type annotated with @ArezComponent" }, new Object[]{ "com.example.cascade_dispose.BadType1MethodComponent", "@CascadeDispose target must return a type assignable to arez.Disposable or a type annotated with @ArezComponent" }, new Object[]{ "com.example.cascade_dispose.BadType2Component", "@CascadeDispose target must be assignable to arez.Disposable or a type annotated with @ArezComponent" }, new Object[]{ "com.example.cascade_dispose.BadType2MethodComponent", "@CascadeDispose target must return a type assignable to arez.Disposable or a type annotated with @ArezComponent" }, new Object[]{ "com.example.cascade_dispose.BadType3Component", "@CascadeDispose target must be assignable to arez.Disposable or a type annotated with @ArezComponent" }, new Object[]{ "com.example.cascade_dispose.BadType3MethodComponent", "@CascadeDispose target must return a type assignable to arez.Disposable or a type annotated with @ArezComponent" }, new Object[]{ "com.example.cascade_dispose.NonFinalMethodComponent", "@CascadeDispose target must be final" }, new Object[]{ "com.example.cascade_dispose.ParametersMethodComponent", "@CascadeDispose target must not have any parameters" }, new Object[]{ "com.example.cascade_dispose.PrivateComponent", "@CascadeDispose target must not be private" }, new Object[]{ "com.example.cascade_dispose.PrivateMethodComponent", "@CascadeDispose target must not be private" }, new Object[]{ "com.example.cascade_dispose.StaticComponent", "@CascadeDispose target must not be static" }, new Object[]{ "com.example.cascade_dispose.StaticMethodComponent", "@CascadeDispose target must not be static" }, new Object[]{ "com.example.cascade_dispose.ThrowsMethodComponent", "@CascadeDispose target must not throw any exceptions" }, new Object[]{ "com.example.component.ConcreteComponent", "@ArezComponent target must be abstract unless the allowConcrete parameter is set to true" }, new Object[]{ "com.example.component.DeferredButNoObserveModel", "@ArezComponent target has specified the deferSchedule = true annotation parameter but has no methods annotated with @Observe" }, new Object[]{ "com.example.component.ModelWithAbstractMethod", "@ArezComponent target has an abstract method not implemented by framework. The method is named someMethod" }, new Object[]{ "com.example.component.NonEmptyComponent", "@ArezComponent target has specified allowEmpty = true but has methods annotated with @Action, @CascadeDispose, @Memoize, @Observable, @Inverse, @Reference, @ComponentDependency or @Observe" }, new Object[]{ "com.example.component.BadTypeComponent", "@ArezComponent target specified an invalid type ''. The type must be a valid java identifier." }, new Object[]{ "com.example.component.BadTypeComponent2", "@ArezComponent target specified an invalid type 'long'. The type must not be a java keyword." }, new Object[]{ "com.example.component.EmptyComponent", "@ArezComponent target has no methods annotated with @Action, @CascadeDispose, @Memoize, @Observable, @Inverse, @Reference, @ComponentDependency or @Observe" }, new Object[]{ "com.example.component.EmptyTypeComponent", "@ArezComponent target specified an invalid type ''. The type must be a valid java identifier." }, new Object[]{ "com.example.component.EnumModel", "@ArezComponent target must be a class or an interface" }, new Object[]{ "com.example.component.FinalModel", "@ArezComponent target must not be final" }, new Object[]{ "com.example.component.NonObservableWithDisposeOnDeactivateModel", "@ArezComponent target has specified observable = DISABLE and disposeOnDeactivate = true which is not a valid combination" }, new Object[]{ "com.example.component.NonStaticNestedModel", "@ArezComponent target must not be a non-static nested class" }, new Object[]{ "com.example.component.UnexpectedAbstractComponent", "@ArezComponent target must be concrete if the allowConcrete parameter is set to true" }, new Object[]{ "com.example.component_id.ComponentIdDuplicatedModel", "@ComponentId target duplicates existing method named getId" }, new Object[]{ "com.example.component_id.ComponentIdMustNotHaveParametersModel", "@ComponentId target must not have any parameters" }, new Object[]{ "com.example.component_id.ComponentIdNotAbstractModel", "@ComponentId target must not be abstract" }, new Object[]{ "com.example.component_id.ComponentIdMustReturnValueModel", "@ComponentId target must return a value" }, new Object[]{ "com.example.component_id.ComponentIdNotFinalModel", "@ComponentId target must be final" }, new Object[]{ "com.example.component_id.ComponentIdNotPrivateModel", "@ComponentId target must not be private" }, new Object[]{ "com.example.component_id.ComponentIdNotStaticModel", "@ComponentId target must not be static" }, new Object[]{ "com.example.component_type_name.ComponentTypeNameDuplicateModel", "@ComponentTypeNameRef target duplicates existing method named getTypeName" }, new Object[]{ "com.example.component_type_name.ComponentTypeNameFinalModel", "@ComponentTypeNameRef target must not be final" }, new Object[]{ "com.example.component_type_name.ComponentTypeNameMustNotHaveParametersModel", "@ComponentTypeNameRef target must not have any parameters" }, new Object[]{ "com.example.component_type_name.ComponentTypeNameMustReturnValueModel", "@ComponentTypeNameRef target must return a value" }, new Object[]{ "com.example.component_type_name.ComponentTypeNamePrivateModel", "@ComponentTypeNameRef target must not be private" }, new Object[]{ "com.example.component_type_name.ComponentTypeNameReturnNonStringModel", "@ComponentTypeNameRef target must return a String" }, new Object[]{ "com.example.component_type_name.ComponentTypeNameStaticModel", "@ComponentTypeNameRef target must not be static" }, new Object[]{ "com.example.component_type_name.ComponentTypeNameThrowsExceptionModel", "@ComponentTypeNameRef target must not throw any exceptions" }, new Object[]{ "com.example.component_id_ref.BadType1Model", "@ComponentIdRef target has a return type java.lang.String but no @ComponentId annotated method. The type is expected to be of type int." }, new Object[]{ "com.example.component_id_ref.BadType2Model", "@ComponentIdRef target has a return type java.lang.String and a @ComponentId annotated method with a return type java.lang.String. The types must match." }, new Object[]{ "com.example.component_id_ref.ConcreteModel", "@ComponentIdRef target must be abstract" }, new Object[]{ "com.example.component_id_ref.DuplicateModel", "@ComponentIdRef target duplicates existing method named getId" }, new Object[]{ "com.example.component_id_ref.FinalModel", "@ComponentIdRef target must not be final" }, new Object[]{ "com.example.component_id_ref.NoReturnModel", "@ComponentIdRef target must return a value" }, new Object[]{ "com.example.component_id_ref.ParametersModel", "@ComponentIdRef target must not have any parameters" }, new Object[]{ "com.example.component_id_ref.PrivateModel", "@ComponentIdRef target must not be private" }, new Object[]{ "com.example.component_id_ref.StaticModel", "@ComponentIdRef target must not be static" }, new Object[]{ "com.example.component_id_ref.ThrowsModel", "@ComponentIdRef target must not throw any exceptions" }, new Object[]{ "com.example.component_name_ref.ComponentNameRefDuplicateModel", "@ComponentNameRef target duplicates existing method named getTypeName" }, new Object[]{ "com.example.component_name_ref.ComponentNameRefFinalModel", "@ComponentNameRef target must not be final" }, new Object[]{ "com.example.component_name_ref.ComponentNameRefMustNotHaveParametersModel", "@ComponentNameRef target must not have any parameters" }, new Object[]{ "com.example.component_name_ref.ComponentNameRefMustReturnValueModel", "@ComponentNameRef target must return a value" }, new Object[]{ "com.example.component_name_ref.ComponentNameRefPrivateModel", "@ComponentNameRef target must not be private" }, new Object[]{ "com.example.component_name_ref.ComponentNameRefStaticModel", "@ComponentNameRef target must not be static" }, new Object[]{ "com.example.component_name_ref.ComponentNameRefThrowsExceptionModel", "@ComponentNameRef target must not throw any exceptions" }, new Object[]{ "com.example.memoize.AbstractModel", "@Memoize target must not be abstract" }, new Object[]{ "com.example.memoize.BadName2Model", "@Memoize target specified an invalid name 'public'. The name must not be a java keyword." }, new Object[]{ "com.example.memoize.BadName1Model", "@Memoize target specified an invalid name '-ace'. The name must be a valid java identifier." }, new Object[]{ "com.example.memoize.BadStreamTypeModel", "@Memoize target must not return a value of type java.util.stream.Stream as the type is single use and thus does not make sense to cache as a computable value" }, new Object[]{ "com.example.memoize.ThrowsExceptionModel", "@Memoize target must not throw any exceptions" }, new Object[]{ "com.example.memoize.DuplicateModel", "Method annotated with @Memoize specified name ace that duplicates @Memoize defined by method getX" }, new Object[]{ "com.example.memoize.FinalModel", "@Memoize target must not be final" }, new Object[]{ "com.example.memoize.KeepAliveWithParametersModel", "@Memoize target specified parameter keepAlive as true but has parameters." }, new Object[]{ "com.example.memoize.MissingComputableValueRefModel", "@Memoize target specified depType = AREZ_OR_EXTERNAL but there is no associated @ComputableValueRef method." }, new Object[]{ "com.example.memoize.PrivateModel", "@Memoize target must not be private" }, new Object[]{ "com.example.memoize.StaticModel", "@Memoize target must not be static" }, new Object[]{ "com.example.memoize.ReturnVoidModel", "@Memoize target must return a value" }, new Object[]{ "com.example.component_ref.FinalModel", "@ComponentRef target must not be final" }, new Object[]{ "com.example.component_ref.StaticModel", "@ComponentRef target must not be static" }, new Object[]{ "com.example.component_ref.PrivateModel", "@ComponentRef target must not be private" }, new Object[]{ "com.example.component_ref.VoidModel", "@ComponentRef target must return a value" }, new Object[]{ "com.example.component_ref.BadTypeModel", "Method annotated with @ComponentRef must return an instance of arez.Component" }, new Object[]{ "com.example.component_ref.ThrowsExceptionModel", "@ComponentRef target must not throw any exceptions" }, new Object[]{ "com.example.component_ref.DuplicateModel", "@ComponentRef target duplicates existing method named getComponent" }, new Object[]{ "com.example.component_ref.ParametersModel", "@ComponentRef target must not have any parameters" }, new Object[]{ "com.example.context_ref.FinalModel", "@ContextRef target must not be final" }, new Object[]{ "com.example.context_ref.StaticModel", "@ContextRef target must not be static" }, new Object[]{ "com.example.context_ref.PrivateModel", "@ContextRef target must not be private" }, new Object[]{ "com.example.context_ref.VoidModel", "@ContextRef target must return a value" }, new Object[]{ "com.example.context_ref.BadTypeModel", "Method annotated with @ContextRef must return an instance of arez.ArezContext" }, new Object[]{ "com.example.context_ref.ThrowsExceptionModel", "@ContextRef target must not throw any exceptions" }, new Object[]{ "com.example.context_ref.DuplicateModel", "@ContextRef target duplicates existing method named getContext" }, new Object[]{ "com.example.context_ref.ParametersModel", "@ContextRef target must not have any parameters" }, new Object[]{ "com.example.component_dependency.AbstractDependency", "@ArezComponent target has an abstract method not implemented by framework. The method is named getTime" }, new Object[]{ "com.example.component_dependency.BadTypeDependency", "@ComponentDependency target must return an instance compatible with arez.component.DisposeNotifier or a type annotated with @ArezComponent(disposeNotifier=ENABLE)" }, new Object[]{ "com.example.component_dependency.BadTypeFieldDependency", "@ComponentDependency target must be an instance compatible with arez.component.DisposeNotifier or a type annotated with @ArezComponent(disposeNotifier=ENABLE)" }, new Object[]{ "com.example.component_dependency.CascadeDisposeAndFieldDependency", "Method can not be annotated with both @ComponentDependency and @CascadeDispose" }, new Object[]{ "com.example.component_dependency.MemoizeDependency", "Method can not be annotated with both @Memoize and @ComponentDependency" }, new Object[]{ "com.example.component_dependency.NonFinalDependency", "@ComponentDependency target must be final" }, new Object[]{ "com.example.component_dependency.NonFinalFieldDependency", "@ComponentDependency target must be final" }, new Object[]{ "com.example.component_dependency.ParametersDependency", "@ComponentDependency target must not have any parameters" }, new Object[]{ "com.example.component_dependency.PrimitiveFieldDependency", "@ComponentDependency target must be a non-primitive value" }, new Object[]{ "com.example.component_dependency.PrimitiveReturnDependency", "@ComponentDependency target must return a non-primitive value" }, new Object[]{ "com.example.component_dependency.PrivateDependency", "@ComponentDependency target must not be private" }, new Object[]{ "com.example.component_dependency.SetNullBasicDependency", "@ComponentDependency target defined an action of 'SET_NULL' but the dependency is not an observable so the annotation processor does not know how to set the value to null." }, new Object[]{ "com.example.component_dependency.SetNullFieldDependency", "@ComponentDependency target defined an action of 'SET_NULL' but the dependency is on a final field and can not be set to null." }, new Object[]{ "com.example.component_dependency.SetNullObservableNoSetterDependency", "@ComponentDependency target defined an action of 'SET_NULL' but the dependency is an observable with no setter defined so the annotation processor does not know how to set the value to null." }, new Object[]{ "com.example.component_dependency.SetNullOnNonnullDependency", "@ComponentDependency target defined an action of 'SET_NULL' but the setter is annotated with @javax.annotation.Nonnull." }, new Object[]{ "com.example.component_dependency.StaticDependency", "@ComponentDependency target must not be static" }, new Object[]{ "com.example.component_dependency.StaticFieldDependency", "@ComponentDependency target must not be static" }, new Object[]{ "com.example.component_dependency.ThrowsDependency", "@ComponentDependency target must not throw any exceptions" }, new Object[]{ "com.example.component_dependency.VoidReturnDependency", "@ComponentDependency target must return a value" }, new Object[]{ "com.example.dispose_notifier.NoDisposeNotifierWithRepositoryModel", "@ArezComponent target has specified the disposeNotifier = DISABLE annotation parameter but is also annotated with @Repository that requires disposeNotifier = ENABLE." }, new Object[]{ "com.example.id.DisableIdAndComponentId", "@ArezComponent target has specified the idRequired = DISABLE annotation parameter but also has annotated a method with @ComponentId that requires idRequired = ENABLE." }, new Object[]{ "com.example.id.DisableIdAndComponentIdRef", "@ArezComponent target has specified the idRequired = DISABLE annotation parameter but also has annotated a method with @ComponentIdRef that requires idRequired = ENABLE." }, new Object[]{ "com.example.id.DisableIdAndRepository", "@ArezComponent target has specified the idRequired = DISABLE annotation parameter but is also annotated with @Repository that requires idRequired = ENABLE." }, new Object[]{ "com.example.inject.MultipleConstructorsModel", "@ArezComponent specified inject parameter but has more than one constructor" }, new Object[]{ "com.example.inject.DaggerEnableNonPublicModel", "@ArezComponent target is not public but is configured as inject = PROVIDE using the dagger injection framework. Due to constraints within the dagger framework the type needs to made public." }, new Object[]{ "com.example.inject.DaggerEnableInjectDisabledModel", "@ArezComponent target has a dagger parameter that resolved to ENABLE but the inject parameter is set to NONE and this is not a valid combination of parameters." }, new Object[]{ "com.example.inject.InjectFieldsInjectDisabledModel", "@ArezComponent target has fields annotated with the javax.inject.Inject annotation but the inject parameter is set to NONE and this is not a valid scenario. Remove the @Inject annotation(s) or change the inject parameter to a value other than NONE." }, new Object[]{ "com.example.inject.InjectMethodsInjectDisabledModel", "@ArezComponent target has methods annotated with the javax.inject.Inject annotation but the inject parameter is set to NONE and this is not a valid scenario. Remove the @Inject annotation(s) or change the inject parameter to a value other than NONE." }, new Object[]{ "com.example.inject.MultipleConstructorsScopedModel", "@ArezComponent target has specified a scope annotation but has more than one constructor and thus is not a candidate for injection" }, new Object[]{ "com.example.inject.MultipleScopesModel", "@ArezComponent target has specified multiple scope annotations: [javax.inject.Singleton, com.example.inject.MultipleScopesModel.MyScope]" }, new Object[]{ "com.example.inject.PerInstanceParamOnProvideModel", "@ArezComponent target has specified at least one @PerInstance parameter on the constructor but has set inject parameter to PROVIDE. The component cannot be provided to other components if the invoker must supply per-instance parameters so either change the inject parameter to CONSUME or remove the @PerInstance parameter." }, new Object[]{ "com.example.inject.PublicCtorModel", "@ArezComponent target has a public constructor but the inject parameter does not resolve to NONE. Public constructors are not necessary when the instantiation of the component is managed by the injection framework." }, new Object[]{ "com.example.inject.ScopePresentInjectDisabledModel", "@ArezComponent target is annotated with scope annotation @javax.inject.Singleton but the inject parameter is set to NONE and this is not a valid scenario. Remove the scope annotation or change the inject parameter to a value other than NONE." }, new Object[]{ "com.example.inverse.BadCollectionTypeInverseModel", "@Inverse target expected to return a type annotated with arez.annotations.ArezComponent" }, new Object[]{ "com.example.inverse.BadInverseName1InverseModel", "@Reference target specified an invalid inverseName '-sxkw'. The inverseName must be a valid java identifier." }, new Object[]{ "com.example.inverse.BadInverseName2InverseModel", "@Reference target specified an invalid inverseName 'byte'. The inverseName must not be a java keyword." }, new Object[]{ "com.example.inverse.BadInverseType1InverseModel", "@Inverse target expected to find an associated @Reference annotation with a target type equal to com.example.inverse.BadInverseType1InverseModel.OtherEntity but the actual target type is com.example.inverse.BadInverseType1InverseModel.MyEntity" }, new Object[]{ "com.example.inverse.BadMultiplicity1InverseModel", "@Inverse target has a multiplicity of MANY but that associated @Reference has a multiplicity of ONE. The multiplicity must align." }, new Object[]{ "com.example.inverse.BadMultiplicity2InverseModel", "@Inverse target has a multiplicity of MANY but that associated @Reference has a multiplicity of ZERO_OR_ONE. The multiplicity must align." }, new Object[]{ "com.example.inverse.BadMultiplicity3InverseModel", "@Inverse target has a multiplicity of ONE but that associated @Reference has a multiplicity of ZERO_OR_ONE. The multiplicity must align." }, new Object[]{ "com.example.inverse.BadMultiplicity4InverseModel", "@Inverse target has a multiplicity of ONE but that associated @Reference has a multiplicity of MANY. The multiplicity must align." }, new Object[]{ "com.example.inverse.BadMultiplicity5InverseModel", "@Inverse target has a multiplicity of ZERO_OR_ONE but that associated @Reference has a multiplicity of ONE. The multiplicity must align." }, new Object[]{ "com.example.inverse.BadMultiplicity6InverseModel", "@Inverse target has a multiplicity of ZERO_OR_ONE but that associated @Reference has a multiplicity of MANY. The multiplicity must align." }, new Object[]{ "com.example.inverse.BadName1InverseModel", "@Inverse target specified an invalid name '-sss'. The name must be a valid java identifier." }, new Object[]{ "com.example.inverse.BadName2InverseModel", "@Inverse target specified an invalid name 'long'. The name must not be a java keyword." }, new Object[]{ "com.example.inverse.BadReferenceMultiplicity1InverseModel", "@Reference target has an inverseMultiplicity of ONE but that associated @Inverse has a multiplicity of MANY. The multiplicity must align." }, new Object[]{ "com.example.inverse.BadReferenceMultiplicity2InverseModel", "@Reference target has an inverseMultiplicity of ZERO_OR_ONE but that associated @Inverse has a multiplicity of MANY. The multiplicity must align." }, new Object[]{ "com.example.inverse.BadReferenceMultiplicity3InverseModel", "@Reference target has an inverseMultiplicity of MANY but that associated @Inverse has a multiplicity of ONE. The multiplicity must align." }, new Object[]{ "com.example.inverse.BadReferenceMultiplicity4InverseModel", "@Reference target has an inverseMultiplicity of ZERO_OR_ONE but that associated @Inverse has a multiplicity of ONE. The multiplicity must align." }, new Object[]{ "com.example.inverse.BadReferenceMultiplicity5InverseModel", "@Reference target has an inverseMultiplicity of MANY but that associated @Inverse has a multiplicity of ZERO_OR_ONE. The multiplicity must align." }, new Object[]{ "com.example.inverse.BadReferenceMultiplicity6InverseModel", "@Reference target has an inverseMultiplicity of ONE but that associated @Inverse has a multiplicity of ZERO_OR_ONE. The multiplicity must align." }, new Object[]{ "com.example.inverse.BadReferenceName1InverseModel", "@Inverse target specified an invalid referenceName '-sxkw'. The name must be a valid java identifier." }, new Object[]{ "com.example.inverse.BadReferenceName2InverseModel", "@Inverse target specified an invalid referenceName 'long'. The name must not be a java keyword." }, new Object[]{ "com.example.inverse.BadReferenceType2InverseModel", "@Reference target expected to find an associated @Inverse annotation with a name parameter equal to 'badReferenceType2InverseModel' on class com.example.inverse.BadReferenceType2InverseModel.MyEntity but is unable to locate a matching method." }, new Object[]{ "com.example.inverse.BadReferenceTypeInverseModel", "@Reference target expected to find an associated @Inverse annotation with a target type equal to com.example.inverse.BadReferenceTypeInverseModel but the actual target type is com.example.inverse.BadReferenceTypeInverseModel.OtherEntity" }, new Object[]{ "com.example.inverse.BadType1InverseModel", "@Inverse target expected to return a type annotated with arez.annotations.ArezComponent" }, new Object[]{ "com.example.inverse.BadType2InverseModel", "@Inverse target expected to return a type annotated with arez.annotations.ArezComponent" }, new Object[]{ "com.example.inverse.BadType3InverseModel", "@Inverse target expected to return a type annotated with arez.annotations.ArezComponent" }, new Object[]{ "com.example.inverse.BadType4InverseModel", "@Inverse target expected to be annotated with either javax.annotation.Nullable or javax.annotation.Nonnull" }, new Object[]{ "com.example.inverse.ConcreteInverseModel", "@Inverse target must be abstract" }, new Object[]{ "com.example.inverse.DuplicateInverseModel", "@Inverse target defines duplicate inverse for name 'myEntity'. The other inverse is getMyEntity2()" }, new Object[]{ "com.example.inverse.InitializerWithInverseModel", "@Inverse target also specifies @Observable(initializer=ENABLE) but it is not valid to define an initializer for an inverse." }, new Object[]{ "com.example.inverse.MissingInverseOnReferenceModel", "@Inverse target found an associated @Reference on the method 'getCar' on type 'com.example.inverse.MissingInverseOnReferenceModel.Wheel' but the annotation has not configured an inverse." }, new Object[]{ "com.example.inverse.MissingInverseReferenceModel", "@Reference target expected to find an associated @Inverse annotation with a name parameter equal to 'missingInverseReferenceModels' on class com.example.inverse.MissingInverseReferenceModel.MyEntity but is unable to locate a matching method." }, new Object[]{ "com.example.inverse.MissingReference1InverseModel", "@Inverse target expected to find an associated @Reference annotation with a name parameter equal to 'missingReference1InverseModel' on class com.example.inverse.MissingReference1InverseModel.MyEntity but is unable to locate a matching method." }, new Object[]{ "com.example.inverse.NoReturnInverseModel", "@Inverse target must return a value" }, new Object[]{ "com.example.inverse.ParametersInverseModel", "@Inverse target must not have any parameters" }, new Object[]{ "com.example.inverse.PrivateInverseModel", "@Inverse target must not be private" }, new Object[]{ "com.example.inverse.ReferenceSpecifiesNonComponentInverseModel", "@Reference target expected to return a type annotated with arez.annotations.ArezComponent if there is an inverse reference." }, new Object[]{ "com.example.inverse.StaticInverseModel", "@Inverse target must not be static" }, new Object[]{ "com.example.inverse.ThrowsInverseModel", "@Inverse target must not throw any exceptions" }, new Object[]{ "com.example.inverse.UnexpectedInverseForReferenceModel", "@Reference target has not configured an inverse but there is an associated @Inverse annotated method named 'getWheels' on type 'com.example.inverse.UnexpectedInverseForReferenceModel.Car'." }, new Object[]{ "com.example.observable_value_ref.BadNameModel", "@ObservableValueRef target specified an invalid name '-ace'. The name must be a valid java identifier." }, new Object[]{ "com.example.observable_value_ref.BadNameModel2", "@ObservableValueRef target specified an invalid name 'const'. The name must not be a java keyword." }, new Object[]{ "com.example.observable_value_ref.BadReturnTypeModel", "Method annotated with @ObservableValueRef must return an instance of arez.ObservableValue" }, new Object[]{ "com.example.observable_value_ref.BadReturnTypeParameter2Model", "@ObservableValueRef target has a type parameter of ? but @Observable method returns type of long" }, new Object[]{ "com.example.observable_value_ref.BadReturnTypeParameterModel", "@ObservableValueRef target has a type parameter of java.lang.String but @Observable method returns type of long" }, new Object[]{ "com.example.observable_value_ref.DuplicateRefMethodModel", "Method annotated with @ObservableValueRef defines duplicate ref accessor for observable named time" }, new Object[]{ "com.example.observable_value_ref.FinalModel", "@ObservableValueRef target must not be final" }, new Object[]{ "com.example.observable_value_ref.NonAbstractModel", "@ObservableValueRef target must be abstract" }, new Object[]{ "com.example.observable_value_ref.NonAlignedNameModel", "Method annotated with @ObservableValueRef should specify name or be named according to the convention get[Name]Observable" }, new Object[]{ "com.example.observable_value_ref.NoObservableModel", "@ObservableValueRef target unable to be associated with an Observable property" }, new Object[]{ "com.example.observable_value_ref.ParametersModel", "@ObservableValueRef target must not have any parameters" }, new Object[]{ "com.example.observable_value_ref.PrivateModel", "@ObservableValueRef target must not be private" }, new Object[]{ "com.example.observable_value_ref.StaticModel", "@ObservableValueRef target must not be static" }, new Object[]{ "com.example.observable_value_ref.ThrowsExceptionModel", "@ObservableValueRef target must not throw any exceptions" }, new Object[]{ "com.example.computable_value_ref.BadNameModel", "@ComputableValueRef target specified an invalid name '-ace'. The name must be a valid java identifier." }, new Object[]{ "com.example.computable_value_ref.BadNameModel2", "@ComputableValueRef target specified an invalid name 'private'. The name must not be a java keyword." }, new Object[]{ "com.example.computable_value_ref.BadReturnTypeModel", "Method annotated with @ComputableValueRef must return an instance of arez.ComputableValue" }, new Object[]{ "com.example.computable_value_ref.BadReturnType2Model", "@ComputableValueRef target has a type parameter of ? but @Memoize method returns type of long" }, new Object[]{ "com.example.computable_value_ref.BadReturnType3Model", "@ComputableValueRef target has a type parameter of java.lang.String but @Memoize method returns type of long" }, new Object[]{ "com.example.computable_value_ref.DuplicateRefMethodModel", "@ComputableValueRef target duplicates existing method named getTimeComputableValue" }, new Object[]{ "com.example.computable_value_ref.FinalModel", "@ComputableValueRef target must not be final" }, new Object[]{ "com.example.computable_value_ref.MemoizeHasDifferentParameters1Model", "@ComputableValueRef target and the associated @Memoize target do not have the same parameters." }, new Object[]{ "com.example.computable_value_ref.MemoizeHasDifferentParameters2Model", "@ComputableValueRef target and the associated @Memoize target do not have the same parameters." }, new Object[]{ "com.example.computable_value_ref.MemoizeHasDifferentParameters3Model", "@ComputableValueRef target and the associated @Memoize target do not have the same parameters." }, new Object[]{ "com.example.computable_value_ref.MemoizeHasDifferentParameters4Model", "@ComputableValueRef target and the associated @Memoize target do not have the same parameters." }, new Object[]{ "com.example.computable_value_ref.NoMemoizeModel", "@ComputableValueRef exists but there is no corresponding @Memoize" }, new Object[]{ "com.example.computable_value_ref.NonAlignedNameModel", "Method annotated with @ComputableValueRef should specify name or be named according to the convention get[Name]ComputableValue" }, new Object[]{ "com.example.computable_value_ref.PrivateModel", "@ComputableValueRef target must not be private" }, new Object[]{ "com.example.computable_value_ref.StaticModel", "@ComputableValueRef target must not be static" }, new Object[]{ "com.example.computable_value_ref.ThrowsExceptionModel", "@ComputableValueRef target must not throw any exceptions" }, new Object[]{ "com.example.observer_ref.BadNameModel", "@ObserverRef target specified an invalid name '-ace'. The name must be a valid java identifier." }, new Object[]{ "com.example.observer_ref.BadNameModel2", "@ObserverRef target specified an invalid name 'int'. The name must not be a java keyword." }, new Object[]{ "com.example.observer_ref.BadReturnTypeModel", "Method annotated with @ObserverRef must return an instance of arez.Observer" }, new Object[]{ "com.example.observer_ref.DuplicateNameModel", "Method annotated with @ObserverRef defines duplicate ref accessor for observer named doStuff" }, new Object[]{ "com.example.observer_ref.ExceptionModel", "@ObserverRef target must not throw any exceptions" }, new Object[]{ "com.example.observer_ref.FinalModel", "@ObserverRef target must not be final" }, new Object[]{ "com.example.observer_ref.NoNameModel", "Method annotated with @ObserverRef should specify name or be named according to the convention get[Name]Observer" }, new Object[]{ "com.example.observer_ref.ParametersModel", "@ObserverRef target must not have any parameters" }, new Object[]{ "com.example.observer_ref.PrivateModel", "@ObserverRef target must not be private" }, new Object[]{ "com.example.observer_ref.RefOnNeitherModel", "@ObserverRef target defined observer named 'render' but no @Observe method with that name exists" }, new Object[]{ "com.example.observer_ref.StaticModel", "@ObserverRef target must not be static" }, new Object[]{ "com.example.observer_ref.VoidReturnModel", "Method annotated with @ObserverRef must return an instance of arez.Observer" }, new Object[]{ "com.example.name_duplicates.ActionDuplicatesObservableNameModel", "Method annotated with @Action specified name field that duplicates @Observable defined by method getField" }, new Object[]{ "com.example.on_activate.MemoizeHasParametersModel", "@OnActivate target associated with @Memoize method that has parameters." }, new Object[]{ "com.example.on_activate.OnActivateAbstractModel", "@OnActivate target must not be abstract" }, new Object[]{ "com.example.on_activate.OnActivateNoMemoizeModel", "@OnActivate exists but there is no corresponding @Memoize" }, new Object[]{ "com.example.on_activate.OnActivateBadNameModel", "@OnActivate as does not match on[Name]Activate pattern. Please specify name." }, new Object[]{ "com.example.on_activate.OnActivateBadNameModel2", "@OnActivate target specified an invalid name 'final'. The name must not be a java keyword." }, new Object[]{ "com.example.on_activate.OnActivateBadNameModel3", "@OnActivate target specified an invalid name '-f-f-'. The name must be a valid java identifier." }, new Object[]{ "com.example.on_activate.OnActivatePrivateModel", "@OnActivate target must not be private" }, new Object[]{ "com.example.on_activate.OnActivateStaticModel", "@OnActivate target must not be static" }, new Object[]{ "com.example.on_activate.OnActivateOnKeepAliveModel", "@OnActivate exists for @Memoize property that specified parameter keepAlive as true." }, new Object[]{ "com.example.on_activate.OnActivateParametersModel", "@OnActivate target must not have any parameters" }, new Object[]{ "com.example.on_activate.OnActivateReturnValueModel", "@OnActivate target must not return a value" }, new Object[]{ "com.example.on_activate.OnActivateThrowsExceptionModel", "@OnActivate target must not throw any exceptions" }, new Object[]{ "com.example.on_activate.OnActivateDuplicateModel", "@OnActivate target duplicates existing method named foo" }, new Object[]{ "com.example.on_deactivate.MemoizeHasParametersModel", "@OnDeactivate target associated with @Memoize method that has parameters." }, new Object[]{ "com.example.on_deactivate.OnDeactivateAbstractModel", "@OnDeactivate target must not be abstract" }, new Object[]{ "com.example.on_deactivate.OnDeactivateNoMemoizeModel", "@OnDeactivate exists but there is no corresponding @Memoize" }, new Object[]{ "com.example.on_deactivate.OnDeactivateBadNameModel", "@OnDeactivate as does not match on[Name]Deactivate pattern. Please specify name." }, new Object[]{ "com.example.on_deactivate.OnDeactivateBadNameModel2", "@OnDeactivate target specified an invalid name 'abstract'. The name must not be a java keyword." }, new Object[]{ "com.example.on_deactivate.OnDeactivateBadNameModel3", "@OnDeactivate target specified an invalid name '-a-'. The name must be a valid java identifier." }, new Object[]{ "com.example.on_deactivate.OnDeactivatePrivateModel", "@OnDeactivate target must not be private" }, new Object[]{ "com.example.on_deactivate.OnDeactivateStaticModel", "@OnDeactivate target must not be static" }, new Object[]{ "com.example.on_deactivate.OnDeactivateKeepAliveModel", "@OnDeactivate exists for @Memoize property that specified parameter keepAlive as true." }, new Object[]{ "com.example.on_deactivate.OnDeactivateParametersModel", "@OnDeactivate target must not have any parameters" }, new Object[]{ "com.example.on_deactivate.OnDeactivateReturnValueModel", "@OnDeactivate target must not return a value" }, new Object[]{ "com.example.on_deactivate.OnDeactivateThrowsExceptionModel", "@OnDeactivate target must not throw any exceptions" }, new Object[]{ "com.example.on_deactivate.OnDeactivateDuplicateModel", "@OnDeactivate target duplicates existing method named foo" }, new Object[]{ "com.example.on_stale.MemoizeHasParametersModel", "@OnStale target associated with @Memoize method that has parameters." }, new Object[]{ "com.example.on_stale.OnStaleAbstractModel", "@OnStale target must not be abstract" }, new Object[]{ "com.example.on_stale.OnStaleNoMemoizeModel", "@OnStale exists but there is no corresponding @Memoize" }, new Object[]{ "com.example.on_stale.OnStaleBadNameModel", "@OnStale as does not match on[Name]Stale pattern. Please specify name." }, new Object[]{ "com.example.on_stale.OnStaleBadNameModel2", "@OnStale target specified an invalid name 'if'. The name must not be a java keyword." }, new Object[]{ "com.example.on_stale.OnStaleBadNameModel3", "@OnStale target specified an invalid name '-a-'. The name must be a valid java identifier." }, new Object[]{ "com.example.on_stale.OnStalePrivateModel", "@OnStale target must not be private" }, new Object[]{ "com.example.on_stale.OnStaleStaticModel", "@OnStale target must not be static" }, new Object[]{ "com.example.on_stale.OnStaleParametersModel", "@OnStale target must not have any parameters" }, new Object[]{ "com.example.on_stale.OnStaleReturnValueModel", "@OnStale target must not return a value" }, new Object[]{ "com.example.on_stale.OnStaleThrowsExceptionModel", "@OnStale target must not throw any exceptions" }, new Object[]{ "com.example.on_stale.OnStaleDuplicateModel", "@OnStale target duplicates existing method named foo" }, new Object[]{ "com.example.pre_dispose.PreDisposeAbstractModel", "@PreDispose target must not be abstract" }, new Object[]{ "com.example.pre_dispose.PreDisposePrivateModel", "@PreDispose target must not be private" }, new Object[]{ "com.example.pre_dispose.PreDisposeStaticModel", "@PreDispose target must not be static" }, new Object[]{ "com.example.pre_dispose.PreDisposeParametersModel", "@PreDispose target must not have any parameters" }, new Object[]{ "com.example.pre_dispose.PreDisposeReturnValueModel", "@PreDispose target must not return a value" }, new Object[]{ "com.example.pre_dispose.PreDisposeThrowsExceptionModel", "@PreDispose target must not throw any exceptions" }, new Object[]{ "com.example.pre_dispose.PreDisposeDuplicateModel", "@PreDispose target duplicates existing method named foo" }, new Object[]{ "com.example.post_dispose.PostDisposeAbstractModel", "@PostDispose target must not be abstract" }, new Object[]{ "com.example.post_dispose.PostDisposePrivateModel", "@PostDispose target must not be private" }, new Object[]{ "com.example.post_dispose.PostDisposeStaticModel", "@PostDispose target must not be static" }, new Object[]{ "com.example.post_dispose.PostDisposeParametersModel", "@PostDispose target must not have any parameters" }, new Object[]{ "com.example.post_dispose.PostDisposeReturnValueModel", "@PostDispose target must not return a value" }, new Object[]{ "com.example.post_dispose.PostDisposeThrowsExceptionModel", "@PostDispose target must not throw any exceptions" }, new Object[]{ "com.example.post_dispose.PostDisposeDuplicateModel", "@PostDispose target duplicates existing method named foo" }, new Object[]{ "com.example.priority_override.AbstractModel", "@PriorityOverride target must not be abstract" }, new Object[]{ "com.example.priority_override.BadNameModel", "@PriorityOverride target specified an invalid name '-ace'. The name must be a valid java identifier." }, new Object[]{ "com.example.priority_override.BadNameModel2", "@PriorityOverride target specified an invalid name 'int'. The name must not be a java keyword." }, new Object[]{ "com.example.priority_override.BadNameModel3", "Method annotated with @PriorityOverride should specify name or be named according to the convention [name]Priority" }, new Object[]{ "com.example.priority_override.BadParameterModel", "@PriorityOverride target must have no parameters or a single int parameter" }, new Object[]{ "com.example.priority_override.BadReturnTypeModel", "@PriorityOverride target must return an int value" }, new Object[]{ "com.example.priority_override.MultipleParametersModel", "@PriorityOverride target must have no parameters or a single int parameter" }, new Object[]{ "com.example.priority_override.NoAssociatedModel", "@PriorityOverride target has no corresponding @Memoize or @Observe methods" }, new Object[]{ "com.example.priority_override.PrivateModel", "@PriorityOverride target must not be private" }, new Object[]{ "com.example.priority_override.StaticModel", "@PriorityOverride target must not be static" }, new Object[]{ "com.example.priority_override.ThrowsModel", "@PriorityOverride target must not throw any exceptions" }, new Object[]{ "com.example.priority_override.VoidReturnModel", "@PriorityOverride target must return a value" }, new Object[]{ "com.example.observable.PrivateObservableGetterModel", "@Observable target must not be private" }, new Object[]{ "com.example.observable.PrivateObservableSetterModel", "@Observable target must not be private" }, new Object[]{ "com.example.observable.SetterAlwaysMutatesFalseOnAbstractMethods", "@Observable target defines setterAlwaysMutates = false but but has defined abstract getters and setters." }, new Object[]{ "com.example.observable.SetterAlwaysMutatesFalseWhenNoSetter", "@Observable target defines expectSetter = false setterAlwaysMutates = false but this is an invalid configuration." }, new Object[]{ "com.example.observable.MissingObservableGetterModel", "@Observable target defined setter but no getter was defined and no getter could be automatically determined" }, new Object[]{ "com.example.observable.MissingObservableSetterModel", "@Observable target defined getter but no setter was defined and no setter could be automatically determined" }, new Object[]{ "com.example.name_duplicates.ActionAndMemoizeSameNameModel", "Method annotated with @Action specified name x that duplicates @Memoize defined by method m1" }, new Object[]{ "com.example.name_duplicates.ActionAndObservableSameNameModel", "Method annotated with @Observable specified name x that duplicates @Action defined by method m1" }, new Object[]{ "com.example.name_duplicates.ActionAndObservableSameNameNoGetterYetModel", "Method annotated with @Action specified name x that duplicates @Observable defined by method setTime" }, new Object[]{ "com.example.name_duplicates.MemoizeAndObservableSameNameModel", "Method annotated with @Observable specified name x that duplicates @Memoize defined by method m1" }, new Object[]{ "com.example.reference.BadExpectSetterObservableReferenceModel", "@ReferenceId added to @Observable method but expectSetter = false on property which is not compatible with @ReferenceId" }, new Object[]{ "com.example.reference.BadName2ReferenceIdModel", "@ReferenceId target specified an invalid name 'long'. The name must not be a java keyword." }, new Object[]{ "com.example.reference.BadNameReferenceIdModel", "@ReferenceId target specified an invalid name '-hello'. The name must be a valid java identifier." }, new Object[]{ "com.example.reference.BadName3ReferenceIdModel", "@ReferenceId target has not specified a name and does not follow the convention \"get[Name]Id\" or \"[name]Id\"" }, new Object[]{ "com.example.reference.BadName2ReferenceModel", "@Reference target specified an invalid name 'short'. The name must not be a java keyword." }, new Object[]{ "com.example.reference.BadNameReferenceModel", "@Reference target specified an invalid name '-meep-'. The name must be a valid java identifier." }, new Object[]{ "com.example.reference.ConcreteReferenceModel", "@Reference target must be abstract" }, new Object[]{ "com.example.reference.MissingReferenceIdReferenceModel", "@Reference exists but there is no corresponding @ReferenceId" }, new Object[]{ "com.example.reference.MissingReferenceReferenceIdModel", "@ReferenceId exists but there is no corresponding @Reference" }, new Object[]{ "com.example.reference.NoReturnReferenceIdModel", "@ReferenceId target must return a value" }, new Object[]{ "com.example.reference.NoReturnReferenceModel", "@Reference target must return a value" }, new Object[]{ "com.example.reference.ParameterReferenceIdModel", "@ReferenceId target must not have any parameters" }, new Object[]{ "com.example.reference.NoSetterObservableReferenceModel", "@Reference exists but there is no corresponding @ReferenceId" }, new Object[]{ "com.example.reference.ParameterReferenceModel", "@Reference target must not have any parameters" }, new Object[]{ "com.example.reference.PrivateReferenceIdModel", "@ReferenceId target must not be private" }, new Object[]{ "com.example.reference.PrivateReferenceModel", "@Reference target must not be private" }, new Object[]{ "com.example.reference.StaticReferenceIdModel", "@ReferenceId target must not be static" }, new Object[]{ "com.example.reference.StaticReferenceModel", "@Reference target must not be static" }, new Object[]{ "com.example.reference.ThrowsReferenceIdModel", "@ReferenceId target must not throw any exceptions" }, new Object[]{ "com.example.reference.ThrowsReferenceModel", "@Reference target must not throw any exceptions" }, new Object[]{ "com.example.on_deps_change.OnDepsChangeNotAbstractModel", "@OnDepsChange target must not be abstract" }, new Object[]{ "com.example.on_deps_change.OnDepsChangeDuplicatedModel", "@OnDepsChange target duplicates existing method named onRenderDepsChange" }, new Object[]{ "com.example.on_deps_change.OnDepsChangeNotStaticModel", "@OnDepsChange target must not be static" }, new Object[]{ "com.example.on_deps_change.OnDepsChangeNotPrivateModel", "@OnDepsChange target must not be private" }, new Object[]{ "com.example.on_deps_change.OnDepsChangeMustNotHaveParametersModel", "@OnDepsChange target must not have any parameters" }, new Object[]{ "com.example.on_deps_change.OnDepsChangeMustNotReturnValueModel", "@OnDepsChange target must not return a value" }, new Object[]{ "com.example.on_deps_change.OnDepsChangeThrowsExceptionModel", "@OnDepsChange target must not throw any exceptions" }, new Object[]{ "com.example.on_deps_change.OnDepsChangeBadName", "@OnDepsChange target specified an invalid name '-ace'. The name must be a valid java identifier." }, new Object[]{ "com.example.on_deps_change.OnDepsChangeBadName2", "@OnDepsChange target specified an invalid name 'class'. The name must not be a java keyword." }, new Object[]{ "com.example.on_deps_change.OnDepsChangeBadName3", "@OnDepsChange target specified an invalid name '-ace-'. The name must be a valid java identifier." }, new Object[]{ "com.example.on_deps_change.OnDepsChangeNoTracked", "@OnDepsChange target has no corresponding @Observe that could be automatically determined" }, new Object[]{ "com.example.post_construct.EjbPostConstructModel", "@javax.annotation.PostConstruct annotation not supported in components annotated with @ArezComponent, use the @arez.annotations.PostConstruct annotation instead." }, new Object[]{ "com.example.post_construct.PostConstructAbstractModel", "@PostConstruct target must not be abstract" }, new Object[]{ "com.example.post_construct.PostConstructDuplicateModel", "@PostConstruct target duplicates existing method named postConstruct1" }, new Object[]{ "com.example.post_construct.PostConstructMustNotHaveParametersModel", "@PostConstruct target must not have any parameters" }, new Object[]{ "com.example.post_construct.PostConstructMustNotReturnValueModel", "@PostConstruct target must not return a value" }, new Object[]{ "com.example.post_construct.PostConstructNotStaticModel", "@PostConstruct target must not be static" }, new Object[]{ "com.example.post_construct.PostConstructNotPrivateModel", "@PostConstruct target must not be private" }, new Object[]{ "com.example.name_duplicates.ObservableAndActionMethodModel", "Method can not be annotated with both @Action and @Observable" }, new Object[]{ "com.example.name_duplicates.ObservableAndPreDisposeMethodModel", "Method can not be annotated with both @Observable and @PreDispose" }, new Object[]{ "com.example.name_duplicates.ObservableAndPostDisposeMethodModel", "Method can not be annotated with both @Observable and @PostDispose" }, new Object[]{ "com.example.name_duplicates.ObservableAndMemoizeMethodModel", "Method can not be annotated with both @Observable and @Memoize" }, new Object[]{ "com.example.name_duplicates.ObservableAndContainerIdMethodModel", "Method can not be annotated with both @Observable and @ComponentId" }, new Object[]{ "com.example.name_duplicates.ObservableAndOnActivateMethodModel", "Method can not be annotated with both @Observable and @OnActivate" }, new Object[]{ "com.example.name_duplicates.ObservableAndOnDeactivateMethodModel", "Method can not be annotated with both @Observable and @OnDeactivate" }, new Object[]{ "com.example.name_duplicates.ObservableAndOnStaleMethodModel", "Method can not be annotated with both @Observable and @OnStale" }, new Object[]{ "com.example.name_duplicates.ActionAndObserveMethodModel", "Method can not be annotated with both @Action and @Observe" }, new Object[]{ "com.example.name_duplicates.ActionAndMemoizeMethodModel", "Method can not be annotated with both @Action and @Memoize" }, new Object[]{ "com.example.name_duplicates.ActionAndPreDisposeMethodModel", "Method can not be annotated with both @Action and @PreDispose" }, new Object[]{ "com.example.name_duplicates.ActionAndPostDisposeMethodModel", "Method can not be annotated with both @Action and @PostDispose" }, new Object[]{ "com.example.name_duplicates.ActionAndContainerIdMethodModel", "Method can not be annotated with both @Action and @ComponentId" }, new Object[]{ "com.example.name_duplicates.ActionAndOnActivateMethodModel", "Method can not be annotated with both @Action and @OnActivate" }, new Object[]{ "com.example.name_duplicates.ActionAndOnDeactivateMethodModel", "Method can not be annotated with both @Action and @OnDeactivate" }, new Object[]{ "com.example.name_duplicates.ActionAndOnStaleMethodModel", "Method can not be annotated with both @Action and @OnStale" }, new Object[]{ "com.example.name_duplicates.MemoizeAndContainerIdMethodModel", "Method can not be annotated with both @Memoize and @ComponentId" }, new Object[]{ "com.example.name_duplicates.MemoizeAndPreDisposeMethodModel", "Method can not be annotated with both @Memoize and @PreDispose" }, new Object[]{ "com.example.name_duplicates.MemoizeAndObserveMethodModel", "Method can not be annotated with both @Observe and @Memoize" }, new Object[]{ "com.example.name_duplicates.MemoizeAndPostDisposeMethodModel", "Method can not be annotated with both @Memoize and @PostDispose" }, new Object[]{ "com.example.name_duplicates.MemoizeAndOnActivateMethodModel", "Method can not be annotated with both @Memoize and @OnActivate" }, new Object[]{ "com.example.name_duplicates.MemoizeAndOnDeactivateMethodModel", "Method can not be annotated with both @Memoize and @OnDeactivate" }, new Object[]{ "com.example.name_duplicates.MemoizeAndOnStaleMethodModel", "Method can not be annotated with both @Memoize and @OnStale" }, new Object[]{ "com.example.pre_dispose.PreDisposeAndPostDisposeMethodModel", "Method can not be annotated with both @PreDispose and @PostDispose" }, new Object[]{ "com.example.observable.AbstractGetterNoSetterModel", "@Observable target defines expectSetter = false but is abstract. This is not compatible as there is no opportunity for the processor to generate the setter." }, new Object[]{ "com.example.observable.AbstractGetterThrowsExceptionModel", "@Observable property is abstract but the getter declares an exception." }, new Object[]{ "com.example.observable.AbstractSetterThrowsExceptionModel", "@Observable property is abstract but the setter declares an exception." }, new Object[]{ "com.example.observable.NonAbstractGetterModel", "@Observable property defines an abstract setter but a concrete getter. Both getter and setter must be concrete or both must be abstract." }, new Object[]{ "com.example.observable.NonAbstractSetterModel", "@Observable property defines an abstract getter but a concrete setter. Both getter and setter must be concrete or both must be abstract." }, new Object[]{ "com.example.observable.BadTypesModel", "@Observable property defines a setter and getter with different types. Getter type: long Setter type: int." }, new Object[]{ "com.example.observable.NoSetterOrRefModel", "@Observable target defines expectSetter = false but there is no ref method for observable and thus never possible to report it as changed and thus should not be observable." }, new Object[]{ "com.example.observable.SetterButExpectSetterFalseModel", "Method annotated with @Observable defines expectSetter = false but a setter exists for observable named field" }, new Object[]{ "com.example.observable.SetterButExpectSetterFalse2Model", "Method annotated with @Observable defines expectSetter = false but a setter exists named setFieldfor observable named field" }, new Object[]{ "com.example.observable.SetterWithExpectSetterFalseModel", "Method annotated with @Observable is a setter but defines expectSetter = false for observable named field" }, new Object[]{ "com.example.observable.BadObservableNameModel", "@Observable target specified an invalid name '-ace'. The name must be a valid java identifier." }, new Object[]{ "com.example.observable.BadObservableName2Model", "@Observable target specified an invalid name 'default'. The name must not be a java keyword." }, new Object[]{ "com.example.observable.ExtraParameterSetterModel", "@Observable target should be a setter or getter" }, new Object[]{ "com.example.observable.ExtraParameterGetterModel", "@Observable target should be a setter or getter" }, new Object[]{ "com.example.observable.DuplicateSetterModel", "@Observable defines duplicate setter for observable named field" }, new Object[]{ "com.example.observable.DuplicateGetterModel", "@Observable defines duplicate getter for observable named field" }, new Object[]{ "com.example.observable.StaticObservableGetterModel", "@Observable target must not be static" }, new Object[]{ "com.example.observable.StaticObservableSetterModel", "@Observable target must not be static" }, new Object[]{ "com.example.observable.InitializerOnConcreteGetterModel", "@Observable target set initializer parameter to ENABLED but method is not abstract." }, new Object[]{ "com.example.observable.InitializerOnConcreteSetterModel", "@Observable target set initializer parameter to ENABLED but method is not abstract." }, new Object[]{ "com.example.observable.InitializerParametersDisagreeModel", "@Observable target set initializer parameter to value that differs from the paired observable method." }, new Object[]{ "com.example.observable.FinalObservableGetterModel", "@Observable target must not be final" }, new Object[]{ "com.example.observable.FinalObservableSetterModel", "@Observable target must not be final" }, new Object[]{ "com.example.observable.TypeArgumentsOnObservableGetterModel", "@Observable target defines type variables. Method level type parameters are not supported for observable values." }, new Object[]{ "com.example.observable.TypeArgumentsOnObservableSetterModel", "@Observable target defines type variables. Method level type parameters are not supported for observable values." }, new Object[]{ "com.example.repository.RepositoryExtensionIsClass", "Class annotated with @Repository defined an extension that is not an interface. Extension: com.example.repository.RepositoryExtensionIsClass.Foo" }, new Object[]{ "com.example.repository.RepositoryExtensionNotInterface", "Class annotated with @Repository defined an extension that is not an interface. Extension: com.example.repository.RepositoryExtensionNotInterface.Foo" }, new Object[]{ "com.example.repository.RepositoryExtensionHasBadSelf", "Class annotated with @Repository defined an extension that has a non default method. Extension: com.example.repository.RepositoryExtensionHasBadSelf.Foo Method: self(int)" }, new Object[]{ "com.example.repository.RepositoryExtensionHasAbstractMethod", "Class annotated with @Repository defined an extension that has a non default method. Extension: com.example.repository.RepositoryExtensionHasAbstractMethod.Foo Method: other(int)" }, new Object[]{ "com.example.repository.RepositoryNotObservable", "@ArezComponent target has specified observable = DISABLE and but is also annotated with the @Repository annotation which requires that the observable != DISABLE." }, new Object[]{ "com.example.repository.SingletonAndRepository", "@ArezComponent target is annotated with both the @arez.annotations.Repository annotation and the javax.inject.Singleton annotation which is an invalid combination." } }; } @Test( dataProvider = "failedCompiles" ) public void processFailedCompile( @Nonnull final String classname, @Nonnull final String errorMessageFragment ) { assertFailedCompile( classname, errorMessageFragment ); } @DataProvider( name = "packageAccessElementInDifferentPackage" ) public Object[][] packageAccessElementInDifferentPackage() { return new Object[][] { new Object[]{ "Action", "Action" }, new Object[]{ "Observe", "Observe" }, new Object[]{ "CascadeDispose", "CascadeDispose" }, new Object[]{ "CascadeDispose", "CascadeDisposeMethod" }, new Object[]{ "ComponentId", "ComponentId" }, new Object[]{ "ComponentNameRef", "ComponentNameRef" }, new Object[]{ "ComponentRef", "ComponentRef" }, new Object[]{ "Memoize", "Memoize" }, new Object[]{ "OnActivate", "OnActivate" }, new Object[]{ "OnDeactivate", "OnDeactivate" }, new Object[]{ "OnStale", "OnStale" }, new Object[]{ "ComputableValueRef", "ComputableValueRef" }, new Object[]{ "ContextRef", "ContextRef" }, new Object[]{ "ComponentDependency", "ComponentDependency" }, new Object[]{ "Observable", "Observable" }, new Object[]{ "ObservableValueRef", "ObservableValueRef" }, new Object[]{ "ObserverRef", "ObserverRef" }, new Object[]{ "PostConstruct", "PostConstruct" }, new Object[]{ "OnDepsChange", "OnDepsChange" } }; } @Test( dataProvider = "packageAccessElementInDifferentPackage" ) public void processFailedCompileInheritedPackageAccessInDifferentPackage( @Nonnull final String annotation, @Nonnull final String name ) { final JavaFileObject source1 = fixture( "bad_input/com/example/package_access/other/Base" + name + "Model.java" ); final JavaFileObject source2 = fixture( "bad_input/com/example/package_access/" + name + "Model.java" ); assertFailedCompileResource( Arrays.asList( source1, source2 ), "@" + annotation + " target must not be package access if " + "the method is in a different package from the @ArezComponent" ); } @Test public void processFailedCompileInheritedPackageAccessInDifferentPackageWhenInRoot() { final JavaFileObject source1 = fixture( "bad_input/com/example/package_access/other/BaseActionModel.java" ); final JavaFileObject source2 = fixture( "bad_input/PackageAccessActionModel.java" ); assertFailedCompileResource( Arrays.asList( source1, source2 ), "@Action target must not be package access if " + "the method is in a different package from the @ArezComponent" ); } @Test public void processFailedCompileInheritedPackageAccessInDifferentPackageObservable_Setter() { final JavaFileObject source1 = fixture( "bad_input/com/example/package_access/other/BaseObservable2Model.java" ); final JavaFileObject source2 = fixture( "bad_input/com/example/package_access/Observable2Model.java" ); assertFailedCompileResource( Arrays.asList( source1, source2 ), "@Observable target must not be package access if " + "the method is in a different package from the @ArezComponent" ); } @Test public void processFailedCompileInheritedPackageAccessInDifferentPackageObservable_Getter() { final JavaFileObject source1 = fixture( "bad_input/com/example/package_access/other/BaseObservable3Model.java" ); final JavaFileObject source2 = fixture( "bad_input/com/example/package_access/Observable3Model.java" ); assertFailedCompileResource( Arrays.asList( source1, source2 ), "@Observable target must not be package access if " + "the method is in a different package from the @ArezComponent" ); } }
package com.continuuity.test; import com.continuuity.api.Application; import com.continuuity.api.ApplicationSpecification; import com.continuuity.api.flow.FlowSpecification; import com.continuuity.api.flow.FlowletDefinition; import com.continuuity.api.flow.flowlet.GeneratorFlowlet; import com.continuuity.api.procedure.ProcedureSpecification; import com.continuuity.app.guice.BigMamaModule; import com.continuuity.app.program.ManifestFields; import com.continuuity.app.services.AppFabricService; import com.continuuity.app.services.AuthToken; import com.continuuity.app.services.DeploymentStatus; import com.continuuity.app.services.ResourceIdentifier; import com.continuuity.app.services.ResourceInfo; import com.continuuity.common.conf.CConfiguration; import com.continuuity.data.runtime.DataFabricModules; import com.continuuity.discovery.DiscoveryService; import com.continuuity.discovery.DiscoveryServiceClient; import com.continuuity.filesystem.Location; import com.continuuity.filesystem.LocationFactory; import com.continuuity.internal.app.BufferFileInputStream; import com.continuuity.internal.test.ApplicationManagerFactory; import com.continuuity.internal.test.DefaultApplicationManager; import com.continuuity.internal.test.DefaultProcedureClient; import com.continuuity.internal.test.DefaultStreamWriter; import com.continuuity.internal.test.ProcedureClientFactory; import com.continuuity.internal.test.StreamWriterFactory; import com.continuuity.internal.test.bytecode.FlowletRewriter; import com.continuuity.internal.test.bytecode.ProcedureRewriter; import com.google.common.base.Preconditions; import com.google.common.base.Throwables; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.common.collect.Sets; import com.google.common.io.ByteStreams; import com.google.common.io.Files; import com.google.inject.AbstractModule; import com.google.inject.Guice; import com.google.inject.Injector; import com.google.inject.assistedinject.FactoryModuleBuilder; import org.junit.AfterClass; import org.junit.BeforeClass; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.net.URL; import java.nio.ByteBuffer; import java.util.Collections; import java.util.Enumeration; import java.util.Map; import java.util.Queue; import java.util.Set; import java.util.concurrent.TimeUnit; import java.util.jar.JarEntry; import java.util.jar.JarOutputStream; import java.util.jar.Manifest; /** * Base class to inherit from that provides testing functionality for {@link com.continuuity.api.Application}. */ public class AppFabricTestBase { private static File testAppDir; private static File tmpDir; private static AppFabricService.Iface appFabricServer; private static LocationFactory locationFactory; private static Injector injector; private static DiscoveryServiceClient discoveryServiceClient; /** * Deploys an {@link com.continuuity.api.Application}. The {@link com.continuuity.api.flow.Flow Flows} and * {@link com.continuuity.api.procedure.Procedure Procedures} defined in the application * must be in the same or children package as the application. * * @param applicationClz The application class * @return An {@link ApplicationManager} to manage the deployed application. */ protected ApplicationManager deployApplication(Class<? extends Application> applicationClz) { Preconditions.checkNotNull(applicationClz, "Application cannot be null."); final String accountId = "developer"; Application application = null; try { application = applicationClz.newInstance(); } catch (Exception e) { throw Throwables.propagate(e); } ApplicationSpecification appSpec = application.configure(); final String applicationId = appSpec.getName(); // Create the deployment jar Location deployedJar = locationFactory.create(createDeploymentJar(applicationClz, appSpec).getAbsolutePath()); try { // Call init to get a session identifier - yes, the name needs to be changed. final AuthToken token = new AuthToken("appFabricTest"); ResourceIdentifier id = appFabricServer.init( token, new ResourceInfo(accountId, "", applicationId, 0, System.currentTimeMillis())); // Upload the jar file to remote location. BufferFileInputStream is = new BufferFileInputStream(deployedJar.getInputStream(), 100*1024); try { byte[] chunk = is.read(); while (chunk.length > 0) { appFabricServer.chunk(token, id, ByteBuffer.wrap(chunk)); chunk = is.read(); DeploymentStatus status = appFabricServer.dstatus(token, id); Preconditions.checkState(status.getOverall() == 2, "Fail to deploy app."); } } finally { is.close(); } // Deploy the app appFabricServer.deploy(token, id); int status = appFabricServer.dstatus(token, id).getOverall(); while(status == 3) { status = appFabricServer.dstatus(token, id).getOverall(); TimeUnit.MILLISECONDS.sleep(100); } Preconditions.checkState(status == 5, "Fail to deploy app."); return injector.getInstance(ApplicationManagerFactory.class).create(token, accountId, applicationId, appFabricServer, deployedJar, appSpec); } catch (Exception e) { throw Throwables.propagate(e); } } @BeforeClass public static final void init() { testAppDir = Files.createTempDir(); File outputDir = new File(testAppDir, "app"); tmpDir = new File(testAppDir, "tmp"); outputDir.mkdirs(); tmpDir.mkdirs(); CConfiguration configuration = CConfiguration.create(); configuration.set("app.output.dir", outputDir.getAbsolutePath()); configuration.set("app.tmp.dir", tmpDir.getAbsolutePath()); injector = Guice.createInjector(new DataFabricModules().getInMemoryModules(), new BigMamaModule(configuration), new AbstractModule() { @Override protected void configure() { install(new FactoryModuleBuilder() .implement(ApplicationManager.class, DefaultApplicationManager.class) .build(ApplicationManagerFactory.class)); install(new FactoryModuleBuilder() .implement(StreamWriter.class, DefaultStreamWriter.class) .build(StreamWriterFactory.class)); install(new FactoryModuleBuilder() .implement(ProcedureClient.class, DefaultProcedureClient.class) .build(ProcedureClientFactory.class)); } }); discoveryServiceClient = injector.getInstance(DiscoveryServiceClient.class); discoveryServiceClient.startAndWait(); injector.getInstance(DiscoveryService.class).startAndWait(); appFabricServer = injector.getInstance(AppFabricService.Iface.class); locationFactory = injector.getInstance(LocationFactory.class); } @AfterClass public static final void finish() { cleanDir(testAppDir); } private static void cleanDir(File dir) { File[] files = dir.listFiles(); if (files == null) { return; } for (File file : files) { if (file.isFile()) { file.delete(); } else { cleanDir(file); } } } private static String pathToClassName(String path) { return path.replace('/', '.').substring(0, path.length() - ".class".length()); } /** * Creates a jar of a directory and rewrite Flowlet and Procedure bytecodes to emit metrics. * * @param dir Directory root for creating jar entries. * @param manifest The Jar manifest content. * @param outputFile Location of the Jar file. * @param appSpec The {@link com.continuuity.api.ApplicationSpecification} of the deploying application. */ private static File jarDir(File dir, File relativeBase, Manifest manifest, File outputFile, ApplicationSpecification appSpec) throws IOException, ClassNotFoundException { JarOutputStream jarOut = new JarOutputStream(new FileOutputStream(outputFile), manifest); Queue<File> queue = Lists.newLinkedList(); Collections.addAll(queue, dir.listFiles()); // Find all flowlet classes (flowlet class => flowId) // FIXME: Limitation now is that the same flowlet class can be used in one flow only (can have multiple names) Map<String, String> flowletClassNames = Maps.newHashMap(); for (FlowSpecification flowSpec : appSpec.getFlows().values()) { for (FlowletDefinition flowletDef : flowSpec.getFlowlets().values()) { flowletClassNames.put(flowletDef.getFlowletSpec().getClassName(), flowSpec.getName()); } } // Find all procedure classes Set<String> procedureClassNames = Sets.newHashSet(); for (ProcedureSpecification procedureSpec : appSpec.getProcedures().values()) { procedureClassNames.add(procedureSpec.getClassName()); } FlowletRewriter flowletRewriter = new FlowletRewriter(appSpec.getName(), false); FlowletRewriter generatorRewriter = new FlowletRewriter(appSpec.getName(), true); ProcedureRewriter procedureRewriter = new ProcedureRewriter(appSpec.getName()); URI basePath = relativeBase.toURI(); while (!queue.isEmpty()) { File file = queue.remove(); String entryName = basePath.relativize(file.toURI()).toString(); jarOut.putNextEntry(new JarEntry(entryName)); if (file.isFile()) { InputStream is = new FileInputStream(file); try { byte[] bytes = ByteStreams.toByteArray(is); String className = pathToClassName(entryName); if (flowletClassNames.containsKey(className)) { if (GeneratorFlowlet.class.isAssignableFrom(Class.forName(className))) { jarOut.write(generatorRewriter.generate(bytes, flowletClassNames.get(className))); } else { jarOut.write(flowletRewriter.generate(bytes, flowletClassNames.get(className))); } } else if (procedureClassNames.contains(className)) { jarOut.write(procedureRewriter.generate(bytes)); } else { jarOut.write(bytes); } } finally { is.close(); } } else { Collections.addAll(queue, file.listFiles()); } jarOut.closeEntry(); } jarOut.close(); return outputFile; } private File createDeploymentJar(Class<?> clz, ApplicationSpecification appSpec) { // Creates Manifest Manifest manifest = new Manifest(); manifest.getMainAttributes().put(ManifestFields.MANIFEST_VERSION, "1.0"); manifest.getMainAttributes().put(ManifestFields.MAIN_CLASS, clz.getName()); ClassLoader loader = clz.getClassLoader(); Preconditions.checkArgument(loader != null, "Cannot get ClassLoader for class " + clz); String classFile = clz.getName().replace('.', '/') + ".class"; try { for(Enumeration<URL> itr = loader.getResources(classFile); itr.hasMoreElements(); ) { URI uri = itr.nextElement().toURI(); if (uri.getScheme().equals("file")) { File baseDir = new File(uri).getParentFile(); Package appPackage = clz.getPackage(); String packagePath = appPackage == null ? "" : appPackage.getName().replace('.', '/'); String basePath = baseDir.getAbsolutePath(); File relativeBase = new File(basePath.substring(0, basePath.length() - packagePath.length())); File jarFile = File.createTempFile( String.format("%s-%d", clz.getSimpleName(), System.currentTimeMillis()), ".jar", tmpDir); return jarDir(baseDir, relativeBase, manifest, jarFile, appSpec); } else if (uri.getScheme().equals("jar")) { return new File(uri.getPath()); } } } catch(Exception e) { throw Throwables.propagate(e); } return null; } }
package com.janrain.android.engage.session; import android.content.Context; import android.content.pm.ApplicationInfo; import android.text.TextUtils; import android.util.Log; import android.webkit.CookieManager; import com.janrain.android.R; import com.janrain.android.engage.JREngage; import com.janrain.android.engage.JREngageError; import com.janrain.android.engage.JREngageError.ConfigurationError; import com.janrain.android.engage.JREngageError.ErrorType; import com.janrain.android.engage.JREngageError.SocialPublishingError; import com.janrain.android.engage.net.JRConnectionManager; import com.janrain.android.engage.net.JRConnectionManagerDelegate; import com.janrain.android.engage.net.async.HttpResponseHeaders; import com.janrain.android.engage.types.JRActivityObject; import com.janrain.android.engage.types.JRDictionary; import com.janrain.android.utils.AndroidUtils; import com.janrain.android.utils.Archiver; import com.janrain.android.utils.CollectionUtils; import com.janrain.android.utils.LogUtils; import com.janrain.android.utils.PrefUtils; import com.janrain.android.utils.StringUtils; import org.apache.http.HttpStatus; import org.apache.http.NameValuePair; import org.apache.http.message.BasicNameValuePair; import org.json.JSONException; 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.UUID; import static com.janrain.android.utils.LogUtils.throwDebugException; import static com.janrain.android.utils.WebViewUtils.deleteWebViewCookiesForDomains; public class JRSession implements JRConnectionManagerDelegate { private static final String TAG = JRSession.class.getSimpleName(); private static final String ARCHIVE_ALL_PROVIDERS = "allProviders"; private static final String ARCHIVE_AUTH_PROVIDERS = "authProviders"; private static final String ARCHIVE_SHARING_PROVIDERS = "sharingProviders"; private static final String ARCHIVE_AUTH_USERS_BY_PROVIDER = "jrAuthenticatedUsersByProvider"; private static final String RPXNOW_BASE_URL = "https://rpxnow.com"; private static String mEngageBaseUrl = RPXNOW_BASE_URL; private static final String UNFORMATTED_CONFIG_URL = "%s/openid/mobile_config_and_baseurl?appId=%s&device=android&app_name=%s&version=%s"; private static final String TAG_GET_CONFIGURATION = "getConfiguration"; private static JRSession sInstance; public static final String USERDATA_ACTION_KEY = "action"; public static final String USERDATA_ACTION_CALL_TOKEN_URL = "callTokenUrl"; public static final String USERDATA_TOKEN_URL_KEY = "tokenUrl"; public static final String USERDATA_PROVIDER_NAME_KEY = "providerName"; public static final String USERDATA_ACTIVITY_KEY = "activity"; public static final String USERDATA_ACTION_SHARE_ACTIVITY = "shareActivity"; private List<JRSessionDelegate> mDelegates; private JRProvider mCurrentlyAuthenticatingProvider; private JRProvider mCurrentlyPublishingProvider; private String mReturningAuthProvider; private String mReturningSharingProvider; private Map<String, JRProvider> mAllProviders; private List<String> mAuthProviders; private List<String> mEnabledAuthenticationProviders; private List<String> mEnabledSharingProviders; private List<String> mSharingProviders; private Map<String, JRAuthenticatedUser> mAuthenticatedUsersByProvider; private JRActivityObject mActivity; private String mTokenUrl; private String mAppId; private String mRpBaseUrl; private String mUrlEncodedAppName; private String mUniqueIdentifier; private boolean mConfigDone = false; private String mOldEtag; private String mSavedConfigurationBlock; private String mSavedEtag; private String mNewEtag; private String mUrlEncodedLibraryVersion; private boolean mHidePoweredBy; private boolean mAlwaysForceReauth; private boolean mSkipLandingPage; private int mUiShowingCount; private JREngageError mError; public static JRSession getInstance() { return sInstance; } public static JRSession getInstance(String appId, String tokenUrl, JRSessionDelegate delegate) { if (sInstance != null) { if (sInstance.isUiShowing()) { Log.e(TAG, "Cannot reinitialize JREngage while its UI is showing"); } else { LogUtils.logd(TAG, "[getInstance] reinitializing, registered delegates will be unregistered"); sInstance.initialize(appId, tokenUrl, delegate); } } else { LogUtils.logd(TAG, "[getInstance] returning new instance."); sInstance = new JRSession(appId, tokenUrl, delegate); } return sInstance; } private JRSession(String appId, String tokenUrl, JRSessionDelegate delegate) { initialize(appId, tokenUrl, delegate); } /* We runtime type check the deserialized generics so we can safely ignore these unchecked * assignment warnings. */ @SuppressWarnings("unchecked") private void initialize(String appId, String tokenUrl, JRSessionDelegate delegate) { LogUtils.logd(TAG, "[initialize] initializing instance."); // for configurability to test against e.g. staging String t = StringUtils.trim(AndroidUtils.readAsset(getApplicationContext(), "engage_base_url.txt")); if (t != null) mEngageBaseUrl = t; mDelegates = new ArrayList<JRSessionDelegate>(); mDelegates.add(delegate); mAppId = appId; mTokenUrl = tokenUrl; mUniqueIdentifier = this.getUniqueIdentifier(); ApplicationInfo ai = AndroidUtils.getApplicationInfo(); String appName = getApplicationContext().getPackageManager().getApplicationLabel(ai).toString(); appName += ":" + getApplicationContext().getPackageName(); mUrlEncodedAppName = AndroidUtils.urlEncode(appName); mUrlEncodedLibraryVersion = AndroidUtils.urlEncode(getApplicationContext().getString(R.string.jr_git_describe)); try { if (!mUrlEncodedLibraryVersion.equals(PrefUtils.getString(PrefUtils.KEY_JR_ENGAGE_LIBRARY_VERSION, ""))) { // If the library versions don't match start with fresh state in order to break out of // any invalid state. throw new Archiver.LoadException("New library version with old serialized state"); } /* load the last used auth and social providers */ mReturningSharingProvider = PrefUtils.getString(PrefUtils.KEY_JR_LAST_USED_SHARING_PROVIDER, ""); mReturningAuthProvider = PrefUtils.getString(PrefUtils.KEY_JR_LAST_USED_AUTH_PROVIDER, ""); /* Load the library state from disk */ mAuthenticatedUsersByProvider = Archiver.load(ARCHIVE_AUTH_USERS_BY_PROVIDER); mAllProviders = Archiver.load(ARCHIVE_ALL_PROVIDERS); /* Fix up the provider objects with data that isn't serialized along with them */ for (Object provider : mAllProviders.values()) ((JRProvider)provider).loadDynamicVariables(); /* Load the list of auth providers */ mAuthProviders = Archiver.load(ARCHIVE_AUTH_PROVIDERS); for (Object v : mAuthProviders) { if (!(v instanceof String)) throw new Archiver.LoadException("Non String in mAuthProviders"); } LogUtils.logd(TAG, "auth providers: [" + TextUtils.join(",", mAuthProviders) + "]"); /* Load the list of social providers */ mSharingProviders = Archiver.load(ARCHIVE_SHARING_PROVIDERS); for (Object v : mSharingProviders) { if (!(v instanceof String)) { throw new Archiver.LoadException("Non String in mSharingProviders"); } } LogUtils.logd(TAG, "sharing providers: [" + TextUtils.join(",", mSharingProviders) + "]"); /* Load the RP's base url */ mRpBaseUrl = PrefUtils.getString(PrefUtils.KEY_JR_RP_BASE_URL, ""); /* Figure out of we're suppose to hide the powered by line */ mHidePoweredBy = PrefUtils.getBoolean(PrefUtils.KEY_JR_HIDE_POWERED_BY, false); /* If the configuration for this RP has changed, the etag will have changed, and we need * to update our current configuration information. */ mOldEtag = PrefUtils.getString(PrefUtils.KEY_JR_CONFIGURATION_ETAG, ""); //throw new Archiver.LoadException(null); } catch (Archiver.LoadException e) { Log.w(TAG, "LoadException loading serialized configuration, initializing from empty state. " + " Version: " + mUrlEncodedLibraryVersion + " LoadException: " + e.getStackTrace()[0].toString() + " Nested exception: " + e.getCause()); /* Blank slate */ mAuthenticatedUsersByProvider = new HashMap<String, JRAuthenticatedUser>(); Archiver.asyncSave(ARCHIVE_AUTH_USERS_BY_PROVIDER, mAuthenticatedUsersByProvider); // Note that these values are removed from the settings when resetting state to prevent // uninitialized state from being read on startup as valid state mAllProviders = new HashMap<String, JRProvider>(); Archiver.delete(ARCHIVE_ALL_PROVIDERS); mAuthProviders = new ArrayList<String>(); Archiver.delete(ARCHIVE_AUTH_PROVIDERS); mSharingProviders = new ArrayList<String>(); Archiver.delete(ARCHIVE_SHARING_PROVIDERS); mRpBaseUrl = ""; PrefUtils.remove(PrefUtils.KEY_JR_RP_BASE_URL); mHidePoweredBy = true; PrefUtils.remove(PrefUtils.KEY_JR_HIDE_POWERED_BY); mOldEtag = ""; PrefUtils.remove(PrefUtils.KEY_JR_CONFIGURATION_ETAG); // Note that these values are not removed from the Prefs, they can't result in invalid state // (The library is accepting of values not belonging to the set of enabled providers.) mReturningAuthProvider = PrefUtils.getString(PrefUtils.KEY_JR_LAST_USED_AUTH_PROVIDER, null); mReturningSharingProvider = PrefUtils.getString(PrefUtils.KEY_JR_LAST_USED_SHARING_PROVIDER, null); //mConfigDone = false; } mError = startGetConfiguration(); } public JREngageError getError() { return mError; } public JRActivityObject getJRActivity() { return mActivity; } public void setJRActivity(JRActivityObject activity) { mActivity = activity; } public void setSkipLandingPage(boolean skipLandingPage) { mSkipLandingPage = skipLandingPage; } public boolean getSkipLandingPage() { return mSkipLandingPage; } public boolean getAlwaysForceReauth() { return mAlwaysForceReauth; } public void setAlwaysForceReauth(boolean force) { mAlwaysForceReauth = force; } public void setTokenUrl(String tokenUrl) { mTokenUrl = tokenUrl; } public JRProvider getCurrentlyAuthenticatingProvider() { return mCurrentlyAuthenticatingProvider; } public void setCurrentlyAuthenticatingProvider(JRProvider provider) { LogUtils.logd(TAG, "[setCurrentlyAuthenticatingProvider] to " + (provider != null ? provider.getName() : null)); mCurrentlyAuthenticatingProvider = provider; } public ArrayList<JRProvider> getAuthProviders() { ArrayList<JRProvider> providerList = new ArrayList<JRProvider>(); if ((mAuthProviders != null) && (mAuthProviders.size() > 0)) { for (String name : mAuthProviders) { // Filter by enabled provider list if available if (mEnabledAuthenticationProviders != null && !mEnabledAuthenticationProviders.contains(name)) continue; providerList.add(mAllProviders.get(name)); } } return providerList; } /** * Gets the configured and enabled sharing providers * * @return an ArrayList&lt;Provider>, does not return null. */ public ArrayList<JRProvider> getSharingProviders() { ArrayList<JRProvider> providerList = new ArrayList<JRProvider>(); if ((mSharingProviders != null) && (mSharingProviders.size() > 0)) { for (String name : mSharingProviders) { // Filter by enabled provider list if available if (mEnabledSharingProviders != null && !mEnabledSharingProviders.contains(name)) continue; providerList.add(mAllProviders.get(name)); } } return providerList; } public String getReturningAuthProvider() { /* This is here so that when a calling application sets mSkipLandingPage, the dialog always opens * to the providers list. (See JRProviderListFragment.onCreate for an explanation of the flow control * when there's a "returning provider.") */ if (mSkipLandingPage) return null; return mReturningAuthProvider; } public void setReturningAuthProvider(String returningAuthProvider) { if (TextUtils.isEmpty(returningAuthProvider)) returningAuthProvider = ""; // nulls -> ""s if (!getAuthProviders().contains(getProviderByName(returningAuthProvider))) { returningAuthProvider = ""; } mReturningAuthProvider = returningAuthProvider; PrefUtils.putString(PrefUtils.KEY_JR_LAST_USED_AUTH_PROVIDER, returningAuthProvider); } public String getReturningSharingProvider() { return mReturningSharingProvider; } public void setReturningSharingProvider(String returningSharingProvider) { if (TextUtils.isEmpty(returningSharingProvider)) returningSharingProvider = ""; // nulls -> ""s if (!getSharingProviders().contains(getProviderByName(returningSharingProvider))) { returningSharingProvider = ""; } mReturningSharingProvider = returningSharingProvider; PrefUtils.putString(PrefUtils.KEY_JR_LAST_USED_SHARING_PROVIDER, returningSharingProvider); } public String getRpBaseUrl() { return mRpBaseUrl; } public boolean getHidePoweredBy() { return mHidePoweredBy; } public void setUiIsShowing(boolean uiIsShowing) { if (uiIsShowing) { mUiShowingCount++; } else { mUiShowingCount } if (mUiShowingCount == 0 && mSavedConfigurationBlock != null) { String s = mSavedConfigurationBlock; mSavedConfigurationBlock = null; mNewEtag = mSavedEtag; finishGetConfiguration(s); } } public void connectionDidFail(Exception ex, HttpResponseHeaders responseHeaders, byte[] payload, String requestUrl, Object tag) { if (tag == null) { Log.e(TAG, "[connectionDidFail] unexpected null userdata"); } else if (tag instanceof String) { if (tag.equals(TAG_GET_CONFIGURATION)) { Log.e(TAG, "[connectionDidFail] for getConfiguration"); mError = new JREngageError( getApplicationContext().getString(R.string.jr_getconfig_network_failure_message), ConfigurationError.CONFIGURATION_INFORMATION_ERROR, JREngageError.ErrorType.CONFIGURATION_FAILED, ex); triggerConfigDidFinish(); } else { Log.e(TAG, "[connectionDidFail] unrecognized ConnectionManager tag: " + tag + " with Exception: " + ex); } } else if (tag instanceof JRDictionary) { JRDictionary tagAsDict = (JRDictionary) tag; if (tagAsDict.getAsString(USERDATA_ACTION_KEY).equals(USERDATA_ACTION_CALL_TOKEN_URL)) { Log.e(TAG, "[connectionDidFail] call to token url failed: " + ex); JREngageError error = new JREngageError( "Error: " + ex.getLocalizedMessage(), JREngageError.AuthenticationError.AUTHENTICATION_TOKEN_URL_FAILED, "Failed to reach authentication token URL", ex); for (JRSessionDelegate delegate : getDelegatesCopy()) { delegate.authenticationCallToTokenUrlDidFail( tagAsDict.getAsString(USERDATA_TOKEN_URL_KEY), error, tagAsDict.getAsString(USERDATA_PROVIDER_NAME_KEY)); } } else if (tagAsDict.getAsString(USERDATA_ACTION_KEY).equals(USERDATA_ACTION_SHARE_ACTIVITY)) { // set status uses this same connection handler. processShareActivityResponse(new String(payload), tagAsDict); } } } private void processShareActivityResponse(String payload, JRDictionary userDataTag) { String providerName = userDataTag.getAsString(USERDATA_PROVIDER_NAME_KEY); JRDictionary responseDict; try { responseDict = JRDictionary.fromJsonString(payload); } catch (JSONException e) { // No JSON response setCurrentlyPublishingProvider(null); triggerPublishingJRActivityDidFail( new JREngageError(payload, SocialPublishingError.FAILED, ErrorType.PUBLISH_FAILED), (JRActivityObject) userDataTag.get(USERDATA_ACTIVITY_KEY), providerName); return; } if (!"ok".equals(responseDict.get("stat"))) { // Bad or missing stat value setCurrentlyPublishingProvider(null); JRDictionary errorDict = responseDict.getAsDictionary("err"); JREngageError publishError; if (errorDict != null) { // report the error as found in the err dict publishError = processShareActivityFailureResponse(errorDict); } else { // bad api response publishError = new JREngageError( getApplicationContext().getString(R.string.jr_problem_sharing), SocialPublishingError.FAILED, ErrorType.PUBLISH_FAILED); } triggerPublishingJRActivityDidFail(publishError, (JRActivityObject) userDataTag.get(USERDATA_ACTIVITY_KEY), providerName); return; } // No error setReturningSharingProvider(getCurrentlyPublishingProvider().getName()); setCurrentlyPublishingProvider(null); triggerPublishingJRActivityDidSucceed(mActivity, providerName); } private JREngageError processShareActivityFailureResponse(JRDictionary errorDict) { JREngageError publishError; int code = (errorDict.containsKey("code")) ? errorDict.getAsInt("code") : 1000; String errorMessage = errorDict.getAsString("msg", ""); switch (code) { case 0: /* "Missing parameter: apiKey" */ publishError = new JREngageError( errorMessage, SocialPublishingError.MISSING_API_KEY, ErrorType.PUBLISH_NEEDS_REAUTHENTICATION); break; case 4: /* "Facebook Error: Invalid OAuth 2.0 Access Token" */ if (errorMessage.matches(".*nvalid ..uth.*") || errorMessage.matches(".*session.*invalidated.*") || errorMessage.matches(".*rror validating access token.*")) { publishError = new JREngageError( errorMessage, SocialPublishingError.INVALID_OAUTH_TOKEN, ErrorType.PUBLISH_NEEDS_REAUTHENTICATION); } else if (errorMessage.matches(".*eed action request limit.*")) { publishError = new JREngageError( errorMessage, SocialPublishingError.FEED_ACTION_REQUEST_LIMIT, ErrorType.PUBLISH_FAILED); } else { publishError = new JREngageError( errorMessage, SocialPublishingError.FAILED, ErrorType.PUBLISH_FAILED); } break; case 100: // TODO LinkedIn character limit error publishError = new JREngageError( errorMessage, SocialPublishingError.LINKEDIN_CHARACTER_EXCEEDED, ErrorType.PUBLISH_INVALID_ACTIVITY); break; case 6: if (errorMessage.matches(".witter.*uplicate.*")) { publishError = new JREngageError( errorMessage, SocialPublishingError.DUPLICATE_TWITTER, ErrorType.PUBLISH_INVALID_ACTIVITY); } else { publishError = new JREngageError( errorMessage, SocialPublishingError.FAILED, ErrorType.PUBLISH_INVALID_ACTIVITY); } break; case 1000: /* Extracting code failed; Fall through. */ default: // TODO Other errors (find them) publishError = new JREngageError( getApplicationContext().getString(R.string.jr_problem_sharing), SocialPublishingError.FAILED, ErrorType.PUBLISH_FAILED); break; } return publishError; } public void connectionDidFinishLoading(HttpResponseHeaders headers, byte[] payload, String requestUrl, Object tag) { String payloadString = new String(payload); LogUtils.logd(TAG, "[connectionDidFinishLoading] payload: " + payloadString); if (tag instanceof JRDictionary) { JRDictionary dictionary = (JRDictionary) tag; if (dictionary.getAsString(USERDATA_ACTION_KEY).equals(USERDATA_ACTION_SHARE_ACTIVITY)) { processShareActivityResponse(payloadString, dictionary); } else if (dictionary.containsKey(USERDATA_TOKEN_URL_KEY)) { for (JRSessionDelegate delegate : getDelegatesCopy()) { delegate.authenticationDidReachTokenUrl( dictionary.getAsString(USERDATA_TOKEN_URL_KEY), headers, payloadString, dictionary.getAsString(USERDATA_PROVIDER_NAME_KEY)); } } else { Log.e(TAG, "unexpected userdata found in ConnectionDidFinishLoading full"); } } else if (tag instanceof String) { if (tag.equals(TAG_GET_CONFIGURATION)) { if (headers.getResponseCode() == HttpStatus.SC_NOT_MODIFIED) { /* If the ETag matched, we're done. */ LogUtils.logd(TAG, "[connectionDidFinishLoading] HTTP_NOT_MODIFIED -> matched ETag"); triggerConfigDidFinish(); return; } finishGetConfiguration(payloadString, headers.getETag()); } else { Log.e(TAG, "unexpected userData found in ConnectionDidFinishLoading full"); } } } public void addDelegate(JRSessionDelegate delegate) { LogUtils.logd(TAG, "[addDelegate]"); mDelegates.add(delegate); } public void removeDelegate(JRSessionDelegate delegate) { LogUtils.logd(TAG, "[removeDelegate]"); mDelegates.remove(delegate); } public void tryToReconfigureLibrary() { LogUtils.logd(TAG, "[tryToReconfigureLibrary]"); mConfigDone = false; mError = null; mError = startGetConfiguration(); } private JREngageError startGetConfiguration() { String urlString = String.format(UNFORMATTED_CONFIG_URL, mEngageBaseUrl, mAppId, mUrlEncodedAppName, mUrlEncodedLibraryVersion); LogUtils.logd(TAG, "[startGetConfiguration] url: " + urlString); BasicNameValuePair eTagHeader = new BasicNameValuePair("If-None-Match", mOldEtag); List<NameValuePair> headerList = new ArrayList<NameValuePair>(); headerList.add(eTagHeader); JRConnectionManager.createConnection(urlString, this, TAG_GET_CONFIGURATION, headerList, null, false); return null; } private void finishGetConfiguration(String dataStr) { LogUtils.logd(TAG, "[finishGetConfiguration]"); JRDictionary jsonDict; try { jsonDict = JRDictionary.fromJsonString(dataStr); } catch (JSONException e) { LogUtils.loge("[finishGetConfiguration] failed."); mError = new JREngageError( getApplicationContext().getString(R.string.jr_getconfig_parse_error_message), ConfigurationError.JSON_ERROR, ErrorType.CONFIGURATION_FAILED, e); return; } mRpBaseUrl = StringUtils.chomp(jsonDict.getAsString("baseurl", ""), "/"); PrefUtils.putString(PrefUtils.KEY_JR_RP_BASE_URL, mRpBaseUrl); mAllProviders = new HashMap<String, JRProvider>(); JRDictionary providerInfo = jsonDict.getAsDictionary("provider_info"); for (String name : providerInfo.keySet()) { mAllProviders.put(name, new JRProvider(name, providerInfo.getAsDictionary(name))); } Archiver.asyncSave(ARCHIVE_ALL_PROVIDERS, mAllProviders); mAuthProviders = jsonDict.getAsListOfStrings("enabled_providers"); mSharingProviders = jsonDict.getAsListOfStrings("social_providers"); Archiver.asyncSave(ARCHIVE_AUTH_PROVIDERS, mAuthProviders); Archiver.asyncSave(ARCHIVE_SHARING_PROVIDERS, mSharingProviders); mHidePoweredBy = jsonDict.getAsBoolean("hide_tagline", false); PrefUtils.putBoolean(PrefUtils.KEY_JR_HIDE_POWERED_BY, mHidePoweredBy); /* Ensures that the returning auth and sharing providers, * if set, are members of the configured set of providers. */ setReturningAuthProvider(mReturningAuthProvider); setReturningSharingProvider(mReturningSharingProvider); PrefUtils.putString(PrefUtils.KEY_JR_CONFIGURATION_ETAG, mNewEtag); PrefUtils.putString(PrefUtils.KEY_JR_ENGAGE_LIBRARY_VERSION, mUrlEncodedLibraryVersion); mError = null; triggerConfigDidFinish(); } private void finishGetConfiguration(String dataStr, String eTag) { LogUtils.logd(TAG, "[finishGetConfiguration-etag]"); /* Only update all the config if the UI isn't currently displayed / using that * information. Otherwise, the library may crash/behave inconsistently. In the case * where a dialog is showing but there isn't any config data that it could be using (that * is, the lists of auth and sharing providers are empty), update the config. */ if (!isUiShowing() || (CollectionUtils.isEmpty(mAuthProviders) && CollectionUtils.isEmpty(mSharingProviders))) { mNewEtag = eTag; finishGetConfiguration(dataStr); return; } /* Otherwise, we have to save all this information for later. When no UI is displayed * mSavedConfigurationBlock is checked and the config is updated then. */ mSavedConfigurationBlock = dataStr; mSavedEtag = eTag; mError = null; } private boolean isUiShowing() { return mUiShowingCount != 0; } private String getWelcomeMessageFromCookieString() { LogUtils.logd(TAG, "[getWelcomeMessageFromCookieString]"); String cookies = CookieManager.getInstance().getCookie(getRpBaseUrl()); String cookieString = cookies.replaceAll(".*welcome_info=([^;]*).*", "$1"); if (!TextUtils.isEmpty(cookieString)) { String[] parts = cookieString.split("%22"); if (parts.length > 5) return "Sign in as " + AndroidUtils.urlDecode(parts[5]); } return null; } public void saveLastUsedAuthProvider() { LogUtils.logd(TAG, "[saveLastUsedAuthProvider]"); setReturningAuthProvider(mCurrentlyAuthenticatingProvider.getName()); } public URL startUrlForCurrentlyAuthenticatingProvider() { LogUtils.logd(TAG, "[startUrlForCurrentlyAuthenticatingProvider]"); // What's this for? if (mCurrentlyAuthenticatingProvider == null) return null; String oid; /* open identifier */ if (!TextUtils.isEmpty(mCurrentlyAuthenticatingProvider.getOpenIdentifier())) { oid = String.format("openid_identifier=%s&", mCurrentlyAuthenticatingProvider.getOpenIdentifier()); if (mCurrentlyAuthenticatingProvider.requiresInput()) { oid = oid.replaceAll("%@", mCurrentlyAuthenticatingProvider.getUserInput()); } else { oid = oid.replaceAll("%@", ""); } } else { oid = ""; } String fullStartUrl; boolean forceReauth = mAlwaysForceReauth || mCurrentlyAuthenticatingProvider.getForceReauth(); if (forceReauth) { deleteWebViewCookiesForDomains(getApplicationContext(), mCurrentlyAuthenticatingProvider.getCookieDomains()); } fullStartUrl = String.format("%s%s?%s%sdevice=android&extended=true&installation_id=%s", mRpBaseUrl, mCurrentlyAuthenticatingProvider.getStartAuthenticationUrl(), oid, (forceReauth ? "force_reauth=true&" : ""), AndroidUtils.urlEncode(mUniqueIdentifier) ); LogUtils.logd("startUrl: " + fullStartUrl); URL url = null; try { url = new URL(fullStartUrl); } catch (MalformedURLException e) { throwDebugException(new RuntimeException("URL create failed for string: " + fullStartUrl, e)); } return url; } private String getUniqueIdentifier() { String idString = PrefUtils.getString(PrefUtils.KEY_JR_UNIVERSALLY_UNIQUE_ID, null); if (idString == null) { UUID id = UUID.randomUUID(); idString = id.toString(); PrefUtils.putString(PrefUtils.KEY_JR_UNIVERSALLY_UNIQUE_ID, idString); } return idString; } public JRAuthenticatedUser getAuthenticatedUserForProvider(JRProvider provider) { LogUtils.logd(); return mAuthenticatedUsersByProvider.get(provider.getName()); } public void signOutUserForProvider(String providerName) { LogUtils.logd(); if (mAllProviders == null) throwDebugException(new IllegalStateException()); JRProvider provider = mAllProviders.get(providerName); if (provider == null) { throwDebugException(new IllegalStateException("Unknown provider name:" + providerName)); } else { deleteWebViewCookiesForDomains(getApplicationContext(), provider.getCookieDomains()); } if (mAuthenticatedUsersByProvider == null) throwDebugException(new IllegalStateException()); if (mAuthenticatedUsersByProvider.containsKey(providerName)) { mAuthenticatedUsersByProvider.get(providerName).deleteCachedProfilePic(); mAuthenticatedUsersByProvider.remove(providerName); Archiver.asyncSave(ARCHIVE_AUTH_USERS_BY_PROVIDER, mAuthenticatedUsersByProvider); triggerUserWasSignedOut(providerName); } } public void signOutAllAuthenticatedUsers() { LogUtils.logd(TAG, "[signOutAllAuthenticatedUsers]"); for (String p : mAllProviders.keySet()) signOutUserForProvider(p); } public JRProvider getProviderByName(String name) { return mAllProviders.get(name); } public void notifyEmailSmsShare(String method) { StringBuilder body = new StringBuilder(); body.append("method=").append(method); body.append("&device=").append("android"); body.append("&appId=").append(mAppId); String url = mEngageBaseUrl + "/social/record_activity"; LogUtils.logd(TAG, "[notifyEmailSmsShare]: " + url + " data: " + body.toString()); JRConnectionManagerDelegate jrcmd = new SimpleJRConnectionManagerDelegate() { @Override public void connectionDidFinishLoading(HttpResponseHeaders headers, byte[] payload, String requestUrl, Object tag) { LogUtils.logd(TAG, "[notifyEmailSmsShare]: success"); } @Override public void connectionDidFail(Exception ex, HttpResponseHeaders responseHeaders, byte[] payload, String requestUrl, Object tag) { Log.e(TAG, "[notifyEmailSmsShare]: failure", ex); } }; JRConnectionManager.createConnection(url, jrcmd, null, null, body.toString().getBytes(), false); } public void shareActivityForUser(JRAuthenticatedUser user) { LogUtils.logd(TAG, "[shareActivityForUser]"); setCurrentlyPublishingProvider(user.getProviderName()); /* Truncate the resource description if necessary */ int descMaxChars = getCurrentlyPublishingProvider().getSocialSharingProperties() .getAsInt(JRDictionary.KEY_DESC_MAX_CHARS, -1); if (descMaxChars > 0 && mActivity.getDescription().length() > descMaxChars) { mActivity.setDescription(mActivity.getDescription().substring(0, 255)); } String deviceToken = user.getDeviceToken(); String activityJson = mActivity.toJRDictionary().toJson(); String urlEncodedActivityJson = AndroidUtils.urlEncode(activityJson); StringBuilder body = new StringBuilder(); body.append("activity=").append(urlEncodedActivityJson); /* These are undocumented parameters for the mobile library's use */ body.append("&device_token=").append(deviceToken); body.append("&url_shortening=true"); body.append("&provider=").append(user.getProviderName()); body.append("&device=android"); body.append("&app_name=").append(mUrlEncodedAppName); String url = mEngageBaseUrl + "/api/v2/activity"; LogUtils.logd(TAG, "[shareActivityForUser]: " + url + " data: " + body); JRDictionary tag = new JRDictionary(); tag.put(USERDATA_ACTION_KEY, USERDATA_ACTION_SHARE_ACTIVITY); tag.put(USERDATA_ACTIVITY_KEY, mActivity); tag.put(USERDATA_PROVIDER_NAME_KEY, mCurrentlyPublishingProvider.getName()); JRConnectionManager.createConnection(url, this, tag, null, body.toString().getBytes(), false); LogUtils.logd(TAG, "[shareActivityForUser] connection started for url: " + url); } public void setStatusForUser(JRAuthenticatedUser user) { LogUtils.logd(TAG, "[shareActivityForUser]"); setCurrentlyPublishingProvider(user.getProviderName()); String deviceToken = user.getDeviceToken(); String status = mActivity.getUserGeneratedContent(); // TODO: this should also include other pieces of the activity StringBuilder body = new StringBuilder(); // TODO: include truncate parameter here? body.append("status=").append(status); /* These are [undocumented] parameters available for use by the mobile library when * making calls to the Engage API. */ body.append("&device_token=").append(deviceToken); body.append("&device=android"); body.append("&app_name=").append(mUrlEncodedAppName); String url = mEngageBaseUrl + "/api/v2/set_status"; LogUtils.logd(TAG, "[setStatusForUser]: " + url + " data: " + body.toString()); // TODO: same callback handler for status as activity? JRDictionary tag = new JRDictionary(); tag.put(USERDATA_ACTION_KEY, USERDATA_ACTION_SHARE_ACTIVITY); tag.put(USERDATA_ACTIVITY_KEY, mActivity); tag.put(USERDATA_PROVIDER_NAME_KEY, mCurrentlyPublishingProvider.getName()); JRConnectionManager.createConnection(url, this, tag, null, body.toString().getBytes(), false); LogUtils.logd(TAG, "[setStatusForUser] connection started for url: " + url); } private void makeCallToTokenUrl(String tokenUrl, String token, String providerName) { LogUtils.logd(TAG, "[makeCallToTokenUrl] token: " + token); LogUtils.logd(TAG, "[makeCallToTokenUrl] tokenUrl: " + tokenUrl); String body = "token=" + token; byte[] postData = body.getBytes(); JRDictionary tag = new JRDictionary(); tag.put(USERDATA_ACTION_KEY, USERDATA_ACTION_CALL_TOKEN_URL); tag.put(USERDATA_TOKEN_URL_KEY, tokenUrl); tag.put(USERDATA_PROVIDER_NAME_KEY, providerName); JRConnectionManager.createConnection(tokenUrl, this, tag, null, postData, false); } public void triggerAuthenticationDidCompleteWithPayload(JRDictionary rpx_result) { LogUtils.logd(TAG, "[triggerAuthenticationDidCompleteWithPayload]"); JRAuthenticatedUser user = new JRAuthenticatedUser( rpx_result, mCurrentlyAuthenticatingProvider.getName(), getWelcomeMessageFromCookieString()); mAuthenticatedUsersByProvider.put(mCurrentlyAuthenticatingProvider.getName(), user); Archiver.asyncSave(ARCHIVE_AUTH_USERS_BY_PROVIDER, mAuthenticatedUsersByProvider); String authInfoToken = rpx_result.getAsString("token"); JRDictionary authInfoDict = rpx_result.getAsDictionary("auth_info"); authInfoDict.put("token", authInfoToken); authInfoDict.put("device_token", user.getDeviceToken()); for (JRSessionDelegate delegate : getDelegatesCopy()) { delegate.authenticationDidComplete( authInfoDict, mCurrentlyAuthenticatingProvider.getName()); } if (!TextUtils.isEmpty(mTokenUrl)) { makeCallToTokenUrl(mTokenUrl, authInfoToken, mCurrentlyAuthenticatingProvider.getName()); } mCurrentlyAuthenticatingProvider.setForceReauth(false); setCurrentlyAuthenticatingProvider(null); } public void triggerAuthenticationDidFail(JREngageError error) { LogUtils.logd(TAG, "[triggerAuthenticationDidFailWithError]"); if (mCurrentlyAuthenticatingProvider == null) { throwDebugException(new RuntimeException("Unexpected state")); } String providerName = mCurrentlyAuthenticatingProvider.getName(); //mCurrentlyAuthenticatingProvider.setForceReauth(true); signOutUserForProvider(providerName); setCurrentlyAuthenticatingProvider(null); mReturningAuthProvider = null; mReturningSharingProvider = null; for (JRSessionDelegate delegate : getDelegatesCopy()) { delegate.authenticationDidFail(error, providerName); } } public void triggerAuthenticationDidCancel() { LogUtils.logd(TAG, "[triggerAuthenticationDidCancel]"); setCurrentlyAuthenticatingProvider(null); setReturningAuthProvider(null); for (JRSessionDelegate delegate : getDelegatesCopy()) delegate.authenticationDidCancel(); } public void triggerAuthenticationDidRestart() { LogUtils.logd(TAG, "[triggerAuthenticationDidRestart]"); for (JRSessionDelegate delegate : getDelegatesCopy()) delegate.authenticationDidRestart(); } public void triggerUserWasSignedOut(String provider) { LogUtils.logd(TAG, "[triggerUserWasSignedOut]"); for (JRSessionDelegate d : getDelegatesCopy()) d.userWasSignedOut(provider); } public void triggerPublishingDidComplete() { LogUtils.logd(TAG, "[triggerPublishingDidComplete]"); for (JRSessionDelegate delegate : getDelegatesCopy()) delegate.publishingDidComplete(); } public void triggerPublishingJRActivityDidFail(JREngageError error, JRActivityObject activity, String providerName) { LogUtils.logd(TAG, "[triggerPublishingJRActivityDidFail]"); for (JRSessionDelegate delegate : getDelegatesCopy()) { delegate.publishingJRActivityDidFail(activity, error, providerName); } } private void triggerPublishingJRActivityDidSucceed(JRActivityObject mActivity, String providerName) { for (JRSessionDelegate delegate : getDelegatesCopy()) { delegate.publishingJRActivityDidSucceed(mActivity, providerName); } } /** * Informs delegates that the publishing dialog failed to display. * @param err * The error to send to delegates */ public void triggerPublishingDialogDidFail(JREngageError err) { LogUtils.logd(TAG, "[triggerPublishingDialogDidFail]"); for (JRSessionDelegate delegate : getDelegatesCopy()) delegate.publishingDialogDidFail(err); } public void triggerPublishingDidCancel() { LogUtils.logd(TAG, "[triggerPublishingDidCancel]"); for (JRSessionDelegate delegate : getDelegatesCopy()) delegate.publishingDidCancel(); } private void triggerConfigDidFinish() { mConfigDone = true; for (JRSessionDelegate d : getDelegatesCopy()) d.configDidFinish(); } private synchronized List<JRSessionDelegate> getDelegatesCopy() { return (mDelegates == null) ? new ArrayList<JRSessionDelegate>() : new ArrayList<JRSessionDelegate>(mDelegates); } public JRProvider getCurrentlyPublishingProvider() { return mCurrentlyPublishingProvider; } public void setCurrentlyPublishingProvider(String provider) { LogUtils.logd(TAG, "[setCurrentlyPublishingProvider]: " + provider); mCurrentlyPublishingProvider = getProviderByName(provider); } public boolean isConfigDone() { return mConfigDone; } public String getUrlEncodedAppName() { return mUrlEncodedAppName; } public void setEnabledAuthenticationProviders(List<String> enabledProviders) { mEnabledAuthenticationProviders = enabledProviders; // redundantly call the setter to ensure the provider is still available setReturningAuthProvider(mReturningAuthProvider); } public List<String> getEnabledAuthenticationProviders() { if (mEnabledAuthenticationProviders == null) { return mAuthProviders; } else { return mEnabledAuthenticationProviders; } } public void setEnabledSharingProviders(List<String> enabledSharingProviders) { mEnabledSharingProviders = enabledSharingProviders; // redundantly call the setter to ensure the provider is still available setReturningSharingProvider(mReturningSharingProvider); } //public List<String> getEnabledSharingProviders() { // if (mEnabledSharingProviders == null) { // return mSharingProviders; // } else { // return mEnabledSharingProviders; private Context getApplicationContext() { return JREngage.getApplicationContext(); } /* package */ String getEngageBaseUrl() { return mEngageBaseUrl; } public String getTokenUrl() { return mTokenUrl; } }
package com.currencycloud.client.model; import com.fasterxml.jackson.databind.PropertyNamingStrategy; import com.fasterxml.jackson.databind.annotation.JsonNaming; import java.util.Date; // todo: this is entirely untested @JsonNaming(PropertyNamingStrategy.LowerCaseWithUnderscoresStrategy.class) public class Contact { private String loginId; // john.smith private String id; // 543477161-91de-012f-e284-1e0030c7f352 private String yourReference; // ACME12345 private String firstName; // John private String lastName; // Smith private String accountId; // 87077161-91de-012f-e284-1e0030c7f352 private String accountName; // Company PLC private String status; // enabled private String phoneNumber; // 06554 87845 private String mobilePhoneNumber; // 07564 534 54 private String locale; // en-US private String timezone; // Europe/London private String emailAddress; // john.smith@company.com private Date dateOfBirth; // 1980-01-22 private Date createdAt; // 2014-01-12T00:00:00+00:00 private Date updatedAt; // 2014-01-12T00:00:00+00:00 public String getLoginId() { return loginId; } public String getId() { return id; } public String getYourReference() { return yourReference; } public String getFirstName() { return firstName; } public String getLastName() { return lastName; } public String getAccountId() { return accountId; } public String getAccountName() { return accountName; } public String getStatus() { return status; } public String getPhoneNumber() { return phoneNumber; } public String getMobilePhoneNumber() { return mobilePhoneNumber; } public String getLocale() { return locale; } public String getTimezone() { return timezone; } public String getEmailAddress() { return emailAddress; } public Date getDateOfBirth() { return dateOfBirth; } public Date getCreatedAt() { return createdAt; } public Date getUpdatedAt() { return updatedAt; } @Override public String toString() { return String.format("Contact{loginId='%s', id='%s', yourReference='%s', firstName='%s', lastName='%s', accountId='%s', accountName='%s', status='%s', phoneNumber='%s', mobilePhoneNumber='%s', locale='%s', timezone='%s', emailAddress='%s', dateOfBirth=%s, createdAt=%s, updatedAt=%s}", loginId, id, yourReference, firstName, lastName, accountId, accountName, status, phoneNumber, mobilePhoneNumber, locale, timezone, emailAddress, dateOfBirth, createdAt, updatedAt); } }
// This file is part of the Kaltura Collaborative Media Suite which allows users // to do with audio, video, and animation what Wiki platforms allow them to do with // text. // This program is free software: you can redistribute it and/or modify // published by the Free Software Foundation, either version 3 of the // This program is distributed in the hope that it will be useful, // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // @ignore package com.kaltura.client; import com.kaltura.client.utils.request.ConnectionConfiguration; import com.kaltura.client.types.BaseResponseProfile; /** * This class was generated using generate.php * against an XML schema provided by Kaltura. * * MANUAL CHANGES TO THIS CLASS WILL BE OVERWRITTEN. */ @SuppressWarnings("serial") public class Client extends ClientBase { public Client(ConnectionConfiguration config) { super(config); this.setClientTag("java:21-11-05"); this.setApiVersion("17.12.0"); this.clientConfiguration.put("format", 1); // JSON } /** * @param clientTag */ public void setClientTag(String clientTag){ this.clientConfiguration.put("clientTag", clientTag); } /** * @return String */ public String getClientTag(){ if(this.clientConfiguration.containsKey("clientTag")){ return(String) this.clientConfiguration.get("clientTag"); } return null; } /** * @param apiVersion */ public void setApiVersion(String apiVersion){ this.clientConfiguration.put("apiVersion", apiVersion); } /** * @return String */ public String getApiVersion(){ if(this.clientConfiguration.containsKey("apiVersion")){ return(String) this.clientConfiguration.get("apiVersion"); } return null; } /** * @param partnerId Impersonated partner id */ public void setPartnerId(Integer partnerId){ this.requestConfiguration.put("partnerId", partnerId); } /** * Impersonated partner id * * @return Integer */ public Integer getPartnerId(){ if(this.requestConfiguration.containsKey("partnerId")){ return(Integer) this.requestConfiguration.get("partnerId"); } return 0; } /** * @param ks Kaltura API session */ public void setKs(String ks){ this.requestConfiguration.put("ks", ks); } /** * Kaltura API session * * @return String */ public String getKs(){ if(this.requestConfiguration.containsKey("ks")){ return(String) this.requestConfiguration.get("ks"); } return null; } /** * @param sessionId Kaltura API session */ public void setSessionId(String sessionId){ this.requestConfiguration.put("ks", sessionId); } /** * Kaltura API session * * @return String */ public String getSessionId(){ if(this.requestConfiguration.containsKey("ks")){ return(String) this.requestConfiguration.get("ks"); } return null; } /** * @param responseProfile Response profile - this attribute will be automatically unset after every API call. */ public void setResponseProfile(BaseResponseProfile responseProfile){ this.requestConfiguration.put("responseProfile", responseProfile); } /** * Response profile - this attribute will be automatically unset after every API call. * * @return BaseResponseProfile */ public BaseResponseProfile getResponseProfile(){ if(this.requestConfiguration.containsKey("responseProfile")){ return(BaseResponseProfile) this.requestConfiguration.get("responseProfile"); } return null; } }
package com.squareup.spoon; import com.github.mustachejava.DefaultMustacheFactory; import com.github.mustachejava.Mustache; import com.madgag.gif.fmsware.AnimatedGifEncoder; import org.apache.commons.io.FileUtils; import org.apache.commons.io.IOUtils; import javax.imageio.ImageIO; import java.io.File; import java.io.FileOutputStream; import java.io.FileWriter; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.TimeUnit; import static java.util.Collections.synchronizedList; import static java.util.Collections.synchronizedMap; import static java.util.Collections.unmodifiableList; import static java.util.Collections.unmodifiableMap; public class ExecutionSummary { static final ThreadLocal<DateFormat> DISPLAY_TIME = new ThreadLocal<DateFormat>() { @Override protected DateFormat initialValue() { return new SimpleDateFormat("yyyy-MM-dd hh:mm a"); } }; /** Assets which need to be copied to the output directory when generating HTML. */ private static final String[] ASSETS = { "bootstrap.min.css", "bootstrap.min.js", "jquery.min.js", "lightbox.js", "spoon.css", "lightbox.css", "loading.gif", "next.png", "prev.png", "close.png", "jquery-ui-1.8.18.custom.min.js", "jquery.smooth-scroll.min.js", "icon-animated.png", "icon-devices.png" }; private final File output; private final String title; private final List<ExecutionResult> results; private final Map<String, InstrumentationTestClass> instrumentationTestClasses; private final Exception exception; private final long totalTime; private final Calendar started; private final Calendar ended; private final int totalTests; private final int totalSuccess; private final int totalFailure; private final String displayTime; public ExecutionSummary(File output, String title, List<ExecutionResult> results, Map<String, InstrumentationTestClass> testClasses, Exception exception, long totalTime, Calendar started, Calendar ended, int totalTests, int totalSuccess, int totalFailure, String displayTime) { this.output = output; this.title = title; this.results = unmodifiableList(results); this.instrumentationTestClasses = unmodifiableMap(testClasses); this.exception = exception; this.totalTime = totalTime; this.started = started; this.ended = ended; this.totalTests = totalTests; this.totalSuccess = totalSuccess; this.totalFailure = totalFailure; this.displayTime = displayTime; } public String getTitle() { return title; } public List<ExecutionResult> getResults() { return results; } public Collection<InstrumentationTestClass> getInstrumentationTestClasses() { return instrumentationTestClasses.values(); } public Exception getException() { return exception; } /** Total execution time (in seconds). */ public long getTotalTime() { return totalTime; } public Calendar getStarted() { return started; } public Calendar getEnded() { return ended; } public int getTotalTests() { return totalTests; } public int getTotalSuccess() { return totalSuccess; } public int getTotalFailure() { return totalFailure; } public String getDisplayTime() { return displayTime; } public void writeHtml() { for (String asset : ASSETS) { copyResourceToOutput(asset, output); } DefaultMustacheFactory mustacheFactory = new DefaultMustacheFactory(); Mustache summary = mustacheFactory.compile("index.html"); Mustache device = mustacheFactory.compile("index-device.html"); Mustache test = mustacheFactory.compile("index-test.html"); try { summary.execute(new FileWriter(new File(output, "index.html")), this).flush(); for (ExecutionResult result : results) { result.updateDynamicValues(); File deviceOutput = new File(output, result.serial + "/index.html"); device.execute(new FileWriter(deviceOutput), result).flush(); } for (InstrumentationTestClass instrumentationTestClass : getInstrumentationTestClasses()) { File testDir = new File(output, instrumentationTestClass.classSimpleName); testDir.mkdirs(); for (InstrumentationTest instrumentationTest : instrumentationTestClass.tests()) { File testOutput = new File(testDir.getPath(), instrumentationTest.testName + ".html"); test.execute(new FileWriter(testOutput), instrumentationTest).flush(); for (ExecutionTestResult result : instrumentationTest.results()) { makeGif(result); } } } } catch (IOException e) { throw new RuntimeException("Unable to write output HTML.", e); } } private static void copyResourceToOutput(String resource, File outputDirectory) { InputStream is = null; OutputStream os = null; try { is = ExecutionSummary.class.getResourceAsStream("/" + resource); os = new FileOutputStream(new File(outputDirectory, resource)); IOUtils.copy(is, os); } catch (IOException e) { throw new RuntimeException("Unable to copy resource " + resource, e); } finally { IOUtils.closeQuietly(is); IOUtils.closeQuietly(os); } } private void makeGif(ExecutionTestResult result) { AnimatedGifEncoder encoder = new AnimatedGifEncoder(); String name = result.classSimpleName + "-" + result.testName + ".gif"; encoder.start(FileUtils.getFile(output, result.serial, name).getAbsolutePath()); encoder.setDelay(1000); // 1 frame per second. encoder.setRepeat(0); // 0 repeats infinitely. encoder.setQuality(1); // Highest quality, scale is from 1 to 256 (lower is better). try { for (ExecutionTestResult.Screenshot screenshot : result.screenshots) { encoder.addFrame(ImageIO.read(screenshot.file)); } } catch (IOException ex) { throw new RuntimeException("Unable to write animated GIF of test.", ex); } encoder.finish(); } public static class Builder { private String title; private File outputDirectory; private long startNano; private Calendar started; private Calendar ended; private Exception exception; private List<ExecutionResult> results = synchronizedList(new ArrayList<ExecutionResult>()); private Map<String, InstrumentationTestClass> testClasses = synchronizedMap(new HashMap<String, InstrumentationTestClass>()); public Builder() { } public Builder setTitle(String title) { this.title = title; return this; } public Builder setOutputDirectory(File outputDirectory) { this.outputDirectory = outputDirectory; return this; } public Builder start() { if (started != null) { throw new IllegalStateException("start() may only be called once."); } startNano = System.nanoTime(); started = Calendar.getInstance(); return this; } public Builder addResult(ExecutionResult result) { results.add(result); for (InstrumentationTestClass testClass : result.testClasses()) { if (testClasses.containsKey(testClass.className)) { // We need to add all our tests to this class. for (InstrumentationTest test : testClass.tests()) { InstrumentationTestClass existingTestClass = testClasses.get(testClass.className); if (existingTestClass.containsTest(test.identifier)) { // Merge both tests' results. existingTestClass.getTest(test.identifier).mergeResults(test); } else { existingTestClass.addTest(test); } } } else { testClasses.put(testClass.className, testClass); } } return this; } public Builder setException(Exception exception) { if (this.exception != null) { throw new IllegalStateException("Only one top-level exception can be set."); } this.exception = exception; return this; } public ExecutionSummary end() { if (started == null) { throw new IllegalStateException("You must call start() first."); } if (ended != null) { throw new IllegalStateException("end() may only be called once."); } ended = Calendar.getInstance(); int totalTests = 0; int totalSuccess = 0; int totalFailure = 0; for (ExecutionResult result : results) { totalTests += result.testsStarted; totalSuccess += result.testsPassed(); totalFailure += result.testsFailed; } long totalTime = TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startNano); String displayTime = DISPLAY_TIME.get().format(ended.getTime()); return new ExecutionSummary(outputDirectory, title, results, testClasses, exception, totalTime, started, ended, totalTests, totalSuccess, totalFailure, displayTime); } } }
package com.fiftyonred.mock_jedis; import com.fiftyonred.utils.WildcardMatcher; import redis.clients.jedis.*; import redis.clients.jedis.exceptions.JedisDataException; import java.util.*; import static com.fiftyonred.mock_jedis.DataContainer.CHARSET; public class MockPipeline extends Pipeline { private static final int NUM_DBS = 16; private static final byte[] STRING_TYPE = "string".getBytes(CHARSET); private static final byte[] LIST_TYPE = "list".getBytes(CHARSET); private static final byte[] SET_TYPE = "set".getBytes(CHARSET); private static final byte[] NONE_TYPE = "none".getBytes(CHARSET); private static final byte[] OK_RESPONSE = "OK".getBytes(CHARSET); private static final byte[] PONG_RESPONSE = "PONG".getBytes(CHARSET); private final WildcardMatcher wildcardMatcher = new WildcardMatcher(); private final List<Map<DataContainer, KeyInformation>> allKeys; private final List<Map<DataContainer, DataContainer>> allStorage; private final List<Map<DataContainer, Map<DataContainer, DataContainer>>> allHashStorage; private final List<Map<DataContainer, List<DataContainer>>> allListStorage; private final List<Map<DataContainer, Set<DataContainer>>> allSetStorage; private int currentDB; private Map<DataContainer, KeyInformation> keys; private Map<DataContainer, DataContainer> storage; private Map<DataContainer, Map<DataContainer, DataContainer>> hashStorage; private Map<DataContainer, List<DataContainer>> listStorage; private Map<DataContainer, Set<DataContainer>> setStorage; public MockPipeline() { allKeys = new ArrayList<Map<DataContainer, KeyInformation>>(NUM_DBS); allStorage = new ArrayList<Map<DataContainer, DataContainer>>(NUM_DBS); allHashStorage = new ArrayList<Map<DataContainer, Map<DataContainer, DataContainer>>>(NUM_DBS); allListStorage = new ArrayList<Map<DataContainer, List<DataContainer>>>(NUM_DBS); allSetStorage = new ArrayList<Map<DataContainer, Set<DataContainer>>>(NUM_DBS); for (int i = 0; i < NUM_DBS; ++i) { allKeys.add(new HashMap<DataContainer, KeyInformation>()); allStorage.add(new HashMap<DataContainer, DataContainer>()); allHashStorage.add(new HashMap<DataContainer, Map<DataContainer, DataContainer>>()); allListStorage.add(new HashMap<DataContainer, List<DataContainer>>()); allSetStorage.add(new HashMap<DataContainer, Set<DataContainer>>()); } select(0); } public int getCurrentDB() { return currentDB; } protected static <T> T getRandomElementFromSet(final Set<T> set) { return (T) set.toArray()[(int) (Math.random() * set.size())]; } @Override public Response<String> ping() { final Response<String> response = new Response<String>(BuilderFactory.STRING); response.set(PONG_RESPONSE); return response; } @Override public Response<String> echo(final String string) { final Response<String> response = new Response<String>(BuilderFactory.STRING); response.set(echo(string.getBytes(CHARSET)).get()); return response; } @Override public Response<byte[]> echo(final byte[] string) { final Response<byte[]> response = new Response<byte[]>(BuilderFactory.BYTE_ARRAY); response.set(string); return response; } @Override public synchronized Response<Long> dbSize() { final Response<Long> response = new Response<Long>(BuilderFactory.LONG); response.set((long) keys.size()); return response; } @Override public synchronized Response<String> flushAll() { final Response<String> response = new Response<String>(BuilderFactory.STRING); for (int dbNum = 0; dbNum < NUM_DBS; ++dbNum) { allKeys.get(dbNum).clear(); allStorage.get(dbNum).clear(); allHashStorage.get(dbNum).clear(); allListStorage.get(dbNum).clear(); } response.set(OK_RESPONSE); return response; } @Override public synchronized Response<String> flushDB() { final Response<String> response = new Response<String>(BuilderFactory.STRING); keys.clear(); storage.clear(); hashStorage.clear(); listStorage.clear(); response.set(OK_RESPONSE); return response; } @Override public synchronized Response<String> rename(final String oldkey, final String newkey) { return rename(DataContainer.from(oldkey), DataContainer.from(newkey)); } @Override public Response<String> rename(final byte[] oldkey, final byte[] newkey) { return rename(DataContainer.from(oldkey), DataContainer.from(newkey)); } private Response<String> rename(final DataContainer oldkey, final DataContainer newkey) { if (oldkey.equals(newkey)) { throw new JedisDataException("ERR source and destination objects are the same"); } final Response<String> response = new Response<String>(BuilderFactory.STRING); final KeyInformation info = keys.get(oldkey); switch (info.getType()) { case HASH: hashStorage.put(newkey, hashStorage.get(oldkey)); hashStorage.remove(oldkey); break; case LIST: listStorage.put(newkey, listStorage.get(oldkey)); listStorage.remove(oldkey); break; case STRING: default: storage.put(newkey, storage.get(oldkey)); storage.remove(oldkey); } keys.put(newkey, info); keys.remove(oldkey); response.set(OK_RESPONSE); return response; } @Override public synchronized Response<Long> renamenx(final String oldkey, final String newkey) { return renamenx(DataContainer.from(oldkey), DataContainer.from(newkey)); } @Override public Response<Long> renamenx(final byte[] oldkey, final byte[] newkey) { return renamenx(DataContainer.from(oldkey), DataContainer.from(newkey)); } private Response<Long> renamenx(final DataContainer oldkey, final DataContainer newkey) { if (oldkey.equals(newkey)) { throw new JedisDataException("ERR source and destination objects are the same"); } final Response<Long> response = new Response<Long>(BuilderFactory.LONG); final KeyInformation newInfo = keys.get(newkey); if (newInfo == null) { rename(oldkey, newkey); response.set(1L); } else { response.set(0L); } return response; } @Override public synchronized Response<String> set(final String key, final String value) { return set(DataContainer.from(key), DataContainer.from(value)); } @Override public synchronized Response<String> set(final byte[] key, final byte[] value) { return set(DataContainer.from(key), DataContainer.from(value)); } private Response<String> set(final DataContainer key, final DataContainer value) { final Response<String> response = new Response<String>(BuilderFactory.STRING); createOrUpdateKey(key, KeyType.STRING, true); storage.put(key, value); response.set(OK_RESPONSE); return response; } @Override public synchronized Response<Long> setnx(final String key, final String value) { return setnx(DataContainer.from(key), DataContainer.from(value)); } @Override public synchronized Response<Long> setnx(final byte[] key, final byte[] value) { return setnx(DataContainer.from(key), DataContainer.from(value)); } private Response<Long> setnx(final DataContainer key, final DataContainer value) { final Response<Long> response = new Response<Long>(BuilderFactory.LONG); final DataContainer result = getContainerFromStorage(key, false); if (result == null) { set(key, value); response.set(1L); } else { response.set(0L); } return response; } @Override public synchronized Response<String> get(final String key) { final Response<String> response = new Response<String>(BuilderFactory.STRING); final DataContainer val = getContainerFromStorage(DataContainer.from(key), false); response.set(DataContainer.toBytes(val)); return response; } @Override public synchronized Response<byte[]> get(final byte[] key) { final Response<byte[]> response = new Response<byte[]>(BuilderFactory.BYTE_ARRAY); final DataContainer val = getContainerFromStorage(DataContainer.from(key), false); response.set(DataContainer.toBytes(val)); return response; } @Override public synchronized Response<String> getSet(final String key, final String value) { final Response<String> response = get(key); set(key, value); return response; } @Override public synchronized Response<byte[]> getSet(final byte[] key, final byte[] value) { final Response<byte[]> response = get(key); set(key, value); return response; } @Override public Response<byte[]> dump(final byte[] key) { return get(key); } @Override public Response<byte[]> dump(final String key) { return get(key.getBytes(CHARSET)); } @Override public Response<String> restore(final String key, final int ttl, final byte[] serializedValue) { return setex(key.getBytes(CHARSET), ttl, serializedValue); } @Override public Response<String> restore(final byte[] key, final int ttl, final byte[] serializedValue) { return setex(key, ttl, serializedValue); } @Override public synchronized Response<Boolean> exists(final String key) { return exists(DataContainer.from(key)); } @Override public synchronized Response<Boolean> exists(final byte[] key) { return exists(DataContainer.from(key)); } private Response<Boolean> exists(final DataContainer key) { final Response<Boolean> response = new Response<Boolean>(BuilderFactory.BOOLEAN); response.set(keys.containsKey(key) ? 1L : 0L); return response; } @Override public synchronized Response<String> type(final String key) { return type(DataContainer.from(key)); } @Override public synchronized Response<String> type(final byte[] key) { return type(DataContainer.from(key)); } private Response<String> type(final DataContainer key) { final Response<String> response = new Response<String>(BuilderFactory.STRING); final KeyInformation info = keys.get(key); if (info != null && info.getType() == KeyType.STRING) { response.set(STRING_TYPE); } else if (info != null && info.getType() == KeyType.LIST) { response.set(LIST_TYPE); } else if (info != null && info.getType() == KeyType.SET) { response.set(SET_TYPE); } else { response.set(NONE_TYPE); } return response; } @Override public synchronized Response<Long> move(final String key, final int dbIndex) { return move(DataContainer.from(key), dbIndex); } @Override public synchronized Response<Long> move(final byte[] key, final int dbIndex) { return move(DataContainer.from(key), dbIndex); } private Response<Long> move(final DataContainer key, final int dbIndex) { if (dbIndex < 0 || dbIndex >= NUM_DBS) { throw new JedisDataException("ERR index out of range"); } final Response<Long> response = new Response<Long>(BuilderFactory.LONG); final KeyInformation info = keys.get(key); if (info == null) { response.set(0L); } else { final KeyInformation infoNew = allKeys.get(dbIndex).get(key); if (infoNew == null) { allKeys.get(dbIndex).put(key, info); switch (info.getType()) { case HASH: allHashStorage.get(dbIndex).put(key, hashStorage.get(key)); hashStorage.remove(key); break; case LIST: allListStorage.get(dbIndex).put(key, listStorage.get(key)); listStorage.remove(key); break; case STRING: default: allStorage.get(dbIndex).put(key, storage.get(key)); storage.remove(key); } keys.remove(key); response.set(1L); } else { response.set(0L); } } return response; } @Override public synchronized Response<String> randomKey() { final Response<String> response = new Response<String>(BuilderFactory.STRING); if (keys.isEmpty()) { response.set(null); } else { final DataContainer result = getRandomElementFromSet(keys.keySet()); response.set(result.getBytes()); } return response; } @Override public Response<byte[]> randomKeyBinary() { final Response<byte[]> response = new Response<byte[]>(BuilderFactory.BYTE_ARRAY); final String result = randomKey().get(); response.set(result == null ? null : result.getBytes(CHARSET)); return response; } @Override public Response<String> select(final int dbIndex) { if (dbIndex < 0 || dbIndex >= NUM_DBS) { throw new JedisDataException("ERR invalid DB index"); } final Response<String> response = new Response<String>(BuilderFactory.STRING); currentDB = dbIndex; keys = allKeys.get(dbIndex); storage = allStorage.get(dbIndex); hashStorage = allHashStorage.get(dbIndex); listStorage = allListStorage.get(dbIndex); setStorage = allSetStorage.get(dbIndex); response.set(OK_RESPONSE); return response; } @Override public Response<String> setex(final String key, final int seconds, final String value) { return psetex(key, seconds * 1000, value); } @Override public Response<String> setex(final byte[] key, final int seconds, final byte[] value) { return psetex(key, seconds * 1000, value); } @Override public synchronized Response<String> psetex(final String key, final int milliseconds, final String value) { final Response<String> response = set(key, value); pexpire(key, milliseconds); return response; } @Override public Response<String> psetex(final byte[] key, final int milliseconds, final byte[] value) { final Response<String> response = set(key, value); pexpire(key, milliseconds); return response; } @Override public Response<Long> expire(final String key, final int seconds) { return expireAt(key, System.currentTimeMillis() / 1000 + seconds); } @Override public Response<Long> expire(final byte[] key, final int seconds) { return expireAt(key, System.currentTimeMillis() / 1000 + seconds); } @Override public Response<Long> expireAt(final String key, final long unixTime) { return pexpireAt(key, unixTime * 1000L); } @Override public Response<Long> expireAt(final byte[] key, final long unixTime) { return pexpireAt(key, unixTime * 1000L); } @Override public Response<Long> pexpire(final String key, final int milliseconds) { return pexpireAt(key, System.currentTimeMillis() + milliseconds); } @Override public Response<Long> pexpire(final byte[] key, final int milliseconds) { return pexpireAt(key, System.currentTimeMillis() + milliseconds); } @Override public Response<Long> pexpire(final String key, final long milliseconds) { return pexpireAt(key, System.currentTimeMillis() + milliseconds); } @Override public Response<Long> pexpire(final byte[] key, final long milliseconds) { return pexpireAt(key, System.currentTimeMillis() + milliseconds); } @Override public synchronized Response<Long> pexpireAt(final String key, final long millisecondsTimestamp) { final Response<Long> response = new Response<Long>(BuilderFactory.LONG); response.set(pexpireAt(DataContainer.from(key), millisecondsTimestamp)); return response; } @Override public synchronized Response<Long> pexpireAt(final byte[] key, final long millisecondsTimestamp) { final Response<Long> response = new Response<Long>(BuilderFactory.LONG); response.set(pexpireAt(DataContainer.from(key), millisecondsTimestamp)); return response; } public synchronized Long pexpireAt(final DataContainer key, final long millisecondsTimestamp) { final KeyInformation info = keys.get(key); if (info == null || info.isTTLSetAndKeyExpired()) { return 0L; } else { info.setExpiration(millisecondsTimestamp); return 1L; } } @Override public Response<Long> ttl(final String key) { return ttl(DataContainer.from(key)); } @Override public Response<Long> ttl(final byte[] key) { return ttl(DataContainer.from(key)); } public Response<Long> ttl(final DataContainer key) { Long pttlInResponse = pttl(key).get(); final Response<Long> response = new Response<Long>(BuilderFactory.LONG); if (pttlInResponse != -1L) { if (pttlInResponse > 0L && pttlInResponse < 1000L) { pttlInResponse = 1000L; } response.set(pttlInResponse / 1000L); } else { response.set(pttlInResponse); } return response; } @Override public synchronized Response<Long> append(final String key, final String value) { return append(DataContainer.from(key), DataContainer.from(value)); } @Override public synchronized Response<Long> append(final byte[] key, final byte[] value) { return append(DataContainer.from(key), DataContainer.from(value)); } private Response<Long> append(final DataContainer key, final DataContainer value) { final Response<Long> response = new Response<Long>(BuilderFactory.LONG); DataContainer container = getContainerFromStorage(key, true); final DataContainer newVal = container.append(value); set(key, newVal); response.set((long) newVal.getString().length()); return response; } @Override public synchronized Response<Long> pttl(final String key) { return pttl(DataContainer.from(key)); } private Response<Long> pttl(final DataContainer key) { final Response<Long> response = new Response<Long>(BuilderFactory.LONG); final KeyInformation info = keys.get(key); response.set(info == null ? -1L : info.getTTL()); return response; } @Override public synchronized Response<Long> persist(final String key) { return persist(DataContainer.from(key)); } @Override public synchronized Response<Long> persist(final byte[] key) { return persist(DataContainer.from(key)); } private Response<Long> persist(final DataContainer key) { final Response<Long> response = new Response<Long>(BuilderFactory.LONG); final KeyInformation info = keys.get(key); if (info.getTTL() == -1) { response.set(0L); } else { info.setExpiration(-1L); response.set(1L); } return response; } @Override public synchronized Response<List<String>> mget(final String... keys) { if (keys.length <= 0) { throw new JedisDataException("ERR wrong number of arguments for 'mget' command"); } final Response<List<String>> response = new Response<List<String>>(BuilderFactory.STRING_LIST); final List<byte[]> result = new ArrayList<byte[]>(keys.length); for (final String key : keys) { final DataContainer val = getContainerFromStorage(DataContainer.from(key), false); result.add(val == null ? null : val.getBytes()); } response.set(result); return response; } @Override public synchronized Response<List<byte[]>> mget(final byte[]... keys) { if (keys.length <= 0) { throw new JedisDataException("ERR wrong number of arguments for 'mget' command"); } final Response<List<byte[]>> response = new Response<List<byte[]>>(BuilderFactory.BYTE_ARRAY_LIST); final List<byte[]> result = new ArrayList<byte[]>(keys.length); for (final byte[] key : keys) { final DataContainer val = getContainerFromStorage(DataContainer.from(key), false); result.add(val == null ? null : val.getBytes()); } response.set(result); return response; } @Override public synchronized Response<String> mset(final String... keysvalues) { final int l = keysvalues.length; if (l <= 0 || l % 2 != 0) { throw new JedisDataException("ERR wrong number of arguments for 'mset' command"); } for (int i = 0; i < l; i += 2) { set(keysvalues[i], keysvalues[i + 1]); } final Response<String> response = new Response<String>(BuilderFactory.STRING); response.set(OK_RESPONSE); return response; } @Override public Response<String> mset(final byte[]... keysvalues) { return mset(convertToStrings(keysvalues)); } @Override public synchronized Response<Long> msetnx(final String... keysvalues) { final int l = keysvalues.length; if (l <= 0 || l % 2 != 0) { throw new JedisDataException("ERR wrong number of arguments for 'msetnx' command"); } long result = 1L; for (int i = 0; i < l; i += 2) { if (setnx(keysvalues[i], keysvalues[i + 1]).get() == 0L) { result = 0L; } } final Response<Long> response = new Response<Long>(BuilderFactory.LONG); response.set(result); return response; } @Override public Response<Long> msetnx(final byte[]... keysvalues) { return msetnx(convertToStrings(keysvalues)); } @Override public Response<Long> decr(final String key) { return decrBy(key, 1L); } @Override public Response<Long> decr(final byte[] key) { return decrBy(key, 1L); } @Override public Response<Long> decrBy(final String key, final long integer) { return incrBy(key, -integer); } @Override public Response<Long> decrBy(final byte[] key, final long integer) { return incrBy(key, -integer); } @Override public Response<Long> incr(final String key) { return incrBy(key, 1L); } @Override public Response<Long> incr(final byte[] key) { return incrBy(key, 1L); } @Override public synchronized Response<Long> incrBy(final String key, final long integer) { return incrBy(DataContainer.from(key), integer); } @Override public Response<Long> incrBy(final byte[] key, final long integer) { return incrBy(DataContainer.from(key), integer); } private Response<Long> incrBy(final DataContainer key, final long integer) { final Response<Long> response = new Response<Long>(BuilderFactory.LONG); final DataContainer val = getContainerFromStorage(key, true); final long oldValue; try { oldValue = val == null || val.getString().isEmpty() ? 0L : Long.parseLong(val.getString()); } catch (final NumberFormatException ignored) { throw new JedisDataException("ERR value is not an integer or out of range"); } // check for overflow if (oldValue > 0L ? integer > Long.MAX_VALUE - oldValue : integer < Long.MIN_VALUE - oldValue) { throw new JedisDataException("ERR value is not an integer or out of range"); } final long result = oldValue + integer; storage.put(key, DataContainer.from(Long.toString(result))); response.set(result); return response; } @Override public synchronized Response<Double> incrByFloat(final String key, final double increment) { return incrByFloat(DataContainer.from(key), increment); } @Override public Response<Double> incrByFloat(final byte[] key, final double increment) { return incrByFloat(DataContainer.from(key), increment); } public synchronized Response<Double> incrByFloat(final DataContainer key, final double increment) { final Response<Double> response = new Response<Double>(BuilderFactory.DOUBLE); final DataContainer val = getContainerFromStorage(key, true); final Double result; try { result = val == null || val.getString().isEmpty() ? increment : Double.parseDouble(val.getString()) + increment; } catch (final NumberFormatException ignored) { throw new JedisDataException("ERR value is not a valid float"); } storage.put(key, DataContainer.from(result.toString())); response.set(result.toString().getBytes(CHARSET)); return response; } @Override public Response<List<String>> sort(final String key) { return sort(key, new SortingParams()); } @Override public Response<Long> sort(final String key, final String dstkey) { return sort(key, new SortingParams(), dstkey); } @Override public Response<Long> sort(final byte[] key, final byte[] dstkey) { return sort(key, new SortingParams(), dstkey); } private static Comparator<DataContainer> makeComparator(final Collection<String> params) { final Comparator<DataContainer> comparator; final int direction = params.contains(Protocol.Keyword.DESC.name().toLowerCase()) ? -1 : 1; if (params.contains(Protocol.Keyword.ALPHA.name().toLowerCase())) { comparator = new Comparator<DataContainer>() { @Override public int compare(final DataContainer o1, final DataContainer o2) { return o1.compareTo(o2) * direction; } }; } else { comparator = new Comparator<DataContainer>() { @Override public int compare(final DataContainer o1, final DataContainer o2) { final Long i1, i2; try { i1 = Long.parseLong(o1.getString()); i2 = Long.parseLong(o2.getString()); } catch (final NumberFormatException e) { throw new JedisDataException("ERR One or more scores can't be converted into double"); } return i1.compareTo(i2) * direction; } }; } return comparator; } @Override public Response<List<String>> sort(final String key, final SortingParams sortingParameters) { final Response<List<String>> response = new Response<List<String>>(BuilderFactory.STRING_LIST); List<DataContainer> sortedList = sort(DataContainer.from(key), sortingParameters); response.set(DataContainer.toBytes(sortedList)); return response; } @Override public Response<List<byte[]>> sort(final byte[] key, final SortingParams sortingParameters) { final Response<List<byte[]>> response = new Response<List<byte[]>>(BuilderFactory.BYTE_ARRAY_LIST); List<DataContainer> sortedList = sort(DataContainer.from(key), sortingParameters); response.set(DataContainer.toBytes(sortedList)); return response; } public List<DataContainer> sort(final DataContainer key, final SortingParams sortingParameters) { final List<DataContainer> result = new ArrayList<DataContainer>(); final KeyInformation info = keys.get(key); if (info != null) { switch (info.getType()) { case LIST: result.addAll(listStorage.get(key)); break; case SET: result.addAll(setStorage.get(key)); break; case SORTED_SET: throw new RuntimeException("Not implemented"); default: throw new JedisDataException("WRONGTYPE Operation against a key holding the wrong kind of value"); } } final List<String> params = convertToStrings(sortingParameters.getParams()); Collections.sort(result, makeComparator(params)); final List<DataContainer> filteredResult = new ArrayList<DataContainer>(result.size()); final int limitpos = params.indexOf(Protocol.Keyword.LIMIT.name().toLowerCase()); if (limitpos >= 0) { final int start = Math.max(Integer.parseInt(params.get(limitpos + 1)), 0); final int end = Math.min(Integer.parseInt(params.get(limitpos + 2)) + start, result.size()); for (final DataContainer entry : result.subList(start, end)) { filteredResult.add(entry); } } else { for (final DataContainer entry : result) { filteredResult.add(entry); } } return filteredResult; } @Override public synchronized Response<Long> sort(final String key, final SortingParams sortingParameters, final String dstkey) { return sort(DataContainer.from(key), sortingParameters, DataContainer.from(dstkey)); } @Override public Response<Long> sort(final byte[] key, final SortingParams sortingParameters, final byte[] dstkey) { return sort(DataContainer.from(key), sortingParameters, DataContainer.from(dstkey)); } public synchronized Response<Long> sort(final DataContainer key, final SortingParams sortingParameters, final DataContainer dstkey) { List<DataContainer> sorted = sort(key, sortingParameters); del(dstkey); keys.put(dstkey, new KeyInformation(KeyType.LIST)); listStorage.put(dstkey, sorted); final Response<Long> response = new Response<Long>(BuilderFactory.LONG); response.set((long) sorted.size()); return response; } @Override public Response<List<byte[]>> sort(final byte[] key) { return sort(key, new SortingParams()); } @Override public Response<Long> strlen(final String key) { final Response<Long> response = new Response<Long>(BuilderFactory.LONG); final DataContainer val = getContainerFromStorage(DataContainer.from(key), false); response.set(val == null ? 0L : val.getString().length()); return response; } @Override public Response<Long> strlen(final byte[] key) { return strlen(new String(key, CHARSET)); } @Override public Response<Long> del(final String... keys) { final Response<Long> response = new Response<Long>(BuilderFactory.LONG); long result = 0L; for (final String key : keys) { result += del(key).get(); } response.set(result); return response; } @Override public Response<Long> del(final byte[]... keys) { final Response<Long> response = new Response<Long>(BuilderFactory.LONG); long result = 0L; for (final byte[] key : keys) { result += del(key).get(); } response.set(result); return response; } @Override public synchronized Response<Long> del(final String key) { return del(DataContainer.from(key)); } @Override public synchronized Response<Long> del(final byte[] key) { return del(DataContainer.from(key)); } private Response<Long> del(final DataContainer key) { final Response<Long> response = new Response<Long>(BuilderFactory.LONG); long result = 0L; final KeyInformation info = this.keys.remove(key); if (info != null) { switch (info.getType()) { case HASH: hashStorage.remove(key); break; case LIST: listStorage.remove(key); break; case STRING: default: storage.remove(key); } ++result; } response.set(result); return response; } @Override public synchronized Response<String> hget(final String key, final String field) { final Response<String> response = new Response<String>(BuilderFactory.STRING); final Map<DataContainer, DataContainer> result = getHashFromStorage(DataContainer.from(key), false); if (result == null) { response.set(null); return response; } final DataContainer fieldValue = result.get(DataContainer.from(field)); response.set(DataContainer.toBytes(fieldValue)); return response; } @Override public synchronized Response<byte[]> hget(final byte[] key, final byte[] field) { final Response<byte[]> response = new Response<byte[]>(BuilderFactory.BYTE_ARRAY); final Map<DataContainer, DataContainer> result = getHashFromStorage(DataContainer.from(key), false); if (result == null) { response.set(null); return response; } final DataContainer fieldValue = result.get(DataContainer.from(field)); response.set(DataContainer.toBytes(fieldValue)); return response; } @Override public synchronized Response<Map<String, String>> hgetAll(final String key) { final Response<Map<String, String>> response = new Response<Map<String, String>>(BuilderFactory.STRING_MAP); final Map<DataContainer, DataContainer> result = getHashFromStorage(DataContainer.from(key), false); if (result != null) { final List<byte[]> encodedResult = new ArrayList<byte[]>(result.size()); for (final Map.Entry<DataContainer, DataContainer> e : result.entrySet()) { encodedResult.add(e.getKey().getBytes()); encodedResult.add(e.getValue().getBytes()); } response.set(encodedResult); } else { response.set(new ArrayList<byte[]>(0)); } return response; } @Override public synchronized Response<Map<byte[], byte[]>> hgetAll(final byte[] key) { final Response<Map<byte[], byte[]>> response = new Response<Map<byte[], byte[]>>(BuilderFactory.BYTE_ARRAY_MAP); final Map<DataContainer, DataContainer> result = getHashFromStorage(DataContainer.from(key), false); if (result != null) { final List<byte[]> encodedResult = new ArrayList<byte[]>(result.size()); for (final Map.Entry<DataContainer, DataContainer> e : result.entrySet()) { encodedResult.add(e.getKey().getBytes()); encodedResult.add(e.getValue().getBytes()); } response.set(encodedResult); } else { response.set(new ArrayList<byte[]>(0)); } return response; } @Override public synchronized Response<Set<String>> hkeys(final String key) { final Response<Set<String>> response = new Response<Set<String>>(BuilderFactory.STRING_SET); final Map<DataContainer, DataContainer> result = getHashFromStorage(DataContainer.from(key), false); if (result != null) { response.set(DataContainer.toBytes(result.keySet())); } else { response.set(new ArrayList<byte[]>()); } return response; } @Override public synchronized Response<Set<byte[]>> hkeys(final byte[] key) { final Response<Set<byte[]>> response = new Response<Set<byte[]>>(BuilderFactory.BYTE_ARRAY_ZSET); final Map<DataContainer, DataContainer> result = getHashFromStorage(DataContainer.from(key), false); if (result != null) { response.set(DataContainer.toBytes(result.keySet())); } else { response.set(new ArrayList<byte[]>()); } return response; } @Override public synchronized Response<List<String>> hvals(final String key) { final Response<List<String>> response = new Response<List<String>>(BuilderFactory.STRING_LIST); final Map<DataContainer, DataContainer> result = getHashFromStorage(DataContainer.from(key), false); if (result != null) { response.set(DataContainer.toBytes(result.values())); } else { response.set(new ArrayList<byte[]>()); } return response; } @Override public synchronized Response<List<byte[]>> hvals(final byte[] key) { final Response<List<byte[]>> response = new Response<List<byte[]>>(BuilderFactory.BYTE_ARRAY_LIST); final Map<DataContainer, DataContainer> result = getHashFromStorage(DataContainer.from(key), false); if (result != null) { response.set(DataContainer.toBytes(result.values())); } else { response.set(new ArrayList<byte[]>()); } return response; } @Override public synchronized Response<Long> hset(final String key, final String field, final String value) { return hset(DataContainer.from(key), DataContainer.from(field), DataContainer.from(value)); } @Override public synchronized Response<Long> hset(final byte[] key, final byte[] field, final byte[] value) { return hset(DataContainer.from(key), DataContainer.from(field), DataContainer.from(value)); } private Response<Long> hset(final DataContainer key, final DataContainer field, final DataContainer value) { final Response<Long> response = new Response<Long>(BuilderFactory.LONG); final Map<DataContainer, DataContainer> m = getHashFromStorage(key, true); response.set(m.containsKey(field) ? 0L : 1L); m.put(field, value); return response; } @Override public synchronized Response<Long> hsetnx(final String key, final String field, final String value) { return hsetnx(DataContainer.from(key), DataContainer.from(field), DataContainer.from(value)); } @Override public synchronized Response<Long> hsetnx(final byte[] key, final byte[] field, final byte[] value) { return hsetnx(DataContainer.from(key), DataContainer.from(field), DataContainer.from(value)); } private Response<Long> hsetnx(final DataContainer key, final DataContainer field, final DataContainer value) { final Response<Long> response = new Response<Long>(BuilderFactory.LONG); final Map<DataContainer, DataContainer> m = getHashFromStorage(key, true); long result = 0L; if (!m.containsKey(field)) { m.put(field, value); result = 1L; } response.set(result); return response; } @Override public synchronized Response<List<String>> hmget(final String key, final String... fields) { final Response<List<String>> response = new Response<List<String>>(BuilderFactory.STRING_LIST); final List<byte[]> result = new ArrayList<byte[]>(); final Map<DataContainer, DataContainer> hash = getHashFromStorage(DataContainer.from(key), false); if (hash == null) { for (final String ignored : fields) { result.add(null); } response.set(result); return response; } for (final String field : fields) { final DataContainer v = hash.get(DataContainer.from(field)); result.add(DataContainer.toBytes(v)); } response.set(result); return response; } @Override public synchronized Response<List<byte[]>> hmget(final byte[] key, final byte[]... fields) { final Response<List<byte[]>> response = new Response<List<byte[]>>(BuilderFactory.BYTE_ARRAY_LIST); final List<byte[]> result = new ArrayList<byte[]>(); final Map<DataContainer, DataContainer> hash = getHashFromStorage(DataContainer.from(key), false); if (hash == null) { for (final byte[] ignored : fields) { result.add(null); } response.set(result); return response; } for (final byte[] field : fields) { final DataContainer v = hash.get(DataContainer.from(field)); result.add(DataContainer.toBytes(v)); } response.set(result); return response; } @Override public synchronized Response<String> hmset(final String key, final Map<String, String> hash) { final Response<String> response = new Response<String>(BuilderFactory.STRING); final Map<DataContainer, DataContainer> m = getHashFromStorage(DataContainer.from(key), true); for (final Map.Entry<String, String> e : hash.entrySet()) { m.put(DataContainer.from(e.getKey()), DataContainer.from(e.getValue())); } response.set(OK_RESPONSE); return response; } @Override public synchronized Response<String> hmset(final byte[] key, final Map<byte[], byte[]> hash) { final Response<String> response = new Response<String>(BuilderFactory.STRING); final Map<DataContainer, DataContainer> m = getHashFromStorage(DataContainer.from(key), true); for (final Map.Entry<byte[], byte[]> e : hash.entrySet()) { m.put(DataContainer.from(e.getKey()), DataContainer.from(e.getValue())); } response.set(OK_RESPONSE); return response; } @Override public synchronized Response<Long> hincrBy(final String key, final String field, final long value) { return hincrBy(DataContainer.from(key), DataContainer.from(field), value); } @Override public synchronized Response<Long> hincrBy(final byte[] key, final byte[] field, final long value) { return hincrBy(DataContainer.from(key), DataContainer.from(field), value); } private Response<Long> hincrBy(final DataContainer key, final DataContainer field, final long value) { final Response<Long> response = new Response<Long>(BuilderFactory.LONG); final Map<DataContainer, DataContainer> m = getHashFromStorage(key, true); DataContainer val = m.get(field); if (val == null) { val = DataContainer.from(Long.valueOf(0L).toString()); } final Long result; try { result = Long.valueOf(val.getString()) + value; } catch (final NumberFormatException ignored) { throw new JedisDataException("ERR value is not an integer or out of range"); } m.put(field, DataContainer.from(result.toString())); response.set(result); return response; } @Override public synchronized Response<Double> hincrByFloat(final String key, final String field, final double increment) { return hincrByFloat(DataContainer.from(key), DataContainer.from(field), increment); } @Override public synchronized Response<Double> hincrByFloat(final byte[] key, final byte[] field, final double increment) { return hincrByFloat(DataContainer.from(key), DataContainer.from(field), increment); } private Response<Double> hincrByFloat(final DataContainer key, final DataContainer field, final double increment) { final Response<Double> response = new Response<Double>(BuilderFactory.DOUBLE); final Map<DataContainer, DataContainer> m = getHashFromStorage(key, true); DataContainer val = m.get(field); if (val == null) { val = DataContainer.from(Double.valueOf(0.0D).toString()); } final Double result; try { result = Double.parseDouble(val.toString()) + increment; } catch (final NumberFormatException ignored) { throw new JedisDataException("ERR value is not a valid float"); } DataContainer resultContainer = DataContainer.from(result.toString()); m.put(field, resultContainer); response.set(resultContainer.getBytes()); return response; } @Override public synchronized Response<Long> hdel(final String key, final String... field) { return hdel(DataContainer.from(key), DataContainer.from(field)); } @Override public synchronized Response<Long> hdel(final byte[] key, final byte[]... field) { return hdel(DataContainer.from(key), DataContainer.from(field)); } private Response<Long> hdel(final DataContainer key, final DataContainer... fields) { final Response<Long> response = new Response<Long>(BuilderFactory.LONG); final Map<DataContainer, DataContainer> m = getHashFromStorage(key, true); long result = 0L; for (final DataContainer currentField : fields) { if (m.remove(currentField) != null) { ++result; } } response.set(result); return response; } @Override public synchronized Response<Boolean> hexists(final String key, final String field) { return hexists(DataContainer.from(key), DataContainer.from(field)); } @Override public synchronized Response<Boolean> hexists(final byte[] key, final byte[] field) { return hexists(DataContainer.from(key), DataContainer.from(field)); } private Response<Boolean> hexists(final DataContainer key, final DataContainer field) { final Response<Boolean> response = new Response<Boolean>(BuilderFactory.BOOLEAN); final Map<DataContainer, DataContainer> hash = getHashFromStorage(key, false); response.set(hash != null && hash.containsKey(field) ? 1L : 0L); return response; } @Override public synchronized Response<Long> hlen(final String key) { return hlen(DataContainer.from(key)); } @Override public synchronized Response<Long> hlen(final byte[] key) { return hlen(DataContainer.from(key)); } private Response<Long> hlen(final DataContainer key) { final Response<Long> response = new Response<Long>(BuilderFactory.LONG); final Map<DataContainer, DataContainer> hash = getHashFromStorage(key, false); if (hash != null) { response.set((long) hash.size()); } else { response.set(0L); } return response; } @Override public synchronized Response<Long> lpush(final String key, final String... string) { return lpush(DataContainer.from(key), DataContainer.from(string)); } @Override public synchronized Response<Long> lpush(final byte[] key, final byte[]... string) { return lpush(DataContainer.from(key), DataContainer.from(string)); } private Response<Long> lpush(final DataContainer key, final DataContainer... string) { final Response<Long> response = new Response<Long>(BuilderFactory.LONG); List<DataContainer> list = getListFromStorage(key, true); if (list == null) { list = new ArrayList<DataContainer>(); listStorage.put(key, list); } Collections.addAll(list, string); response.set((long) list.size()); return response; } @Override public synchronized Response<String> lpop(final String key) { final Response<String> response = new Response<String>(BuilderFactory.STRING); final List<DataContainer> list = getListFromStorage(DataContainer.from(key), true); if (list == null || list.isEmpty()) { response.set(null); } else { response.set(list.remove(list.size() - 1).getBytes()); } return response; } @Override public synchronized Response<byte[]> lpop(final byte[] key) { final Response<byte[]> response = new Response<byte[]>(BuilderFactory.BYTE_ARRAY); final List<DataContainer> list = getListFromStorage(DataContainer.from(key), true); if (list == null || list.isEmpty()) { response.set(null); } else { response.set(list.remove(list.size() - 1).getBytes()); } return response; } @Override public synchronized Response<Long> llen(final String key) { return llen(DataContainer.from(key)); } @Override public Response<Long> llen(final byte[] key) { return llen(DataContainer.from(key)); } public synchronized Response<Long> llen(final DataContainer key) { final Response<Long> response = new Response<Long>(BuilderFactory.LONG); final List<DataContainer> list = getListFromStorage(key, false); if (list == null) { response.set(0L); } else { response.set((long) list.size()); } return response; } @Override public Response<List<String>> lrange(final String key, long start, long end) { final Response<List<String>> response = new Response<List<String>>(BuilderFactory.STRING_LIST); List<DataContainer> result = lrange(DataContainer.from(key), start, end); response.set(DataContainer.toBytes(result)); return response; } @Override public Response<List<byte[]>> lrange(final byte[] key, long start, long end) { final Response<List<byte[]>> response = new Response<List<byte[]>>(BuilderFactory.BYTE_ARRAY_LIST); List<DataContainer> result = lrange(DataContainer.from(key), start, end); response.set(DataContainer.toBytes(result)); return response; } public List<DataContainer> lrange(final DataContainer key, long start, long end) { final List<DataContainer> full = getListFromStorage(key, false); List<DataContainer> result = new ArrayList<DataContainer>(); if (start < 0L) { start = Math.max(full.size() + start, 0L); } if (end < 0L) { end = full.size() + end; } if (start > full.size() || start > end) { return Collections.emptyList(); } end = Math.min(full.size() - 1, end); for (int i = (int) start; i <= end; i++) { result.add(full.get(i)); } return result; } @Override public void sync() { // do nothing } @Override public synchronized Response<Set<String>> keys(final String pattern) { final Response<Set<String>> response = new Response<Set<String>>(BuilderFactory.STRING_SET); Set<DataContainer> result = keys(DataContainer.from(pattern)); response.set(DataContainer.toBytes(result)); return response; } @Override public synchronized Response<Set<byte[]>> keys(final byte[] pattern) { final Response<Set<byte[]>> response = new Response<Set<byte[]>>(BuilderFactory.BYTE_ARRAY_ZSET); Set<DataContainer> result = keys(DataContainer.from(pattern)); response.set(DataContainer.toBytes(result)); return response; } private Set<DataContainer> keys(final DataContainer pattern) { Set<DataContainer> result = new HashSet<DataContainer>(); for (final DataContainer key : keys.keySet()) { if (wildcardMatcher.match(key.getString(), pattern.getString())) { result.add(key); } } return result; } protected boolean createOrUpdateKey(final DataContainer key, final KeyType type, final boolean resetTTL) { KeyInformation info = keys.get(key); if (info == null) { info = new KeyInformation(type); keys.put(key, info); return true; } else { if (info.getType() != type) { throw new JedisDataException("ERR Operation against a key holding the wrong kind of value"); } if (resetTTL) { info.setExpiration(-1L); } return false; } } protected DataContainer getContainerFromStorage(final DataContainer key, final boolean createIfNotExist) { final KeyInformation info = keys.get(key); if (info == null) { if (createIfNotExist) { createOrUpdateKey(key, KeyType.STRING, true); DataContainer container = DataContainer.from(""); storage.put(key, container); return container; } return null; // no such key exists } if (info.getType() != KeyType.STRING) { throw new JedisDataException("ERR Operation against a key holding the wrong kind of value"); } if (info.isTTLSetAndKeyExpired()) { storage.remove(key); keys.remove(key); return null; } return storage.get(key); } protected Map<DataContainer, DataContainer> getHashFromStorage(final DataContainer key, final boolean createIfNotExist) { final KeyInformation info = keys.get(key); if (info == null) { if (createIfNotExist) { createOrUpdateKey(key, KeyType.HASH, false); final Map<DataContainer, DataContainer> result = new HashMap<DataContainer, DataContainer>(); hashStorage.put(key, result); return result; } return null; // no such key exists } if (info.getType() != KeyType.HASH) { throw new JedisDataException("ERR Operation against a key holding the wrong kind of value"); } if (info.isTTLSetAndKeyExpired()) { hashStorage.remove(key); keys.remove(key); return null; } return hashStorage.get(key); } protected List<DataContainer> getListFromStorage(final DataContainer key, final boolean createIfNotExist) { final KeyInformation info = keys.get(key); if (info == null) { if (createIfNotExist) { createOrUpdateKey(key, KeyType.LIST, false); final List<DataContainer> result = new ArrayList<DataContainer>(); listStorage.put(key, result); return result; } return null; // no such key exists } if (info.getType() != KeyType.LIST) { throw new JedisDataException("ERR Operation against a key holding the wrong kind of value"); } if (info.isTTLSetAndKeyExpired()) { listStorage.remove(key); keys.remove(key); return null; } return listStorage.get(key); } protected Set<DataContainer> getSetFromStorage(final DataContainer key, final boolean createIfNotExist) { final KeyInformation info = keys.get(key); if (info == null) { if (createIfNotExist) { createOrUpdateKey(key, KeyType.SET, false); final Set<DataContainer> result = new HashSet<DataContainer>(); setStorage.put(key, result); return result; } return null; // no such key exists } if (info.getType() != KeyType.SET) { throw new JedisDataException("ERR Operation against a key holding the wrong kind of value"); } if (info.isTTLSetAndKeyExpired()) { setStorage.remove(key); keys.remove(key); return null; } return setStorage.get(key); } protected static String[] convertToStrings(final byte[][] b) { final int l = b.length; final String[] result = new String[l]; for (int i = 0; i < l; ++i) { result[i] = new String(b[i], CHARSET); } return result; } protected static List<String> convertToStrings(final Collection<byte[]> collection) { final List<String> result = new LinkedList<String>(); for (final byte[] entry : collection) { result.add(new String(entry, CHARSET)); } return result; } @Override public synchronized Response<Long> sadd(final String key, final String... member) { return sadd(DataContainer.from(key), DataContainer.from(member)); } @Override public synchronized Response<Long> sadd(final byte[] key, final byte[]... member) { return sadd(DataContainer.from(key), DataContainer.from(member)); } private Response<Long> sadd(final DataContainer key, final DataContainer... members) { final Response<Long> response = new Response<Long>(BuilderFactory.LONG); final Set<DataContainer> set = getSetFromStorage(key, true); Long added = 0L; for (final DataContainer s : members) { if (set.add(s)) { added++; } } response.set(added); return response; } @Override public synchronized Response<Long> srem(final String key, final String... member) { return srem(DataContainer.from(key), DataContainer.from(member)); } @Override public synchronized Response<Long> srem(final byte[] key, final byte[]... member) { return srem(DataContainer.from(key), DataContainer.from(member)); } private Response<Long> srem(final DataContainer key, final DataContainer... member) { final Response<Long> response = new Response<Long>(BuilderFactory.LONG); final Set<DataContainer> set = getSetFromStorage(key, true); Long removed = 0L; for (final DataContainer s : member) { if (set.remove(s)) { removed++; } } response.set(removed); return response; } @Override public synchronized Response<Long> scard(final String key) { return scard(DataContainer.from(key)); } @Override public synchronized Response<Long> scard(final byte[] key) { return scard(DataContainer.from(key)); } private Response<Long> scard(final DataContainer key) { final Response<Long> response = new Response<Long>(BuilderFactory.LONG); final Set<DataContainer> set = getSetFromStorage(key, true); response.set((long) set.size()); return response; } @Override public synchronized Response<Set<String>> sdiff(final String... keys) { final Response<Set<String>> response = new Response<Set<String>>(BuilderFactory.STRING_SET); DataContainer[] keyContainers = DataContainer.from(keys); Collection<DataContainer> collection = sdiff(keyContainers); List<byte[]> data = DataContainer.toBytes(collection); response.set(data); return response; } @Override public synchronized Response<Set<byte[]>> sdiff(final byte[]... keys) { final Response<Set<byte[]>> response = new Response<Set<byte[]>>(BuilderFactory.BYTE_ARRAY_ZSET); DataContainer[] keyContainers = DataContainer.from(keys); Collection<DataContainer> collection = sdiff(keyContainers); List<byte[]> data = DataContainer.toBytes(collection); response.set(data); return response; } private Set<DataContainer> sdiff(final DataContainer... keys) { final int l = keys.length; if (l <= 0) { throw new JedisDataException("ERR wrong number of arguments for 'sdiff' command"); } final Set<DataContainer> result = new HashSet<DataContainer>(getSetFromStorage(keys[0], true)); for (int i = 1; i < l; ++i) { final Set<DataContainer> set = getSetFromStorage(keys[i], true); result.removeAll(set); } return result; } @Override public synchronized Response<Long> sdiffstore(final String dstKey, final String... keys) { return sdiffstore(DataContainer.from(dstKey), DataContainer.from(keys)); } @Override public synchronized Response<Long> sdiffstore(final byte[] dstKey, final byte[]... keys) { return sdiffstore(DataContainer.from(dstKey), DataContainer.from(keys)); } private Response<Long> sdiffstore(final DataContainer dstKey, final DataContainer... keys) { if (keys.length <= 0) { throw new JedisDataException("ERR wrong number of arguments for 'sdiff' command"); } final Response<Long> response = new Response<Long>(BuilderFactory.LONG); final Set<DataContainer> diff = sdiff(keys); final Set<DataContainer> dst = getSetFromStorage(dstKey, true); if (!dst.isEmpty()) { dst.clear(); } dst.addAll(diff); response.set((long) diff.size()); return response; } @Override public synchronized Response<Set<String>> sinter(final String... keys) { final Response<Set<String>> response = new Response<Set<String>>(BuilderFactory.STRING_SET); DataContainer[] keyContainers = DataContainer.from(keys); Collection<DataContainer> collection = sinter(keyContainers); List<byte[]> data = DataContainer.toBytes(collection); response.set(data); return response; } @Override public synchronized Response<Set<byte[]>> sinter(final byte[]... keys) { final Response<Set<byte[]>> response = new Response<Set<byte[]>>(BuilderFactory.BYTE_ARRAY_ZSET); DataContainer[] keyContainers = DataContainer.from(keys); Collection<DataContainer> collection = sinter(keyContainers); List<byte[]> data = DataContainer.toBytes(collection); response.set(data); return response; } private Set<DataContainer> sinter(final DataContainer... keys) { final int l = keys.length; if (l <= 0) { throw new JedisDataException("ERR wrong number of arguments for 'sinter' command"); } final Set<DataContainer> firstSet = new HashSet<DataContainer>(getSetFromStorage(keys[0], true)); for (int i = 1; i < l; ++i) { final Set<DataContainer> set = getSetFromStorage(keys[i], true); firstSet.retainAll(set); } return firstSet; } @Override public synchronized Response<Long> sinterstore(final String dstKey, final String... keys) { return sinterstore(DataContainer.from(dstKey), DataContainer.from(keys)); } @Override public synchronized Response<Long> sinterstore(final byte[] dstkey, final byte[]... keys) { return sinterstore(DataContainer.from(dstkey), DataContainer.from(keys)); } private Response<Long> sinterstore(final DataContainer dstKey, final DataContainer... keys) { if (keys.length <= 0) { throw new JedisDataException("ERR wrong number of arguments for 'sinterstore' command"); } final Response<Long> response = new Response<Long>(BuilderFactory.LONG); final Set<DataContainer> inter = sinter(keys); final Set<DataContainer> dst = getSetFromStorage(dstKey, true); if (!dst.isEmpty()) { dst.clear(); } dst.addAll(inter); response.set((long) inter.size()); return response; } @Override public synchronized Response<Boolean> sismember(final String key, final String member) { return sismember(DataContainer.from(key), DataContainer.from(member)); } @Override public synchronized Response<Boolean> sismember(final byte[] key, final byte[] member) { return sismember(DataContainer.from(key), DataContainer.from(member)); } private Response<Boolean> sismember(final DataContainer key, final DataContainer member) { final Response<Boolean> response = new Response<Boolean>(BuilderFactory.BOOLEAN); final Set<DataContainer> set = getSetFromStorage(key, false); response.set(set != null && set.contains(member) ? 1L : 0L); return response; } @Override public synchronized Response<Long> smove(final String srckey, final String dstkey, final String member) { return smove(DataContainer.from(srckey), DataContainer.from(dstkey), DataContainer.from(member)); } @Override public synchronized Response<Long> smove(final byte[] srckey, final byte[] dstkey, final byte[] member) { return smove(DataContainer.from(srckey), DataContainer.from(dstkey), DataContainer.from(member)); } private Response<Long> smove(final DataContainer srckey, final DataContainer dstkey, final DataContainer member) { final Response<Long> response = new Response<Long>(BuilderFactory.LONG); final Set<DataContainer> src = getSetFromStorage(srckey, false); final Set<DataContainer> dst = getSetFromStorage(dstkey, true); if (src.remove(member)) { dst.add(member); response.set(1L); } else { response.set(0L); } return response; } @Override public synchronized Response<String> spop(final String key) { final Response<String> response = new Response<String>(BuilderFactory.STRING); DataContainer result = spop(DataContainer.from(key)); response.set(DataContainer.toBytes(result)); return response; } @Override public synchronized Response<byte[]> spop(final byte[] key) { final Response<byte[]> response = new Response<byte[]>(BuilderFactory.BYTE_ARRAY); DataContainer result = spop(DataContainer.from(key)); response.set(DataContainer.toBytes(result)); return response; } private DataContainer spop(final DataContainer key) { DataContainer member = srandmember(key); if (member != null) { final Set<DataContainer> src = getSetFromStorage(key, false); src.remove(member); } return member; } @Override public synchronized Response<String> srandmember(final String key) { final Response<String> response = new Response<String>(BuilderFactory.STRING); final DataContainer result = srandmember(DataContainer.from(key)); response.set(result == null ? null : result.getBytes()); return response; } @Override public synchronized Response<byte[]> srandmember(final byte[] key) { final Response<byte[]> response = new Response<byte[]>(BuilderFactory.BYTE_ARRAY); final DataContainer result = srandmember(DataContainer.from(key)); response.set(result == null ? null : result.getBytes()); return response; } private DataContainer srandmember(final DataContainer key) { final Set<DataContainer> src = getSetFromStorage(key, false); if (src == null) { return null; } else { return getRandomElementFromSet(src); } } @Override public synchronized Response<Set<String>> smembers(final String key) { final Response<Set<String>> response = new Response<Set<String>>(BuilderFactory.STRING_SET); final Set<DataContainer> members = smembers(DataContainer.from(key)); response.set(DataContainer.toBytes(members)); return response; } @Override public synchronized Response<Set<byte[]>> smembers(final byte[] key) { final Response<Set<byte[]>> response = new Response<Set<byte[]>>(BuilderFactory.BYTE_ARRAY_ZSET); final Set<DataContainer> members = smembers(DataContainer.from(key)); response.set(DataContainer.toBytes(members)); return response; } private Set<DataContainer> smembers(final DataContainer key) { return getSetFromStorage(key, true); } @Override public synchronized Response<Set<String>> sunion(final String... keys) { final Response<Set<String>> response = new Response<Set<String>>(BuilderFactory.STRING_SET); Set<DataContainer> result = sunion(DataContainer.from(keys)); response.set(DataContainer.toBytes(result)); return response; } @Override public synchronized Response<Set<byte[]>> sunion(final byte[]... keys) { final Response<Set<byte[]>> response = new Response<Set<byte[]>>(BuilderFactory.BYTE_ARRAY_ZSET); Set<DataContainer> result = sunion(DataContainer.from(keys)); response.set(DataContainer.toBytes(result)); return response; } private Set<DataContainer> sunion(final DataContainer... keys) { final int l = keys.length; if (l <= 0) { throw new JedisDataException("ERR wrong number of arguments for 'sunion' command"); } final Set<DataContainer> result = new HashSet<DataContainer>(getSetFromStorage(keys[0], true)); for (int i = 1; i < l; ++i) { final Set<DataContainer> set = getSetFromStorage(keys[i], true); result.addAll(set); } return result; } @Override public synchronized Response<Long> sunionstore(final String dstkey, final String... keys) { return sunionstore(DataContainer.from(dstkey), DataContainer.from(keys)); } @Override public synchronized Response<Long> sunionstore(final byte[] dstkey, final byte[]... keys) { return sunionstore(DataContainer.from(dstkey), DataContainer.from(keys)); } private Response<Long> sunionstore(final DataContainer dstkey, final DataContainer... keys) { if (keys.length <= 0) { throw new JedisDataException("ERR wrong number of arguments for 'sunionstore' command"); } final Response<Long> response = new Response<Long>(BuilderFactory.LONG); final Set<DataContainer> inter = sunion(keys); final Set<DataContainer> dst = getSetFromStorage(dstkey, true); if (!dst.isEmpty()) { dst.clear(); } dst.addAll(inter); response.set((long) inter.size()); return response; } }
// This file is part of the Kaltura Collaborative Media Suite which allows users // to do with audio, video, and animation what Wiki platfroms allow them to do with // text. // This program is free software: you can redistribute it and/or modify // published by the Free Software Foundation, either version 3 of the // This program is distributed in the hope that it will be useful, // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // @ignore package com.kaltura.client; import com.kaltura.client.utils.request.ConnectionConfiguration; import com.kaltura.client.types.BaseResponseProfile; /** * This class was generated using generate.php * against an XML schema provided by Kaltura. * * MANUAL CHANGES TO THIS CLASS WILL BE OVERWRITTEN. */ @SuppressWarnings("serial") public class Client extends ClientBase { public Client(ConnectionConfiguration config) { super(config); this.setClientTag("java:19-03-27"); this.setApiVersion("14.17.0"); this.clientConfiguration.put("format", 1); // JSON } /** * @param clientTag */ public void setClientTag(String clientTag){ this.clientConfiguration.put("clientTag", clientTag); } /** * @return String */ public String getClientTag(){ if(this.clientConfiguration.containsKey("clientTag")){ return(String) this.clientConfiguration.get("clientTag"); } return null; } /** * @param apiVersion */ public void setApiVersion(String apiVersion){ this.clientConfiguration.put("apiVersion", apiVersion); } /** * @return String */ public String getApiVersion(){ if(this.clientConfiguration.containsKey("apiVersion")){ return(String) this.clientConfiguration.get("apiVersion"); } return null; } /** * @param partnerId Impersonated partner id */ public void setPartnerId(Integer partnerId){ this.requestConfiguration.put("partnerId", partnerId); } /** * Impersonated partner id * * @return Integer */ public Integer getPartnerId(){ if(this.requestConfiguration.containsKey("partnerId")){ return(Integer) this.requestConfiguration.get("partnerId"); } return 0; } /** * @param ks Kaltura API session */ public void setKs(String ks){ this.requestConfiguration.put("ks", ks); } /** * Kaltura API session * * @return String */ public String getKs(){ if(this.requestConfiguration.containsKey("ks")){ return(String) this.requestConfiguration.get("ks"); } return null; } /** * @param sessionId Kaltura API session */ public void setSessionId(String sessionId){ this.requestConfiguration.put("ks", sessionId); } /** * Kaltura API session * * @return String */ public String getSessionId(){ if(this.requestConfiguration.containsKey("ks")){ return(String) this.requestConfiguration.get("ks"); } return null; } /** * @param responseProfile Response profile - this attribute will be automatically unset after every API call. */ public void setResponseProfile(BaseResponseProfile responseProfile){ this.requestConfiguration.put("responseProfile", responseProfile); } /** * Response profile - this attribute will be automatically unset after every API call. * * @return BaseResponseProfile */ public BaseResponseProfile getResponseProfile(){ if(this.requestConfiguration.containsKey("responseProfile")){ return(BaseResponseProfile) this.requestConfiguration.get("responseProfile"); } return null; } }
package net.drewgottlieb.soapy; import android.util.Log; import com.squareup.okhttp.ConnectionSpec; import com.squareup.okhttp.FormEncodingBuilder; import com.squareup.okhttp.MediaType; import com.squareup.okhttp.OkHttpClient; import com.squareup.okhttp.Request; import com.squareup.okhttp.RequestBody; import com.squareup.okhttp.Response; import com.squareup.okhttp.TlsVersion; import org.jdeferred.Deferred; import org.jdeferred.DeferredManager; import org.jdeferred.DoneCallback; import org.jdeferred.FailCallback; import org.jdeferred.Promise; import org.jdeferred.impl.DefaultDeferredManager; import org.jdeferred.impl.DeferredObject; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import javax.net.ssl.HttpsURLConnection; public class SoapyWebAPI { private static String TAG = "SoapyWebAPI"; private static final ExecutorService executorService = Executors.newCachedThreadPool(); private static final DeferredManager dm = new DefaultDeferredManager(executorService); private static final MediaType MEDIA_TYPE_JSON = MediaType.parse( "application/json; charset=utf-8"); public static class SoapyWebError extends Exception { public SoapyWebError(String message) { super(message); } } protected enum RequestType { GET, POST } private static SoapyWebAPI instance = null; private SoapyPreferences preferences = null; private OkHttpClient client = new OkHttpClient(); public static SoapyWebAPI getInstance() { if (instance == null) { instance = new SoapyWebAPI(); } return instance; } protected SoapyWebAPI() { preferences = SoapyPreferences.getInstance(); // Only allow TLSv1.0 because CSH servers don't support SSLv3, and newer TLS doesn't seem to work. ConnectionSpec spec = new ConnectionSpec.Builder(ConnectionSpec.MODERN_TLS) .tlsVersions(TlsVersion.TLS_1_0) .build(); client.setConnectionSpecs(Collections.singletonList(spec)); } public Promise<JSONObject, SoapyWebError, Void> get(String route) { return request(RequestType.GET, route, (RequestBody) null); } public Promise<JSONObject, SoapyWebError, Void> post(String route, Map<String, String> vars) { return request(RequestType.POST, route, vars); } public Promise<JSONObject, SoapyWebError, Void> post(String route, String body) { return request(RequestType.POST, route, body); } protected Promise<JSONObject, SoapyWebError, Void> request(final RequestType type, String route, final Map<String, String> vars) { RequestBody rBody = null; if (type == RequestType.POST) { FormEncodingBuilder bodyBuilder = new FormEncodingBuilder(); if (vars != null) { for (String key : vars.keySet()) { bodyBuilder.add(key, vars.get(key)); } } rBody = bodyBuilder.build(); } return request(type, route, rBody); } protected Promise<JSONObject, SoapyWebError, Void> request(final RequestType type, String route, final String body) { RequestBody rBody = null; if (type == RequestType.POST) { rBody = RequestBody.create(MEDIA_TYPE_JSON, body); } return request(type, route, rBody); } protected Promise<JSONObject, SoapyWebError, Void> request(final RequestType type, String route, final RequestBody body) { final Deferred<JSONObject, SoapyWebError, Void> deferred = new DeferredObject<>(); URL url = null; try { url = new URL(preferences.getSoapyUrl() + route); } catch (MalformedURLException e) { e.printStackTrace(); deferred.reject(new SoapyWebError("Malformed URL: " + url)); return deferred.promise(); } final URL fURL = url; executorService.submit(new Runnable() { public void run() { String result = null; try { Request.Builder builder = new Request.Builder() .url(fURL) .header("X-Soapy-Secret", preferences.getSoapySecret()); if (type == RequestType.POST) { builder.method("POST", body); } Response response = client.newCall(builder.build()).execute(); result = response.body().string(); } catch (IOException e) { e.printStackTrace(); deferred.reject(new SoapyWebError("IOException: " + e.getMessage())); return; } JSONObject obj = null; try { obj = new JSONObject(result); } catch (JSONException e) { e.printStackTrace(); deferred.reject(new SoapyWebError("JSONException: " + e.getMessage())); Log.w(TAG, "Received JSON was:\n" + result); return; } if (obj.has("error")) { try { deferred.reject(new SoapyWebError(obj.getString("error"))); } catch (JSONException e) { e.printStackTrace(); deferred.reject(new SoapyWebError("Failed to read response error.")); } return; } deferred.resolve(obj); } }); return deferred.promise(); } public Promise<Void, SoapyWebError, Void> setSelectedPlaylist(final String rfid, final String playlistUri) { final Deferred<Void, SoapyWebError, Void> deferred = new DeferredObject<>(); HashMap<String, String> vars = new HashMap<>(); vars.put("playlist_uri", playlistUri); dm.when(post("api/rfid/" + rfid + "/playlist/set", vars)).done(new DoneCallback<JSONObject>() { @Override public void onDone(JSONObject result) { try { if (result.has("error")) { String errorMsg = result.getString("error"); deferred.reject(new SoapyWebError("Remote error: " + errorMsg)); return; } } catch (JSONException e) { e.printStackTrace(); deferred.reject(new SoapyWebError("Failed to parse response JSON: " + e.getMessage())); } deferred.resolve(null); } }).fail(new FailCallback<SoapyWebError>() { @Override public void onFail(SoapyWebError result) { deferred.reject(result); } }); return deferred.promise(); } public Promise<Void, Throwable, Void> uploadLogs(final List<LogService.LogEvent> events) { final Deferred<Void, Throwable, Void> deferred = new DeferredObject<>(); String json = null; try { JSONObject jObj = new JSONObject(); jObj.put("bathroom", preferences.getBathroomName()); JSONArray jEvents = new JSONArray(); for (LogService.LogEvent event : events) { JSONObject jEvent = new JSONObject(); jEvent.put("level", event.getLevel().toString()); jEvent.put("time", event.getDate().toString()); jEvent.put("tag", event.getTag()); jEvent.put("message", event.getMessage()); jEvents.put(jEvent); } jObj.put("events", jEvents); json = jObj.toString(); } catch (JSONException e) { deferred.reject(e); return deferred.promise(); } dm.when(post("api/log/add", json)).done(new DoneCallback<JSONObject>() { @Override public void onDone(JSONObject result) { try { if (result.has("error")) { String errorMsg = result.getString("error"); deferred.reject(new SoapyWebError("Remote error: " + errorMsg)); return; } } catch (JSONException e) { e.printStackTrace(); deferred.reject(new SoapyWebError("Failed to parse response JSON: " + e.getMessage())); } deferred.resolve(null); } }).fail(new FailCallback<SoapyWebError>() { @Override public void onFail(SoapyWebError result) { deferred.reject(result); } }); return deferred.promise(); } public Promise<SoapyUser, SoapyWebError, Void> fetchUserAndPlaylists(String rfid) { return fetchUser(rfid, "playlists"); } public Promise<SoapyUser, SoapyWebError, Void> fetchUserAndTracks(String rfid) { return fetchUser(rfid, "tracks"); } /** * @param rfid * @param request either "playlists" or "tracks" */ protected Promise<SoapyUser, SoapyWebError, Void> fetchUser(final String rfid, String request) { final Deferred<SoapyUser, SoapyWebError, Void> deferred = new DeferredObject<>(); dm.when(get("api/rfid/" + rfid + "/" + request)).done(new DoneCallback<JSONObject>() { public void onDone(JSONObject obj) { try { if (obj.has("error")) { String errorMsg = obj.getString("error"); deferred.reject(new SoapyWebError("Remote error: " + errorMsg)); return; } SoapyUser user = new SoapyUser(rfid, obj); deferred.resolve(user); } catch (JSONException e) { e.printStackTrace(); deferred.reject(new SoapyWebError("Failed to parse playlist JSON: " + e.getMessage())); } } }).fail(new FailCallback<SoapyWebError>() { public void onFail(SoapyWebAPI.SoapyWebError e) { deferred.reject(e); } }); return deferred.promise(); } }
package smp.components.general; import java.awt.Color; import java.awt.Image; import java.awt.Toolkit; import java.awt.image.BufferedImage; import java.awt.image.FilteredImageSource; import java.awt.image.ImageFilter; import java.awt.image.ImageProducer; import java.awt.image.RGBImageFilter; import java.io.EOFException; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.ObjectInputStream; import java.io.StreamCorruptedException; import java.text.ParseException; import java.util.ArrayList; import java.util.Scanner; import javax.swing.JFileChooser; import javax.swing.JOptionPane; import javax.swing.filechooser.FileFilter; import javax.swing.filechooser.FileNameExtensionFilter; import smp.components.Values; import smp.components.staff.Staff; import smp.components.staff.sequences.StaffArrangement; import smp.components.staff.sequences.StaffNote; import smp.components.staff.sequences.StaffNoteLine; import smp.components.staff.sequences.StaffSequence; import smp.components.staff.sequences.mpc.MPCDecoder; import smp.fx.Dialog; import smp.fx.SMPFXController; import smp.stateMachine.StateMachine; /** * A somewhat useful utilities class for images and such. Not so much use right * now yet, but will gain some functionality eventually. * * @author RehdBlob * @since 2012.08.20 */ public class Utilities { /** * From StackOverflow - "PhiLo" and "corgrath" made this. * * @param im * An image to have its background be made transparent. * @param color * The color to be made transparent. * @return A BufferedImage that now has all of <code>color</code> removed. */ public static BufferedImage makeColorTransparent(BufferedImage im, final Color color) { ImageFilter filter = new RGBImageFilter() { // the color we are looking for... Alpha bits are set to opaque public int markerRGB = color.getRGB() | 0xFF000000; @Override public final int filterRGB(int x, int y, int rgb) { if ((rgb | 0xFF000000) == markerRGB) { // Mark the alpha bits as zero - transparent return 0x00FFFFFF & rgb; } else { // nothing to do return rgb; } } }; ImageProducer ip = new FilteredImageSource(im.getSource(), filter); return imageToBufferedImage(Toolkit.getDefaultToolkit().createImage(ip)); } /** * From StackOverflow - "PhiLo" and "corgrath" made this. * * @param image * An Image to be converted to a BufferedImage * @return A BufferedImage from an Image. */ private static BufferedImage imageToBufferedImage(Image image) { BufferedImage bufferedImage = new BufferedImage(image.getWidth(null), image.getHeight(null), BufferedImage.TYPE_INT_ARGB); /* * Graphics2D g2 = bufferedImage.createGraphics(); g2.drawImage(image, * 0, 0, null); g2.dispose(); */ return bufferedImage; } /** * Opens a file dialog that people can choose a file from. This is a Java * Swing version. * * @return A File reference that the user has chosen. * @throws IOException */ public static File openFileDialog() throws IOException, NullPointerException { JFileChooser fd = new JFileChooser("."); FileFilter filter = new FileNameExtensionFilter("Text File (*.txt)", "txt"); FileFilter filter2 = new FileNameExtensionFilter( "AMS Sequence (*.mss)", "mss"); fd.addChoosableFileFilter(filter); fd.addChoosableFileFilter(filter2); fd.setFileFilter(filter); int returnVal = fd.showOpenDialog(null); if (returnVal == JFileChooser.APPROVE_OPTION) { return fd.getSelectedFile(); } else if (returnVal == JFileChooser.CANCEL_OPTION) { throw new NullPointerException(); } else { System.out.print("Error opening file!"); throw new IOException(); } } /** * Opens some dialog box that contains some text in it. Whether this is done * in Swing or JavaFX is TBD. * * @param in * What should be shown in this dialog box. */ public static void openDialog(String in) { JOptionPane.showMessageDialog(null, in, "Information", JOptionPane.INFORMATION_MESSAGE); } /** * Makes a sequence fit on the screen, and also trims excessive whitespace * at the end of a file. * * @param theSeq * The sequence to normalize. */ public static void normalize(StaffSequence theSeq) { ArrayList<StaffNoteLine> theLines = theSeq.getTheLines(); int last = theLines.size() - 1; for (int i = theLines.size() - 1; i >= 0; i if (i < Values.DEFAULT_LINES_PER_SONG) break; else if (!theLines.get(i).isEmpty()) { last = i; break; } } last = theLines.size() - last; for (int i = 0; i < last - 1; i++) theLines.remove(theLines.size() - 1); while (theLines.size() % 4 != 0 || theLines.size() % Values.NOTELINES_IN_THE_WINDOW != 0) { theLines.add(new StaffNoteLine()); } } /** * Loads a song from the file specified. * * @param inputFile * The file to load from. * @return A loaded song file. The format is a StaffSequence. * @throws FileNotFoundException * @throws IOException * @throws ClassNotFoundException */ public static StaffSequence loadSong(File inputFile) throws FileNotFoundException, IOException, NullPointerException { FileInputStream f_in = new FileInputStream(inputFile); StaffSequence loaded = null; try { // Decode as object ObjectInputStream o_in = new ObjectInputStream(f_in); loaded = (StaffSequence) o_in.readObject(); o_in.close(); } catch (ClassNotFoundException | ClassCastException | EOFException | StreamCorruptedException e) { // If it's not an object, try using the human-readable option. f_in.close(); f_in = new FileInputStream(inputFile); Scanner sc = new Scanner(f_in); ArrayList<String> read = new ArrayList<String>(); while (sc.hasNext()) { read.add(sc.nextLine()); } sc.close(); loaded = parseText(read); } f_in.close(); if (loaded == null) { throw new NullPointerException(); } return loaded; } /** * Parses a bunch of text from a save file and makes a * <code>StaffSequence</code> out of it. * * @param read * <code>ArrayList</code> of notes and parameters. * @return Hopefully, a decoded <code>StaffSequence</code> */ private static StaffSequence parseText(ArrayList<String> read) { StaffSequence loaded = new StaffSequence(); for (String s : read) { if (s.contains("TEMPO") || s.contains("EXT") || s.contains("TIME")) { String[] sp = s.split(","); for (String spl : sp) { String num = spl.substring(spl.indexOf(":") + 1); if (spl.contains("TEMPO")) { loaded.setTempo(Double.parseDouble(num.trim())); } else if (spl.contains("EXT")) { loaded.setNoteExtensions(Utilities.boolFromLong( Long.parseLong(num.trim()))); } else if (spl.contains("TIME")) { loaded.setTimeSignature(num.trim()); } } } else { String[] sp = s.split(","); int lineNum = 0; StaffNoteLine st = new StaffNoteLine(); for (String spl : sp) { if (spl.contains(":") && !spl.contains("VOL")) { String[] meas = spl.split(":"); if (meas.length != 2) { continue; } lineNum = (Integer.parseInt(meas[0]) - 1) * loaded.getTimeSignature().top() + Integer.parseInt(meas[1]); } else { if (spl.contains("VOL")) { st.setVolume(Double.parseDouble(spl.substring( spl.indexOf(":") + 1).trim())); } else { try { st.add(new StaffNote(spl)); } catch (ParseException e) { e.printStackTrace(); } } } } if (loaded.getTheLines().size() < lineNum + 1) { int add = lineNum - loaded.getTheLines().size(); for (int i = 0; i < add; i++) { loaded.addLine(new StaffNoteLine()); } } if (lineNum >= loaded.getTheLines().size()) { loaded.addLine(st); } else { loaded.setLine(lineNum, st); } } } if (loaded.getTheLines().size() % 10 != 0) { do { loaded.addLine(new StaffNoteLine()); } while (loaded.getTheLines().size() % 10 != 0); } return loaded; } /** * Creates a boolean array from a parsed long array, from a loaded file. * @param parseLong The long that we want to parse. * @return A boolean array based on the long integer that we have loaded. */ private static boolean[] boolFromLong(long parseLong) { boolean[] loaded = new boolean[Values.NUMINSTRUMENTS]; for (int i = 0; i < Values.NUMINSTRUMENTS; i++) { loaded[i] = ((1 << i) & parseLong) != 0 ? true : false; } return loaded; } /** * Creates a long integer from a parsed boolean array. * @param parseBool The boolean array that we want to parse. * @return A long integer that is a bitfield that represents * the boolean array. */ public static long longFromBool(boolean[] parseBool) { long parsed = 0; for (int i = 0; i < parseBool.length; i++) { if (parseBool[i]) { parsed |= (1 << i); } } return parsed; } /** * Parses a bunch of text from a save file and makes a * <code>StaffArrangement</code> out of it. * * @param read * <code>ArrayList</code> of filenames and paths. * @return Hopefully, a decoded <code>StaffArrangement</code> */ private static StaffArrangement parseArrText(ArrayList<String> read) { StaffArrangement loaded = new StaffArrangement(); File f = null; ArrayList<File> files = new ArrayList<File>(); ArrayList<String> names = new ArrayList<String>(); for (String s : read) { names.add(s); f = new File(s + ".txt"); files.add(f); } loaded.setTheSequenceNames(names); loaded.setTheSequenceFiles(files); return loaded; } /** * Loads an arrangement from the file specified. * * @param inputFile * The file to load from. * @return A loaded arrangement file. The format is StaffArrangement. * @throws FileNotFoundException * @throws IOException * @throws ClassNotFoundException */ public static StaffArrangement loadArrangement(File inputFile) throws FileNotFoundException, IOException, ClassNotFoundException { FileInputStream f_in = new FileInputStream(inputFile); StaffArrangement loaded = null; try { ObjectInputStream o_in = new ObjectInputStream(f_in); loaded = (StaffArrangement) o_in.readObject(); o_in.close(); } catch (ClassNotFoundException | ClassCastException | EOFException | StreamCorruptedException e) { // If it's not an object, try using the human-readable option. f_in.close(); f_in = new FileInputStream(inputFile); Scanner sc = new Scanner(f_in); ArrayList<String> read = new ArrayList<String>(); while (sc.hasNext()) { read.add(sc.nextLine()); } sc.close(); loaded = parseArrText(read); } f_in.close(); return loaded; } /** * Loads a sequence from an input file. Intended usage is in arranger mode. * We assume that the input files are located in a folder named "Songs" for * now. * * @param inputFile * This is the input filename. */ public static StaffSequence loadSequenceFromArrangement(File inputFile, Staff theStaff, SMPFXController controller) { try { inputFile = new File(inputFile.getParent() + "\\" + inputFile.getName()); if (!inputFile.exists()) { inputFile = new File(inputFile.getParent() + "\\" + inputFile.getName()); } StaffSequence loaded = loadSong(inputFile); populateStaff(loaded, inputFile, false, theStaff, controller); return loaded; } catch (ClassCastException | EOFException | StreamCorruptedException | NullPointerException e) { try { StaffSequence loaded = MPCDecoder.decode(inputFile); Utilities.populateStaff(loaded, inputFile, true, theStaff, controller); return loaded; } catch (Exception e1) { e1.printStackTrace(); Dialog.showDialog("Not a valid song file."); return null; } } catch (FileNotFoundException e) { e.printStackTrace(); Dialog.showDialog("Not a valid song file."); return null; } catch (IOException e) { e.printStackTrace(); Dialog.showDialog("Not a valid song file."); return null; } } /** * Populates the staff with the sequence given. * * @param loaded * The loaded sequence. * @param inputFile * The input file. * @param mpc * Whether this is an MPC file. */ public static String populateStaff(StaffSequence loaded, File inputFile, boolean mpc, Staff theStaff, SMPFXController controller) { Utilities.normalize(loaded); theStaff.setSequence(loaded); theStaff.setSequenceFile(inputFile); StateMachine.setTempo(loaded.getTempo()); theStaff.updateCurrTempo(); theStaff.getControlPanel() .getScrollbar() .setMax(loaded.getTheLines().size() - Values.NOTELINES_IN_THE_WINDOW); theStaff.setLocation(0); theStaff.getNoteMatrix().redraw(); String fname = inputFile.getName(); try { if (mpc) fname = fname.substring(0, fname.indexOf(']')); else fname = fname.substring(0, fname.indexOf(".")); } catch (IndexOutOfBoundsException e) { // Do nothing } theStaff.setSequenceName(fname); StateMachine.setNoteExtensions(loaded.getNoteExtensions()); controller.getInstBLine().updateNoteExtensions(); return fname; } /** * Arrangement files might have absolute paths in them. Here's something * that will help a little bit with relative paths. * * @param loaded * The loaded staff arrangement. * @param filePath * The location in which this arrangement was found. */ public static void normalizeArrangement(StaffArrangement loaded, File filePath) { String basePath = filePath.getParent() + "\\"; for (int i = 0; i < loaded.getTheSequenceFiles().size(); i++) { File f = loaded.getTheSequenceFiles().get(i); String fName = f.getName(); int dot = f.getName().lastIndexOf("."); String newPath = basePath + fName; File f2 = new File(newPath); if (!f2.exists() && dot != -1) { fName = fName.substring(0, dot) + "]MarioPaint.txt"; newPath = basePath + fName; loaded.getTheSequenceFiles().set(i, new File(newPath)); continue; } loaded.getTheSequenceFiles().set(i, new File(newPath)); } } /** * Populates the staff with the arrangement given. * * @param loaded * The loaded arrangement. * @param inputFile * The input file. * @param mpc * Whether this is an MPC file. */ public static void populateStaffArrangement(StaffArrangement loaded, File inputFile, boolean mpc, Staff theStaff, SMPFXController controller) { File firstFile = loaded.getTheSequenceFiles().get(0); StaffSequence first = loadSequenceFromArrangement(firstFile, theStaff, controller); String fname = inputFile.getName(); boolean[] j = first.getNoteExtensions(); controller.getNameTextField().setText(fname); StateMachine.setNoteExtensions(j); controller.getInstBLine().updateNoteExtensions(); try { if (mpc) fname = fname.substring(0, fname.indexOf(']')); else fname = fname.substring(0, fname.indexOf(".")); } catch (IndexOutOfBoundsException e) { // Do nothing } theStaff.setArrangement(loaded); theStaff.setArrangementName(fname); theStaff.getArrangementList().getItems().clear(); theStaff.getArrangementList().getItems() .addAll(loaded.getTheSequenceNames()); ArrayList<File> files = loaded.getTheSequenceFiles(); ArrayList<StaffSequence> seq = new ArrayList<StaffSequence>(); for (int i = 0; i < files.size(); i++) { try { seq.add(Utilities.loadSong(files.get(i))); } catch (ClassCastException | EOFException | StreamCorruptedException | NullPointerException e) { try { seq.add(MPCDecoder.decode(files.get(i))); } catch (Exception e1) { e1.printStackTrace(); return; } } catch (FileNotFoundException e) { e.printStackTrace(); return; } catch (IOException e) { e.printStackTrace(); return; } } theStaff.getArrangement().setTheSequences(seq); controller.getNameTextField().setText(fname); } }
// This file is part of the Kaltura Collaborative Media Suite which allows users // to do with audio, video, and animation what Wiki platfroms allow them to do with // text. // This program is free software: you can redistribute it and/or modify // published by the Free Software Foundation, either version 3 of the // This program is distributed in the hope that it will be useful, // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // @ignore package com.kaltura.client; import com.kaltura.client.utils.request.ConnectionConfiguration; import com.kaltura.client.types.BaseResponseProfile; /** * This class was generated using generate.php * against an XML schema provided by Kaltura. * * MANUAL CHANGES TO THIS CLASS WILL BE OVERWRITTEN. */ @SuppressWarnings("serial") public class Client extends ClientBase { public Client(ConnectionConfiguration config) { super(config); this.setClientTag("java:21-04-03"); this.setApiVersion("16.19.0"); this.clientConfiguration.put("format", 1); // JSON } /** * @param clientTag */ public void setClientTag(String clientTag){ this.clientConfiguration.put("clientTag", clientTag); } /** * @return String */ public String getClientTag(){ if(this.clientConfiguration.containsKey("clientTag")){ return(String) this.clientConfiguration.get("clientTag"); } return null; } /** * @param apiVersion */ public void setApiVersion(String apiVersion){ this.clientConfiguration.put("apiVersion", apiVersion); } /** * @return String */ public String getApiVersion(){ if(this.clientConfiguration.containsKey("apiVersion")){ return(String) this.clientConfiguration.get("apiVersion"); } return null; } /** * @param partnerId Impersonated partner id */ public void setPartnerId(Integer partnerId){ this.requestConfiguration.put("partnerId", partnerId); } /** * Impersonated partner id * * @return Integer */ public Integer getPartnerId(){ if(this.requestConfiguration.containsKey("partnerId")){ return(Integer) this.requestConfiguration.get("partnerId"); } return 0; } /** * @param ks Kaltura API session */ public void setKs(String ks){ this.requestConfiguration.put("ks", ks); } /** * Kaltura API session * * @return String */ public String getKs(){ if(this.requestConfiguration.containsKey("ks")){ return(String) this.requestConfiguration.get("ks"); } return null; } /** * @param sessionId Kaltura API session */ public void setSessionId(String sessionId){ this.requestConfiguration.put("ks", sessionId); } /** * Kaltura API session * * @return String */ public String getSessionId(){ if(this.requestConfiguration.containsKey("ks")){ return(String) this.requestConfiguration.get("ks"); } return null; } /** * @param responseProfile Response profile - this attribute will be automatically unset after every API call. */ public void setResponseProfile(BaseResponseProfile responseProfile){ this.requestConfiguration.put("responseProfile", responseProfile); } /** * Response profile - this attribute will be automatically unset after every API call. * * @return BaseResponseProfile */ public BaseResponseProfile getResponseProfile(){ if(this.requestConfiguration.containsKey("responseProfile")){ return(BaseResponseProfile) this.requestConfiguration.get("responseProfile"); } return null; } }
package ca.ualberta.cs.cmput301w15t12; import java.io.Serializable; import java.math.BigDecimal; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Locale; public class ExpenseItem implements Serializable{ private static final long serialVersionUID = -2552967637419002646L; private String name; private String category; private String description; private BigDecimal Amount; private String Currency; private Date date; private boolean flag; private boolean receipt; public ExpenseItem(String name,String category, String description, String currency, BigDecimal amount, Date date){ this.name = name; this.category = category; this.description = description; this.Amount = amount; this.Currency = currency; this.date = date; this.flag = false; this.receipt = false; } //for printing the list of expense items public String toStringList() { String d = df.format(date); String block = "["+d+"] "+name+"\n"+category+" - "+Amount+" "+Currency+"\n"+description; return block; } public String toEmail() { String ds = df.format(date); String string = name+"\n"; string += category+"\n"+description+"\n"; string += ds+"\n"+toACString()+"\n"; return string; } //returns string format of Amount and Currency --> for printing the total List public String toACString() { return Amount.toString()+" "+this.Currency; } - public void incomplete() { - if (name == null || category == null || description == null || Amount == null || Currency == null || date == null){ - flag = true; - } - } //getters and setters for the attributes public boolean getFlag() { return flag; } public void setFlag(boolean flag) { this.flag = flag; } public boolean getReceipt(){ return receipt; } public void setReceipt(boolean receipt){ this.receipt = receipt; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getCategory() { return category; } public void setCategory(String category) { this.category = category; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public Date getDate() { return date; } public void setDate(Date date) { this.date = date; } public BigDecimal getAmount() { return Amount; } public void setAmount(BigDecimal amount) { this.Amount = amount; } public String getCurrency() { return Currency; } public void setCurrency(String currency){ this.Currency = currency; } }
package som.primitives.arrays; import som.interpreter.Invokable; import som.interpreter.nodes.dispatch.AbstractDispatchNode; import som.interpreter.nodes.dispatch.UninitializedValuePrimDispatchNode; import som.interpreter.nodes.nary.BinaryExpressionNode; import som.primitives.BlockPrims.ValuePrimitiveNode; import som.primitives.LengthPrim; import som.vm.constants.Nil; import som.vmobjects.SArray; import som.vmobjects.SArray.ArrayType; import som.vmobjects.SBlock; import som.vmobjects.SObject; import com.oracle.truffle.api.CompilerAsserts; import com.oracle.truffle.api.CompilerDirectives; import com.oracle.truffle.api.dsl.NodeChild; import com.oracle.truffle.api.dsl.Specialization; import com.oracle.truffle.api.frame.VirtualFrame; import com.oracle.truffle.api.nodes.Node; import com.oracle.truffle.api.nodes.RootNode; @NodeChild(value = "length", type = LengthPrim.class, executeWith = "receiver") public abstract class PutAllNode extends BinaryExpressionNode implements ValuePrimitiveNode { @Child private AbstractDispatchNode block; public PutAllNode() { super(null); block = new UninitializedValuePrimDispatchNode(); } @Override public void adoptNewDispatchListHead(final AbstractDispatchNode node) { block = insert(node); } protected final static boolean notABlock(final SArray rcvr, final Object value) { return !(value instanceof SBlock); } protected final static boolean valueIsNil(final SArray rcvr, final SObject value) { return value == Nil.nilObject; } public final static boolean isEmptyType(final SArray receiver) { return receiver.getType() == ArrayType.EMPTY; } public final static boolean isPartiallyEmptyType(final SArray receiver) { return receiver.getType() == ArrayType.PARTIAL_EMPTY; } public final static boolean isObjectType(final SArray receiver) { return receiver.getType() == ArrayType.OBJECT; } protected final static boolean valueNeitherLongNorDouble(final SArray rcvr, final Object value) { return !(value instanceof Long) && !(value instanceof Double); } @Specialization(guards = {"isEmptyType", "valueIsNil"}) public SArray doPutNilInEmptyArray(final SArray rcvr, final SObject nil, final long length) { // NO OP return rcvr; } @Specialization(guards = {"valueIsNil"}, contains = {"doPutNilInEmptyArray"}) public SArray doPutNilInOtherArray(final SArray rcvr, final SObject nil, final long length) { rcvr.transitionToEmpty(length); return rcvr; } private void evalBlockForRemaining(final VirtualFrame frame, final SBlock block, final long length, final Object[] storage) { for (int i = SArray.FIRST_IDX + 1; i < length; i++) { storage[i] = this.block.executeDispatch(frame, new Object[] {block}); } } @Specialization public SArray doPutEvalBlock(final VirtualFrame frame, final SArray rcvr, final SBlock block, final long length) { if (length <= 0) { return rcvr; } try { Object result = this.block.executeDispatch(frame, new Object[] {block}); Object[] newStorage = new Object[(int) length]; newStorage[0] = result; evalBlockForRemaining(frame, block, length, newStorage); rcvr.transitionToObject(newStorage); } finally { if (CompilerDirectives.inInterpreter()) { reportLoopCount(length); } } return rcvr; } protected final void reportLoopCount(final long count) { if (count == 0) { return; } CompilerAsserts.neverPartOfCompilation("reportLoopCount"); Node current = getParent(); while (current != null && !(current instanceof RootNode)) { current = current.getParent(); } if (current != null) { ((Invokable) current).propagateLoopCountThroughoutLexicalScope(count); } } @Specialization public SArray doPutLong(final SArray rcvr, final long value, final long length) { rcvr.transitionToLongWithAll(length, value); return rcvr; } @Specialization public SArray doPutDouble(final SArray rcvr, final double value, final long length) { rcvr.transitionToDoubleWithAll(length, value); return rcvr; } @Specialization(guards = {"notABlock", "valueNeitherLongNorDouble"}) public SArray doPutObject(final SArray rcvr, final Object value, final long length) { rcvr.transitionToObjectWithAll(length, value); return rcvr; } }
// This file is part of the Kaltura Collaborative Media Suite which allows users // to do with audio, video, and animation what Wiki platfroms allow them to do with // text. // This program is free software: you can redistribute it and/or modify // published by the Free Software Foundation, either version 3 of the // This program is distributed in the hope that it will be useful, // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // @ignore package com.kaltura.client; import com.kaltura.client.utils.request.ConnectionConfiguration; import com.kaltura.client.types.BaseResponseProfile; /** * This class was generated using generate.php * against an XML schema provided by Kaltura. * * MANUAL CHANGES TO THIS CLASS WILL BE OVERWRITTEN. */ @SuppressWarnings("serial") public class Client extends ClientBase { public Client(ConnectionConfiguration config) { super(config); this.setClientTag("java:18-03-18"); this.setApiVersion("3.3.0"); this.clientConfiguration.put("format", 1); // JSON } /** * @param clientTag */ public void setClientTag(String clientTag){ this.clientConfiguration.put("clientTag", clientTag); } /** * @return String */ public String getClientTag(){ if(this.clientConfiguration.containsKey("clientTag")){ return(String) this.clientConfiguration.get("clientTag"); } return null; } /** * @param apiVersion */ public void setApiVersion(String apiVersion){ this.clientConfiguration.put("apiVersion", apiVersion); } /** * @return String */ public String getApiVersion(){ if(this.clientConfiguration.containsKey("apiVersion")){ return(String) this.clientConfiguration.get("apiVersion"); } return null; } /** * @param partnerId Impersonated partner id */ public void setPartnerId(Integer partnerId){ this.requestConfiguration.put("partnerId", partnerId); } /** * Impersonated partner id * * @return Integer */ public Integer getPartnerId(){ if(this.requestConfiguration.containsKey("partnerId")){ return(Integer) this.requestConfiguration.get("partnerId"); } return 0; } /** * @param ks Kaltura API session */ public void setKs(String ks){ this.requestConfiguration.put("ks", ks); } /** * Kaltura API session * * @return String */ public String getKs(){ if(this.requestConfiguration.containsKey("ks")){ return(String) this.requestConfiguration.get("ks"); } return null; } /** * @param sessionId Kaltura API session */ public void setSessionId(String sessionId){ this.requestConfiguration.put("ks", sessionId); } /** * Kaltura API session * * @return String */ public String getSessionId(){ if(this.requestConfiguration.containsKey("ks")){ return(String) this.requestConfiguration.get("ks"); } return null; } /** * @param responseProfile Response profile - this attribute will be automatically unset after every API call. */ public void setResponseProfile(BaseResponseProfile responseProfile){ this.requestConfiguration.put("responseProfile", responseProfile); } /** * Response profile - this attribute will be automatically unset after every API call. * * @return BaseResponseProfile */ public BaseResponseProfile getResponseProfile(){ if(this.requestConfiguration.containsKey("responseProfile")){ return(BaseResponseProfile) this.requestConfiguration.get("responseProfile"); } return null; } }
package claw.tatsu.xcodeml.backend; import claw.tatsu.xcodeml.xnode.common.XcodeML; import org.w3c.dom.Document; import org.xml.sax.SAXException; import xcodeml.util.*; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import java.io.*; import java.util.logging.Level; import java.util.logging.Logger; /** * Wrapper class to call the Fortran decompiler of OMNI Compiler directly * from Java instead of calling it as a separated program. * * @author clementval */ public class OmniBackendDriver { private BufferedReader _reader; private XmToolFactory _toolFactory; /** * Constructs a new OmniBackendDriver object. * * @param lang Language of output. * @throws XmException If instantiation of the XmToolFactory fails. */ public OmniBackendDriver(Lang lang) throws XmException { if(lang == Lang.FORTRAN) { _toolFactory = new XmToolFactory("F"); } else if(lang == Lang.C) { _toolFactory = new XmToolFactory("C"); } } private boolean openXcodeMLFile(String inputFilepath) { if(_reader != null) { try { _reader.close(); } catch(IOException e) { Logger.getAnonymousLogger().log(Level.SEVERE, e.getMessage()); return false; } } try { _reader = new BufferedReader(new FileReader(inputFilepath)); return true; } catch(IOException e) { return false; } } /** * Decompile the XcodeML file into Fortran code. * * @param outputFilepath Fortran output file path. * @param xcodeml XcodeML translation unit. * @param maxColumns Maximum number of column for the output file. * @param lineDirectives If true, preprocessor line directives are added. * @return True if the decompilation succeeded. False otherwise. */ public boolean decompile(String outputFilepath, XcodeML xcodeml, int maxColumns, boolean lineDirectives) { return decompile(outputFilepath, xcodeml.getDocument(), maxColumns, lineDirectives); } /** * Decompile the XcodeML file into Fortran code. * * @param outputFilepath Fortran output file path. * @param xcodeml XcodeML document. * @param maxColumns Maximum number of column for the output file. * @param lineDirectives If true, preprocessor line directives are added. * @return True if the decompilation succeeded. False otherwise. */ private boolean decompile(String outputFilepath, Document xcodeml, int maxColumns, boolean lineDirectives) { if(!lineDirectives) { XmOption.setIsSuppressLineDirective(true); } XmOption.setDebugOutput(false); PrintWriter writer = null; try { if(outputFilepath == null || outputFilepath.isEmpty()) { writer = new PrintWriter(System.out); } else { writer = new PrintWriter(new BufferedWriter(new FileWriter(outputFilepath))); } } catch(IOException e) { Logger.getAnonymousLogger().log(Level.SEVERE, e.getMessage()); } try { XmDecompiler decompiler = _toolFactory.createDecompiler(); XmDecompilerContext context = _toolFactory.createDecompilerContext(); if(maxColumns > 0) { context.setProperty(XmDecompilerContext.KEY_MAX_COLUMNS, "" + maxColumns); } decompiler.decompile(context, xcodeml, writer); if(writer != null) { writer.flush(); } else { return false; } return true; } catch(Exception ex) { if(_reader != null) { try { _reader.close(); } catch(IOException ignored) { } } if(writer != null) { writer.close(); } } return false; } /** * Decompile the XcodeML file into Fortran code. * * @param outputFilepath Fortran output file path. * @param inputFilepath XcodeML input file path. * @param maxColumns Maximum number of column for the output file. * @param lineDirectives If true, preprocessor line directives are added. * @return True if the decompilation succeeded. False otherwise. */ public boolean decompileFromFile(String outputFilepath, String inputFilepath, int maxColumns, boolean lineDirectives) { if(!openXcodeMLFile(inputFilepath)) { return false; } try { DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = docFactory.newDocumentBuilder(); Document xcodeml = builder.parse(inputFilepath); return decompile(outputFilepath, xcodeml, maxColumns, lineDirectives); } catch(ParserConfigurationException | SAXException | IOException e) { return false; } } public enum Lang { C, FORTRAN } }
// This file is part of the Kaltura Collaborative Media Suite which allows users // to do with audio, video, and animation what Wiki platforms allow them to do with // text. // This program is free software: you can redistribute it and/or modify // published by the Free Software Foundation, either version 3 of the // This program is distributed in the hope that it will be useful, // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // @ignore package com.kaltura.client; import com.kaltura.client.utils.request.ConnectionConfiguration; import com.kaltura.client.types.BaseResponseProfile; /** * This class was generated using generate.php * against an XML schema provided by Kaltura. * * MANUAL CHANGES TO THIS CLASS WILL BE OVERWRITTEN. */ @SuppressWarnings("serial") public class Client extends ClientBase { public Client(ConnectionConfiguration config) { super(config); this.setClientTag("java:22-10-05"); this.setApiVersion("18.15.0"); this.clientConfiguration.put("format", 1); // JSON } /** * @param clientTag */ public void setClientTag(String clientTag){ this.clientConfiguration.put("clientTag", clientTag); } /** * @return String */ public String getClientTag(){ if(this.clientConfiguration.containsKey("clientTag")){ return(String) this.clientConfiguration.get("clientTag"); } return null; } /** * @param apiVersion */ public void setApiVersion(String apiVersion){ this.clientConfiguration.put("apiVersion", apiVersion); } /** * @return String */ public String getApiVersion(){ if(this.clientConfiguration.containsKey("apiVersion")){ return(String) this.clientConfiguration.get("apiVersion"); } return null; } /** * @param partnerId Impersonated partner id */ public void setPartnerId(Integer partnerId){ this.requestConfiguration.put("partnerId", partnerId); } /** * Impersonated partner id * * @return Integer */ public Integer getPartnerId(){ if(this.requestConfiguration.containsKey("partnerId")){ return(Integer) this.requestConfiguration.get("partnerId"); } return 0; } /** * @param ks Kaltura API session */ public void setKs(String ks){ this.requestConfiguration.put("ks", ks); } /** * Kaltura API session * * @return String */ public String getKs(){ if(this.requestConfiguration.containsKey("ks")){ return(String) this.requestConfiguration.get("ks"); } return null; } /** * @param sessionId Kaltura API session */ public void setSessionId(String sessionId){ this.requestConfiguration.put("ks", sessionId); } /** * Kaltura API session * * @return String */ public String getSessionId(){ if(this.requestConfiguration.containsKey("ks")){ return(String) this.requestConfiguration.get("ks"); } return null; } /** * @param language language */ public void setLanguage(String language){ this.requestConfiguration.put("language", language); } /** * language * * @return String */ public String getLanguage(){ if(this.requestConfiguration.containsKey("language")){ return(String) this.requestConfiguration.get("language"); } return null; } /** * @param responseProfile Response profile - this attribute will be automatically unset after every API call. */ public void setResponseProfile(BaseResponseProfile responseProfile){ this.requestConfiguration.put("responseProfile", responseProfile); } /** * Response profile - this attribute will be automatically unset after every API call. * * @return BaseResponseProfile */ public BaseResponseProfile getResponseProfile(){ if(this.requestConfiguration.containsKey("responseProfile")){ return(BaseResponseProfile) this.requestConfiguration.get("responseProfile"); } return null; } }
// CloudCoder - a web-based pedagogical programming environment // This program is free software: you can redistribute it and/or modify // (at your option) any later version. // This program is distributed in the hope that it will be useful, // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the package org.cloudcoder.app.client.page; import org.cloudcoder.app.client.model.CourseSelection; import org.cloudcoder.app.client.model.Section; import org.cloudcoder.app.client.model.Session; import org.cloudcoder.app.client.model.StatusMessage; import org.cloudcoder.app.client.rpc.RPC; import org.cloudcoder.app.client.view.PageNavPanel; import org.cloudcoder.app.client.view.StatusMessageView; import org.cloudcoder.app.client.view.StudentProgressView; import org.cloudcoder.app.shared.model.Course; import org.cloudcoder.app.shared.model.Problem; import org.cloudcoder.app.shared.util.Publisher; import org.cloudcoder.app.shared.util.Subscriber; import org.cloudcoder.app.shared.util.SubscriptionRegistrar; import com.google.gwt.core.client.GWT; import com.google.gwt.dom.client.Style.Unit; import com.google.gwt.event.dom.client.ChangeEvent; import com.google.gwt.event.dom.client.ChangeHandler; import com.google.gwt.event.dom.client.ClickEvent; import com.google.gwt.event.dom.client.ClickHandler; import com.google.gwt.user.client.rpc.AsyncCallback; import com.google.gwt.user.client.ui.Button; import com.google.gwt.user.client.ui.Composite; import com.google.gwt.user.client.ui.DockLayoutPanel; import com.google.gwt.user.client.ui.FlowPanel; import com.google.gwt.user.client.ui.InlineHTML; import com.google.gwt.user.client.ui.InlineLabel; import com.google.gwt.user.client.ui.IsWidget; import com.google.gwt.user.client.ui.Label; import com.google.gwt.user.client.ui.LayoutPanel; import com.google.gwt.user.client.ui.ListBox; /** * Page for displaying statistics for a given {@link Problem}. * * @author David Hovemeyer */ public class StatisticsPage extends CloudCoderPage { private class UI extends Composite implements Subscriber { private static final double STATS_OPTION_PANEL_HEIGHT_PX = 28.0; private PageNavPanel pageNavPanel; private Label problemLabel; private StatusMessageView statusMessageView; private StudentProgressView studentProgressView; private Button downloadCsvButton; private ListBox chooseSectionBox; public UI() { DockLayoutPanel dockLayoutPanel = new DockLayoutPanel(Unit.PX); // North panel: problem label, page nav panel, stats options LayoutPanel northPanel = new LayoutPanel(); // page nav panel this.pageNavPanel = new PageNavPanel(); northPanel.add(pageNavPanel); northPanel.setWidgetRightWidth(pageNavPanel, 0.0, Unit.PX, PageNavPanel.WIDTH_PX, Unit.PX); northPanel.setWidgetTopHeight(pageNavPanel, 0.0, Unit.PX, PageNavPanel.HEIGHT_PX, Unit.PX); // label to display the problem name this.problemLabel = new Label(""); problemLabel.setStyleName("cc-problemName", true); northPanel.add(problemLabel); northPanel.setWidgetLeftRight(problemLabel, 0.0, Unit.PX, PageNavPanel.WIDTH_PX, Unit.PX); northPanel.setWidgetTopHeight(problemLabel, 0.0, Unit.PX, 22.0, Unit.PX); // stats options (choose section, sorting, download CSV) FlowPanel statsOptionPanel = new FlowPanel(); InlineLabel chooseSectionLabel = new InlineLabel("Section: "); statsOptionPanel.add(chooseSectionLabel); this.chooseSectionBox = new ListBox(); chooseSectionBox.setWidth("80px"); chooseSectionBox.addChangeHandler(new ChangeHandler() { @Override public void onChange(ChangeEvent event) { handleSectionChange(); } }); statsOptionPanel.add(chooseSectionBox); statsOptionPanel.add(new InlineHTML(" ")); this.downloadCsvButton = new Button("Download"); downloadCsvButton.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { handleDownloadCsv(); } }); statsOptionPanel.add(downloadCsvButton); // Create a hidden iframe element for the CSV download InlineHTML iframe = new InlineHTML("<iframe id=\"ccCsvDownload\" style=\"height: 1px; width: 1px; display: none;\"></iframe>"); statsOptionPanel.add(iframe); northPanel.add(statsOptionPanel); northPanel.setWidgetLeftRight(statsOptionPanel, 0.0, Unit.PX, 0.0, Unit.PX); northPanel.setWidgetBottomHeight(statsOptionPanel, 0.0, Unit.PX, STATS_OPTION_PANEL_HEIGHT_PX, Unit.PX); dockLayoutPanel.addNorth(northPanel, PageNavPanel.HEIGHT_PX + STATS_OPTION_PANEL_HEIGHT_PX); // South panel: just a status message view statusMessageView = new StatusMessageView(); dockLayoutPanel.addSouth(statusMessageView, StatusMessageView.HEIGHT_PX); // Center panel: stats view LayoutPanel centerPanel = new LayoutPanel(); this.studentProgressView = new StudentProgressView(); centerPanel.add(studentProgressView); centerPanel.setWidgetLeftRight(studentProgressView, 0.0, Unit.PX, 0.0, Unit.PX); centerPanel.setWidgetTopBottom(studentProgressView, 10.0, Unit.PX, 10.0, Unit.PX); dockLayoutPanel.add(centerPanel); initWidget(dockLayoutPanel); } private String getSectionChoice() { int selected = chooseSectionBox.getSelectedIndex(); return selected < 0 ? null : chooseSectionBox.getItemText(selected); } protected void handleSectionChange() { String choice = getSectionChoice(); if (choice != null) { // Add a Section object to the session. // The StudentProgressView listens for these events, // and updates the results appropriately. if (choice.equals("All")) { getSession().add(new Section()); // all sections } else { int section = Integer.parseInt(choice); getSession().add(new Section(section)); } } } protected void handleDownloadCsv() { // Redirect to the /admin/problems servlet with the chosen // course/problem/section Problem problem = getSession().get(Problem.class); // Build the path info string for the request, which specifies // course id and problem id, and (optionally) section number StringBuilder pathInfo = new StringBuilder(); pathInfo.append(problem.getCourseId()); String sectionChoice = getSectionChoice(); if (sectionChoice != null && !sectionChoice.equals("All")) { pathInfo.append("-"); pathInfo.append(sectionChoice); } pathInfo.append("/"); pathInfo.append(problem.getProblemId()); // Build the full URL String url = GWT.getHostPageBaseURL() + "admin/problems/" + pathInfo.toString(); // Set the src attribute in the hidden download iframe GWT.log("Redirecting iframe to " + url); doDownloadCsv(url); } private native void doDownloadCsv(String url) /*-{ var elt = $doc.getElementById("ccCsvDownload"); elt.src = url; }-*/; public void activate(final Session session, final SubscriptionRegistrar subscriptionRegistrar) { // Initially, results for all sections are shown session.add(new Section()); // Activate views statusMessageView.activate(session, subscriptionRegistrar); studentProgressView.activate(session, subscriptionRegistrar); // Set title Problem problem = session.get(Problem.class); CourseSelection courseSelection = session.get(CourseSelection.class); problemLabel.setText("Statistics for " + problem.toNiceString() + " in " + courseSelection.getCourse().getName()); // Set section numbers chooseSectionBox.addItem("All"); RPC.getCoursesAndProblemsService.getSectionsForCourse(courseSelection.getCourse(), new AsyncCallback<Integer[]>() { @Override public void onSuccess(Integer[] result) { for (Integer section : result) { chooseSectionBox.addItem(section.toString()); } } @Override public void onFailure(Throwable caught) { session.add(StatusMessage.error("Couldn't get section numbers for course", caught)); } }); // Set back/logout handlers pageNavPanel.setBackHandler(new Runnable() { @Override public void run() { // Go back to course admin page session.notifySubscribers(Session.Event.COURSE_ADMIN, session.get(Course.class)); } }); pageNavPanel.setLogoutHandler(new LogoutHandler(session)); } @Override public void eventOccurred(Object key, Publisher publisher, Object hint) { // TODO Auto-generated method stub } } private UI ui; @Override public void createWidget() { this.ui = new UI(); } @Override public void activate() { ui.activate(getSession(), getSubscriptionRegistrar()); } @Override public void deactivate() { getSubscriptionRegistrar().cancelAllSubscriptions(); } @Override public IsWidget getWidget() { return ui; } @Override public boolean isActivity() { return true; } }
// This file is part of the Kaltura Collaborative Media Suite which allows users // to do with audio, video, and animation what Wiki platforms allow them to do with // text. // This program is free software: you can redistribute it and/or modify // published by the Free Software Foundation, either version 3 of the // This program is distributed in the hope that it will be useful, // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // @ignore package com.kaltura.client; import com.kaltura.client.utils.request.ConnectionConfiguration; import com.kaltura.client.types.BaseResponseProfile; /** * This class was generated using generate.php * against an XML schema provided by Kaltura. * * MANUAL CHANGES TO THIS CLASS WILL BE OVERWRITTEN. */ @SuppressWarnings("serial") public class Client extends ClientBase { public Client(ConnectionConfiguration config) { super(config); this.setClientTag("java:21-06-09"); this.setApiVersion("17.2.0"); this.clientConfiguration.put("format", 1); // JSON } /** * @param clientTag */ public void setClientTag(String clientTag){ this.clientConfiguration.put("clientTag", clientTag); } /** * @return String */ public String getClientTag(){ if(this.clientConfiguration.containsKey("clientTag")){ return(String) this.clientConfiguration.get("clientTag"); } return null; } /** * @param apiVersion */ public void setApiVersion(String apiVersion){ this.clientConfiguration.put("apiVersion", apiVersion); } /** * @return String */ public String getApiVersion(){ if(this.clientConfiguration.containsKey("apiVersion")){ return(String) this.clientConfiguration.get("apiVersion"); } return null; } /** * @param partnerId Impersonated partner id */ public void setPartnerId(Integer partnerId){ this.requestConfiguration.put("partnerId", partnerId); } /** * Impersonated partner id * * @return Integer */ public Integer getPartnerId(){ if(this.requestConfiguration.containsKey("partnerId")){ return(Integer) this.requestConfiguration.get("partnerId"); } return 0; } /** * @param ks Kaltura API session */ public void setKs(String ks){ this.requestConfiguration.put("ks", ks); } /** * Kaltura API session * * @return String */ public String getKs(){ if(this.requestConfiguration.containsKey("ks")){ return(String) this.requestConfiguration.get("ks"); } return null; } /** * @param sessionId Kaltura API session */ public void setSessionId(String sessionId){ this.requestConfiguration.put("ks", sessionId); } /** * Kaltura API session * * @return String */ public String getSessionId(){ if(this.requestConfiguration.containsKey("ks")){ return(String) this.requestConfiguration.get("ks"); } return null; } /** * @param responseProfile Response profile - this attribute will be automatically unset after every API call. */ public void setResponseProfile(BaseResponseProfile responseProfile){ this.requestConfiguration.put("responseProfile", responseProfile); } /** * Response profile - this attribute will be automatically unset after every API call. * * @return BaseResponseProfile */ public BaseResponseProfile getResponseProfile(){ if(this.requestConfiguration.containsKey("responseProfile")){ return(BaseResponseProfile) this.requestConfiguration.get("responseProfile"); } return null; } }
package example.armeria.grpc; import static example.armeria.grpc.HelloServiceImpl.toMessage; import static example.armeria.grpc.Main.configureServices; import static org.assertj.core.api.Assertions.assertThat; import static org.awaitility.Awaitility.await; import java.time.Duration; import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.RegisterExtension; import com.google.common.base.Stopwatch; import com.google.common.util.concurrent.FutureCallback; import com.google.common.util.concurrent.Futures; import com.google.common.util.concurrent.ListenableFuture; import com.google.common.util.concurrent.MoreExecutors; import com.google.protobuf.InvalidProtocolBufferException; import com.google.protobuf.util.JsonFormat; import com.linecorp.armeria.client.WebClient; import com.linecorp.armeria.client.grpc.GrpcClients; import com.linecorp.armeria.common.grpc.GrpcSerializationFormats; import com.linecorp.armeria.server.ServerBuilder; import com.linecorp.armeria.testing.junit5.server.ServerExtension; import example.armeria.grpc.Hello.HelloReply; import example.armeria.grpc.Hello.HelloRequest; import example.armeria.grpc.HelloServiceGrpc.HelloServiceBlockingStub; import example.armeria.grpc.HelloServiceGrpc.HelloServiceFutureStub; import example.armeria.grpc.HelloServiceGrpc.HelloServiceStub; import io.grpc.stub.StreamObserver; class HelloServiceTest { @RegisterExtension static final ServerExtension server = new ServerExtension() { @Override protected void configure(ServerBuilder sb) throws Exception { configureServices(sb); } }; @Test void getReply() { final HelloServiceBlockingStub helloService = GrpcClients.newClient(uri(), HelloServiceBlockingStub.class); assertThat(helloService.hello(HelloRequest.newBuilder().setName("Armeria").build()).getMessage()) .isEqualTo("Hello, Armeria!"); } @Test void testsTheErrorUnframedResponseWithJsonContentType() throws InvalidProtocolBufferException { final WebClient client = WebClient.builder(server.httpUri()) .addHeader("content-type", "application/json; charset=utf-8; protocol=gRPC") .build(); final String response = client.post("example.grpc.hello.HelloService/Hello", JsonFormat.printer().print(HelloRequest.getDefaultInstance())) .aggregate() .join() .contentUtf8(); assertThat(response).startsWith( "{\"grpc-code\":\"FAILED_PRECONDITION\",\"message\":\"Name cannot be empty\"," + "\"stack-trace\":\"io.grpc.StatusException"); } @Test void getReplyWithDelay() { final HelloServiceFutureStub helloService = GrpcClients.newClient(uri(), HelloServiceFutureStub.class); final ListenableFuture<HelloReply> future = helloService.lazyHello(HelloRequest.newBuilder().setName("Armeria").build()); final AtomicBoolean completed = new AtomicBoolean(); Futures.addCallback(future, new FutureCallback<>() { @Override public void onSuccess(HelloReply result) { assertThat(result.getMessage()).isEqualTo("Hello, Armeria!"); completed.set(true); } @Override public void onFailure(Throwable t) { // Should never reach here. throw new Error(t); } }, MoreExecutors.directExecutor()); await().untilTrue(completed); } @Test void getReplyFromServerSideBlockingCall() { final HelloServiceBlockingStub helloService = GrpcClients.newClient(uri(), HelloServiceBlockingStub.class); final Stopwatch watch = Stopwatch.createStarted(); assertThat(helloService.blockingHello(HelloRequest.newBuilder().setName("Armeria").build()) .getMessage()).isEqualTo("Hello, Armeria!"); assertThat(watch.elapsed(TimeUnit.SECONDS)).isGreaterThanOrEqualTo(3); } @Test void getLotsOfReplies() { final HelloServiceStub helloService = helloService(); final AtomicBoolean completed = new AtomicBoolean(); final AtomicInteger sequence = new AtomicInteger(); helloService.lotsOfReplies( HelloRequest.newBuilder().setName("Armeria").build(), new StreamObserver<>() { @Override public void onNext(HelloReply value) { assertThat(value.getMessage()) .isEqualTo("Hello, Armeria! (sequence: " + sequence.incrementAndGet() + ')'); } @Override public void onError(Throwable t) { // Should never reach here. throw new Error(t); } @Override public void onCompleted() { assertThat(sequence).hasValue(5); completed.set(true); } }); await().atMost(Duration.ofSeconds(15)) .untilAsserted(() -> assertThat(completed) .overridingErrorMessage(() -> "sequence is " + sequence) .isTrue()); } @Test void blockForLotsOfReplies() throws Exception { final HelloServiceStub helloService = helloService(); final BlockingQueue<HelloReply> replies = new LinkedBlockingQueue<>(); final AtomicBoolean completed = new AtomicBoolean(); helloService.lotsOfReplies( HelloRequest.newBuilder().setName("Armeria").build(), new StreamObserver<>() { @Override public void onNext(HelloReply value) { replies.offer(value); } @Override public void onError(Throwable t) { // Should never reach here. throw new Error(t); } @Override public void onCompleted() { completed.set(true); } }); int sequence = 0; while (!completed.get() || !replies.isEmpty()) { final HelloReply value = replies.poll(100, TimeUnit.MILLISECONDS); if (value == null) { // Timed out, try again. continue; } assertThat(value.getMessage()) .isEqualTo("Hello, Armeria! (sequence: " + ++sequence + ')'); } assertThat(sequence).isEqualTo(5); } @Test void sendLotsOfGreetings() { final HelloServiceStub helloService = helloService(); final String[] names = { "Armeria", "Grpc", "Streaming" }; final AtomicBoolean completed = new AtomicBoolean(); final StreamObserver<HelloRequest> request = helloService.lotsOfGreetings(new StreamObserver<>() { private boolean received; @Override public void onNext(HelloReply value) { assertThat(received).isFalse(); received = true; assertThat(value.getMessage()) .isEqualTo(toMessage(String.join(", ", names))); } @Override public void onError(Throwable t) { // Should never reach here. throw new Error(t); } @Override public void onCompleted() { assertThat(received).isTrue(); completed.set(true); } }); for (String name : names) { request.onNext(HelloRequest.newBuilder().setName(name).build()); } request.onCompleted(); await().untilTrue(completed); } @Test void bidirectionalHello() { final HelloServiceStub helloService = helloService(); final String[] names = { "Armeria", "Grpc", "Streaming" }; final AtomicBoolean completed = new AtomicBoolean(); final StreamObserver<HelloRequest> request = helloService.bidiHello(new StreamObserver<>() { private int received; @Override public void onNext(HelloReply value) { assertThat(value.getMessage()) .isEqualTo(toMessage(names[received++])); } @Override public void onError(Throwable t) { // Should never reach here. throw new Error(t); } @Override public void onCompleted() { assertThat(received).isEqualTo(names.length); completed.set(true); } }); for (String name : names) { request.onNext(HelloRequest.newBuilder().setName(name).build()); } request.onCompleted(); await().untilTrue(completed); } private static HelloServiceStub helloService() { return GrpcClients.newClient(uri(), HelloServiceStub.class); } private static String uri() { return server.httpUri(GrpcSerializationFormats.PROTO).toString(); } }
package com.knewton.mrtool.io; import com.knewton.mrtool.util.ObjectDecorator; import com.google.common.collect.Lists; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonDeserializer; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FSDataInputStream; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.io.LongWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.io.Writable; import org.apache.hadoop.io.compress.CompressionCodec; import org.apache.hadoop.io.compress.CompressionCodecFactory; import org.apache.hadoop.mapreduce.InputSplit; import org.apache.hadoop.mapreduce.RecordReader; import org.apache.hadoop.mapreduce.TaskAttemptContext; import org.apache.hadoop.mapreduce.lib.input.FileSplit; import org.apache.hadoop.util.LineReader; import java.io.IOException; import java.lang.reflect.Type; import java.util.List; /** * JSON record reader that reads files containing json objects and returns back a deserialized * instantiated object of type V. The json deserialization happens with gson. Note that this record * reader doesn't yet take advantage of splittable compressed codecs. * * @author Giannis Neokleous * * @param <V> */ // TODO: Add support for splittable compressed codecs. public abstract class JsonRecordReader<V extends Writable> extends RecordReader<LongWritable, V> { private LongWritable key; private V value; private long start; private long end; private CompressionCodecFactory compressionCodecs; private LineReader in; private long pos; private Gson gson; private GsonBuilder gsonBuilder; private List<ObjectDecorator<String>> decorators; public static final String APPEND_FILENAME_TO_JSON = "com.knewton.mapreduce.jsonrecordreader.append_filename"; public JsonRecordReader() { gsonBuilder = new GsonBuilder(); decorators = Lists.newArrayList(); gson = gsonBuilder.create(); } /** * Should be called before any key or value is read to setup any initialization actions. If you * want to inject the name of the file to the json record set the * {@link JsonRecordReader.APPEND_FILENAME_TO_JSON} property to true. */ @Override public void initialize(InputSplit split, TaskAttemptContext context) throws IOException, InterruptedException { Configuration conf = context.getConfiguration(); FileSplit fileSplit = (FileSplit) split; start = fileSplit.getStart(); end = start + fileSplit.getLength(); compressionCodecs = new CompressionCodecFactory(conf); in = initLineReader(fileSplit, conf); pos = start; } /** * Get the line reader to be used for the file. A <code>LineReader</code> can read a file line * by line. This separate method helps with testing too. * * @param fileSplit * @param conf * @return * @throws IOException */ protected LineReader initLineReader(FileSplit fileSplit, Configuration conf) throws IOException { final Path file = fileSplit.getPath(); final CompressionCodec codec = compressionCodecs.getCodec(file); FileSystem fs = file.getFileSystem(conf); FSDataInputStream fileIn = fs.open(fileSplit.getPath()); boolean skipFirstLine = false; LineReader lineReader; if (codec != null) { lineReader = new LineReader(codec.createInputStream(fileIn), conf); end = Long.MAX_VALUE; } else { // if the start is not the beginning of the file then skip the first line to get the // next complete json record. The previous json record will be read by the record reader // that got assigned the previous InputSplit. if (start != 0) { skipFirstLine = true; --start; fileIn.seek(start); } lineReader = new LineReader(fileIn, conf); } if (skipFirstLine) { start += lineReader.readLine(new Text(), 0, (int) Math.min((long) Integer.MAX_VALUE, end - start)); } return lineReader; } /** * {@inheritDoc} */ @Override public boolean nextKeyValue() throws IOException, InterruptedException { // This is here in case nextKeyValue() gets called again after the record reader reached the // end of the split and doesn't have any more records to return. It avoids a null pointer // exception. if (key == null) { key = new LongWritable(); } key.set(pos); Text jsonText = new Text(); int newSize = 0; if (pos < end) { newSize = in.readLine(jsonText); if (newSize > 0 && !jsonText.toString().isEmpty()) { for (ObjectDecorator<String> decorator : decorators) { jsonText = new Text( decorator.decorateObject(jsonText.toString())); } // This helps with avoiding to supress warnings for the entire method. @SuppressWarnings("unchecked") V tempValue = (V) gson.fromJson(jsonText.toString(), getDataClass(jsonText.toString())); value = tempValue; } pos += newSize; } if (newSize == 0 || jsonText.toString().isEmpty()) { key = null; value = null; return false; } else { return true; } } /** * {@inheritDoc} */ @Override public LongWritable getCurrentKey() throws IOException, InterruptedException { return key; } /** * {@inheritDoc} */ @Override public V getCurrentValue() throws IOException, InterruptedException { return value; } /** * {@inheritDoc} */ @Override public float getProgress() throws IOException, InterruptedException { if (start == end) { return 0.0f; } else { return Math.max(0.0f, Math.min(1.0f, (pos - start) / (float) (end - start))); } } /** * {@inheritDoc} */ @Override public void close() throws IOException { if (in != null) { in.close(); } } /** * * @return The compression factory to be used when reading files. */ public CompressionCodecFactory getCompressionCodecFactory() { return compressionCodecs; } /** * Adds a decorator for this record reader. Decorators modify each record read. To define your * own decorator you can inherit from {@link ObjectDecorator} * * @param decorator */ public void addDecorator(ObjectDecorator<String> decorator) { decorators.add(decorator); } /** * Needs to be implemented by the subclass to return the type of object that needs to be * instantiated * * @param jsonStr * Useful if information about the type of the object is contained inside the JSON * string. * @return Class to be instantiated */ protected abstract Class<?> getDataClass(String jsonStr); /** * Registers a deserializer for deserializing a custom object from a Json string * * @param type * @param jsonDes */ public void registerDeserializer(Type type, JsonDeserializer<?> jsonDes) { gsonBuilder.registerTypeAdapter(type, jsonDes); } }
package com.jme3.post; import com.jme3.export.JmeExporter; import com.jme3.export.JmeImporter; import com.jme3.renderer.Renderer; import com.jme3.renderer.queue.RenderQueue; import com.jme3.asset.AssetManager; import com.jme3.export.InputCapsule; import com.jme3.export.OutputCapsule; import com.jme3.export.Savable; import com.jme3.material.Material; import com.jme3.material.RenderState; import com.jme3.renderer.Camera; import com.jme3.renderer.Caps; import com.jme3.renderer.RenderManager; import com.jme3.renderer.ViewPort; import com.jme3.texture.FrameBuffer; import com.jme3.texture.Image.Format; import com.jme3.texture.Texture2D; import com.jme3.ui.Picture; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.List; public class FilterPostProcessor implements SceneProcessor, Savable { private RenderManager renderManager; private Renderer renderer; private ViewPort viewPort; private FrameBuffer renderFrameBufferMS; private int numSamples = 1; private FrameBuffer renderFrameBuffer; private Texture2D filterTexture; private Texture2D depthTexture; private List<Filter> filters = new ArrayList<Filter>(); private AssetManager assetManager; private Camera filterCam = new Camera(1, 1); private Picture fsQuad; private boolean computeDepth = false; private FrameBuffer outputBuffer; private int width; private int height; private float bottom; private float left; private float right; private float top; private int originalWidth; private int originalHeight; private int lastFilterIndex = -1; private boolean cameraInit = false; /** * Create a FilterProcessor * @param assetManager the assetManager */ public FilterPostProcessor(AssetManager assetManager) { this.assetManager = assetManager; } /** * Don't use this constructor use {@link FilterPostProcessor(AssetManager assetManager)}<br> * This constructor is used for serialization only */ public FilterPostProcessor() { } /** * Adds a filter to the filters list<br> * @param filter the filter to add */ public void addFilter(Filter filter) { filters.add(filter); filter.setProcessor(this); if (isInitialized()) { initFilter(filter, viewPort); } setFilterState(filter, filter.isEnabled()); } /** * removes this filters from the filters list * @param filter */ public void removeFilter(Filter filter) { filters.remove(filter); filter.cleanup(renderer); updateLastFilterIndex(); } public Iterator<Filter> getFilterIterator(){ return filters.iterator(); } public void initialize(RenderManager rm, ViewPort vp) { renderManager = rm; renderer = rm.getRenderer(); viewPort = vp; fsQuad = new Picture("filter full screen quad"); Camera cam = vp.getCamera(); //save view port diensions left = cam.getViewPortLeft(); right = cam.getViewPortRight(); top = cam.getViewPortTop(); bottom = cam.getViewPortBottom(); originalWidth = cam.getWidth(); originalHeight = cam.getHeight(); //first call to reshape reshape(vp, cam.getWidth(), cam.getHeight()); } /** * init the given filter * @param filter * @param vp */ private void initFilter(Filter filter, ViewPort vp) { filter.init(assetManager, renderManager, vp, width, height); if (filter.isRequiresDepthTexture()) { if (!computeDepth && renderFrameBuffer != null) { depthTexture = new Texture2D(width, height, Format.Depth24); renderFrameBuffer.setDepthTexture(depthTexture); } computeDepth = true; filter.getMaterial().setTexture("DepthTexture", depthTexture); } } /** * renders a filter on a fullscreen quad * @param r * @param buff * @param mat */ private void renderProcessing(Renderer r, FrameBuffer buff, Material mat) { if (buff == outputBuffer) { fsQuad.setWidth(width); fsQuad.setHeight(height); filterCam.resize(originalWidth, originalHeight, true); fsQuad.setPosition(left * originalWidth, bottom * originalHeight); } else { fsQuad.setWidth(buff.getWidth()); fsQuad.setHeight(buff.getHeight()); filterCam.resize(buff.getWidth(), buff.getHeight(), true); fsQuad.setPosition(0, 0); } if (mat.getAdditionalRenderState().isDepthWrite()) { mat.getAdditionalRenderState().setDepthTest(false); mat.getAdditionalRenderState().setDepthWrite(false); } fsQuad.setMaterial(mat); fsQuad.updateGeometricState(); renderManager.setCamera(filterCam, true); r.setFrameBuffer(buff); r.clearBuffers(false, true, true); renderManager.renderGeometry(fsQuad); } public boolean isInitialized() { return viewPort != null; } public void postQueue(RenderQueue rq) { for (Iterator<Filter> it = filters.iterator(); it.hasNext();) { Filter filter = it.next(); if (filter.isEnabled()) { filter.postQueue(renderManager, viewPort); } } } Picture pic = new Picture("debug"); /** * iterate through the filter list and renders filters * @param r * @param sceneFb */ private void renderFilterChain(Renderer r, FrameBuffer sceneFb) { Texture2D tex = filterTexture; FrameBuffer buff = sceneFb; boolean msDepth = depthTexture != null && depthTexture.getImage().getMultiSamples() > 1; for (int i = 0; i < filters.size(); i++) { Filter filter = filters.get(i); if (filter.isEnabled()) { if (filter.getPostRenderPasses() != null) { for (Iterator<Filter.Pass> it1 = filter.getPostRenderPasses().iterator(); it1.hasNext();) { Filter.Pass pass = it1.next(); pass.beforeRender(); if (pass.requiresSceneAsTexture()) { pass.getPassMaterial().setTexture("Texture", tex); if (tex.getImage().getMultiSamples() > 1) { pass.getPassMaterial().setInt("NumSamples", tex.getImage().getMultiSamples()); } else { pass.getPassMaterial().clearParam("NumSamples"); } } if (pass.requiresDepthAsTexture()) { pass.getPassMaterial().setTexture("DepthTexture", depthTexture); if (msDepth) { pass.getPassMaterial().setInt("NumSamplesDepth", depthTexture.getImage().getMultiSamples()); } else { pass.getPassMaterial().clearParam("NumSamplesDepth"); } } renderProcessing(r, pass.getRenderFrameBuffer(), pass.getPassMaterial()); } } filter.postFrame(renderManager, viewPort, buff, sceneFb); Material mat = filter.getMaterial(); if (msDepth && filter.isRequiresDepthTexture()) { mat.setInt("NumSamplesDepth", depthTexture.getImage().getMultiSamples()); } if (filter.isRequiresSceneTexture()) { mat.setTexture("Texture", tex); if (tex.getImage().getMultiSamples() > 1) { mat.setInt("NumSamples", tex.getImage().getMultiSamples()); } else { mat.clearParam("NumSamples"); } } buff = outputBuffer; if (i != lastFilterIndex) { buff = filter.getRenderFrameBuffer(); tex = filter.getRenderedTexture(); } renderProcessing(r, buff, mat); } } } public void postFrame(FrameBuffer out) { FrameBuffer sceneBuffer = renderFrameBuffer; if (renderFrameBufferMS != null && !renderer.getCaps().contains(Caps.OpenGL31)) { renderer.copyFrameBuffer(renderFrameBufferMS, renderFrameBuffer); } else if (renderFrameBufferMS != null) { sceneBuffer = renderFrameBufferMS; } renderFilterChain(renderer, sceneBuffer); renderManager.setCamera(viewPort.getCamera(), false); renderer.setFrameBuffer(outputBuffer); } public void preFrame(float tpf) { if (filters.isEmpty() || lastFilterIndex == -1) { //If the camera is initialized and there are no filter to render, the camera viewport is restored as it was if (cameraInit) { viewPort.getCamera().resize(originalWidth, originalHeight, true); viewPort.getCamera().setViewPort(left, right, bottom, top); viewPort.setOutputFrameBuffer(outputBuffer); cameraInit = false; } } else { if (renderFrameBufferMS != null) { viewPort.setOutputFrameBuffer(renderFrameBufferMS); } else { viewPort.setOutputFrameBuffer(renderFrameBuffer); } //init of the camera if it wasn't already if (!cameraInit) { viewPort.getCamera().resize(width, height, true); viewPort.getCamera().setViewPort(0, 1, 0, 1); } } for (Iterator<Filter> it = filters.iterator(); it.hasNext();) { Filter filter = it.next(); if (filter.isEnabled()) { filter.preFrame(tpf); } } } /** * sets the filter to enabled or disabled * @param filter * @param enabled */ protected void setFilterState(Filter filter, boolean enabled) { if (filters.contains(filter)) { filter.enabled = enabled; updateLastFilterIndex(); } } /** * compute the index of the last filter to render */ private void updateLastFilterIndex() { lastFilterIndex = -1; for (int i = filters.size() - 1; i >= 0 && lastFilterIndex == -1; i if (filters.get(i).isEnabled()) { lastFilterIndex = i; return; } } if (lastFilterIndex == -1) { cleanup(); } } public void cleanup() { if (viewPort != null) { //reseting the viewport camera viewport to its initial value viewPort.getCamera().resize(originalWidth, originalHeight, true); viewPort.getCamera().setViewPort(left, right, bottom, top); viewPort.setOutputFrameBuffer(outputBuffer); viewPort = null; } } public void reshape(ViewPort vp, int w, int h) { //this has no effect at first init but is useful when resizing the canvas with multi views Camera cam = vp.getCamera(); cam.setViewPort(left, right, bottom, top); //resizing the camera to fit the new viewport and saving original dimensions cam.resize(w, h, false); left = cam.getViewPortLeft(); right = cam.getViewPortRight(); top = cam.getViewPortTop(); bottom = cam.getViewPortBottom(); originalWidth = w; originalHeight = h; cam.setViewPort(0, 1, 0, 1); //computing real dimension of the viewport and resizing he camera width = (int) (w * (Math.abs(right - left))); height = (int) (h * (Math.abs(bottom - top))); width = Math.max(1, width); height = Math.max(1, height); cam.resize(width, height, false); cameraInit = true; computeDepth = false; if (renderFrameBuffer == null) { outputBuffer = viewPort.getOutputFrameBuffer(); } Collection<Caps> caps = renderer.getCaps(); //antialiasing on filters only supported in opengl 3 due to depth read problem if (numSamples > 1 && caps.contains(Caps.FrameBufferMultisample)) { renderFrameBufferMS = new FrameBuffer(width, height, numSamples); if (caps.contains(Caps.OpenGL31)) { Texture2D msColor = new Texture2D(width, height, numSamples, Format.RGBA8); Texture2D msDepth = new Texture2D(width, height, numSamples, Format.Depth); renderFrameBufferMS.setDepthTexture(msDepth); renderFrameBufferMS.setColorTexture(msColor); filterTexture = msColor; depthTexture = msDepth; } else { renderFrameBufferMS.setDepthBuffer(Format.Depth); renderFrameBufferMS.setColorBuffer(Format.RGBA8); } } if (numSamples <= 1 || !caps.contains(Caps.OpenGL31)) { renderFrameBuffer = new FrameBuffer(width, height, 1); renderFrameBuffer.setDepthBuffer(Format.Depth); filterTexture = new Texture2D(width, height, Format.RGBA8); renderFrameBuffer.setColorTexture(filterTexture); } for (Iterator<Filter> it = filters.iterator(); it.hasNext();) { Filter filter = it.next(); initFilter(filter, vp); } if (renderFrameBufferMS != null) { viewPort.setOutputFrameBuffer(renderFrameBufferMS); } else { viewPort.setOutputFrameBuffer(renderFrameBuffer); } } /** * return the number of samples for antialiasing * @return numSamples */ public int getNumSamples() { return numSamples; } /** * * Removes all the filters from this processor */ public void removeAllFilters() { filters.clear(); updateLastFilterIndex(); } /** * Sets the number of samples for antialiasing * @param numSamples the number of Samples */ public void setNumSamples(int numSamples) { if (numSamples <= 0) { throw new IllegalArgumentException("numSamples must be > 0"); } this.numSamples = numSamples; } /** * Sets the asset manager for this processor * @param assetManager */ public void setAssetManager(AssetManager assetManager) { this.assetManager = assetManager; } public void write(JmeExporter ex) throws IOException { OutputCapsule oc = ex.getCapsule(this); oc.write(numSamples, "numSamples", 0); oc.writeSavableArrayList((ArrayList) filters, "filters", null); } public void read(JmeImporter im) throws IOException { InputCapsule ic = im.getCapsule(this); numSamples = ic.readInt("numSamples", 0); filters = ic.readSavableArrayList("filters", null); assetManager = im.getAssetManager(); } /** * For internal use only<br> * returns the depth texture of the scene * @return */ public Texture2D getDepthTexture() { return depthTexture; } /** * For internal use only<br> * returns the rendered texture of the scene * @return */ public Texture2D getFilterTexture() { return filterTexture; } }
package com.kolich.havalo; import static com.kolich.havalo.HavaloConfigurationFactory.HAVALO_ADMIN_API_SECRET_PROPERTY; import static com.kolich.havalo.HavaloConfigurationFactory.HAVALO_ADMIN_API_UUID_PROPERTY; import static com.kolich.havalo.HavaloConfigurationFactory.HAVALO_REPO_BASE_CONFIG_PROPERTY; import static com.kolich.havalo.HavaloConfigurationFactory.getConfigInstance; import static com.kolich.havalo.HavaloConfigurationFactory.getHavaloAdminSecret; import static com.kolich.havalo.HavaloConfigurationFactory.getHavaloAdminUUID; import static com.kolich.havalo.HavaloConfigurationFactory.getMaxFilenameLength; import static com.kolich.havalo.HavaloConfigurationFactory.getRepositoryBase; import static com.kolich.havalo.entities.types.UserRole.ADMIN; import static org.apache.commons.lang3.StringUtils.abbreviate; import static org.slf4j.LoggerFactory.getLogger; import java.io.File; import java.util.Arrays; import java.util.UUID; import javax.servlet.ServletContext; import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; import org.slf4j.Logger; import com.kolich.havalo.entities.types.HavaloUUID; import com.kolich.havalo.entities.types.KeyPair; import com.kolich.havalo.entities.types.UserRole; import com.kolich.havalo.exceptions.BootstrapException; import com.kolich.havalo.exceptions.repositories.RepositoryCreationException; import com.kolich.havalo.io.managers.RepositoryManager; import com.kolich.havalo.servlets.auth.HavaloAuthenticator; import com.kolich.havalo.servlets.auth.HavaloUserService; import com.typesafe.config.Config; public final class HavaloServletContext implements ServletContextListener { private static final Logger logger__ = getLogger(HavaloServletContext.class); public static final String HAVALO_CONTEXT_REPO_MANAGER_ATTRIBUTE = "havalo.repomanager"; public static final String HAVALO_CONTEXT_USER_SERVICE_ATTRIBUTE = "havalo.userservice"; public static final String HAVALO_CONTEXT_AUTHENTICATOR_ATTRIBUTE = "havalo.authenticator"; private static final String REPO_BASE_DEFAULT = "WEB-INF/work"; private ServletContext context_; @Override public void contextInitialized(final ServletContextEvent event) { logger__.info("Servlet context initialized."); // Get the default servlet context. context_ = event.getServletContext(); final Config config = getConfigInstance(); // Create a new repository manager based on the desired // underlying repository root directory on disk. final RepositoryManager repoManager = createInitialAdminRepository(context_, config); context_.setAttribute(HAVALO_CONTEXT_REPO_MANAGER_ATTRIBUTE, repoManager); // Create a new user lookup (auth) service. final HavaloUserService userService = createUserService(repoManager); context_.setAttribute(HAVALO_CONTEXT_USER_SERVICE_ATTRIBUTE, userService); // Create a new authenticator. final HavaloAuthenticator authenticator = createAuthenticator(userService); context_.setAttribute(HAVALO_CONTEXT_AUTHENTICATOR_ATTRIBUTE, authenticator); } @Override public void contextDestroyed(final ServletContextEvent event) { logger__.info("Servlet context destroyed."); } private static final RepositoryManager getRepositoryManager( final ServletContext context, final Config config) { String repositoryBase = getRepositoryBase(); if(repositoryBase == null) { logger__.warn("Config property '" + HAVALO_REPO_BASE_CONFIG_PROPERTY + "' was not set, using default repository base: " + REPO_BASE_DEFAULT); repositoryBase = REPO_BASE_DEFAULT; } // If the provided repository base path starts with a slash, then // interpret the location as an absolute path on disk. Otherwise, // no preceding slash indicates a path relative to the web application // root directory. final File realPath; if(repositoryBase.startsWith("/")) { realPath = new File(repositoryBase); } else { realPath = new File(context.getRealPath("/" + repositoryBase)); } logger__.info("Using repository root at: " + realPath.getAbsolutePath()); final int maxFilenameLength = getMaxFilenameLength(); logger__.info("Max repository object filename length: " + maxFilenameLength); return new RepositoryManager(realPath, maxFilenameLength); } private static final RepositoryManager createInitialAdminRepository( final ServletContext context, final Config config) { RepositoryManager repoManager = null; try { repoManager = getRepositoryManager(context, config); final String adminUUID = getHavaloAdminUUID(); if(adminUUID == null) { final String msg = "Config property '" + HAVALO_ADMIN_API_UUID_PROPERTY + "' not set. Cannot " + "start until this property contains a valid UUID."; logger__.error(msg); throw new BootstrapException(msg); } else { try { UUID.fromString(adminUUID); } catch (Exception e) { logger__.error("Config property '" + HAVALO_ADMIN_API_UUID_PROPERTY + "' was set, but " + "did not contain a valid UUID. Cannot " + "start until this property contains a well " + "formed UUID.", e); throw new BootstrapException(e); } } // Verify a proper admin API accout secret is set. final String adminSecret = getHavaloAdminSecret(); if(adminSecret == null) { final String msg = "Config property '" + HAVALO_ADMIN_API_SECRET_PROPERTY + "' not set. Cannot " + "start until this property contains a valid secret."; logger__.error(msg); throw new BootstrapException(msg); } logger__.debug("Admin API account initialized (uuid=" + adminUUID + ", secret=" + abbreviate(adminSecret, 8) + ")"); // Create a new keypair for the default ADMIN level user. final KeyPair adminKeyPair = new KeyPair(new HavaloUUID(adminUUID), adminSecret, Arrays.asList(new UserRole[]{ADMIN})); // Actually attempt to create a new Repository for the Admin user. // This should work, if not, bail the whole app. repoManager.createRepository(adminKeyPair.getKey(), adminKeyPair); return repoManager; } catch (RepositoryCreationException e) { // Log in TRACE and continue silently. This is a normal case, // but Havalo is being re-started. logger__.trace("Failed to create ADMIN user repository "repository already exists.", e); } catch (Exception e) { // Hm, something else went wrong on startup, need to log // and then bail. The application cannot continue at this point. logger__.error("Failed to create ADMIN user repository "cannot continue, giving up.", e); throw new BootstrapException(e); } return repoManager; } private static final HavaloUserService createUserService( final RepositoryManager repoManager) { return new HavaloUserService(repoManager); } private static final HavaloAuthenticator createAuthenticator( final HavaloUserService userService) { return new HavaloAuthenticator(userService); } }
package com.lothrazar.samscontent; import org.apache.logging.log4j.Logger; import net.minecraft.init.Blocks; import net.minecraft.init.Items; import net.minecraft.item.ItemStack; import net.minecraft.potion.PotionEffect; import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.common.config.Configuration; import net.minecraftforge.event.entity.player.PlayerInteractEvent; import com.lothrazar.samspowerups.AlterBaseClassMod; import com.lothrazar.util.*; import cpw.mods.fml.client.event.ConfigChangedEvent; import cpw.mods.fml.common.FMLCommonHandler; import cpw.mods.fml.common.Mod; import cpw.mods.fml.common.Mod.EventHandler; import cpw.mods.fml.common.Mod.Instance; import cpw.mods.fml.common.event.FMLInitializationEvent; import cpw.mods.fml.common.event.FMLPreInitializationEvent; import cpw.mods.fml.common.event.FMLServerStartingEvent; import cpw.mods.fml.common.eventhandler.SubscribeEvent; import cpw.mods.fml.common.gameevent.TickEvent.PlayerTickEvent; import cpw.mods.fml.common.registry.GameRegistry; @Mod(modid = ItemBlockMod.MODID, version = ItemBlockMod.VERSION) //,guiFactory = "com.lothrazar.samspowerups.gui.ConfigGuiFactory" public class ItemBlockMod { @Instance(value = ItemBlockMod.MODID) public static ItemBlockMod instance; public static Logger logger; public static Configuration config; protected final static String MODID = "samscontent"; public static final String VERSION = "1"; public static int SLOT_RUNESTONE = 8; public static int RUNESTONE_DURABILITY = 90000;//90 thousand ticks is 4500 seconds which is 75 minutes private static ItemRunestone rune_resistance; private static ItemRunestone rune_jump; private static ItemRunestone rune_goldheart; private static ItemRunestone rune_haste; private static ItemRunestone rune_water; //private static ItemRunestone rune_saturation; private static ItemRunestone rune_speed; private static ItemRunestone rune_fire; //private static ItemRunestone rune_fly; // private static ItemRunestone rune_horse; private BlockXRay block_xray; private boolean blockCaveFinderEnabled; private boolean runestoneEnabled; public static ItemEnderBook itemEnderBook; private boolean fishingBlockEnabled; private boolean magicApplesEnabled; private static boolean weatherCommandBlock; private static boolean gameRuleNatRegen; private static boolean gameRuleMobGrief; private static boolean gameRuleFireTick; private static boolean gameRuleDaylightCycle ; private ItemFoodAppleMagic appleEmerald; private ItemFoodAppleMagic appleDiamond; private ItemFoodAppleMagic appleLapis; private ItemFoodAppleMagic appleChocolate; private boolean enderBookEnabled; public static enum CommandType { Teleport,Gamerule,Weather } @EventHandler public void onPreInit(FMLPreInitializationEvent event) { String category = MODID ; config = new Configuration(event.getSuggestedConfigurationFile()); enderBookEnabled = config.getBoolean( "enderBook",category,true, "This allows you to craft an ender book using 8 ender pearls and a book. "+ "Right click while sneaking to save a location in the book. " + "Attack with the book to teleport. Only works in the overworld." ); magicApplesEnabled = config.getBoolean( "magicApples", category,true, "This allows you to craft golden apples into one of four powerful items: chocolate, lapis, emerald, diamond. " + "Combine the gem with a golden apple. Or surround a regular apple with cocoa. " ) ; fishingBlockEnabled = config.getBoolean( "fishingBlock",category,true, "Build a fishing net block with four planks in the corners, a (fully repaired) fishing pole in the middle, and four cobwebs. " + "If you place this in water (touching on 4 sides and 2 deep below), it will randomly spawn fish " + "(but no treasure or junk like real fishing would)." ); runestoneEnabled = config.getBoolean( "runestoneEnabled",category,true, "Lets you make a rune that enables flying in survival." ); blockCaveFinderEnabled = config.getBoolean( "blockCaveFinder",category,true , "Build a Cave finder block (lets you see like XRay throught the world) with four obsidian "+ "in the corners , glass in the middle, and four cobwebs. " + "This lets you see through the world." ); weatherCommandBlock = config.getBoolean( "weatherCommandBlock",category,true ,"Build a weather command block." ); gameRuleNatRegen = config.getBoolean( "gameRuleNatRegen",category,true ,"Build a command block that toggles the game rule naturalRegeneration." ); gameRuleMobGrief = config.getBoolean( "gameRuleMobGrief",category,true ,"Build a command block that toggles the game rule mobGriefing." ); gameRuleFireTick = config.getBoolean( "gameRuleFireTick",category,true ,"Build a command block that toggles the game rule doFireTick." ); gameRuleDaylightCycle = config.getBoolean( "gameRuleDaylightCycle",category,true ,"Build a command block that toggles the game rule doDaylightCycle." ); syncConfig(); MinecraftForge.EVENT_BUS.register(instance);//??iunstance no worky? FMLCommonHandler.instance().bus().register(instance); } @SubscribeEvent public void onConfigChanged(ConfigChangedEvent.OnConfigChangedEvent eventArgs) { if(eventArgs.modID.equals(MODID)) { instance.syncConfig(); } } public void syncConfig() { if(config.hasChanged()) { config.save(); } } @EventHandler public void onServerLoad(FMLServerStartingEvent event) { MinecraftForge.EVENT_BUS.register(this); } @EventHandler public void onInit(FMLInitializationEvent event) { initXray(); initEnderbook(); initFishing(); initApples(); initCommand(); initRunestones(); } private void initFishing() { BlockFishing block = new BlockFishing(); block.setBlockName("block_fishing") .setBlockTextureName("samspowerups" + ":block_fishing"); GameRegistry.registerBlock(block, "block_fishing"); GameRegistry.addRecipe(new ItemStack(block), "pwp", "wfw", "pwp" , 'w',Blocks.web , 'f', new ItemStack(Items.fishing_rod,1,0) , 'p', Blocks.planks ); GameRegistry.addSmelting(new ItemStack(block),new ItemStack(Blocks.web,4),0); } private void initApples() { int SPEED = 1; int HASTE = 3; //int JUMP = 8; // .addEffect(SATURATION,FIVE_MINUTES,1) int NAUSEA = 9; int REGEN = 10; int RESISTANCE = 11; int FIRE_RESIST=12; int WATER_BREATHING = 13; int BLINDNESS=15; int NIGHT_VISION = 16; int HUNGER = 17; int WEAKNESS = 18; int HEALTH_BOOST = 21; int ABSORP = 22;//same as regular gold apple //int SATURATION = 23; int potionTimeSeconds = 300 * 4;//300 is five minutes. //for the record, the gold BLOCKS apple is 2min absorp, 5minute resistance, 5 minute fire resist. and 30 seconds of REGENH //so if any of these get something like 5 minute of resist or fire resist, it is not OP // the addEffect takes in (effectID, seconds , level) //this seems to be a good balance, haste for speed mining, //which is an advantage since you can do it without making / moving a beacon. //draw back is the weakness int I = 0; int II = 1; int III = 2; int IV = 3; int V = 4; appleEmerald = new ItemFoodAppleMagic(1,false); appleEmerald.addEffect(HASTE,potionTimeSeconds,II) .addEffect(SPEED,potionTimeSeconds,I) .addEffect(ABSORP,potionTimeSeconds,II) .setUnlocalizedName("apple_emerald") .setTextureName("samspowerups"+":apple_emerald"); GameRegistry.registerItem(appleEmerald, "apple_emerald" ); GameRegistry.addShapelessRecipe(new ItemStack(appleEmerald), Items.emerald , Items.golden_apple ); GameRegistry.addSmelting(appleEmerald, new ItemStack(Items.emerald,8),0); //diamond apple : Resistance, night vision, fills hunger, and double the hearts //we do not want to overlap with notch gold apple, so i removed .addEffect(RESISTANCE,FIVE_MINUTES,1) //only diamond is getting the shiny effect appleDiamond = new ItemFoodAppleMagic(1,true); //JUMP,SECONDS,1 //(int potionID, int duration, int level ) appleDiamond.addEffect(HEALTH_BOOST,potionTimeSeconds,V) //ten extra hearts .addEffect(FIRE_RESIST,potionTimeSeconds,II) //resist and fire so it is same as the NOTCH apple .addEffect(RESISTANCE,potionTimeSeconds,II) .addEffect(REGEN,20,II)//just enough to fill those extras .setUnlocalizedName("apple_diamond") .setTextureName("samspowerups"+":apple_diamond"); GameRegistry.registerItem(appleDiamond, "apple_diamond"); GameRegistry.addShapelessRecipe(new ItemStack(appleDiamond), Items.diamond, Items.golden_apple ); GameRegistry.addSmelting(appleDiamond, new ItemStack(Items.diamond,1),0);//getcha that diamond back //woo night vision appleLapis = new ItemFoodAppleMagic(1,false); appleLapis.addEffect(NIGHT_VISION,potionTimeSeconds,II) // night vision potion uses gold carrots maybe cheaper? .addEffect(WATER_BREATHING,potionTimeSeconds,II) //puffer fish are way too rare .addEffect(ABSORP,potionTimeSeconds,II) .setUnlocalizedName("apple_lapis") .setTextureName("samspowerups"+":apple_lapis"); GameRegistry.registerItem(appleLapis, "apple_lapis"); GameRegistry.addShapelessRecipe(new ItemStack(appleLapis), new ItemStack(Items.dye,1,4) , Items.golden_apple ); GameRegistry.addSmelting(appleLapis, new ItemStack(Items.dye,8,4),0);//uncraft //diamond should hvae health boost, speed strength and regen? all together? //this one is less powerful, no gold required appleChocolate = new ItemFoodAppleMagic(4,false); //4 is the hunger points it gives you appleChocolate.addEffect(SPEED,30,II) //just a short burst of speed. mini speed potion .addEffect(HASTE,30,II) .setUnlocalizedName("apple_chocolate") .setTextureName("samspowerups"+":apple_chocolate"); GameRegistry.registerItem(appleChocolate, "apple_chocolate" ); GameRegistry.addRecipe(new ItemStack(appleChocolate), "eee", "eae","eee" , 'e', new ItemStack(Items.dye,1,3) //3 for cocoa , 'a', Items.apple ); } private void initXray() { block_xray = new BlockXRay(); block_xray.setBlockName("block_xray") .setBlockTextureName("samspowerups" + ":block_xray"); GameRegistry.registerBlock(block_xray, "block_xray"); GameRegistry.addRecipe(new ItemStack(block_xray), "owo", "wgw", "owo" , 'w',Blocks.web , 'g',Blocks.glass , 'o',Blocks.obsidian ); GameRegistry.addSmelting(new ItemStack(block_xray),new ItemStack(Blocks.web,4),0); } private void initCommand() { if(gameRuleNatRegen) { BlockCommandBlockCraftable gameruleRegenBlock; gameruleRegenBlock = new BlockCommandBlockCraftable(CommandType.Gamerule ,"naturalRegeneration"); gameruleRegenBlock.setBlockName("grRegenBlock").setBlockTextureName("samspowerups"+":regen_command_block"); GameRegistry.registerBlock(gameruleRegenBlock, "grRegenBlock"); GameRegistry.addRecipe(new ItemStack(gameruleRegenBlock), "rcr", "tet","rcr" , 'c', Items.comparator , 'e', Items.golden_apple , 'r', Blocks.redstone_block , 't', Items.ghast_tear ); } if(weatherCommandBlock) { BlockCommandBlockCraftable weatherblock ; weatherblock = new BlockCommandBlockCraftable(CommandType.Weather); weatherblock.setBlockName("weatherCommandBlock").setBlockTextureName("samspowerups"+":weather_command_block"); GameRegistry.registerBlock(weatherblock, "weatherCommandBlock"); GameRegistry.addRecipe(new ItemStack(weatherblock), "rcr", "tet","rcr", 'c', Items.comparator, 'e',Items.water_bucket, 'r', Blocks.redstone_block , 't', Items.ghast_tear); } if(gameRuleMobGrief) { BlockCommandBlockCraftable gamerulemobGriefingblock; gamerulemobGriefingblock = new BlockCommandBlockCraftable(CommandType.Gamerule ,"mobGriefing"); gamerulemobGriefingblock.setBlockName("grmobGriefingblock").setBlockTextureName("samspowerups"+":mobgrief_command_block"); GameRegistry.registerBlock(gamerulemobGriefingblock,"grmobGriefingblock"); GameRegistry.addRecipe(new ItemStack(gamerulemobGriefingblock), "rcr", "tet","rcr" , 'c', Items.comparator , 'e', Blocks.tnt , 'r', Blocks.redstone_block , 't', Items.ghast_tear); } if(gameRuleFireTick) { BlockCommandBlockCraftable gameruleFiretickblock; gameruleFiretickblock = new BlockCommandBlockCraftable(CommandType.Gamerule ,"doFireTick"); gameruleFiretickblock.setBlockName("grdoFiretickblock").setBlockTextureName("samspowerups"+":firetick_command_block"); GameRegistry.registerBlock(gameruleFiretickblock, "grdoFiretickblock"); GameRegistry.addRecipe(new ItemStack(gameruleFiretickblock), "rcr", "tet","rcr" , 'c', Items.comparator , 'e', Items.lava_bucket , 'r', Blocks.redstone_block , 't', Items.ghast_tear); } if(gameRuleDaylightCycle) { BlockCommandBlockCraftable day; day = new BlockCommandBlockCraftable(CommandType.Gamerule ,"doDaylightCycle"); day.setBlockName("daycycle_command_block").setBlockTextureName("samspowerups"+":daycycle_command_block"); GameRegistry.registerBlock(day, "daycycle_command_block"); GameRegistry.addRecipe(new ItemStack(day), "rcr", "tet","rcr" , 'c', Items.comparator , 'e', Blocks.glowstone , 'r', Blocks.redstone_block , 't', Items.ghast_tear); } } private void initEnderbook() { itemEnderBook = new ItemEnderBook(); itemEnderBook.setTextureName("samspowerups"+":book_ender").setUnlocalizedName("book_ender"); GameRegistry.registerItem(itemEnderBook, "book_ender"); GameRegistry.addRecipe(new ItemStack(itemEnderBook) ,"eee" ,"ebe" ,"eee" , 'e', Items.ender_pearl , 'b', Items.book); GameRegistry.addSmelting(itemEnderBook, new ItemStack(Items.ender_pearl,8),0); } private void initRunestones() { boolean shiny = true; boolean not_shiny = false; //since number 1 will give "Speed II" so the roman numeral names show that int I = 0; int II = 1; int III = 2; int IV = 3; int V = 4; //changing to register item before adding recipes. it fixed a bug in other mods rune_jump = new ItemRunestone(new int[]{Reference.potion_JUMP},new int[]{V},not_shiny); rune_jump.setUnlocalizedName("rune_jump").setTextureName("samspowerups"+":rune_jump"); GameRegistry.registerItem(rune_jump, "rune_jump"); GameRegistry.addRecipe(new ItemStack(rune_jump), "eee", "eae","eee" , 'e', Items.emerald // could be slime ball/block? , 'a', Items.nether_star ); GameRegistry.addSmelting(rune_jump, new ItemStack(Items.nether_star,1),0); rune_resistance = new ItemRunestone(new int[]{Reference.potion_RESISTANCE,Reference.potion_HUNGER},new int[]{II,I},shiny); rune_resistance.setUnlocalizedName("rune_resistance").setTextureName("samspowerups"+":rune_resistance"); GameRegistry.registerItem(rune_resistance, "rune_resistance"); GameRegistry.addRecipe(new ItemStack(rune_resistance), "eee", "eae","eee" , 'e', Items.diamond , 'a', Items.nether_star ); GameRegistry.addSmelting(rune_resistance, new ItemStack(Items.nether_star,1),0); rune_goldheart = new ItemRunestone(new int[]{Reference.potion_HEALTH_BOOST,Reference.potion_HUNGER},new int[]{V,I},not_shiny); rune_goldheart.setUnlocalizedName("rune_goldheart").setTextureName("samspowerups"+":rune_goldheart"); GameRegistry.registerItem(rune_goldheart, "rune_goldheart"); GameRegistry.addRecipe(new ItemStack(rune_goldheart), "eee", "eae","eee" , 'e', Blocks.gold_block , 'a', Items.nether_star ); GameRegistry.addSmelting(rune_goldheart, new ItemStack(Items.nether_star,1),0); rune_haste = new ItemRunestone(new int[]{Reference.potion_HASTE,Reference.potion_WEAKNESS},new int[]{II,II},not_shiny); rune_haste.setUnlocalizedName( "rune_haste" ).setTextureName("samspowerups"+":rune_haste"); GameRegistry.registerItem(rune_haste, "rune_haste" ); GameRegistry.addRecipe(new ItemStack(rune_haste), "eee", "eae","eee" , 'e', Blocks.redstone_block , 'a', Items.nether_star ); GameRegistry.addSmelting(rune_haste, new ItemStack(Items.nether_star,1),0); rune_water = new ItemRunestone(new int[]{Reference.potion_WATER_BREATHING,Reference.potion_NIGHT_VISION },new int[]{V,II},not_shiny); rune_water.setUnlocalizedName("rune_water").setTextureName("samspowerups"+":rune_water"); GameRegistry.registerItem(rune_water, "rune_water"); GameRegistry.addRecipe(new ItemStack(rune_water), "eee", "eae","eee" , 'e', Blocks.lapis_block // new ItemStack(Items.dye,1,Reference.dye_lapis)//LAPIS , 'a', Items.nether_star ); GameRegistry.addSmelting(rune_water, new ItemStack(Items.nether_star,1),0); rune_speed = new ItemRunestone(new int[]{Reference.potion_SPEED,Reference.potion_FATIGUE},new int[]{II,II},not_shiny); rune_speed.setUnlocalizedName("rune_speed").setTextureName("samspowerups"+":rune_speed"); GameRegistry.registerItem(rune_speed, "rune_speed"); GameRegistry.addRecipe(new ItemStack(rune_speed), "eee", "eae","eee" , 'e', Items.sugar , 'a', Items.nether_star ); GameRegistry.addSmelting(rune_speed, new ItemStack(Items.nether_star,1),0); rune_fire = new ItemRunestone(new int[]{Reference.potion_FIRERESIST,Reference.potion_WEAKNESS,Reference.potion_FATIGUE},new int[]{I,II,II},shiny); rune_fire.setUnlocalizedName("rune_fire" ).setTextureName("samspowerups"+":rune_fire"); GameRegistry.registerItem(rune_fire, "rune_fire" ); GameRegistry.addRecipe(new ItemStack(rune_fire), "eee", "eae","eee" , 'e', Items.blaze_rod , 'a', Items.nether_star ); GameRegistry.addSmelting(rune_fire, new ItemStack(Items.nether_star,1),0); } @SubscribeEvent public void onPlayerInteract(PlayerInteractEvent event) { //if(event.entityPlayer.isSneaking() == false){ return;} //BiomeGenBase biome = event.world.getBiomeGenForCoords((int)event.entityPlayer.posX, (int)event.entityPlayer.posZ); ItemStack itemStack = event.entityPlayer.getCurrentEquippedItem(); if(itemStack == null) { return; } if(event.action.LEFT_CLICK_BLOCK == event.action) { //public void onPlayerLeftClick(PlayerInteractEvent event) if(itemStack.getItem() != itemEnderBook){return;} if (itemStack.stackTagCompound == null) {return;} ItemEnderBook.teleport(event.entityPlayer, itemStack); } else { if(itemStack.getItem() == ItemBlockMod.itemEnderBook) { ItemBlockMod.itemEnderBook.saveCurrentLocation(event.entityPlayer, itemStack); } } } @SubscribeEvent public void onPlayerTick(PlayerTickEvent event) { ItemStack runestone = event.player.inventory.getStackInSlot(ItemBlockMod.SLOT_RUNESTONE); if(runestone == null || (runestone.getItem() instanceof ItemRunestone) == false) {return;} ItemRunestone itemRunestone = (ItemRunestone) runestone.getItem(); //no need to check for null here, it is done in the method ItemRunestone.applyRunestoneToPlayer(event.player ,runestone); //applyRunestoneToPlayer(event, MIDDLE_LEFT); //applyRunestoneToPlayer(event, LOWER_LEFT); }// end player tick event }
package de.uka.ipd.sdq.beagle.core; import static de.uka.ipd.sdq.beagle.core.testutil.ExceptionThrownMatcher.throwsException; import static de.uka.ipd.sdq.beagle.core.testutil.NullHandlingMatchers.notAcceptingNull; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.collection.IsEmptyCollection.empty; import static org.hamcrest.core.Is.is; import static org.hamcrest.core.IsEqual.equalTo; import static org.hamcrest.core.IsNull.notNullValue; import de.uka.ipd.sdq.beagle.core.evaluableexpressions.EvaluableExpression; import de.uka.ipd.sdq.beagle.core.measurement.BranchDecisionMeasurementResult; import de.uka.ipd.sdq.beagle.core.measurement.LoopRepetitionCountMeasurementResult; import de.uka.ipd.sdq.beagle.core.measurement.ParameterChangeMeasurementResult; import de.uka.ipd.sdq.beagle.core.measurement.ResourceDemandMeasurementResult; import de.uka.ipd.sdq.beagle.core.testutil.factories.BlackboardFactory; import de.uka.ipd.sdq.beagle.core.testutil.factories.EvaluableExpressionFactory; import de.uka.ipd.sdq.beagle.core.testutil.factories.ExternalCallParameterFactory; import de.uka.ipd.sdq.beagle.core.testutil.factories.ResourceDemandingInternalActionFactory; import de.uka.ipd.sdq.beagle.core.testutil.factories.SeffBranchFactory; import de.uka.ipd.sdq.beagle.core.testutil.factories.SeffLoopFactory; import org.junit.Before; import org.junit.Test; import java.util.Arrays; import java.util.HashSet; import java.util.Set; /** * Tests for {@link Blackboard}. * * @author Joshua Gleitze */ public class BlackboardTest { /** * A {@link Blackboard} factory to easily obtain new blackboards from. */ private static final BlackboardFactory BLACKBOARD_FACTORY = new BlackboardFactory(); /** * A {@link SeffBranch} factory to easily obtain new instances from. */ private static final SeffBranchFactory SEFF_BRANCH_FACTORY = new SeffBranchFactory(); /** * A {@link SeffLoop} factory to easily obtain new instances from. */ private static final SeffLoopFactory SEFF_LOOP_FACTORY = new SeffLoopFactory(); /** * An {@link ExternalCallParameter} factory to easily obtain new instances from. */ private static final ExternalCallParameterFactory EXTERNAL_CALL_PARAMETER_FACTORY = new ExternalCallParameterFactory(); /** * A {@link ResourceDemandingInternalAction} factory to easily obtain new instances * from. */ private static final ResourceDemandingInternalActionFactory RDIA_FACTORY = new ResourceDemandingInternalActionFactory(); /** * An {@link EvaluableExpression} factory to easily obtain new instances from. */ private static final EvaluableExpressionFactory EVALUABLE_EXPRESSION_FACTORY = new EvaluableExpressionFactory(); /** * A new, empty Blackboard will be put in here before each test. Please note that it * should only be used in a test as long as it is not modified. If it was modified, a * new one should be created. * * @see BlackboardFactory#getEmpty() */ private Blackboard emptyBlackboard; /** * A new, filled Blackboard will be put in here before each test. Please note that it * should only be used in a test as long as it is not modified. If it was modified, a * new one should be created. * * @see BlackboardFactory#getEmpty() */ private Blackboard filledBlackboard; /** * Puts a new, empty Blackboard into {{@link #emptyBlackboard}. */ @Before public void createEmptyBlackboard() { this.emptyBlackboard = BLACKBOARD_FACTORY.getEmpty(); this.filledBlackboard = BLACKBOARD_FACTORY.getWithToBeMeasuredContent(); } /** * Creates an empty SeffBranch-set. * * @return empty {@link SeffBranch} set. */ private Set<SeffBranch> getEmptySetOfSeffBranch() { return new HashSet<SeffBranch>(); } /** * Creates an empty SeffLoop-set. * * @return empty {@link SeffLoop} set. */ private Set<SeffLoop> getEmptySetOfSeffLoop() { return new HashSet<SeffLoop>(); } /** * Creates an empty RDIA-set. * * @return empty {@link ResourceDemandingInternalAction rdia} set. */ private Set<ResourceDemandingInternalAction> getEmptySetOfRdia() { return new HashSet<ResourceDemandingInternalAction>(); } /** * Creates an empty ExternalCallParameter-set. * * @return empty {@link ExternalCallParameter} set. */ private Set<ExternalCallParameter> getEmptySetOfExternalCallParameter() { return new HashSet<ExternalCallParameter>(); } /** * Test method for * {@link Blackboard#Blackboard(java.util.Set, java.util.Set, java.util.Set)} . Assert * that: * * <li> Constructor does not accept {@code null} parameters * * <li> Constructor works with valid input */ @Test public void testBlackboard() { assertThat("Blackboard constructur must not accept any measurable seff element = null", () -> new Blackboard(null, null, null, null), throwsException(NullPointerException.class)); assertThat("Blackboard constructur must not accept any measurable seff element = null", () -> new Blackboard(RDIA_FACTORY.getAllAsSet(), SEFF_BRANCH_FACTORY.getAllAsSet(), SEFF_LOOP_FACTORY.getAllAsSet(), null), throwsException(NullPointerException.class)); assertThat("Blackboard constructur must not accept any measurable seff element = null", () -> new Blackboard(RDIA_FACTORY.getAllAsSet(), SEFF_BRANCH_FACTORY.getAllAsSet(), null, EXTERNAL_CALL_PARAMETER_FACTORY.getAllAsSet()), throwsException(NullPointerException.class)); assertThat("Blackboard constructur must not accept any measurable seff element = null", () -> new Blackboard(RDIA_FACTORY.getAllAsSet(), null, SEFF_LOOP_FACTORY.getAllAsSet(), EXTERNAL_CALL_PARAMETER_FACTORY.getAllAsSet()), throwsException(NullPointerException.class)); assertThat("Blackboard constructur must not accept any measurable seff element = null", () -> new Blackboard(null, SEFF_BRANCH_FACTORY.getAllAsSet(), SEFF_LOOP_FACTORY.getAllAsSet(), EXTERNAL_CALL_PARAMETER_FACTORY.getAllAsSet()), throwsException(NullPointerException.class)); new Blackboard(RDIA_FACTORY.getAllAsSet(), SEFF_BRANCH_FACTORY.getAllAsSet(), SEFF_LOOP_FACTORY.getAllAsSet(), EXTERNAL_CALL_PARAMETER_FACTORY.getAllAsSet()); } /** * Test method for {@link Blackboard#getAllRdias()}. Assert that <li> Blackboard does * not return {@code null} for getter-method * * <ul> * * <li> The Blackboard will not return {@code null} by any getter-method. * * <li> Once set, SeffElements will not change. * * <li> Manipulating the returned set will not affect the corresponding set on the * blackboard. * * </ul> */ @Test public void testGetAllRdias() { assertThat("Blackboard should not return null for getAllRdias()", this.emptyBlackboard.getAllRdias(), is(notNullValue())); assertThat("Empty blackboard should not contain any Rdias", this.emptyBlackboard.getAllRdias(), is(empty())); final Set<ResourceDemandingInternalAction> rdiaSet = RDIA_FACTORY.getAllAsSet(); final Blackboard blackboard = new Blackboard(rdiaSet, this.getEmptySetOfSeffBranch(), this.getEmptySetOfSeffLoop(), this.getEmptySetOfExternalCallParameter()); assertThat("Rdias on the blackboard should not change!", blackboard.getAllRdias(), is(equalTo(rdiaSet))); final Set<ResourceDemandingInternalAction> blackboardSet = blackboard.getAllRdias(); blackboardSet.removeAll(blackboardSet); assertThat("Blackboard getter-methods should return copies of Sets, not their own!", blackboard.getAllRdias(), is(equalTo(rdiaSet))); } /** * Test method for {@link Blackboard#getAllSeffBranches()}. Assert that <li> * Blackboard does not return {@code null} for getter-method * * <ul> * * <li> The Blackboard will not return {@code null} by any getter-method. * * <li> Once set, SeffElements will not change. * * <li> Manipulating the returned set will not affect the corresponding set on the * blackboard. * * </ul> */ @Test public void testGetAllSeffBranches() { assertThat("Blackboard should not return null for getAllSeffBranches()", this.emptyBlackboard.getAllSeffBranches(), is(notNullValue())); assertThat("Empty blackboard should not contain any Rdias", this.emptyBlackboard.getAllSeffBranches(), is(empty())); final Set<SeffBranch> seffBranchSet = SEFF_BRANCH_FACTORY.getAllAsSet(); final Blackboard blackboard = new Blackboard(this.getEmptySetOfRdia(), seffBranchSet, this.getEmptySetOfSeffLoop(), this.getEmptySetOfExternalCallParameter()); assertThat("SeffBranches on the blackboard should not change!", blackboard.getAllSeffBranches(), is(equalTo(seffBranchSet))); final Set<SeffBranch> blackboardSet = blackboard.getAllSeffBranches(); blackboardSet.removeAll(blackboardSet); assertThat("Blackboard getter-methods should return copies of Sets, not their own!", blackboard.getAllSeffBranches(), is(equalTo(seffBranchSet))); } /** * Test method for {@link Blackboard#getAllSeffLoops()}. Assert that <li> Blackboard * does not return {@code null} for getter-method * * <ul> * * <li> The Blackboard will not return {@code null} by any getter-method. * * <li> Once set, SeffElements will not change. * * <li> Manipulating the returned set will not affect the corresponding set on the * blackboard. * * </ul> */ @Test public void testGetAllSeffLoops() { assertThat("Blackboard should not return null for getAllSeffLoops()", this.emptyBlackboard.getAllSeffLoops(), is(notNullValue())); assertThat("Empty blackboard should not contain any SeffLoops", this.emptyBlackboard.getAllSeffLoops(), is(empty())); final Set<SeffLoop> seffLoopSet = SEFF_LOOP_FACTORY.getAllAsSet(); final Blackboard blackboard = new Blackboard(this.getEmptySetOfRdia(), this.getEmptySetOfSeffBranch(), seffLoopSet, this.getEmptySetOfExternalCallParameter()); assertThat("SeffLoops on the blackboard should not change!", blackboard.getAllSeffLoops(), is(equalTo(seffLoopSet))); final Set<SeffLoop> blackboardSet = blackboard.getAllSeffLoops(); blackboardSet.removeAll(blackboardSet); assertThat("Blackboard getter-methods should return copies of Sets, not their own!", blackboard.getAllSeffLoops(), is(equalTo(seffLoopSet))); } /** * Test method for {@link Blackboard#getAllExternalCallParameters()}. Assert that <li> * Blackboard does not return {@code null} for getter-method * * <ul> * * <li> The Blackboard will not return {@code null} by any getter-method. * * <li> Once set, SeffElements will not change. * * <li> Manipulating the returned set will not affect the corresponding set on the * blackboard. * * </ul> */ @Test public void testGetAllExternalCallParameters() { assertThat("Blackboard should not return null for getAllExternalCallParameters()", this.emptyBlackboard.getAllExternalCallParameters(), is(notNullValue())); assertThat("Empty blackboard should not contain any ExternalCallParameters", this.emptyBlackboard.getAllExternalCallParameters(), is(empty())); final Set<ExternalCallParameter> externalCallParameterSet = EXTERNAL_CALL_PARAMETER_FACTORY.getAllAsSet(); final Blackboard blackboard = new Blackboard(this.getEmptySetOfRdia(), this.getEmptySetOfSeffBranch(), this.getEmptySetOfSeffLoop(), externalCallParameterSet); assertThat("ExternalCallParameters on the blackboard should not change!", blackboard.getAllExternalCallParameters(), is(equalTo(externalCallParameterSet))); final Set<ExternalCallParameter> blackboardSet = blackboard.getAllExternalCallParameters(); blackboardSet.removeAll(blackboardSet); assertThat("Blackboard getter-methods should return copies of Sets, not their own!", blackboard.getAllExternalCallParameters(), is(equalTo(externalCallParameterSet))); } /** * Test method for {@link Blackboard#getRdiasToBeMeasured()}. Assert That * * <ul> * * <li> Getter does not return {@code null}. * * <li> Manipulating the returned set will not affect the corresponding set on the * blackboard. * * </ul> */ @Test public void testGetRdiasToBeMeasured() { assertThat("Blackboard should not return null for getRdiasToBeMeasured()", this.emptyBlackboard.getRdiasToBeMeasured(), is(notNullValue())); assertThat("Empty blackboard should not contain any RdiasToBeMeasured", this.emptyBlackboard.getRdiasToBeMeasured(), is(empty())); final Set<ResourceDemandingInternalAction> rdiaSet = this.filledBlackboard.getRdiasToBeMeasured(); final Set<ResourceDemandingInternalAction> clone = new HashSet<ResourceDemandingInternalAction>(); clone.addAll(rdiaSet); rdiaSet.removeAll(rdiaSet); assertThat("Blackboard getter-methods should return copies of Sets, not their own!", this.filledBlackboard.getRdiasToBeMeasured(), is(equalTo(clone))); } /** * Test method for {@link Blackboard#getSeffBranchesToBeMeasured()}. Assert That * * <ul> * * <li> Getter does not return {@code null}. * * <li> Manipulating the returned set will not affect the corresponding set on the * blackboard. * * </ul> */ @Test public void testGetSeffBranchesToBeMeasured() { assertThat("Blackboard should not return null for getSeffBranchesToBeMeasured()", this.emptyBlackboard.getSeffBranchesToBeMeasured(), is(notNullValue())); assertThat("Empty blackboard should not contain any SeffBranchesToBeMeasured", this.emptyBlackboard.getSeffBranchesToBeMeasured(), is(empty())); final Set<SeffBranch> seffBranchSet = this.filledBlackboard.getSeffBranchesToBeMeasured(); final Set<SeffBranch> clone = new HashSet<SeffBranch>(); clone.addAll(seffBranchSet); seffBranchSet.removeAll(seffBranchSet); assertThat("Blackboard getter-methods should return copies of Sets, not their own!", this.filledBlackboard.getSeffBranchesToBeMeasured(), is(equalTo(clone))); } /** * Test method for {@link Blackboard#getSeffLoopsToBeMeasured()}. Assert That * * <ul> * * <li> Getter does not return {@code null}. * * <li> Manipulating the returned set will not affect the corresponding set on the * blackboard. * * </ul> */ @Test public void testGetSeffLoopsToBeMeasured() { assertThat("Blackboard should not return null for getSeffLoopsToBeMeasured()", this.emptyBlackboard.getSeffLoopsToBeMeasured(), is(notNullValue())); assertThat("Empty blackboard should not contain any SeffLoopsToBeMeasured", this.emptyBlackboard.getSeffLoopsToBeMeasured(), is(empty())); final Set<SeffLoop> seffLoopSet = this.filledBlackboard.getSeffLoopsToBeMeasured(); final Set<SeffLoop> clone = new HashSet<SeffLoop>(); clone.addAll(seffLoopSet); seffLoopSet.removeAll(seffLoopSet); assertThat("Blackboard getter-methods should return copies of Sets, not their own!", this.filledBlackboard.getSeffLoopsToBeMeasured(), is(equalTo(clone))); } /** * Test method for {@link Blackboard#getExternalCallParametersToBeMeasured()}. Assert * That * * <ul> * * <li> Getter does not return {@code null}. * * <li> Manipulating the returned set will not affect the corresponding set on the * blackboard. * * </ul> */ @Test public void testGetExternalCallParametersToBeMeasured() { assertThat("Blackboard should not return null for getExternalCallParametersToBeMeasured()", this.emptyBlackboard.getExternalCallParametersToBeMeasured(), is(notNullValue())); assertThat("Empty blackboard should not contain any ExternalCallParametersToBeMeasured", this.emptyBlackboard.getExternalCallParametersToBeMeasured(), is(empty())); final Set<ExternalCallParameter> externalCallParameterSet = this.filledBlackboard.getExternalCallParametersToBeMeasured(); final Set<ExternalCallParameter> clone = new HashSet<ExternalCallParameter>(); clone.addAll(externalCallParameterSet); externalCallParameterSet.removeAll(externalCallParameterSet); assertThat("Blackboard getter-methods should return copies of Sets, not their own!", this.filledBlackboard.getExternalCallParametersToBeMeasured(), is(equalTo(clone))); } /** * Test method for {@link Blackboard#addToBeMeasuredRdias(java.util.Collection)} and * {@link Blackboard#addToBeMeasuredRdias(de.uka.ipd.sdq.beagle.core.ResourceDemandingInternalAction[])} * . Asserts that: * * <ul> * * <li>{@code null} cannot be passed as or in the argument. * * </ul> */ @Test public void testAddToBeMeasuredRdias() { assertThat(this.emptyBlackboard::addToBeMeasuredRdias, is(notAcceptingNull(RDIA_FACTORY.getAll()))); assertThat(this.emptyBlackboard::addToBeMeasuredRdias, is(notAcceptingNull(Arrays.asList(RDIA_FACTORY.getAll())))); final Set<ResourceDemandingInternalAction> rdiaSet = this.getEmptySetOfRdia(); rdiaSet.add(RDIA_FACTORY.getOne()); assertThat( "Blackboard should not accept RDIAs to be measured, that are not stored in its RDIA-set." + "Besides an Exception should be thrown, because Measurable Seff Elements should not" + "be created after Blackboard instanciation!", () -> this.emptyBlackboard.addToBeMeasuredRdias(rdiaSet), throwsException(IllegalArgumentException.class)); assertThat( "Blackboard should not accept RDIAs to be measured, that are not stored in its RDIA-set." + "Besides an Exception should be thrown, because Measurable Seff Elements should not" + "be created after Blackboard instanciation!", () -> this.emptyBlackboard.addToBeMeasuredRdias(RDIA_FACTORY.getAll()), throwsException(IllegalArgumentException.class)); } /** * Test method for * {@link Blackboard#addToBeMeasuredSeffBranches(java.util.Collection)} and * {@link Blackboard#addToBeMeasuredSeffBranches(de.uka.ipd.sdq.beagle.core.SeffBranch[])} * . Asserts that: * * <ul> * * <li>{@code null} cannot be passed as or in the argument. * * </ul> */ @Test public void testAddToBeMeasuredSeffBranches() { assertThat(this.emptyBlackboard::addToBeMeasuredSeffBranches, is(notAcceptingNull(SEFF_BRANCH_FACTORY.getAll()))); assertThat(this.emptyBlackboard::addToBeMeasuredSeffBranches, is(notAcceptingNull(Arrays.asList(SEFF_BRANCH_FACTORY.getAll())))); final Set<SeffBranch> seffBranchSet = this.getEmptySetOfSeffBranch(); seffBranchSet.add(SEFF_BRANCH_FACTORY.getOne()); assertThat( "Blackboard should not accept SeffBranches to be measured, that are not stored in its SeffBranch-set." + "Besides an Exception should be thrown, because Measurable Seff Elements should not" + "be created after Blackboard instanciation!", () -> this.emptyBlackboard.addToBeMeasuredSeffBranches(seffBranchSet), throwsException(IllegalArgumentException.class)); assertThat( "Blackboard should not accept SeffBranches to be measured, that are not stored in its SeffBranch-set." + "Besides an Exception should be thrown, because Measurable Seff Elements should not" + "be created after Blackboard instanciation!", () -> this.emptyBlackboard.addToBeMeasuredSeffBranches(SEFF_BRANCH_FACTORY.getAll()), throwsException(IllegalArgumentException.class)); } /** * Test method for * {@link Blackboard#addToBeMeasuredSeffLoops(de.uka.ipd.sdq.beagle.core.SeffLoop[])} * and {@link Blackboard#addToBeMeasuredSeffLoops(java.util.Collection)}. Asserts * that: * * <ul> * * <li>{@code null} cannot be passed as or in the argument. * * </ul> */ @Test public void testAddToBeMeasuredSeffLoops() { assertThat(this.emptyBlackboard::addToBeMeasuredSeffLoops, is(notAcceptingNull(SEFF_LOOP_FACTORY.getAll()))); assertThat(this.emptyBlackboard::addToBeMeasuredSeffLoops, is(notAcceptingNull(Arrays.asList(SEFF_LOOP_FACTORY.getAll())))); final Set<SeffLoop> seffLoopSet = this.getEmptySetOfSeffLoop(); seffLoopSet.add(SEFF_LOOP_FACTORY.getOne()); assertThat( "Blackboard should not accept SeffLoops to be measured, that are not stored in its SeffLoop-set." + "Besides an Exception should be thrown, because Measurable Seff Elements should not" + "be created after Blackboard instanciation!", () -> this.emptyBlackboard.addToBeMeasuredSeffLoops(seffLoopSet), throwsException(IllegalArgumentException.class)); assertThat( "Blackboard should not accept SeffLoops to be measured, that are not stored in its SeffLoop-set." + "Besides an Exception should be thrown, because Measurable Seff Elements should not" + "be created after Blackboard instanciation!", () -> this.emptyBlackboard.addToBeMeasuredSeffLoops(SEFF_LOOP_FACTORY.getAll()), throwsException(IllegalArgumentException.class)); } /** * Test method for * {@link Blackboard#addToBeMeasuredExternalCallParameters(ExternalCallParameter[])} * and {@link Blackboard#addToBeMeasuredExternalCallParameters(java.util.Collection)} * . Asserts that: * * <ul> * * <li>{@code null} cannot be passed as or in the argument. * * </ul> */ @Test public void testAddToBeMeasuredExternalCallParameters() { assertThat(this.emptyBlackboard::addToBeMeasuredExternalCallParameters, is(notAcceptingNull(EXTERNAL_CALL_PARAMETER_FACTORY.getAll()))); assertThat(this.emptyBlackboard::addToBeMeasuredExternalCallParameters, is(notAcceptingNull(Arrays.asList(EXTERNAL_CALL_PARAMETER_FACTORY.getAll())))); final Set<ExternalCallParameter> externalCallParameterSet = this.getEmptySetOfExternalCallParameter(); externalCallParameterSet.add(EXTERNAL_CALL_PARAMETER_FACTORY.getOne()); assertThat( "Blackboard should not accept ExternalCallParameters to be measured," + "that are not stored in its ExternalCallParameter-set." + "Besides an Exception should be thrown, because Measurable Seff Elements should not" + "be created after Blackboard instanciation!", () -> this.emptyBlackboard.addToBeMeasuredExternalCallParameters(externalCallParameterSet), throwsException(IllegalArgumentException.class)); assertThat( "Blackboard should not accept ExternalCallParameters to be measured," + "that are not stored in its ExternalCallParameter-set." + "Besides an Exception should be thrown, because Measurable Seff Elements should not" + "be created after Blackboard instanciation!", () -> this.emptyBlackboard.addToBeMeasuredExternalCallParameters(EXTERNAL_CALL_PARAMETER_FACTORY.getAll()), throwsException(IllegalArgumentException.class)); } /** * Test method for * {@link Blackboard#getMeasurementResultsFor(ResourceDemandingInternalAction)} . */ @Test public void testGetMeasurementResultsForResourceDemandingInternalAction() { final ResourceDemandingInternalAction rdia = null; assertThat( "It must not be possible to call getMeasurementResultsFor(ResourceDemandingInternalAction) for null as parameter", () -> this.emptyBlackboard.getMeasurementResultsFor(rdia), throwsException(NullPointerException.class)); } /** * Test method for * {@link Blackboard#getMeasurementResultsFor(de.uka.ipd.sdq.beagle.core.SeffBranch)} * . */ @Test public void testGetMeasurementResultsForSeffBranch() { final SeffBranch seffBranch = null; assertThat("It must not be possible to call getMeasurementResultsFor(SeffBranch) for null as parameter", () -> this.emptyBlackboard.getMeasurementResultsFor(seffBranch), throwsException(NullPointerException.class)); } /** * Test method for * {@link Blackboard#getMeasurementResultsFor(de.uka.ipd.sdq.beagle.core.SeffLoop)} . */ @Test public void testGetMeasurementResultsForSeffLoop() { final SeffLoop seffLoop = null; assertThat("It must not be possible to call getMeasurementResultsFor(SeffLoop) for null as parameter", () -> this.emptyBlackboard.getMeasurementResultsFor(seffLoop), throwsException(NullPointerException.class)); } /** * Test method for * {@link Blackboard#getMeasurementResultsFor(de.uka.ipd.sdq.beagle.core.ExternalCallParameter)} * . */ @Test public void testGetMeasurementResultsForExternalCallParameter() { final ExternalCallParameter externalCallParameter = null; assertThat( "It must not be possible to call getMeasurementResultsFor(externalCallParameter) for null as parameter", () -> this.emptyBlackboard.getMeasurementResultsFor(externalCallParameter), throwsException(NullPointerException.class)); } /** * Test method for * {@link Blackboard#addMeasurementResultFor(ResourceDemandingInternalAction, de.uka.ipd.sdq.beagle.core.measurement.ResourceDemandMeasurementResult)} * . Asserts that: * * <ul> * * <li>{@code null} cannot be passed as any argument. * * </ul> */ @Test public void testAddMeasurementResultForResourceDemandingInternalActionResourceDemandMeasurementResult() { assertThat("It must not be possible to add a measurement result for null", () -> this.emptyBlackboard.addMeasurementResultFor(null, new ResourceDemandMeasurementResult()), throwsException(NullPointerException.class)); assertThat("It must not be possible to add null as measurement result", () -> this.emptyBlackboard.addMeasurementResultFor(RDIA_FACTORY.getOne(), null), throwsException(NullPointerException.class)); } /** * Test method for * {@link Blackboard#addMeasurementResultFor(SeffBranch, de.uka.ipd.sdq.beagle.core.measurement.BranchDecisionMeasurementResult)} * . Asserts that: * * <ul> * * <li>{@code null} cannot be passed as any argument. * * </ul> */ @Test public void testAddMeasurementResultForSeffBranchBranchDecisionMeasurementResult() { assertThat("It must not be possible to add a measurement result for null", () -> this.emptyBlackboard.addMeasurementResultFor(null, new BranchDecisionMeasurementResult()), throwsException(NullPointerException.class)); assertThat("It must not be possible to add null as measurement result", () -> this.emptyBlackboard.addMeasurementResultFor(SEFF_BRANCH_FACTORY.getOne(), null), throwsException(NullPointerException.class)); } /** * Test method for * {@link Blackboard#addMeasurementResultFor(SeffLoop, de.uka.ipd.sdq.beagle.core.measurement.LoopRepetitionCountMeasurementResult)} * . Asserts that: * * <ul> * * <li>{@code null} cannot be passed as any argument. * * </ul> */ @Test public void testAddMeasurementResultForSeffLoopLoopRepetitionCountMeasurementResult() { assertThat("It must not be possible to add a measurement result for null", () -> this.emptyBlackboard.addMeasurementResultFor(null, new LoopRepetitionCountMeasurementResult()), throwsException(NullPointerException.class)); assertThat("It must not be possible to add null as measurement result", () -> this.emptyBlackboard.addMeasurementResultFor(SEFF_LOOP_FACTORY.getOne(), null), throwsException(NullPointerException.class)); } /** * Test method for * {@link Blackboard#addMeasurementResultFor(ExternalCallParameter, de.uka.ipd.sdq.beagle.core.measurement.ParameterChangeMeasurementResult)} * . Asserts that: * * <ul> * * <li>{@code null} cannot be passed as any argument. * * </ul> */ @Test public void testAddMeasurementResultForExternalCallParameterParameterChangeMeasurementResult() { assertThat("It must not be possible to add a measurement result for null", () -> this.emptyBlackboard.addMeasurementResultFor(null, new ParameterChangeMeasurementResult()), throwsException(NullPointerException.class)); assertThat("It must not be possible to add null as measurement result", () -> this.emptyBlackboard.addMeasurementResultFor(EXTERNAL_CALL_PARAMETER_FACTORY.getOne(), null), throwsException(NullPointerException.class)); } /** * Test method for {@link Blackboard#getProposedExpressionFor(MeasurableSeffElement)} * . Asserts that: * * <ul> * * <li>{@code null} cannot be passed. * * </ul> */ @Test public void testGetProposedExpressionFor() { assertThat("It must not be possible get proposed expressions for null", () -> this.emptyBlackboard.getProposedExpressionFor(null), throwsException(NullPointerException.class)); } /** * Test method for * {@link Blackboard#addProposedExpressionFor(MeasurableSeffElement, de.uka.ipd.sdq.beagle.core.evaluableexpressions.EvaluableExpression)} * . Asserts that: * * <ul> * * <li>{@code null} cannot be passed as any argument. * * </ul> */ @Test public void testAddProposedExpressionFor() { assertThat("It must not be possible to add a proposed expression for null", () -> this.emptyBlackboard.addProposedExpressionFor(null, EVALUABLE_EXPRESSION_FACTORY.getOne()), throwsException(NullPointerException.class)); assertThat("It must not be possible to add null as a proposed expression", () -> this.emptyBlackboard.addProposedExpressionFor(SEFF_BRANCH_FACTORY.getOne(), null), throwsException(NullPointerException.class)); } /** * Test method for {@link Blackboard#getFinalExpressionFor(MeasurableSeffElement)}. * Asserts that: * * <ul> * * <li>{@code null} cannot be passed. * * </ul> */ @Test public void testGetFinalExpressionFor() { assertThat("It must not be possible get the final expression for null", () -> this.emptyBlackboard.getFinalExpressionFor(null), throwsException(NullPointerException.class)); } /** * Test method for * {@link Blackboard#setFinalExpressionFor(MeasurableSeffElement, de.uka.ipd.sdq.beagle.core.evaluableexpressions.EvaluableExpression)} * . Asserts that: * * <ul> * * <li>{@code null} can not be passed to one of the arguments. * * </ul> */ @Test public void testSetFinalExpressionFor() { assertThat("It must not be possible to set the final expression for null", () -> this.emptyBlackboard.setFinalExpressionFor(null, EVALUABLE_EXPRESSION_FACTORY.getOne()), throwsException(NullPointerException.class)); // asserts that setting null for the final expression is possible this.emptyBlackboard.setFinalExpressionFor(RDIA_FACTORY.getOne(), null); } /** * Test method for {@link Blackboard#getFitnessFunction()}. */ @Test public void testGetFitnessFunction() { assertThat("Blackboard should not return null for getFitnessFunction()", this.emptyBlackboard.getFitnessFunction(), is(notNullValue())); } /** * Test method for {@link Blackboard#writeFor(java.lang.Class, java.io.Serializable)} * . */ @Test public void testWriteFor() { assertThat("It must not be possible to write on the Blackboard for null as a given parameter", () -> this.emptyBlackboard.writeFor(null, String.class), throwsException(NullPointerException.class)); assertThat("It must not be possible to write on the Blackboard for null as a given parameter", () -> this.emptyBlackboard.writeFor(null, null), throwsException(NullPointerException.class)); } /** * Test method for {@link Blackboard#readFor(java.lang.Class)}. */ @Test public void testReadFor() { assertThat("It must not be possible to read on the Blackboard for null as a given parameter", () -> this.emptyBlackboard.readFor(null), throwsException(NullPointerException.class)); } }
package com.manmoe.example.test; import com.google.common.base.Predicate; import com.manmoe.example.model.PopupPage; import org.openqa.selenium.WebDriver; import org.openqa.selenium.support.ui.WebDriverWait; import org.testng.ITestResult; import org.testng.annotations.AfterClass; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import us.monoid.web.Resty; import java.io.IOException; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertNotNull; import static org.testng.Assert.assertTrue; import static us.monoid.web.Resty.content; import static us.monoid.web.Resty.put; public class FirespottingIT extends AbstractChromeExtensionTest { private static final String EXTENSION_NAME_FROM_MANIFEST = "Firespotting! Interesting Ideas, Every Day!"; public static final long TIME_TO_WAIT_FOR_REFRESH = 3L; /** * sum of entries to be shown on popup page */ public static final int ENTRY_LIST_LENGTH = 15; /** * This is our testmodel. So we don't get lost in details, how to get some elements. */ protected PopupPage popupPage; /** * We set it initially == true, so we can &= each test method result. */ protected boolean testResult = true; /** * Our testClient to send the results to sauceLabs */ protected Resty restClient = new Resty(); /** * Method for setting up the test environment. */ @BeforeClass public void setUp() { this.popupPage = new PopupPage(getWebDriver(), EXTENSION_NAME_FROM_MANIFEST); } /** * We tell the remote selenium server here, that we have finished. */ @AfterClass public void tearDown() throws IOException { // send saucelabs the result of the tests // @TODO should be use @AfterSuite in future String sauceUsername = System.getenv("SAUCE_USERNAME"); String sauceAccessKey = System.getenv("SAUCE_ACCESS_KEY"); String platformString = System.getenv("PLATFORM"); String buildNr = System.getenv("TRAVIS_BUILD_NUMBER"); // if sauceLabs is used, the results should be transmitted if (sauceUsername != null && sauceAccessKey != null && platformString != null) { String jobId = popupPage.getDriver().getSessionId().toString(); // build sauceLabs result String url = "https://saucelabs.com/rest/v1/" + sauceUsername + "/jobs/" + jobId; restClient.authenticate("https://saucelabs.com", sauceUsername, sauceAccessKey.toCharArray()); restClient.withHeader("Content-Type", "application/json"); restClient.json(url, put(content("{\"passed\": " + testResult + ", \"name\": \"Firespotting! " + platformString + " Test\", \"build\": \"" + buildNr + "\"}"))); } this.popupPage.tearDown(); } /** * We want to know, if every method has succeeded. If one method fails, testResult == false. * * @param result Results of all testMethods. */ @AfterMethod(alwaysRun = true) public void report(ITestResult result) { testResult &= result.isSuccess(); } /** * This test checks, if the chrome extension is installed on the remote system. We want to get the extension id * by the remote host (every chrome browser will generate another id). If the id is present, we assume, the the * extension is installed correctly. */ @Test public void isInstalled() { assertTrue(popupPage.getId() != null, "We got null back. The extension is not installed properly"); } /** * Test for checking the popup window. */ @Test public void testPopup() { popupPage.open(); // check title assertEquals(popupPage.getTitle(), "Firespotting!"); } /** * Clicks on every item and checks, if it loads. */ @Test public void testEntry() { popupPage.open(); // check if all entries are there for (int i = 1; i <= ENTRY_LIST_LENGTH; i++) { String linkText = popupPage.getEntryTitle(i); assertNotNull(linkText); popupPage.clickOnEntryLink(linkText); popupPage.getBack(); } } /** * Clicks on the issues link and checks, if it loads. */ @Test public void testIssues() { popupPage.open(); popupPage.getDriver().navigate().refresh(); popupPage.getIssues().click(); assertTrue(popupPage.getDriver().getTitle().startsWith("Issues · quitschibo/firespotting-chrome-extension")); } /** * Clicks on refresh link. * * @throws InterruptedException */ @Test public void testRefresh() throws InterruptedException { popupPage.open(); popupPage.getRefreshLink().click(); WebDriverWait driverWait = new WebDriverWait(popupPage.getDriver(), TIME_TO_WAIT_FOR_REFRESH); driverWait.until(new Predicate<WebDriver>() { @Override public boolean apply(org.openqa.selenium.WebDriver webDriver) { return popupPage.getTitle().equals("Firespotting!"); }; }); assertEquals(popupPage.getTitle(), "Firespotting!"); } /** * Clicks on Options link. */ @Test public void testOpenOptions() { popupPage.open(); popupPage.getDriver().navigate().refresh(); popupPage.getOptionsLink().click(); popupPage.switchToNewTab(); assertEquals(popupPage.getTitle(), "Options"); } }
package com.lucythemoocher.graphics; import java.io.InputStream; import com.lucythemoocher.controls.PlayerController; import com.lucythemoocher.game.Game; import com.lucythemoocher.physics.Box; import com.lucythemoocher.R; import android.content.Context; import android.graphics.Canvas; import android.graphics.ColorMatrix; import android.graphics.ColorMatrixColorFilter; import android.graphics.Paint; import android.graphics.drawable.BitmapDrawable; import android.util.Log; import android.view.MotionEvent; import android.view.SurfaceHolder; import android.view.SurfaceView; public class Camera extends SurfaceView implements SurfaceHolder.Callback { private static final int NORMAL = 0; private static final int BnW = 1; private static final float CAMERASPEED = (float) 0.3; private static final float BACKGROUNDSPEED = (float) 0.5; private static float DT_ = 1; private Box screen_; private Image background_; private float currX_; private float currY_; private int drawing_ = NORMAL; private Paint bnwFilter_; private boolean canDraw_ = false; public Camera(Context context, float h, float w) { super(context); currX_ = 1; currY_ = 1; screen_ = new Box(currX_,currY_,h,w); //Background InputStream is = getResources().openRawResource(R.drawable.background1); BitmapDrawable bd = new BitmapDrawable(is); background_ = new Image(bd); //Black n white filter bnwFilter_ = new Paint(); ColorMatrix cm = new ColorMatrix(); cm.setSaturation(0); ColorMatrixColorFilter f = new ColorMatrixColorFilter(cm); bnwFilter_.setColorFilter(f); getHolder().addCallback(this); setFocusable(true); } /** * Update position of the camera */ public void update() { //Camera follows the player currX_ += (Game.getCharacter().getX()-currX_)*camSpeed(); currY_ += (Game.getCharacter().getY()-currY_)*camSpeed(); screen_.setX(currX_-screen_.getW()/2); screen_.setY(currY_-screen_.getH()/2); } public void refreshScreen() { if ( canDraw_ ) { update(); Canvas canvas = null; try { canvas = getHolder().lockCanvas(); onDraw(canvas); } finally { if ( canvas != null ) { getHolder().unlockCanvasAndPost(canvas); } } } } private float camSpeed() { return CAMERASPEED*DT_; } public void onDraw(Canvas canvas) { // background float x = screen_.getW()/2-Game.getCharacter().getX()*BACKGROUNDSPEED; float y = screen_.getH()/2-Game.getCharacter().getY()*BACKGROUNDSPEED; float offsetX = screen_.getW()*BACKGROUNDSPEED; float offsetY = screen_.getH()*BACKGROUNDSPEED; canvas.drawBitmap(background_.getBitmap().getBitmap(), x-offsetX, y-offsetY, null); //decors Game.getMap().draw(canvas); // player Game.getCharacter().draw(canvas); } public void drawBox(Box box, Canvas canvas, Paint color) { canvas.drawRect(box.getX()-offsetx(), box.getY()-offsety(), box.getX()+box.getW()-offsetx(), box.getY()+box.getH()-offsety(), color); } public void drawRectangle(float x, float y, float h, float w, int color) { //Paint col = new Paint(); //col.setColor(color); //canvas.drawRect(x, y, x+w, y+h, col); } public boolean onTouchEvent(MotionEvent event) { PlayerController.process(event); return true; } public float offsetx() { return screen_.getX(); } public float offsety() { return screen_.getY(); } public float h() { return screen_.getH(); } public float w() { return screen_.getW(); } public void drawImage(Box box, Image image, Canvas canvas) { switch ( drawing_ ) { case NORMAL: canvas.drawBitmap(image.getBitmap().getBitmap(), box.getX()-offsetx(), box.getY()-offsety(), null); break; case BnW: canvas.drawBitmap(image.getBitmap().getBitmap(), box.getX()-offsetx(), box.getY()-offsety(), bnwFilter_); break; default: canvas.drawBitmap(image.getBitmap().getBitmap(), box.getX()-offsetx(), box.getY()-offsety(), null); break; } } public void drawImage(float x, float y, Image image, Canvas canvas) { switch ( drawing_ ) { case NORMAL: canvas.drawBitmap(image.getBitmap().getBitmap(), x-offsetx(), y-offsety(), null); break; case BnW: canvas.drawBitmap(image.getBitmap().getBitmap(), x-offsetx(), y-offsety(), bnwFilter_); break; default: canvas.drawBitmap(image.getBitmap().getBitmap(), x-offsetx(), y-offsety(), null); break; } } public void setNormalDrawing() { drawing_ = NORMAL; } public void setBnWDrawing() { drawing_ = BnW; } public static void setSpeed(float dt) { DT_ = dt; } public void surfaceChanged(SurfaceHolder arg0, int arg1, int arg2, int arg3) {} public void surfaceCreated(SurfaceHolder arg0) { canDraw_ = true; } public void surfaceDestroyed(SurfaceHolder arg0) { canDraw_ = false; } }
package com.manmoe.example.test; import com.google.common.base.Predicate; import com.manmoe.example.model.PopupPage; import org.openqa.selenium.WebDriver; import org.openqa.selenium.support.ui.WebDriverWait; import org.testng.ITestResult; import org.testng.annotations.AfterClass; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import us.monoid.web.Resty; import java.io.IOException; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertNotNull; import static org.testng.Assert.assertTrue; import static us.monoid.web.Resty.content; import static us.monoid.web.Resty.put; public class FirespottingIT extends AbstractChromeExtensionTest { private static final String EXTENSION_NAME_FROM_MANIFEST = "Firespotting! Interesting Ideas, Every Day!"; public static final long TIME_TO_WAIT_FOR_REFRESH = 3L; /** * sum of entries to be shown on popup page */ public static final int ENTRY_LIST_LENGTH = 15; public static final String ISSUES_PAGE_TITLE = "Issues · quitschibo/firespotting-chrome-extension"; /** * This is our testmodel. So we don't get lost in details, how to get some elements. */ protected PopupPage popupPage; /** * We set it initially == true, so we can &= each test method result. */ protected boolean testResult = true; /** * Our testClient to send the results to sauceLabs */ protected Resty restClient = new Resty(); /** * Method for setting up the test environment. */ @BeforeClass public void setUp() { this.popupPage = new PopupPage(getWebDriver(), EXTENSION_NAME_FROM_MANIFEST); } /** * We tell the remote selenium server here, that we have finished. */ @AfterClass public void tearDown() throws IOException { // send saucelabs the result of the tests // @TODO should be use @AfterSuite in future String sauceUsername = getSystemVariable("SAUCE_USERNAME"); String sauceAccessKey = getSystemVariable("SAUCE_ACCESS_KEY"); String platformString = getSystemVariable("PLATFORM"); String buildNr = getSystemVariable("TRAVIS_BUILD_NUMBER"); // if sauceLabs is used, the results should be transmitted if (sauceUsername != null && sauceAccessKey != null && platformString != null) { String jobId = popupPage.getDriver().getSessionId().toString(); // build sauceLabs result String url = "https://saucelabs.com/rest/v1/" + sauceUsername + "/jobs/" + jobId; restClient.authenticate("https://saucelabs.com", sauceUsername, sauceAccessKey.toCharArray()); restClient.withHeader("Content-Type", "application/json"); restClient.json(url, put(content("{\"passed\": " + testResult + ", \"name\": \"Firespotting! " + platformString + " Test\", \"build\": \"" + buildNr + "\"}"))); } this.popupPage.tearDown(); } /** * This method isolates the getting of the env variable for better testability. * * @param envVariableName the name of the env variable we want to get */ protected String getSystemVariable(String envVariableName) { return System.getenv(envVariableName); } /** * We want to know, if every method has succeeded. If one method fails, testResult == false. * * @param result Results of all testMethods. */ @AfterMethod(alwaysRun = true) public void report(ITestResult result) { testResult &= result.isSuccess(); } /** * This test checks, if the chrome extension is installed on the remote system. We want to get the extension id * by the remote host (every chrome browser will generate another id). If the id is present, we assume, the the * extension is installed correctly. */ @Test public void isInstalled() { assertTrue(popupPage.getId() != null, "We got null back. The extension is not installed properly"); } /** * Test for checking the popup window. */ @Test public void testPopup() { popupPage.open(); // check title assertEquals(popupPage.getTitle(), "Firespotting!"); } /** * Clicks on every item and checks, if it loads. */ //@Test public void testEntry() { popupPage.open(); // check if all entries are there for (int i = 1; i <= ENTRY_LIST_LENGTH; i++) { String linkText = popupPage.getEntryTitle(i); assertNotNull(linkText); popupPage.clickOnEntryLink(linkText); popupPage.getBack(); } } /** * Clicks on the issues link and checks, if it loads. */ //@Test public void testIssues() { popupPage.open(); popupPage.getDriver().navigate().refresh(); popupPage.getIssues().click(); assertTrue(popupPage.getDriver().getTitle().startsWith(ISSUES_PAGE_TITLE)); } /** * Clicks on refresh link. * * @throws InterruptedException */ @Test public void testRefresh() throws InterruptedException { popupPage.open(); popupPage.getRefreshLink().click(); WebDriverWait driverWait = createWebDriverWait(popupPage.getDriver(), TIME_TO_WAIT_FOR_REFRESH); driverWait.until(new Predicate<WebDriver>() { @Override public boolean apply(org.openqa.selenium.WebDriver webDriver) { return popupPage.getTitle().equals("Firespotting!"); }; }); assertEquals(popupPage.getTitle(), "Firespotting!"); } /** * Just a helper method to create a WebDriverWait * * @param driver The driver we want to configure * @param timeToWaitForRefresh The time the driver should wait for a refresh * * @return a newly created WebDriverWait */ protected WebDriverWait createWebDriverWait(WebDriver driver, long timeToWaitForRefresh) { return new WebDriverWait(driver, timeToWaitForRefresh); } /** * Clicks on Options link. */ @Test public void testOpenOptions() { popupPage.open(); popupPage.getDriver().navigate().refresh(); popupPage.getOptionsLink().click(); popupPage.switchToNewTab(); assertEquals(popupPage.getTitle(), "Options"); } }
package com.manmoe.example.test; import com.google.common.base.Predicate; import com.manmoe.example.model.PopupPage; import com.sun.istack.internal.Nullable; import org.openqa.selenium.WebDriver; import org.openqa.selenium.support.ui.WebDriverWait; import org.testng.annotations.AfterClass; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertNotNull; import static org.testng.Assert.assertTrue; public class FirespottingIT extends AbstractChromeExtensionTest { private static final String EXTENSION_NAME_FROM_MANIFEST = "Firespotting! Interesting Ideas, Every Day!"; /** * This is our testmodel. So we don't get lost in details, how to get some elements. */ protected PopupPage popupPage; /** * Method for setting up the test environment. */ @BeforeClass public void setUp() { this.popupPage = new PopupPage(getWebDriver(), EXTENSION_NAME_FROM_MANIFEST); } /** * We tell the remote selenium server here, that we have finished. */ @AfterClass public void tearDown() { this.popupPage.tearDown(); } /** * This test checks, if the chrome extension is installed on the remote system. We want to get the extension id * by the remote host (every chrome browser will generate another id). If the id is present, we assume, the the * extension is installed correctly. */ @Test public void isInstalled() { assertTrue(popupPage.getId() != null, "We got null back. The extension is not installed properly"); } /** * Test for checking the popup window. */ @Test public void testPopup() { popupPage.open(); // check title assertEquals(popupPage.getTitle(), "Firespotting!"); } /** * Clicks on every item and checks, if it loads. */ @Test public void testEntry() { popupPage.open(); // check if all 15 entries are there for (int i = 1; i <= 15; i++) { String linkText = popupPage.getEntryTitle(i); assertNotNull(popupPage.getEntryTitle(i)); popupPage.clickOnEntryLink(linkText); popupPage.getBack(); } } /** * Clicks on the issues link and checks, if it loads. */ @Test public void testIssues() { popupPage.open(); popupPage.getDriver().navigate().refresh(); popupPage.getIssues().click(); assertTrue(popupPage.getDriver().getTitle().startsWith("Issues · quitschibo/firespotting-chrome-extension")); } /** * Clicks on refresh link. * * @throws InterruptedException */ @Test public void testRefresh() throws InterruptedException { popupPage.open(); popupPage.getRefreshLink().click(); WebDriverWait driverWait = new WebDriverWait(popupPage.getDriver(), 3L); driverWait.until(new Predicate<WebDriver>() { @Override public boolean apply(@Nullable org.openqa.selenium.WebDriver webDriver) { return popupPage.getTitle().equals("Firespotting!"); }; }); assertEquals(popupPage.getTitle(), "Firespotting!"); } /** * Clicks on Options link. */ @Test public void testOpenOptions() { popupPage.open(); popupPage.getDriver().navigate().refresh(); popupPage.getOptionsLink().click(); popupPage.switchToNewTab(); assertEquals(popupPage.getTitle(), "Options"); } }
package com.matt.forgehax.mods; import com.matt.forgehax.events.RenderEvent; import com.matt.forgehax.util.color.Colors; import com.matt.forgehax.util.command.Setting; import com.matt.forgehax.util.mod.Category; import com.matt.forgehax.util.mod.ToggleMod; import com.matt.forgehax.util.mod.loader.RegisterMod; import com.matt.forgehax.util.schematica.Schematic; import com.matt.forgehax.util.schematica.SchematicaHelper; import com.matt.forgehax.util.tesselation.GeometryMasks; import com.matt.forgehax.util.tesselation.GeometryTessellator; import java.util.Optional; import java.util.OptionalInt; import net.minecraft.block.Block; import net.minecraft.block.state.IBlockState; import net.minecraft.client.renderer.GlStateManager; import net.minecraft.client.renderer.vertex.DefaultVertexFormats; import net.minecraft.item.ItemBlock; import net.minecraft.item.ItemStack; import net.minecraft.util.Tuple; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.RayTraceResult; import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; import org.lwjgl.opengl.GL11; @RegisterMod public class SchematicHelper extends ToggleMod { private final Setting<Float> line_width = getCommandStub() .builders() .<Float>newSettingBuilder() .name("width") .description("Line width") .defaultTo(5f) .min(1f) .build(); public SchematicHelper() { super(Category.RENDER, "SchematicHelper", false, "Render box where a block would be placed"); } @SubscribeEvent public void onRender(RenderEvent event) { if (!SchematicaHelper.isSchematicaPresent()) return; final ItemStack heldStack = MC.player.getHeldItemMainhand(); if (heldStack.isEmpty()) { return; } if (!(heldStack.getItem() instanceof ItemBlock)) { return; } final Block block = ((ItemBlock) heldStack.getItem()).getBlock(); final int metaData = heldStack.getMetadata(); // using metadata is gay and not 1.13 compatible but dont know a better way to get blockstate from itemstack final IBlockState heldBlockState = block.getStateFromMeta(metaData); getBlockPlacePos().ifPresent(pos -> getColor(pos, heldBlockState).ifPresent(color -> { event.getBuffer().begin(GL11.GL_LINES, DefaultVertexFormats.POSITION_COLOR); GlStateManager.glLineWidth(line_width.get()); GeometryTessellator.drawCuboid(event.getBuffer(), pos, GeometryMasks.Line.ALL, color); event.getTessellator().draw(); }) ); } private static OptionalInt getColor(BlockPos pos, IBlockState heldBlock) { final Optional<Tuple<Schematic, BlockPos>> optSchematic = SchematicaHelper.getOpenSchematic(); if (optSchematic.isPresent()) { final Schematic schematic = optSchematic.get().getFirst(); final BlockPos schematicOffset = optSchematic.get().getSecond(); final BlockPos schematicPos = pos.subtract(schematicOffset); if (schematic.inSchematic(schematicPos)) { final IBlockState schematicBlock = schematic.desiredState(schematicPos); return OptionalInt .of(schematicBlock.equals(heldBlock) ? Colors.GREEN.toBuffer() : Colors.RED.toBuffer()); } else { return OptionalInt.empty(); } } else { return OptionalInt.empty(); } } private static Optional<BlockPos> getBlockPlacePos() { return Optional.ofNullable(MC.objectMouseOver) .filter(result -> result.typeOfHit == RayTraceResult.Type.BLOCK) .map(ray -> ray.getBlockPos().offset(ray.sideHit)); } }
package com.modym.client.objects; import java.math.BigDecimal; import java.util.List; import org.apache.commons.lang3.text.WordUtils; import org.joda.time.LocalDateTime; import lombok.Getter; import lombok.Setter; /** * @author bashar * */ @Getter @Setter public class ModymPurchase extends UDFType { private long purchaseId; private String purchaseReferenceId; private long customerId; private String customerReferenceId; private long sourceId; private long sourceReferenceId; private String sourceName; private String note; private LocalDateTime purchaseDate; private BigDecimal earnedPoints; private BigDecimal subtotal; private BigDecimal discount; private BigDecimal tax; private BigDecimal shipping; private BigDecimal grandtotal; private BigDecimal cost; private String currency; private PurchaseStatus status; private List<ModymPurchaseLineItem> lineItems; @Getter @Setter public static class ModymPurchaseLineItem { private long productId; private String productName; private String sku; private BigDecimal quantity; private BigDecimal unitPrice; private BigDecimal unitCost; private BigDecimal lineTotal; } public static enum PurchaseStatus { COMPLETE, CANCELLED, PENDING, CLOSED; @Override public String toString() { return WordUtils.capitalizeFully(this.name()).replaceAll("_", " "); }; } }
package com.nexmo.client.verify; import com.nexmo.client.HttpWrapper; import com.nexmo.client.NexmoClientException; import java.io.IOException; import java.util.ArrayList; import java.util.List; public class SearchEndpoint { private SearchMethod searchMethod; SearchEndpoint(HttpWrapper httpWrapper) { this.searchMethod = new SearchMethod(httpWrapper); } SearchResult[] search(String... requestIds) throws IOException, NexmoClientException { return translateFromSearchVerifyResponse(this.searchMethod.execute(new SearchRequest(requestIds))); } private SearchResult[] translateFromSearchVerifyResponse(SearchVerifyResponse response) { // TODO: Remove in 4.0 List<SearchResult> resultList = new ArrayList<>(); if (response.getStatus() != VerifyStatus.OK) { resultList.add(new SearchResult(response.getStatus().getVerifyStatus(), response.getErrorText(), response.getStatus().isTemporaryError())); } else { for (VerifyDetails details : response.getVerificationRequests()) { resultList.add(new SearchResult(response.getStatus().getVerifyStatus(), details.getRequestId(), details.getAccountId(), translateFromVerifyDetailsStatus(details.getStatus()), details.getNumber(), details.getPrice() != null ? details.getPrice().floatValue() : 0, details.getCurrency(), details.getSenderId(), details.getDateSubmitted(), details.getDateFinalized(), details.getFirstEventDate(), details.getLastEventDate(), translateFromVerifyCheck(details.getChecks()), response.getErrorText(), false)); } } return resultList.toArray(new SearchResult[0]); } private SearchResult.VerificationStatus translateFromVerifyDetailsStatus(VerifyDetails.Status status) { // TODO: Remove in 4.0 // This operates in the same way the XML endpoint does without logging the error. try { return status != null ? SearchResult.VerificationStatus.valueOf(status.name()) : null; } catch (IllegalArgumentException e) { return null; } } private List<SearchResult.VerifyCheck> translateFromVerifyCheck(List<VerifyCheck> checks) { // TODO: Remove in 4.0 List<SearchResult.VerifyCheck> resultChecks = new ArrayList<>(); for (VerifyCheck check : checks) { resultChecks.add(new SearchResult.VerifyCheck(check.getDate(), check.getCode(), SearchResult.VerifyCheck.Status.valueOf(check.getStatus().name()), check.getIpAddress())); } return resultChecks; } }
package com.nhn.pinpoint.web.vo; /** * * @author netspider * * @param <V> * @param <M> */ public class ResultWithMark<V, M> { private V value; private M mark; public V getValue() { return value; } public void setValue(V value) { this.value = value; } public M getMark() { return mark; } public void setMark(M mark) { this.mark = mark; } @Override public String toString() { return "ResultWithMark [value=" + value + ", mark=" + mark + "]"; } }
package com.nkming.utils.widget; import android.animation.Animator; import android.animation.AnimatorListenerAdapter; import android.animation.ObjectAnimator; import android.content.Context; import android.graphics.PixelFormat; import android.graphics.Point; import android.graphics.PointF; import android.graphics.Rect; import android.os.Handler; import android.view.Gravity; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.View; import android.view.ViewConfiguration; import android.view.WindowManager; import android.view.animation.AccelerateDecelerateInterpolator; import android.view.animation.AccelerateInterpolator; import android.view.animation.DecelerateInterpolator; import android.widget.FrameLayout; import com.nkming.utils.Log; import com.nkming.utils.Res; import com.nkming.utils.sys.DeviceInfo; import com.nkming.utils.type.Size; import com.nkming.utils.unit.DimensionUtils; public class PersistentView { public static class Config { public Handler handler; public Context context; /// Resource id for the content view public int resId; /// Alpha value for the view when idle public float alpha = 1.0f; /// Percentage of width that is beyond the edge of the screen public float hiddenW = 0.15f; } public PersistentView(Config config) { mHandler = config.handler; mContext = config.context; mWindowManager = (WindowManager)mContext.getSystemService( Context.WINDOW_SERVICE); Size screenSz = DeviceInfo.getScreenPx(mContext); // Init with a good enough rect mScreenRect = new Rect(0, 0, screenSz.w(), screenSz.h()); initView(config); initDummyView(); mChild.setScaleX(0); mChild.setScaleY(0); show(null); mPrimaryId = -1; mInitialTouchPos = new PointF(); mViewPos = new Point(); mIsMoving = false; mAlpha = config.alpha; mHiddenW = config.hiddenW; mIsAutohide = false; mLongPressRunnable = new Runnable() { @Override public void run() { onLongPress(); } }; } public void show(Animator.AnimatorListener listener) { Log.d(LOG_TAG, "show(...)"); setTouchable(true); mChild.animate().scaleX(1.0f).scaleY(1.0f) .setInterpolator(new DecelerateInterpolator()) .setDuration(Res.ANIMATION_FAST) .setListener(listener); } public void hide(Animator.AnimatorListener listener) { Log.d(LOG_TAG, "hide(...)"); reset(true); // A hidden view should not be responding to touch setTouchable(false); mChild.animate().scaleX(0.0f).scaleY(0.0f) .setInterpolator(new AccelerateInterpolator()) .setDuration(Res.ANIMATION_FAST) .setListener(listener); } public void destroy() { Log.d(LOG_TAG, "destroy()"); mWindowManager.removeView(mContainer); mWindowManager.removeView(mDummyView[0]); mWindowManager.removeView(mDummyView[1]); } /** * Listen to click event on this view * * @param l */ public void setOnClickListener(View.OnClickListener l) { mContainer.setOnClickListener(l); } /** * Listen to long click/press event on this view * * @param l */ public void setOnLongClickListener(View.OnLongClickListener l) { mContainer.setOnLongClickListener(l); } /** * To hide the persistent view when running a fullscreen app * * @param flag */ public void setAutohide(boolean flag) { mIsAutohide = flag; } /** * For the ObjectAnimator and animate the view * * @param x */ public void setX(int x) { mLayoutParams.x = x; mWindowManager.updateViewLayout(mContainer, mLayoutParams); } /** * For the ObjectAnimator and animate the view * * @param y */ public void setY(int y) { mLayoutParams.y = y; mWindowManager.updateViewLayout(mContainer, mLayoutParams); } public void setAlpha(float alpha) { alpha = Math.max(Math.min(alpha, 1.0f), 0.0f); mAlpha = alpha; if (mPrimaryId == -1) { // Set immediately if view is idle, otherwise wait until reset() mChild.animate().alpha(mAlpha) .setInterpolator(new AccelerateDecelerateInterpolator()) .setDuration(Res.ANIMATION_FAST); } } public void setEnableHaptic(boolean flag) { mContainer.setHapticFeedbackEnabled(flag); } private static final String LOG_TAG = PersistentView.class.getCanonicalName(); private class ContainerView extends FrameLayout { public ContainerView(Context context) { super(context); } @Override public boolean onTouchEvent(MotionEvent event) { switch (event.getActionMasked()) { case MotionEvent.ACTION_DOWN: onActionDown(event); break; case MotionEvent.ACTION_POINTER_UP: if (event.getActionIndex() == mPrimaryId) { if (mPrimaryId != -1 && !mIsMoving) { onClick(); } else { reset(false); } } break; case MotionEvent.ACTION_UP: if (mPrimaryId != -1 && !mIsMoving) { onClick(); } else { reset(false); } break; case MotionEvent.ACTION_CANCEL: reset(false); break; case MotionEvent.ACTION_MOVE: if (event.getActionIndex() == mPrimaryId) { onActionMove(event); } break; } return true; } @Override protected void onLayout(boolean changed, int left, int top, int right, int bottom) { super.onLayout(changed, left, top, right, bottom); if (!mHasLayout) { mHasLayout = true; int x = (int)(mScreenRect.width() - getWidth() * (1.0f - mHiddenW)); int y = (int)(mScreenRect.height() * 0.15f); mViewPos.set(x, y); updatePosition(x, y); } } } private void initView(Config config) { mContainer = new ContainerView(mContext); /// Setting attachToRoot to true works differently which we don't want mChild = LayoutInflater.from(mContext).inflate(config.resId, mContainer, false); mChild.setAlpha(config.alpha); mContainer.addView(mChild); mLayoutParams = new WindowManager.LayoutParams( WindowManager.LayoutParams.WRAP_CONTENT, WindowManager.LayoutParams.WRAP_CONTENT, WindowManager.LayoutParams.TYPE_SYSTEM_ALERT, WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE | WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN | WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS, PixelFormat.TRANSLUCENT); mLayoutParams.gravity = Gravity.TOP | Gravity.LEFT; mWindowManager.addView(mContainer, mLayoutParams); } /** * Init the dummy views to detect changes in the screen size */ private void initDummyView() { // We use two views, one for horizontal and one for vertical in order to // prevent having one view to cover the whole screen, which will disable // views with filterTouchesWhenObscured for (int i = 0; i < 2; ++i) { mDummyView[i] = new View(mContext); WindowManager.LayoutParams params = new WindowManager.LayoutParams( (i == 0) ? WindowManager.LayoutParams.MATCH_PARENT : 0, (i == 0) ? 0 : WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.TYPE_SYSTEM_OVERLAY, WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE, PixelFormat.TRANSLUCENT); params.gravity = Gravity.TOP | Gravity.LEFT; mWindowManager.addView(mDummyView[i], params); } final Rect oldRect = new Rect(); mDummyView[0].addOnLayoutChangeListener(new View.OnLayoutChangeListener() { @Override public void onLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) { Log.d(LOG_TAG + ".OnLayoutChangeListener", "onLayoutChange(0)"); if (left != oldRect.left || top != oldRect.top || right != oldRect.right) { // Bottom is invalid in this view Rect newRect = new Rect(left, top, right, oldRect.bottom); onScreenLayoutChange(newRect, oldRect); oldRect.set(newRect); } } }); mDummyView[1].addOnLayoutChangeListener(new View.OnLayoutChangeListener() { @Override public void onLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) { Log.d(LOG_TAG + ".OnLayoutChangeListener", "onLayoutChange(1)"); if (left != oldRect.left || top != oldRect.top || bottom != oldRect.bottom) { // Right is invalid in this view Rect newRect = new Rect(left, top, oldRect.right, bottom); onScreenLayoutChange(newRect, oldRect); oldRect.set(newRect); } } }); } private void onActionDown(MotionEvent event) { mPrimaryId = event.getActionIndex(); mInitialTouchPos = new PointF(event.getRawX(), event.getRawY()); mHandler.postDelayed(mLongPressRunnable, ViewConfiguration.getLongPressTimeout()); for (int i = 0; i < mSnapAnimators.length; ++i) { if (mSnapAnimators[i] != null) { mSnapAnimators[i].cancel(); mSnapAnimators[i] = null; } } } private void onActionMove(MotionEvent event) { boolean wasMoving = mIsMoving; evaluateMoving(event); if (mIsMoving != wasMoving) { onTransitMoveMode(); } // Take center int y = (int)event.getRawY() - mChild.getHeight() / 2; int x = (int)event.getRawX() - mChild.getWidth() / 2; updatePosition(x, y); } /** * User has moved enough distance that we can safely recognize as a move */ private void onTransitMoveMode() { Log.d(LOG_TAG, "onTransitMoveMode()"); mHandler.removeCallbacks(mLongPressRunnable); mChild.animate().alpha(1.0f) .setInterpolator(new AccelerateDecelerateInterpolator()) .setDuration(Res.ANIMATION_FAST); } private void onClick() { Log.d(LOG_TAG, "onClick()"); mContainer.performClick(); reset(true); } private void onLongPress() { Log.d(LOG_TAG, "onLongPress()"); mContainer.performLongClick(); reset(true); } private void onScreenLayoutChange(Rect newRect, Rect oldRect) { Log.d(LOG_TAG, "onScreenLayoutChange()"); int location[] = new int[2]; mDummyView[0].getLocationOnScreen(location); Log.d(LOG_TAG + ".OnLayoutChangeListener", newRect.left + "," + oldRect.left + "\n" + newRect.top + "," + oldRect.top + "\n" + newRect.right + "," + oldRect.right + "\n" + newRect.bottom + "," + oldRect.bottom + "\n" + location[0] + "," + location[1]); Rect rect = new Rect(newRect.left + location[0], newRect.top + location[1], newRect.right + location[0], newRect.bottom + location[1]); if (isFullscreen(rect) && !isFullscreen(mScreenRect)) { onIntoFullscreen(); } else if (!isFullscreen(rect) && isFullscreen(mScreenRect)) { onOutOfFullscreen(); } mScreenRect.set(rect); snap(true); } private void onIntoFullscreen() { Log.d(LOG_TAG, "onIntoFullscreen()"); if (mIsAutohide) { hide(null); } } private void onOutOfFullscreen() { Log.d(LOG_TAG, "onOutOfFullscreen()"); if (mIsAutohide) { show(null); } } private void snap(boolean isAnimate) { // Bound the top and bottom int y = Math.max(Math.min(mLayoutParams.y, mScreenRect.bottom - mChild.getHeight()), mScreenRect.top); int x; // Take center if ((mLayoutParams.x + mChild.getWidth() / 2) < mScreenRect.width() / 2 + mScreenRect.left) { x = (int)(mScreenRect.left - mChild.getWidth() * mHiddenW); } else { x = (int)(mScreenRect.right - mChild.getWidth() * (1.0f - mHiddenW)); } mViewPos.set(x, y); if (isAnimate) { updatePositionAnimated(x, y); } else { updatePosition(x, y); } } private void backInitial(boolean isAnimate) { if (isAnimate) { updatePositionAnimated(mViewPos.x, mViewPos.y); } else { updatePosition(mViewPos.x, mViewPos.y); } } /** * Reset the view's state. If the view is moving, it would be either snapped * to the closest border or back to its initial position, depending on * @a isBackInitial * * @param isBackInitial */ private void reset(boolean isBackInitial) { if (mPrimaryId != -1) { if (isBackInitial) { backInitial(true); } else { snap(true); } mChild.animate().alpha(mAlpha) .setInterpolator(new AccelerateDecelerateInterpolator()) .setDuration(Res.ANIMATION_FAST); mPrimaryId = -1; mInitialTouchPos = new PointF(); mIsMoving = false; mHandler.removeCallbacks(mLongPressRunnable); } } private void evaluateMoving(MotionEvent event) { float threshold = DimensionUtils.dpToPx(mContext, 24); if (Math.abs(event.getRawX() - mInitialTouchPos.x) >= threshold || Math.abs(event.getRawY() - mInitialTouchPos.y) >= threshold) { mIsMoving = true; } } private void updatePosition(int x, int y) { mLayoutParams.x = x; mLayoutParams.y = y; mWindowManager.updateViewLayout(mContainer, mLayoutParams); } private void updatePositionAnimated(int x, int y) { ObjectAnimator animX = ObjectAnimator.ofInt(this, "x", mLayoutParams.x, x); animX.setInterpolator(new AccelerateDecelerateInterpolator()); animX.setDuration(Res.ANIMATION_FAST); animX.addListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animation) { mSnapAnimators[0] = null; } }); animX.start(); mSnapAnimators[0] = animX; ObjectAnimator animY = ObjectAnimator.ofInt(this, "y", mLayoutParams.y, y); animY.setInterpolator(new AccelerateDecelerateInterpolator()); animY.setDuration(Res.ANIMATION_FAST); animY.addListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animation) { mSnapAnimators[1] = null; } }); animY.start(); mSnapAnimators[1] = animY; } private boolean isFullscreen(Rect rect) { if (mFullscreenSize == null) { mFullscreenSize = DeviceInfo.getFullScreenPx(mContext); } // Check whether the orientation is the same if ((rect.height() > rect.width()) == (mFullscreenSize.h() > mFullscreenSize.w())) { return (rect.width() == mFullscreenSize.w() && rect.height() == mFullscreenSize.h()); } else { return (rect.height() == mFullscreenSize.w() && rect.width() == mFullscreenSize.h()); } } private void setTouchable(boolean flag) { if (flag) { mLayoutParams.flags &= ~WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE; } else { mLayoutParams.flags |= WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE; } mWindowManager.updateViewLayout(mContainer, mLayoutParams); } private int mPrimaryId; private PointF mInitialTouchPos; // The position where the view should be, it could be different with the // actual position during animation private Point mViewPos; private Rect mScreenRect; private Size mFullscreenSize; private boolean mIsMoving; private boolean mHasLayout = false; private ObjectAnimator mSnapAnimators[] = new ObjectAnimator[2]; private float mAlpha; private float mHiddenW; private boolean mIsAutohide; private Context mContext; private Handler mHandler; private Runnable mLongPressRunnable; private ContainerView mContainer; private View mChild; private WindowManager mWindowManager; private WindowManager.LayoutParams mLayoutParams; // Used to detect app hiding navigation bar private View mDummyView[] = new View[2]; }
package com.pearson.statsagg.webui; import com.pearson.statsagg.database_objects.suspensions.Suspension; import com.pearson.statsagg.database_objects.suspensions.SuspensionsDao; import com.pearson.statsagg.database_objects.alerts.Alert; import com.pearson.statsagg.database_objects.alerts.AlertsDao; import java.io.PrintWriter; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.pearson.statsagg.globals.GlobalVariables; import com.pearson.statsagg.utilities.KeyValue; import com.pearson.statsagg.utilities.StackTrace; import com.pearson.statsagg.utilities.StringUtilities; import java.util.Map; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * @author Jeffrey Schmidt */ @WebServlet(name = "Suspensions", urlPatterns = {"/Suspensions"}) public class Suspensions extends HttpServlet { private static final Logger logger = LoggerFactory.getLogger(Suspensions.class.getName()); public static final String PAGE_NAME = "Suspensions"; /** * Handles the HTTP * <code>GET</code> method. * * @param request servlet request * @param response servlet response */ @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) { processGetRequest(request, response); } /** * Handles the HTTP * <code>POST</code> method. * * @param request servlet request * @param response servlet response */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) { processPostRequest(request, response); } /** * Returns a short description of the servlet. * * @return a String containing servlet description */ @Override public String getServletInfo() { return PAGE_NAME; } protected void processGetRequest(HttpServletRequest request, HttpServletResponse response) { if ((request == null) || (response == null)) { return; } try { request.setCharacterEncoding("UTF-8"); response.setCharacterEncoding("UTF-8"); response.setContentType("text/html"); } catch (Exception e) { logger.error(e.toString() + System.lineSeparator() + StackTrace.getStringFromStackTrace(e)); } PrintWriter out = null; try { String html = buildSuspensionsHtml(); Document htmlDocument = Jsoup.parse(html); String htmlFormatted = htmlDocument.toString(); out = response.getWriter(); out.println(htmlFormatted); } catch (Exception e) { logger.error(e.toString() + System.lineSeparator() + StackTrace.getStringFromStackTrace(e)); } finally { if (out != null) { out.close(); } } } protected void processPostRequest(HttpServletRequest request, HttpServletResponse response) { if ((request == null) || (response == null)) { return; } try { request.setCharacterEncoding("UTF-8"); response.setCharacterEncoding("UTF-8"); response.setContentType("text/html"); } catch (Exception e) { logger.error(e.toString() + System.lineSeparator() + StackTrace.getStringFromStackTrace(e)); } try { String operation = request.getParameter("Operation"); if ((operation != null) && operation.equals("Enable")) { Integer suspensionId = Integer.parseInt(request.getParameter("Id")); Boolean isEnabled = Boolean.parseBoolean(request.getParameter("Enabled")); changeSuspensionEnabled(suspensionId, isEnabled); } if ((operation != null) && operation.equals("Clone")) { Integer suspensionId = Integer.parseInt(request.getParameter("Id")); cloneSuspension(suspensionId); } if ((operation != null) && operation.equals("Remove")) { Integer suspensionId = Integer.parseInt(request.getParameter("Id")); removeSuspension(suspensionId); } } catch (Exception e) { logger.error(e.toString() + System.lineSeparator() + StackTrace.getStringFromStackTrace(e)); } StatsAggHtmlFramework.redirectAndGet(response, 303, "Suspensions"); } public String changeSuspensionEnabled(Integer suspensionId, Boolean isEnabled) { if ((suspensionId == null) || (isEnabled == null)) { return "Invalid input!"; } boolean isSuccess = false; SuspensionsDao suspensionsDao = new SuspensionsDao(); Suspension suspension = suspensionsDao.getSuspension(suspensionId); if (suspension != null) { suspension.setIsEnabled(isEnabled); SuspensionsLogic suspensionsLogic = new SuspensionsLogic(); suspensionsLogic.alterRecordInDatabase(suspension, suspension.getName()); if (suspensionsLogic.getLastAlterRecordStatus() == SuspensionsLogic.STATUS_CODE_SUCCESS) { isSuccess = true; com.pearson.statsagg.alerts.Suspensions suspensions = new com.pearson.statsagg.alerts.Suspensions(); suspensions.runSuspensionRoutine(); } } if (isSuccess && isEnabled) return "Successfully enabled suspension"; if (isSuccess && !isEnabled) return "Successfully disabled suspension"; else return "Error -- could not alter suspension"; } private void cloneSuspension(Integer suspensionId) { if (suspensionId == null) { return; } try { SuspensionsDao suspensionsDao = new SuspensionsDao(false); Suspension suspension = suspensionsDao.getSuspension(suspensionId); List<Suspension> allSuspensions = suspensionsDao.getAllDatabaseObjectsInTable(); suspensionsDao.close(); if ((suspension != null) && (suspension.getName() != null)) { Set<String> allSuspensionsNames = new HashSet<>(); for (Suspension currentSuspension : allSuspensions) { if (currentSuspension.getName() != null) { allSuspensionsNames.add(currentSuspension.getName()); } } Suspension clonedSuspension = Suspension.copy(suspension); clonedSuspension.setId(-1); String clonedSuspensionName = StatsAggHtmlFramework.createCloneName(suspension.getName(), allSuspensionsNames); clonedSuspension.setName(clonedSuspensionName); clonedSuspension.setUppercaseName(clonedSuspensionName.toUpperCase()); SuspensionsLogic suspensionsLogic = new SuspensionsLogic(); suspensionsLogic.alterRecordInDatabase(clonedSuspension); com.pearson.statsagg.alerts.Suspensions suspensions = new com.pearson.statsagg.alerts.Suspensions(); suspensions.runSuspensionRoutine(); } } catch (Exception e) { logger.error(e.toString() + System.lineSeparator() + StackTrace.getStringFromStackTrace(e)); } } public String removeSuspension(Integer suspensionId) { String returnString = "Suspension id can't be null"; if (suspensionId == null) return returnString; try{ SuspensionsDao suspensionsDao = new SuspensionsDao(); Suspension suspension = suspensionsDao.getSuspension(suspensionId); if (suspension == null) return null; SuspensionsLogic suspensionsLogic = new SuspensionsLogic(); returnString = suspensionsLogic.deleteRecordInDatabase(suspension.getName()); com.pearson.statsagg.alerts.Suspensions suspensions = new com.pearson.statsagg.alerts.Suspensions(); suspensions.runSuspensionRoutine(); return returnString; } catch (Exception e) { logger.error(e.toString() + System.lineSeparator() + StackTrace.getStringFromStackTrace(e)); returnString = "Error removing suspension"; return returnString; } } private String buildSuspensionsHtml() { StringBuilder html = new StringBuilder(); StatsAggHtmlFramework statsAggHtmlFramework = new StatsAggHtmlFramework(); String htmlHeader = statsAggHtmlFramework.createHtmlHeader("StatsAgg - " + PAGE_NAME, ""); StringBuilder htmlBodyStringBuilder = new StringBuilder(); htmlBodyStringBuilder.append( "<div id=\"page-content-wrapper\">\n" + "<!-- Keep all page content within the page-content inset div! -->\n" + "<div class=\"page-content inset statsagg_page_content_font\">\n" + " <div class=\"content-header\"> \n" + " <div class=\"pull-left content-header-h2-min-width-statsagg\"> <h2> " + PAGE_NAME + " </h2> </div>\n" + " <div class=\"pull-right \">\n" + " <a href=\"CreateSuspension\" class=\"btn btn-primary statsagg_page_content_font\">Create New Suspension <i class=\"fa fa-long-arrow-right\"></i></a> \n" + " </div>\n" + " </div>\n" + " <table id=\"SuspensionsTable\" style=\"display:none\" class=\"table table-bordered table-hover\">\n" + " <thead>\n" + " <tr>\n" + " <th>Suspension Name</th>\n" + " <th>Suspend By</th>\n" + " <th>Suspend By Details</th>\n" + " <th># Alert Associations</th>\n" + " <th>Enabled?</th>\n" + " <th>Operations</th>\n" + " </tr>\n" + " </thead>\n" + " <tbody>\n"); SuspensionsDao suspensionsDao = new SuspensionsDao(); List<Suspension> suspensions = suspensionsDao.getAllDatabaseObjectsInTable(); for (Suspension suspension : suspensions) { if (suspension.isOneTime() && suspension.getDeleteAtTimestamp() != null) { if (System.currentTimeMillis() >= suspension.getDeleteAtTimestamp().getTime()) continue; } String rowAlertStatusContext = ""; if (Suspension.isSuspensionActive(suspension)) rowAlertStatusContext = "class=\"info\""; String suspensionDetails = "<a class=\"iframe cboxElement\" href=\"SuspensionDetails?ExcludeNavbar=true&amp;Name=" + StatsAggHtmlFramework.urlEncode(suspension.getName()) + "\">" + StatsAggHtmlFramework.htmlEncode(suspension.getName()) + "</a>"; String suspendBy; StringBuilder suspendByDetails = new StringBuilder(); if (suspension.getSuspendBy() == Suspension.SUSPEND_BY_ALERT_ID) { suspendBy = "Alert Name"; if (suspension.getAlertId() != null) { AlertsDao alertsDao = new AlertsDao(); Alert alert = alertsDao.getAlert(suspension.getAlertId()); if ((alert != null) && (alert.getName() != null)) { String alertDetails = "<a class=\"iframe cboxElement\" href=\"AlertDetails?ExcludeNavbar=true&amp;Name=" + StatsAggHtmlFramework.urlEncode(alert.getName()) + "\">" + StatsAggHtmlFramework.htmlEncode(alert.getName()) + "</a>"; suspendByDetails.append(alertDetails); } } } else if (suspension.getSuspendBy() == Suspension.SUSPEND_BY_METRIC_GROUP_TAGS) { suspendBy = "Metric Group Tags"; List<String> tags = StringUtilities.getListOfStringsFromDelimitedString(suspension.getMetricGroupTagsInclusive(), '\n'); if (tags != null) { for (int i = 0; i < tags.size(); i++) { suspendByDetails.append("<u>").append(StatsAggHtmlFramework.htmlEncode(tags.get(i))).append("</u>"); if ((i + 1) < tags.size()) suspendByDetails.append("&nbsp;&nbsp;"); } } } else if (suspension.getSuspendBy() == Suspension.SUSPEND_BY_EVERYTHING) { suspendBy = "Everything"; List<String> tags = StringUtilities.getListOfStringsFromDelimitedString(suspension.getMetricGroupTagsExclusive(), '\n'); if (tags != null) { for (int i = 0; i < tags.size(); i++) { suspendByDetails.append("<u>").append(StatsAggHtmlFramework.htmlEncode(tags.get(i))).append("</u>"); if ((i + 1) < tags.size()) suspendByDetails.append("&nbsp;&nbsp;"); } } } else if (suspension.getSuspendBy() == Suspension.SUSPEND_BY_METRICS) { suspendBy = "Metrics"; Set<String> matchingMetricKeysAssociatedWithSuspension = GlobalVariables.matchingMetricKeysAssociatedWithSuspension.get(suspension.getId()); int matchingMetricKeysAssociatedWithSuspension_Count = 0; if (matchingMetricKeysAssociatedWithSuspension != null) matchingMetricKeysAssociatedWithSuspension_Count = matchingMetricKeysAssociatedWithSuspension.size(); String associatedAlertsPopup = ("<a class=\"iframe cboxElement\" href=\"Suspension-MetricKeyAssociations?ExcludeNavbar=true&amp;Name=" + StatsAggHtmlFramework.urlEncode(suspension.getName()) + "\">" + StatsAggHtmlFramework.htmlEncode("# Metric Associations: " + Integer.toString(matchingMetricKeysAssociatedWithSuspension_Count)) + "</a>"); suspendByDetails.append(associatedAlertsPopup); } else { suspendBy = "?"; } Map<Integer, Set<Integer>> alertIdAssociationsBySuspensionId; synchronized(GlobalVariables.suspensionIdAssociationsByAlertId) { alertIdAssociationsBySuspensionId = com.pearson.statsagg.alerts.Suspensions.getAlertIdAssociationsBySuspensionId(GlobalVariables.suspensionIdAssociationsByAlertId); } Set<Integer> alertIdAssociations = alertIdAssociationsBySuspensionId.get(suspension.getId()); int suspensionAssociationCount; if (alertIdAssociations == null) suspensionAssociationCount = 0; else suspensionAssociationCount = alertIdAssociations.size(); String alertsAssociationsPopup = ("<a class=\"iframe cboxElement\" href=\"Suspension-AlertAssociations?ExcludeNavbar=true&amp;Name=" + StatsAggHtmlFramework.urlEncode(suspension.getName()) + "\">" + suspensionAssociationCount + "</a>"); String isAlertEnabled = "No"; if ((suspension.isEnabled() != null) && suspension.isEnabled()) isAlertEnabled = "Yes"; String enable; if (suspension.isEnabled()) { List<KeyValue> keysAndValues = new ArrayList<>(); keysAndValues.add(new KeyValue("Operation", "Enable")); keysAndValues.add(new KeyValue("Id", suspension.getId().toString())); keysAndValues.add(new KeyValue("Enabled", "false")); enable = StatsAggHtmlFramework.buildJavaScriptPostLink("Enable_" + suspension.getName(), "Suspensions", "disable", keysAndValues); } else { List<KeyValue> keysAndValues = new ArrayList<>(); keysAndValues.add(new KeyValue("Operation", "Enable")); keysAndValues.add(new KeyValue("Id", suspension.getId().toString())); keysAndValues.add(new KeyValue("Enabled", "true")); enable = StatsAggHtmlFramework.buildJavaScriptPostLink("Enable_" + suspension.getName(), "Suspensions", "enable", keysAndValues); } String alter = "<a href=\"CreateSuspension?Operation=Alter&amp;Name=" + StatsAggHtmlFramework.urlEncode(suspension.getName()) + "\">alter</a>"; List<KeyValue> cloneKeysAndValues = new ArrayList<>(); cloneKeysAndValues.add(new KeyValue("Operation", "Clone")); cloneKeysAndValues.add(new KeyValue("Id", suspension.getId().toString())); String clone = StatsAggHtmlFramework.buildJavaScriptPostLink("Clone_" + suspension.getName(), "Suspensions", "clone", cloneKeysAndValues); List<KeyValue> removeKeysAndValues = new ArrayList<>(); removeKeysAndValues.add(new KeyValue("Operation", "Remove")); removeKeysAndValues.add(new KeyValue("Id", suspension.getId().toString())); String remove = StatsAggHtmlFramework.buildJavaScriptPostLink("Remove_" + suspension.getName(), "Suspensions", "remove", removeKeysAndValues, true, "Are you sure you want to remove this suspension?"); htmlBodyStringBuilder .append("<tr ").append(rowAlertStatusContext).append(">\n") .append("<td class=\"statsagg_force_word_break\">").append(suspensionDetails).append("</td>\n") .append("<td>").append(suspendBy).append("</td>\n") .append("<td class=\"statsagg_force_word_break\">").append(suspendByDetails).append("</td>\n") .append("<td>").append(alertsAssociationsPopup).append("</td>\n") .append("<td>").append(isAlertEnabled).append("</td>\n") .append("<td>").append(enable).append(", ").append(alter).append(", ").append(clone).append(", ").append(remove).append("</td>\n") .append("</tr>\n"); } htmlBodyStringBuilder.append("" + "</tbody>\n" + "<tfoot> \n" + " <tr>\n" + " <th></th>\n" + " <th></th>\n" + " <th></th>\n" + " <th></th>\n" + " <th></th>\n" + " <th></th>\n" + " </tr>\n" + "</tfoot>" + "</table>\n" + "</div>\n" + "</div>\n"); String htmlBody = (statsAggHtmlFramework.createHtmlBody(htmlBodyStringBuilder.toString())); html.append("" + "<!DOCTYPE html>\n" + "<html>\n") .append(htmlHeader) .append(htmlBody) .append("</html>"); return html.toString(); } }
package com.rafaskoberg.gdx.typinglabel; import com.badlogic.gdx.math.MathUtils; import com.badlogic.gdx.utils.Array; import com.badlogic.gdx.utils.reflect.ClassReflection; import com.badlogic.gdx.utils.reflect.Constructor; import com.badlogic.gdx.utils.reflect.ReflectionException; import regexodus.Matcher; import regexodus.Pattern; import regexodus.REFlags; /** Utility class to parse tokens from a {@link TypingLabel}. */ class Parser { private static final Pattern PATTERN_MARKUP_STRIP = Pattern.compile("(\\[{2})|(\\[ private static final String[] BOOLEAN_TRUE = {"true", "yes", "t", "y", "on", "1"}; private static final int INDEX_TOKEN = 1; private static final int INDEX_PARAM = 2; private static Pattern PATTERN_TOKEN_STRIP; private static String RESET_REPLACEMENT; /** Parses all tokens from the given {@link TypingLabel}. */ static void parseTokens(TypingLabel label) { // Compile patterns if necessary if(PATTERN_TOKEN_STRIP == null || TypingConfig.dirtyEffectMaps) { PATTERN_TOKEN_STRIP = compileTokenPattern(); } if(RESET_REPLACEMENT == null || TypingConfig.dirtyEffectMaps) { RESET_REPLACEMENT = getResetReplacement(); } // Adjust and check markup color if(label.forceMarkupColor) label.getBitmapFontCache().getFont().getData().markupEnabled = true; // Remove any previous entries label.tokenEntries.clear(); // Parse all tokens with text replacements, namely color and var. parseReplacements(label); // Parse all regular tokens and properly register them parseRegularTokens(label); // Parse color markups and register SKIP tokens parseColorMarkups(label); // Sort token entries label.tokenEntries.sort(); label.tokenEntries.reverse(); } /** Parse tokens that only replace text, such as colors and variables. */ private static void parseReplacements(TypingLabel label) { // Get text CharSequence text = label.getText(); boolean hasMarkup = label.getBitmapFontCache().getFont().getData().markupEnabled; // Create string builder StringBuilder sb = new StringBuilder(text.length()); Matcher m = PATTERN_TOKEN_STRIP.matcher(text); int matcherIndexOffset = 0; // Iterate through matches while(true) { // Reset StringBuilder and matcher sb.setLength(0); m.setTarget(text); m.setPosition(matcherIndexOffset); // Make sure there's at least one regex match if(!m.find()) break; // Get token and parameter final InternalToken internalToken = InternalToken.fromName(m.group(INDEX_TOKEN)); final String param = m.group(INDEX_PARAM); // If token couldn't be parsed, move one index forward to continue the search if(internalToken == null) { matcherIndexOffset++; continue; } // Process tokens and handle replacement String replacement = ""; switch(internalToken) { case COLOR: if(hasMarkup) replacement = stringToColorMarkup(param); break; case CLEARCOLOR: if(hasMarkup) replacement = "[#" + label.getClearColor().toString() + "]"; break; case VAR: String variable = param; replacement = null; // Try to replace variable through listener. if(label.getTypingListener() != null) { replacement = label.getTypingListener().replaceVariable(variable); } // If replacement is null, get value from maps. if(replacement == null) { variable = variable.toUpperCase(); replacement = label.getVariables().get(variable, variable); } // Make sure we're not inserting "null" to the text. if(replacement == null) replacement = ""; break; case RESET: replacement = RESET_REPLACEMENT + label.getDefaultToken(); break; default: // We don't want to process this token now. Move one index forward to continue the search matcherIndexOffset++; continue; } // Update text with replacement m.setPosition(m.start()); text = m.replaceFirst(replacement); } // Set new text label.setText(text, false); } /** Parses regular tokens that don't need replacement and register their indexes in the {@link TypingLabel}. */ private static void parseRegularTokens(TypingLabel label) { // Get text CharSequence text = label.getText(); // Create matcher and StringBuilder Matcher m = PATTERN_TOKEN_STRIP.matcher(text); StringBuilder sb = new StringBuilder(text.length()); int matcherIndexOffset = 0; // Iterate through matches while(true) { // Reset matcher and StringBuilder m.setTarget(text); sb.setLength(0); m.setPosition(matcherIndexOffset); // Make sure there's at least one regex match if(!m.find()) break; // Get token name and category String tokenName = m.group(INDEX_TOKEN).toUpperCase(); TokenCategory tokenCategory = null; InternalToken tmpToken = InternalToken.fromName(tokenName); if(tmpToken == null) { if(TypingConfig.EFFECT_START_TOKENS.containsKey(tokenName)) { tokenCategory = TokenCategory.EFFECT_START; } else if(TypingConfig.EFFECT_END_TOKENS.containsKey(tokenName)) { tokenCategory = TokenCategory.EFFECT_END; } } else { tokenCategory = tmpToken.category; } // Get token, param and index of where the token begins int groupCount = m.groupCount(); final String paramsString = groupCount == INDEX_PARAM ? m.group(INDEX_PARAM) : null; final String[] params = paramsString == null ? new String[0] : paramsString.split(";"); final String firstParam = params.length > 0 ? params[0] : null; final int index = m.start(0); int indexOffset = 0; // If token couldn't be parsed, move one index forward to continue the search if(tokenCategory == null) { matcherIndexOffset++; continue; } // Process tokens float floatValue = 0; String stringValue = null; Effect effect = null; switch(tokenCategory) { case WAIT: { floatValue = stringToFloat(firstParam, TypingConfig.DEFAULT_WAIT_VALUE); break; } case EVENT: { stringValue = paramsString; indexOffset = -1; break; } case SPEED: { switch(tokenName) { case "SPEED": float minModifier = TypingConfig.MIN_SPEED_MODIFIER; float maxModifier = TypingConfig.MAX_SPEED_MODIFIER; float modifier = MathUtils.clamp(stringToFloat(firstParam, 1), minModifier, maxModifier); floatValue = TypingConfig.DEFAULT_SPEED_PER_CHAR / modifier; break; case "SLOWER": floatValue = TypingConfig.DEFAULT_SPEED_PER_CHAR / 0.500f; break; case "SLOW": floatValue = TypingConfig.DEFAULT_SPEED_PER_CHAR / 0.667f; break; case "NORMAL": floatValue = TypingConfig.DEFAULT_SPEED_PER_CHAR; break; case "FAST": floatValue = TypingConfig.DEFAULT_SPEED_PER_CHAR / 2.000f; break; case "FASTER": floatValue = TypingConfig.DEFAULT_SPEED_PER_CHAR / 4.000f; break; } break; } case EFFECT_START: { Class<? extends Effect> clazz = TypingConfig.EFFECT_START_TOKENS.get(tokenName.toUpperCase()); try { if(clazz != null) { Constructor constructor = ClassReflection.getConstructors(clazz)[0]; int constructorParamCount = constructor.getParameterTypes().length; if(constructorParamCount >= 2) { effect = (Effect) constructor.newInstance(label, params); } else { effect = (Effect) constructor.newInstance(label); } } } catch(ReflectionException e) { String message = "Failed to initialize " + tokenName + " effect token. Make sure the associated class (" + clazz + ") has only one constructor with TypingLabel as first parameter and optionally String[] as second."; throw new IllegalStateException(message, e); } break; } case EFFECT_END: { break; } } // Register token TokenEntry entry = new TokenEntry(tokenName, tokenCategory, index + indexOffset, floatValue, stringValue); entry.effect = effect; label.tokenEntries.add(entry); // Set new text without tokens m.setPosition(0); text = m.replaceFirst(""); } // Update label text label.setText(text, false); } /** Parse color markup tags and register SKIP tokens. */ private static void parseColorMarkups(TypingLabel label) { // Get text final CharSequence text = label.getText(); // Iterate through matches and register skip tokens Matcher m = PATTERN_MARKUP_STRIP.matcher(text); while(m.find()) { final String tag = m.group(0); final int index = m.start(0); label.tokenEntries.add(new TokenEntry("SKIP", TokenCategory.SKIP, index, 0, tag)); } } /** Returns a float value parsed from the given String, or the default value if the string couldn't be parsed. */ static float stringToFloat(String str, float defaultValue) { if(str != null) { try { return Float.parseFloat(str); } catch(Exception e) { } } return defaultValue; } /** Returns a boolean value parsed from the given String, or the default value if the string couldn't be parsed. */ static boolean stringToBoolean(String str) { if(str != null) { for(String booleanTrue : BOOLEAN_TRUE) { if(booleanTrue.equalsIgnoreCase(str)) { return true; } } } return false; } /** Encloses the given string in brackets to work as a regular color markup tag. */ private static String stringToColorMarkup(String str) { if(str != null) str = str.toUpperCase(); return "[" + str + "]"; } /** * Returns a compiled {@link Pattern} that groups the token name in the first group and the params in an optional * second one. Case insensitive. */ private static Pattern compileTokenPattern() { StringBuilder sb = new StringBuilder(); sb.append("\\{("); Array<String> tokens = new Array<>(); TypingConfig.EFFECT_START_TOKENS.keys().toArray(tokens); TypingConfig.EFFECT_END_TOKENS.keys().toArray(tokens); for(InternalToken token : InternalToken.values()) { tokens.add(token.name); } for(int i = 0; i < tokens.size; i++) { sb.append(tokens.get(i)); if((i + 1) < tokens.size) sb.append('|'); } sb.append(")(?:=([; return Pattern.compile(sb.toString(), REFlags.IGNORE_CASE); } /** Returns the replacement string intended to be used on {RESET} tokens. */ private static String getResetReplacement() { Array<String> tokens = new Array<>(); TypingConfig.EFFECT_END_TOKENS.keys().toArray(tokens); tokens.add("CLEARCOLOR"); tokens.add("NORMAL"); StringBuilder sb = new StringBuilder(); for(String token : tokens) { sb.append('{').append(token).append('}'); } return sb.toString(); } }
package cz.muni.fi.jboss.migration.utils; import cz.muni.fi.jboss.migration.RollbackData; import cz.muni.fi.jboss.migration.ex.CliScriptException; import org.apache.commons.io.FileUtils; import org.apache.commons.io.filefilter.FileFilterUtils; import org.apache.commons.io.filefilter.NameFileFilter; import org.w3c.dom.Document; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.util.Collection; import java.util.Enumeration; import java.util.List; import java.util.jar.JarEntry; import java.util.jar.JarFile; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import org.xml.sax.SAXException; /** * Global utils class. * * @author Roman Jakubco */ public class Utils { /** * Method for testing if given string is null or empty and if it is then CliScriptException is thrown with given message * * @param string string for testing * @param errMsg message for exception * @param name name of property of tested value * @throws CliScriptException if tested string is empty or null */ public static void throwIfBlank(String string, String errMsg, String name) throws CliScriptException { if ((string == null) || (string.isEmpty())) { throw new CliScriptException(name + errMsg); } } /** * Helping method for writing help. */ public static void writeHelp() { System.out.println(); System.out.println(" Usage:"); System.out.println(); System.out.println(" java -jar AsMigrator.jar [<option>, ...] [as5.dir=]<as5.dir> [as7.dir=]<as7.dir>"); System.out.println(); System.out.println(" Options:"); System.out.println(); System.out.println(" as5.profile=<name>"); System.out.println(" Path to AS 5 profile."); System.out.println(" Default: \"default\""); System.out.println(); System.out.println(" as7.confPath=<path> "); System.out.println(" Path to AS 7 config file."); System.out.println(" Default: \"standalone/configuration/standalone.xml\""); System.out.println(); System.out.println(" conf.<module>.<property>=<value> := Module-specific options."); System.out.println(" <module> := Name of one of modules. E.g. datasource, jaas, security, ..."); System.out.println(" <property> := Name of the property to set. Specific per module. " + "May occur multiple times."); System.out.println(); } /** * Utils class for finding name of jar file containing class from logging configuration. * * @param className name of the class which must be found * @param dirAS5 AS5 home dir * @param profileAS5 name of AS5 profile * @return name of jar file which contains given class * @throws FileNotFoundException if the jar file is not found * * TODO: This would cause false positives - e.g. class = org.Foo triggered by org/Foo/Blah.class . */ public static String findJarFileWithClass(String className, String dirAS5, String profileAS5) throws FileNotFoundException, IOException { String classFilePath = className.replace(".", "/"); // First look for jar file in lib directory in given AS5 profile File dir = Utils.createPath(dirAS5, "server", profileAS5, "lib"); File jar = lookForJarWithAClass( dir, classFilePath ); if( jar != null ) return jar.getName(); // If not found in profile's lib directory then try common/lib folder (common jars for all profiles) dir = Utils.createPath(dirAS5, "common", profileAS5, "lib"); jar = lookForJarWithAClass( dir, classFilePath ); if( jar != null ) return jar.getName(); throw new FileNotFoundException("Cannot find jar file which contains class: " + className); } private static File lookForJarWithAClass( File dir, String classFilePath ) throws IOException { //SuffixFileFilter sf = new SuffixFileFilter(".jar"); //List<File> list = (List<File>) FileUtils.listFiles(dir, sf, FileFilterUtils.makeCVSAware(null)); Collection<File> list = FileUtils.listFiles(dir, new String[]{".jar"}, true); for( File file : list ) { try (JarFile jarFile = new JarFile(file)) { final Enumeration<JarEntry> entries = jarFile.entries(); while (entries.hasMoreElements()) { final JarEntry entry = entries.nextElement(); if( ( ! entry.isDirectory() ) && entry.getName().contains(classFilePath)) { // Assuming that jar file contains some package with class (common Java practice) //return StringUtils.substringAfterLast(file.getPath(), "/"); return file; } } } } return null; } /** * Searching for file, which is represented as RollbackData in the application, in given directory * * @param rollData object representing file for search * @param dir directory for searching * @return list of found files */ public static List<File> searchForFile(RollbackData rollData, File dir) { NameFileFilter nff; if (rollData.getType().equals(RollbackData.Type.DRIVER)) { final String name = rollData.getName(); nff = new NameFileFilter(name) { @Override public boolean accept(File file) { return file.getName().contains(name) && file.getName().contains("jar"); } }; } else { nff = new NameFileFilter(rollData.getName()); } List<File> list = (List<File>) FileUtils.listFiles(dir, nff, FileFilterUtils.makeCVSAware(null)); // One more search for driver jar. Other types of rollbackData just return list. if(rollData.getType().equals(RollbackData.Type.DRIVER)) { // For now only expecting one jar for driver. Pick the first one. if (list.isEmpty()) { // Special case for freeware jdbc driver jdts.jar if (rollData.getAltName() != null) { final String altName = rollData.getAltName(); nff = new NameFileFilter(altName) { @Override public boolean accept(File file) { return file.getName().contains(altName) && file.getName().contains("jar"); } }; List<File> altList = (List<File>) FileUtils.listFiles(dir, nff, FileFilterUtils.makeCVSAware(null)); return altList; } } } return list; } /** * Builds up a File object with path consisting of given components. */ public static File createPath( String parent, String child, String ... more) { File file = new File(parent, child); for( String component : more ) { file = new File(file, component); } return file; } /** * Creates a new default document builder. */ public static DocumentBuilder createXmlDocumentBuilder() { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(false); try { return dbf.newDocumentBuilder(); } catch( ParserConfigurationException ex ){ throw new RuntimeException(ex); // Tunnel } } public static Document parseXmlToDoc( File file ) throws SAXException, IOException { DocumentBuilder db = Utils.createXmlDocumentBuilder(); Document doc = db.parse(file); return doc; } }// class
package de.themoep.inventorygui; import org.bukkit.inventory.ItemStack; /** * This is an element that allows for controlling the pagination of the gui. * <b>Untested und potentially unfinished.</b> */ public class GuiPageElement extends StaticGuiElement { private PageAction pageAction; /** * An element that allows for controlling the pagination of the gui. * @param slotChar The character to replace in the gui setup string * @param item The {@link ItemStack} representing this element * @param pageAction What kind of page action you want to happen when interacting with the element. * @param text The text to display on this element, placeholders are automatically * replaced, see {@link InventoryGui#replaceVars} for a list of the * placeholder variables. Empty text strings are also filter out, use * a single space if you want to add an empty line!<br> * If it's not set/empty the item's default name will be used */ public GuiPageElement(char slotChar, ItemStack item, PageAction pageAction, String... text) { super(slotChar, item, click -> { switch (pageAction) { case NEXT: if (click.getGui().getPageNumber() + 1 < click.getGui().getPageAmount()) { click.getGui().playClickSound(); click.getGui().setPageNumber(click.getGui().getPageNumber() + 1); } break; case PREVIOUS: if (click.getGui().getPageNumber() > 0) { click.getGui().playClickSound(); click.getGui().setPageNumber(click.getGui().getPageNumber() - 1); } break; case FIRST: click.getGui().playClickSound(); click.getGui().setPageNumber(0); break; case LAST: click.getGui().playClickSound(); click.getGui().setPageNumber(click.getGui().getPageAmount() - 1); break; } return true; }, text); this.pageAction = pageAction; } @Override public ItemStack getItem(int slot) { if ((pageAction == PageAction.NEXT && gui.getPageNumber() + 1 >= gui.getPageAmount()) || (pageAction == PageAction.PREVIOUS && gui.getPageNumber() == 0)) { return gui.getFiller().getItem(slot); } try { if (pageAction == PageAction.PREVIOUS) { setNumber(gui.getPageNumber()); } else if (pageAction == PageAction.NEXT) { setNumber(gui.getPageNumber() + 2); } else if (pageAction == PageAction.LAST) { setNumber(gui.getPageAmount()); } } catch (IllegalArgumentException e) { // cannot set that item amount/number as it isn't supported in Minecraft setNumber(1); } return super.getItem(slot).clone(); } public enum PageAction { NEXT, PREVIOUS, FIRST, LAST; } }
package dk.aau.sw402F15.CodeGenerator; import dk.aau.sw402F15.Symboltable.Scope; import dk.aau.sw402F15.Symboltable.ScopeDepthFirstAdapter; import dk.aau.sw402F15.Symboltable.Symbol; import dk.aau.sw402F15.Symboltable.SymbolArray; import dk.aau.sw402F15.Symboltable.SymbolFunction; import dk.aau.sw402F15.Symboltable.Type.SymbolType; import dk.aau.sw402F15.parser.node.*; import sun.reflect.generics.reflectiveObjects.NotImplementedException; import java.awt.geom.FlatteningPathIterator; import java.io.FileNotFoundException; import java.io.PrintWriter; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.EmptyStackException; public class CodeGenerator extends ScopeDepthFirstAdapter { private int jumpLabel = 0; private int returnlabel; private int nextDAddress = 0; private int nextWAddress = 0; private int nextHAddress = 0; private ArrayList<String> functions; PrintWriter instructionWriter; PrintWriter symbolWriter; public String getNextDAddress(boolean increment) { if (nextDAddress > 32763) throw new OutOfMemoryError(); if (increment) return "D" + (nextDAddress += 2); else return "D" + nextDAddress; } public String getPreviousDAddress() { int tmp = nextDAddress; return "D" + (nextDAddress - 2); } public String getNextWAddress(boolean increment) { if (nextWAddress > 508) throw new OutOfMemoryError(); if (increment) return "W" + ((nextWAddress += 1) * 100); else return "W" + nextWAddress * 100; } public String stackPointer(boolean increment) { if (nextHAddress > 4091) throw new OutOfMemoryError(); int currentAddress = nextHAddress; nextHAddress += 4; if (increment) return "H" + (currentAddress); else return "H" + currentAddress; } public <T> void push(T value) { if (value.getClass() == Integer.class) Emit("MOVL(498) &" + value + " " + stackPointer(true), true); else if (value.getClass() == Float.class || value.getClass() == Double.class) Emit("+F(454) +0,0 +" + value.toString().replace(".", ",") + " " + stackPointer(true) + "", true); else if (value.getClass() == String.class) Emit("MOVL(498) " + value + " " + stackPointer(true), true); else throw new ClassFormatError(); } public String pop() { if (nextHAddress < 0) throw new EmptyStackException(); return "H" + (nextHAddress -= 4); } public String peek() { return "H" + nextHAddress; } public CodeGenerator(Scope scope, ArrayList functions) { super(scope, scope); this.functions = functions; try { // create writer instances instructionWriter = new PrintWriter("InstructionList.txt", "UTF-8"); symbolWriter = new PrintWriter("SymbolList.txt", "UTF-8"); // here we call the init method Emit("LD P_First_Cycle", true); // reset all addresses Emit("SSET(630) " + getNextDAddress(true) + " &32767", true); Emit("SSET(630) " + stackPointer(true) + " &1535", true); Emit("SBS(091) 0", true); // here we call the run Method Emit("LD P_On", true); Emit("SBS(091) 1", true); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } } @Override public void outStart(Start node){ Emit("END(001)", true); instructionWriter.close(); symbolWriter.close(); } @Override public void caseAAssignmentExpr(AAssignmentExpr node) { inAAssignmentExpr(node); if(node.getRight() != null) { node.getRight().apply(this); } if(node.getLeft() != null) { node.getLeft().apply(this); } outAAssignmentExpr(node); } @Override public void outAAssignmentExpr(AAssignmentExpr node) { super.outAAssignmentExpr(node); if(node.getLeft().getClass() == AArrayExpr.class){ String address = pop(); Emit("MOVL(498) " + pop() + " @" + address, true); } else if (!(node.getLeft() instanceof APortOutputExpr)){ Emit("MOVL(498) " + pop() + " " + node.getLeft(), true); } } @Override public void outAArrayExpr(AArrayExpr node){ SymbolArray symbol = (SymbolArray) currentScope.getSymbolOrThrow(node.getName().getText(), node.getName()); push(node.getName().getText()); int size = 1; if (symbol.getContainedType().getType() == SymbolType.Type.Decimal) { size = 2; Emit("*(420) " + pop() + " &2 " + stackPointer(true), true); } // index * size = offset Emit("+(400) " + pop() + " " + pop() + " " + stackPointer(true), true); // offset + start = location Node parent = node.parent(); if (parent.getClass() != AAssignmentExpr.class || ((AAssignmentExpr)parent).getLeft() != node) { String address = pop(); Emit("MOVL(498) @" + address + " " + stackPointer(true), true); // push value to stack if(size == 2) { Emit("+(400) " + address + " 1 " + stackPointer(true), true); Emit("MOVL(498) @" + pop() + " " + stackPointer(true), true); } } } @Override public void caseADeclaration(ADeclaration node){ super.caseADeclaration(node); } @Override public void outABreakStatement(ABreakStatement node){ super.outABreakStatement(node); Emit("BREAK(514)", true); } @Override public void outACaseStatement(ACaseStatement node){ //throw new NotImplementedException(); } @Override public void outAIncrementExpr(AIncrementExpr node) { super.outAIncrementExpr(node); Emit("++(590) " + node.getName(), true); } @Override public void outADecrementExpr(ADecrementExpr node) { super.outADecrementExpr(node); Emit("--(592) " + node.getName(), true); } @Override public void outACompareAndExpr(ACompareAndExpr node){ super.outACompareAndExpr(node); Emit("ANDW(034) D" + (nextDAddress - 4) + " " + getNextDAddress(false) + " " + getNextDAddress(true), true); } @Override public void outACompareOrExpr(ACompareOrExpr node){ super.outACompareOrExpr(node); Emit("ORW(035) D" + (nextDAddress - 4) + " " + getNextDAddress(false) + " " + getNextDAddress(true), true); } @Override public void outACompareEqualExpr(ACompareEqualExpr node){ super.outACompareEqualExpr(node); String arg1 = pop(); String arg2 = pop(); Emit("AND=(300)" + " " + arg2 + " " + arg1, true); Emit("SET " + getNextWAddress(true), true); } @Override public void outACompareGreaterExpr(ACompareGreaterExpr node){ super.outACompareGreaterExpr(node); String arg1 = pop(); String arg2 = pop(); Emit("AND>(320)" + " " + arg2 + " " + arg1, true); Emit("SET " + getNextWAddress(true), true); } @Override public void outACompareGreaterOrEqualExpr(ACompareGreaterOrEqualExpr node){ super.outACompareGreaterOrEqualExpr(node); String arg1 = pop(); String arg2 = pop(); Emit("AND>=(325)" + " " + arg2 + " " + arg1, true); Emit("SET " + getNextWAddress(true), true); } @Override public void outACompareLessExpr(ACompareLessExpr node){ super.outACompareLessExpr(node); String arg1 = pop(); String arg2 = pop(); if (node.parent().getClass() == AWhileStatement.class) { Emit("AND<(310)" + " " + arg1 + " " + arg2, true); Emit("SET " + getNextWAddress(false), true); Emit("AND<(310)" + " " + arg2 + " " + arg1, true); Emit("RSET " + getNextWAddress(false), true); } else { Emit("AND<(310)" + " " + arg2 + " " + arg1, true); Emit("SET " + getNextWAddress(false), true); } } @Override public void outACompareLessOrEqualExpr(ACompareLessOrEqualExpr node) { super.outACompareLessOrEqualExpr(node); String arg1 = pop(); String arg2 = pop(); Emit("AND<=(315)" + " " + arg2 + " " + arg1, true); Emit("SET " + getNextWAddress(true), true); } @Override public void outACompareNotEqualExpr(ACompareNotEqualExpr node) { super.outACompareNotEqualExpr(node); String arg1 = pop(); String arg2 = pop(); Emit("AND<>(305)" + " " + arg2 + " " + arg1, true); Emit("SET " + getNextWAddress(true), true); } @Override public void outAContinueStatement(AContinueStatement node){ //throw new NotImplementedException(); } @Override public void outADeclaration(ADeclaration node) { Symbol symbol = currentScope.getSymbolOrThrow(node.getName().getText(), node); if (symbol.getType().equals(SymbolType.Boolean())) { if (node.getExpr() != null){ declareAndAssignBool(node.getName().getText(), pop()); } else { declareBool(node.getName().getText()); } } else if (symbol.getType().equals(SymbolType.Int())) { if (node.getExpr() != null){ declareAndAssignInt(node.getName().getText(), pop()); } else { declareInt(node.getName().getText()); } } else if (symbol.getType().equals(SymbolType.Char())) { throw new NotImplementedException(); } else if (symbol.getType().equals(SymbolType.Decimal())) { if (node.getExpr() != null){ declareAndAssignDecimal(node.getName().getText(), pop()); } else { declareDecimal(node.getName().getText()); } } else if (symbol.getType().equals(SymbolType.Timer())) { if (node.getExpr() != null){ declareAndAssignTimer(node.getName().getText(), pop()); } else { declareTimer(node.getName().getText()); } } else if (symbol.getType().equals(SymbolType.Timer())) { throw new NotImplementedException(); } else if (symbol.getType().equals(SymbolType.Array())) { declareArray((SymbolArray)symbol); } else if (symbol.getType().equals(SymbolType.Void())){ // Method is a void function throw new NotImplementedException(); } else if (symbol.getType().equals(SymbolType.Type.Function)) { throw new NotImplementedException(); } else if (symbol.getType().equals(SymbolType.Type.Struct)) { throw new NotImplementedException(); } else { // throw new RuntimeException(); // TODO Need new Exception. Pretty unknown error though } } private void declareArray(SymbolArray symbol){ ADeclaration node = (ADeclaration) symbol.getNode(); AArrayDefinition array = (AArrayDefinition) node.getArray(); int size = Integer.parseInt(array.getNumber().getText()); int address = nextDAddress; for (int i = 0; i < size; i++){ getNextDAddress(true); } String name = symbol.getName(); Emit(name + "\tINT\t &"+ address + "\t\t0\t", false); Emit("MOVL(498) &" + (address + 2) + " " + name, true); } private void declareInt(String name){ // get next free address in symbolList String address = getNextDAddress(true); // Declare Emit(name + "\tINT\t" + address + "\t\t0\t", false); } private void declareAndAssignInt(String name, String value){ // get next free address in symbolList String address = getNextDAddress(true); // Declare Emit(name + "\tINT\t" + address + "\t\t0\t", false); // Assign Emit("MOVL(498) " + value + " " + name, true); } private void declareBool(String name){ // get next free address in symbolList String address = getNextWAddress(true); // Declare Emit(name + "\tBOOL\t" + address + "\t\t0\t", false); } private void declareAndAssignBool(String name, String value){ // get next free address in symbolList String address = getNextWAddress(true); // Declare Emit(name + "\tBOOL\t" + address + "\t\t0\t", false); // assign Emit("LD P_On",false); Emit("OUT TR0",false); Emit("AND " + value,false); Emit("SET " + name,false); Emit("LD TR0",false); Emit("ANDNOT " + value,false); Emit("RSET " + name,false); } private void declareDecimal(String name){ // get next free address in symbolList String address = getNextDAddress(true); // Declare Emit(name + "\tREAL\t" + address + "\t\t0\t", false); } private void declareAndAssignDecimal(String name, String value){ // get next free address in symbolList String address = getNextDAddress(true); // Declare Emit(name + "\tREAL\t" + address + "\t\t0\t", false); // Assign Emit("MOVL(498) " + value + " " + name, true); } private void declareTimer(String name){ throw new NotImplementedException(); // get next free address in symbolList //String address = getNextDAddress(true); //Emit(node.getName().getText() + "\tTIMER\tD" + getNextDAddress(true) + "\t\t0\t", false); // Declare //Emit(name + "\tBOOL\t" + address + ".00\t\t0\t", false); // Assign //Emit("MOVL(498) &" + value + " " + address, true); } private void declareAndAssignTimer(String name, String value){ throw new NotImplementedException(); } @Override public void outADefaultStatement(ADefaultStatement node){ //throw new NotImplementedException(); } @Override public void inAFunctionCallExpr(AFunctionCallExpr node){ SymbolFunction function = (SymbolFunction) currentScope.getSymbolOrThrow(node.getName().getText(), node); if (function.getReturnType().equals(SymbolType.Type.Void)) { Emit("LD P_On", true); Emit("SBS(091) " + functions.indexOf(node.getName().getText()), true); } else { Emit("MCRO(099) " + functions.indexOf(node.getName().getText()) + " " + getNextDAddress(true) + " " + pop(), true); } //Emit("SBS(091) " + getFunctionNumber(true), true); } @Override public void inAFunctionRootDeclaration(AFunctionRootDeclaration node){ super.inAFunctionRootDeclaration(node); Emit("SBN(092) " + functions.indexOf(node.getName().getText()), true); if (!node.getStatements().isEmpty()) Emit("LD P_First_Cycle", true); //returnlabel = getNextJump(); } @Override public void outAFunctionRootDeclaration(AFunctionRootDeclaration node) { super.outAFunctionRootDeclaration(node); //Emit("JME(005) #" + returnlabel, true); Emit("RET(093)", true); //Emit("END(001)", true); } @Override public void outAIdentifierExpr(AIdentifierExpr node){ push(node.getName().getText()); } @Override public void outAMemberExpr(AMemberExpr node){ //throw new NotImplementedException(); } @Override public void outANegationExpr(ANegationExpr node){ super.outANegationExpr(node); Emit("NOT " + getNextDAddress(false), true); } @Override public void outAPortAnalogInputExpr(APortAnalogInputExpr node){ //throw new NotImplementedException(); } @Override public void outAPortAnalogOutputExpr(APortAnalogOutputExpr node){ //throw new NotImplementedException(); } @Override public void outAPortInputExpr(APortInputExpr node){ //throw new NotImplementedException(); } @Override public void outAPortOutputExpr(APortOutputExpr node){ super.outAPortOutputExpr(node); Emit("LD " + getNextWAddress(false), true); Emit("OUT " + node.getExpr(), true); } @Override public void outAReturnStatement(AReturnStatement node){ super.outAReturnStatement(node); //Emit("JMP(004) #" + returnlabel, true); //Emit("RET(093)", true); } @Override public void outASwitchStatement(ASwitchStatement node){ //throw new NotImplementedException(); } @Override public void outATrueExpr(ATrueExpr node){ super.outATrueExpr(node); Emit("MOVL(498) #1 " + getNextDAddress(true), true); Emit("SET " + getNextWAddress(true), true); } @Override public void outAFalseExpr(AFalseExpr node) { super.outAFalseExpr(node); Emit("MOVL(498) #0 " + getNextDAddress(true), true); Emit("RSET " + getNextWAddress(true), true); } @Override public void outATypeCastExpr(ATypeCastExpr node){ //throw new NotImplementedException(); } @Override public void caseABranchStatement(ABranchStatement node) { //Do not call super as this function handles calls of the child classes if (node.getRight() != null) { // If - else statement int ifLabel = getNextJump(); int elseLabel = getNextJump(); node.getCondition().apply(this); Emit("CJP(510) #" + ifLabel, true); node.getRight().apply(this); Emit("JMP(004) #" + elseLabel, true); Emit("JME(005) #" + ifLabel, true); node.getLeft().apply(this); Emit("JME(005) #" + elseLabel, true); } else { // If statement int label = getNextJump(); node.getCondition().apply(this); Emit("CJPN(511) #" + label, true); node.getLeft().apply(this); Emit("JME(005) #" + label, true); } } @Override public void caseASwitchStatement(ASwitchStatement node){ //throw new NotImplementedException(); } @Override public void caseAWhileStatement(AWhileStatement node){ int jumpLabel = getNextJump(); int loopLabel = getNextJump(); //node.getCondition().apply(this); Emit("LDNOT " + getNextWAddress(true), true); Emit("JMP(004) #" + jumpLabel, true); node.getStatement().apply(this); node.getCondition().apply(this); Emit("JME(005) #" + jumpLabel, true); Emit("LD P_On", true); } @Override public void outAIntegerExpr(AIntegerExpr node) { super.outAIntegerExpr(node); push(Integer.parseInt(node.getIntegerLiteral().getText())); // TODO Ouch, a hack... } @Override public void outADecimalExpr(ADecimalExpr node) { super.outADecimalExpr(node); if (!(node.parent() instanceof APortOutputExpr)) push(Float.parseFloat(node.getDecimalLiteral().getText())); } @Override public void outAAddExpr(AAddExpr node) { super.outAAddExpr(node); String arg1 = pop(); String arg2 = pop(); if (node.getRight() instanceof ADecimalExpr) Emit("+F(454) " + arg1 + " " + arg2 + " " + stackPointer(true), true); else Emit("+(400) " + arg1 + " " + arg2 + " " + stackPointer(true), true); } @Override public void outADivExpr(ADivExpr node) { super.outADivExpr(node); String arg1 = pop(); String arg2 = pop(); if (node.getRight() instanceof ADecimalExpr) Emit("/F(457) " + arg1 + " " + arg2 + " " + stackPointer(true), true); else Emit("/(430) " + pop() + " " + pop() + " " + stackPointer(true), true); } @Override public void outAMultiExpr(AMultiExpr node) { super.outAMultiExpr(node); String arg1 = pop(); String arg2 = pop(); if (node.getRight() instanceof ADecimalExpr) Emit("*F(456) " + arg1 + " " + arg2 + " " + stackPointer(true), true); else Emit("*(420) " + pop() + " " + pop() + " " + stackPointer(true), true); } @Override public void outASubExpr(ASubExpr node) { super.outASubExpr(node); String arg1 = pop(); String arg2 = pop(); if (node.getRight() instanceof ADecimalExpr) Emit("-F(455) " + arg1 + " " + arg2 + " " + stackPointer(true), true); else Emit("-(410) " + pop() + " " + pop() + " " + stackPointer(true), true); } private int getNextJump(){ jumpLabel = jumpLabel + 1; if(jumpLabel > 255) throw new IndexOutOfBoundsException(); return jumpLabel; } protected void Emit(String s, boolean instruction){ if (instruction == true) { // Write to InstructionList, if instruction instructionWriter.println(s); } else { // Otherwise it's a symbol, then write to SymbolList symbolWriter.println(s); } } }
package de.tum.in.www1.artemis.domain; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonSubTypes; import com.fasterxml.jackson.annotation.JsonTypeInfo; import com.fasterxml.jackson.annotation.JsonView; import de.tum.in.www1.artemis.domain.enumeration.ParticipationState; import de.tum.in.www1.artemis.domain.view.QuizView; import org.hibernate.annotations.Cache; import org.hibernate.annotations.CacheConcurrencyStrategy; import javax.persistence.*; import java.io.Serializable; import java.time.ZonedDateTime; import java.util.HashSet; import java.util.List; import java.util.Objects; import java.util.Set; /** * A Exercise. */ @Entity @Table(name = "exercise") @Inheritance(strategy = InheritanceType.SINGLE_TABLE) @DiscriminatorColumn( name = "discriminator", discriminatorType = DiscriminatorType.STRING ) @DiscriminatorValue(value = "E") // NOTE: Use strict cache to prevent lost updates when updating statistics in semaphore (see StatisticService.java) @Cache(usage = CacheConcurrencyStrategy.READ_WRITE) @JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "type") // Annotation necessary to distinguish between concrete implementations of Exercise when deserializing from JSON @JsonSubTypes({ @JsonSubTypes.Type(value = ProgrammingExercise.class, name = "programming-exercise"), @JsonSubTypes.Type(value = ModelingExercise.class, name = "modeling-exercise"), @JsonSubTypes.Type(value = QuizExercise.class, name = "quiz-exercise") }) public abstract class Exercise implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @JsonView(QuizView.Before.class) private Long id; @Column(name = "title") @JsonView(QuizView.Before.class) private String title; @Column(name = "release_date") @JsonView(QuizView.Before.class) protected ZonedDateTime releaseDate; @Column(name = "due_date") @JsonView(QuizView.Before.class) private ZonedDateTime dueDate; @OneToMany(mappedBy = "exercise") @JsonIgnore @Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE) private Set<Participation> participations = new HashSet<>(); @ManyToOne @JsonView(QuizView.Before.class) private Course course; @Transient private boolean isOpenForSubmission; // jhipster-needle-entity-add-field - JHipster will add fields here, do not remove public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getTitle() { return title; } public Exercise title(String title) { this.title = title; return this; } public void setTitle(String title) { this.title = title; } public ZonedDateTime getReleaseDate() { return releaseDate; } public Exercise releaseDate(ZonedDateTime releaseDate) { this.releaseDate = releaseDate; return this; } public void setReleaseDate(ZonedDateTime releaseDate) { this.releaseDate = releaseDate; } public ZonedDateTime getDueDate() { return dueDate; } public Exercise dueDate(ZonedDateTime dueDate) { this.dueDate = dueDate; return this; } public void setDueDate(ZonedDateTime dueDate) { this.dueDate = dueDate; } public Set<Participation> getParticipations() { return participations; } public Exercise participations(Set<Participation> participations) { this.participations = participations; return this; } public Exercise addParticipations(Participation participation) { this.participations.add(participation); participation.setExercise(this); return this; } public Exercise removeParticipations(Participation participation) { this.participations.remove(participation); participation.setExercise(null); return this; } public void setParticipations(Set<Participation> participations) { this.participations = participations; } public Course getCourse() { return course; } public Exercise course(Course course) { this.course = course; return this; } public void setCourse(Course course) { this.course = course; } public boolean isOpenForSubmission() { if (dueDate != null) { return ZonedDateTime.now().isBefore(dueDate); } return true; } public void setOpenForSubmission(boolean openForSubmission) { isOpenForSubmission = openForSubmission; } // jhipster-needle-entity-add-getters-setters - JHipster will add getters and setters here, do not remove /** * check if students are allowed to see this exercise * * @return true, if students are allowed to see this exercise, otherwise false */ @JsonView(QuizView.Before.class) public Boolean isVisibleToStudents() { if (releaseDate == null) { //no release date means the exercise is visible to students return true; } return releaseDate.isBefore(ZonedDateTime.now()); } /** * find a relevant participation for this exercise * (relevancy depends on ParticipationState) * * @param participations the list of available participations * @return the found participation, or null, if none exist */ public Participation findRelevantParticipation(List<Participation> participations) { Participation result = null; for (Participation participation : participations) { if (participation.getExercise().equals(this)) { if (participation.getInitializationState() == ParticipationState.INITIALIZED) { // ParticipationState INITIALIZED is preferred // => if we find one, we can return immediately return participation; } else if (participation.getInitializationState() == ParticipationState.INACTIVE) { // ParticipationState INACTIVE is also ok // => if we can't find INITIALIZED, we return that one result = participation; } } } return result; } /** * Get the latest relevant result from the given participation * (relevancy depends on Exercise type => this should be overridden by subclasses if necessary) * * @param participation the participation whose results we are considering * @return the latest relevant result in the given participation, or null, if none exist */ public Result findLatestRelevantResult(Participation participation) { // for most types of exercises => return latest result (all results are relevant) Result latestResult = null; for (Result result : participation.getResults()) { if (latestResult == null || latestResult.getCompletionDate().isBefore(result.getCompletionDate())) { latestResult = result; } } return latestResult; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Exercise exercise = (Exercise) o; if (exercise.getId() == null || getId() == null) { return false; } return Objects.equals(getId(), exercise.getId()); } @Override public int hashCode() { return Objects.hashCode(getId()); } @Override public String toString() { return "Exercise{" + "id=" + getId() + ", title='" + getTitle() + "'" + ", releaseDate='" + getReleaseDate() + "'" + ", dueDate='" + getDueDate() + "'" + "}"; } }
package dk.aau.sw402F15.CodeGenerator; import dk.aau.sw402F15.parser.analysis.DepthFirstAdapter; import dk.aau.sw402F15.parser.node.*; import sun.reflect.generics.reflectiveObjects.NotImplementedException; import java.io.FileNotFoundException; import java.io.PrintWriter; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.List; public class CodeGenerator extends DepthFirstAdapter { int jumpLabel = 0; PrintWriter instructionWriter; PrintWriter symbolWriter; public CodeGenerator() { try { instructionWriter = new PrintWriter("InstructionList.txt", "UTF-8"); symbolWriter = new PrintWriter("SymbolList.txt", "UTF-8"); Emit("LD P_First_Cycle", true); Emit("SSET(630) W0 &5", true); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } } @Override public void outStart(Start node){ instructionWriter.close(); symbolWriter.close(); } @Override public void outAAssignmentExpr(AAssignmentExpr node) { super.outAAssignmentExpr(node); // Get location of symbol in memory // Set memory to value of TOS } @Override public void caseAArrayDefinition(AArrayDefinition node){ //throw new NotImplementedException(); } @Override public void caseAArrayExpr(AArrayExpr node){ //throw new NotImplementedException(); } @Override public void caseADeclaration(ADeclaration node){ super.caseADeclaration(node); } @Override public void outABreakStatement(ABreakStatement node){ super.outABreakStatement(node); Emit("BREAK(514)", true); } @Override public void outACaseStatement(ACaseStatement node){ //throw new NotImplementedException(); } @Override public void outACompareAndExpr(ACompareAndExpr node){ super.outACompareAndExpr(node); PopFromStack(); Emit("LD b1", true); Emit("AND b2", true); Emit("SET b1", true); } @Override public void outACompareEqualExpr(ACompareEqualExpr node){ super.outACompareEqualExpr(node); PopFromStack(); Emit("=(300) r1 r2", true); } @Override public void outACompareGreaterExpr(ACompareGreaterExpr node){ super.outACompareGreaterExpr(node); PopFromStack(); Emit(">(320) r1 r2", true); } @Override public void outACompareGreaterOrEqualExpr(ACompareGreaterOrEqualExpr node){ super.outACompareGreaterOrEqualExpr(node); PopFromStack(); Emit(">=(325) r1 r2", true); } @Override public void outACompareLessExpr(ACompareLessExpr node){ super.outACompareLessExpr(node); PopFromStack(); Emit("<(310) r1 r2", true); } @Override public void outACompareLessOrEqualExpr(ACompareLessOrEqualExpr node){ super.outACompareLessOrEqualExpr(node); PopFromStack(); Emit("<=(315) r1 r2", true); } @Override public void outACompareNotEqualExpr(ACompareNotEqualExpr node){ super.outACompareNotEqualExpr(node); PopFromStack(); Emit("<>(305) r1 r2", true); } @Override public void outACompareOrExpr(ACompareOrExpr node){ super.outACompareOrExpr(node); PopFromStack(); Emit("LD b1", true); Emit("OR b2", true); Emit("SET b1", true); } @Override public void outAContinueStatement(AContinueStatement node){ //throw new NotImplementedException(); } @Override public void outADeclaration(ADeclaration node){ //throw new NotImplementedException(); } @Override public void outADefaultStatement(ADefaultStatement node){ //throw new NotImplementedException(); } @Override public void outAFalseExpr(AFalseExpr node){ super.outAFalseExpr(node); Emit("LD P_Off", true); } @Override public void outAFunctionCallExpr(AFunctionCallExpr node){ //throw new NotImplementedException(); } @Override public void outAFunctionRootDeclaration(AFunctionRootDeclaration node){ //throw new NotImplementedException(); } @Override public void outAIdentifierExpr(AIdentifierExpr node){ //throw new NotImplementedException(); } @Override public void outAMemberExpr(AMemberExpr node){ //throw new NotImplementedException(); } @Override public void outANegationExpr(ANegationExpr node){ super.outANegationExpr(node); PopFromStack(); Emit("NOT r1", true); } @Override public void outAPortAnalogInputExpr(APortAnalogInputExpr node){ //throw new NotImplementedException(); } @Override public void outAPortAnalogOutputExpr(APortAnalogOutputExpr node){ //throw new NotImplementedException(); } @Override public void outAPortInputExpr(APortInputExpr node){ //throw new NotImplementedException(); } @Override public void outAPortMemoryExpr(APortMemoryExpr node){ //throw new NotImplementedException(); } @Override public void outAPortOutputExpr(APortOutputExpr node){ //throw new NotImplementedException(); } @Override public void outAReturnStatement(AReturnStatement node){ //throw new NotImplementedException(); } @Override public void outASwitchStatement(ASwitchStatement node){ //throw new NotImplementedException(); } @Override public void outATrueExpr(ATrueExpr node){ super.outATrueExpr(node); Emit("LD P_On", true); } @Override public void outATypeCastExpr(ATypeCastExpr node){ //throw new NotImplementedException(); } @Override public void caseABranchStatement(ABranchStatement node) { super.caseABranchStatement(node); if (node.getRight() != null) { // If - else statement int ifLabel = getNextJump(); int elseLabel = getNextJump(); node.getCondition().apply(this); Emit("CJP(510) #" + ifLabel, true); node.getRight().apply(this); Emit("JMP(004) #" + elseLabel, true); Emit("JME(005) #" + ifLabel, true); node.getLeft().apply(this); Emit("JME(005) #" + elseLabel, true); } else { // If statement int label = getNextJump(); node.getCondition().apply(this); Emit("CJPN(511) #" + label, true); node.getLeft().apply(this); Emit("JME(005) #" + label, true); } } @Override public void caseAForStatement(AForStatement node){ int jumpLabel = getNextJump(); int loopLabel = getNextJump(); { List<PExpr> copy = new ArrayList<PExpr>(node.getInitilizer()); for(PExpr e : copy) { e.apply(this); } } Emit("JMP(004) #" + jumpLabel, true); Emit("JME(005) #" + loopLabel, true); node.getStatement().apply(this); { List<PExpr> copy = new ArrayList<PExpr>(node.getIterator()); for(PExpr e : copy) { e.apply(this); } } Emit("JME(005) #" + jumpLabel, true); node.getCondition().apply(this); Emit("LD b1", true); Emit("CJP(510) #" + loopLabel, true); } @Override public void caseASwitchStatement(ASwitchStatement node){ //throw new NotImplementedException(); } @Override public void caseAWhileStatement(AWhileStatement node){ Emit("LD b1", true); int jumpLabel = getNextJump(); int loopLabel = getNextJump(); Emit("JMP(004) #" + jumpLabel, true); Emit("JME(005) #" + loopLabel, true); node.getStatement().apply(this); Emit("JME(005) #" + jumpLabel, true); node.getCondition().apply(this); Emit("CJP(510) #" + loopLabel, true); } @Override public void outAIntegerExpr(AIntegerExpr node) { super.outAIntegerExpr(node); Emit("PUSH(632) W0 #" + node.getIntegerLiteral().getText(), true); } @Override public void outADecimalExpr(ADecimalExpr node) { super.outADecimalExpr(node); Emit("PUSH(632) W0 #" + node.getDecimalLiteral().getText(), true); } @Override public void outAAddExpr(AAddExpr node) { super.outAAddExpr(node); PopFromStack(); Emit("+(400) r1 r2 r1", true); Emit("PUSH(632) W0 r1", true); } @Override public void outADivExpr(ADivExpr node) { super.outADivExpr(node); PopFromStack(); Emit("/(430) r1 r2 r1", true); Emit("PUSH(632) W0 r1", true); } @Override public void outAMultiExpr(AMultiExpr node) { super.outAMultiExpr(node); PopFromStack(); Emit("*(420) r1 r2 r1", true); Emit("PUSH(632) W0 r1", true); } @Override public void outASubExpr(ASubExpr node) { super.outASubExpr(node); PopFromStack(); Emit("-(410) r1 r2 r1", true); Emit("PUSH(632) W0 r1", true); } private void PopFromStack() { Emit("r1\tINT\tW4\t\t0", false); Emit("r2\tINT\tW5\t\t0", false); Emit("LIFO(634) W0 r1", true); Emit("LIFO(634) W0 r2", true); } private int getNextJump(){ jumpLabel = jumpLabel + 1; if(jumpLabel > 255) throw new IndexOutOfBoundsException(); return jumpLabel; } protected void Emit(String s, boolean inst){ if (inst == true) { instructionWriter.println(s); } else { symbolWriter.println(s); } } }
package edu.hm.hafner.analysis; import java.util.Optional; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.stream.Stream; import java.util.Stack; import edu.hm.hafner.util.LookaheadStream; /** * Parses a report file line by line for issues using a pre-defined regular expression. If the regular expression * matches then the abstract method {@link #createIssue(Matcher, LookaheadStream, IssueBuilder)} will be called. Sub * classes need to provide an implementation that transforms the {@link Matcher} instance into a new issue. If required, * sub classes may consume additional lines from the report file before control is handed back to the template method of * this parser. * * @author Ullrich Hafner */ public abstract class LookaheadParser extends IssueParser { private static final long serialVersionUID = 3240719494150024894L; /** Pattern identifying an ant task debug output prefix. */ protected static final String ANT_TASK = "^(?:.*\\[[^]]*\\])?\\s*"; private static final String ENTERING_DIRECTORY = "Entering directory"; private static final String LEAVING_DIRECTORY = "Leaving directory"; private static final Pattern MAKE_PATH = Pattern.compile(".*make(?:\\[\\d+])?: " + ENTERING_DIRECTORY + " [`'](?<dir>.*)['`]"); private static final String CMAKE_PREFIX = "-- Build files have"; private static final Pattern CMAKE_PATH = Pattern.compile(CMAKE_PREFIX + " been written to: (?<dir>.*)"); private static final int MAX_LINE_LENGTH = 4000; // see JENKINS-55805 private final Pattern pattern; private Stack<String> recursiveMakeDirectories; /** * Creates a new instance of {@link LookaheadParser}. * * @param pattern * pattern of compiler warnings. */ protected LookaheadParser(final String pattern) { super(); this.pattern = Pattern.compile(pattern); this.recursiveMakeDirectories = new Stack<String>(); } @Override public Report parse(final ReaderFactory readerFactory) throws ParsingException, ParsingCanceledException { Report report = new Report(); try (Stream<String> lines = readerFactory.readStream()) { try (LookaheadStream lookahead = new LookaheadStream(lines, readerFactory.getFileName())) { parse(report, lookahead); } } return postProcess(report); } private void parse(final Report report, final LookaheadStream lookahead) { try (IssueBuilder builder = new IssueBuilder()) { while (lookahead.hasNext()) { String line = lookahead.next(); if (line.contains(ENTERING_DIRECTORY)) { final String directory = extractDirectory(line, MAKE_PATH); recursiveMakeDirectories.push(directory); builder.setDirectory(recursiveMakeDirectories.peek()); } else if (line.contains(LEAVING_DIRECTORY)) { if (!recursiveMakeDirectories.isEmpty()) { recursiveMakeDirectories.pop(); } if (!recursiveMakeDirectories.isEmpty()) { builder.setDirectory(recursiveMakeDirectories.peek()); } } else if (line.contains(CMAKE_PREFIX)) { builder.setDirectory(extractDirectory(line, CMAKE_PATH)); } else if (isLineInteresting(line)) { Matcher matcher = pattern.matcher(line); if (matcher.find()) { createIssue(matcher, lookahead, builder).ifPresent(report::add); } } if (Thread.interrupted()) { throw new ParsingCanceledException(); } } } } private String extractDirectory(final String line, final Pattern makePath) throws ParsingException { if (!makePath.toString().contains("<dir>")) { throw new IllegalArgumentException(makePath.toString() + " does not contain a capture group named 'dir'"); } Matcher makeLineMatcher = makePath.matcher(line); if (makeLineMatcher.matches()) { return makeLineMatcher.group("dir"); } throw new ParsingException("Unable to change directory using: " + makePath.toString() + " to match " + line); } /** * Creates a new issue for the specified pattern. This method is called for each matching line in the specified * file. If a match is a false positive, then return {@link Optional#empty()} to ignore this warning. * * @param matcher * the regular expression matcher * @param lookahead * the lookahead stream to read additional lines * @param builder * the issue builder to use * * @return a new annotation for the specified pattern * @throws ParsingException * Signals that during parsing a non recoverable error has been occurred */ protected abstract Optional<Issue> createIssue(Matcher matcher, LookaheadStream lookahead, IssueBuilder builder) throws ParsingException; /** * Returns whether the specified line is interesting. Each interesting line will be matched by the defined regular * expression. Here a parser can implement some fast checks (i.e. string or character comparisons) in order to see * if a required condition is met. This default implementation does always return {@code true}. * * @param line * the line to inspect * * @return {@code true} if the line should be handed over to the regular expression scanner, {@code false} if the * line does not contain a warning. */ protected boolean isLineInteresting(final String line) { return line.length() < MAX_LINE_LENGTH; // skip long lines, see JENKINS-55805 } /** * Post processes the issues. This default implementation does nothing. * * @param report * the issues after the parsing process * * @return the post processed issues */ protected Report postProcess(final Report report) { return report; } }
package dk.aau.sw402F15.CodeGenerator; import dk.aau.sw402F15.Symboltable.Scope; import dk.aau.sw402F15.Symboltable.ScopeDepthFirstAdapter; import dk.aau.sw402F15.Symboltable.Symbol; import dk.aau.sw402F15.Symboltable.SymbolArray; import dk.aau.sw402F15.Symboltable.SymbolFunction; import dk.aau.sw402F15.Symboltable.Type.SymbolType; import dk.aau.sw402F15.parser.node.*; import sun.reflect.generics.reflectiveObjects.NotImplementedException; import java.awt.geom.FlatteningPathIterator; import java.io.FileNotFoundException; import java.io.PrintWriter; import java.io.UnsupportedEncodingException; import java.util.EmptyStackException; public class CodeGenerator extends ScopeDepthFirstAdapter { private int jumpLabel = 0; private int returnlabel; private int nextDAddress = 0; private double nextWAddress = 0.00; private int nextHAddress = 0; private int startFunctionNumber = 0; PrintWriter instructionWriter; PrintWriter symbolWriter; public String getNextDAddress(boolean increment) { if (nextDAddress > 32763) throw new OutOfMemoryError(); if (increment) return "D" + (nextDAddress += 4); else return "D" + nextDAddress; } public String getNextWAddress(boolean increment) { if (nextWAddress > 508) throw new OutOfMemoryError(); if (increment) return "W" + (nextWAddress += 0.1); else return "W" + nextWAddress; } public String stackPointer(boolean increment) { if (nextHAddress > 4091) throw new OutOfMemoryError(); if (increment) return "H" + (nextHAddress += 4); else return "H" + nextHAddress; } public < T > void push(T value) { if (value.getClass() == Integer.class) Emit("MOV(021) &" + value + " " + stackPointer(true), true); else if (value.getClass() == Float.class || value.getClass() == Double.class) Emit("+F(454) +0,0 +" + value.toString().replace(".", ",") + " " + stackPointer(true) + "", true); } public String pop() { if (nextHAddress < 4) throw new EmptyStackException(); return "H" + (nextHAddress -= 4); } public int getFunctionNumber(boolean increment) { if (increment) return startFunctionNumber += 1; else return startFunctionNumber; } public CodeGenerator(Scope scope) { super(scope, scope); try { instructionWriter = new PrintWriter("InstructionList.txt", "UTF-8"); symbolWriter = new PrintWriter("SymbolList.txt", "UTF-8"); Emit("LD P_First_Cycle", true); Emit("SSET(630) " + getNextDAddress(false) + " &32767", true); Emit("SSET(630) " + stackPointer(false) + " &1535", true); // here we call the init method Emit("SBS(091) 0", true); // here we call the run Method } catch (FileNotFoundException e) { e.printStackTrace(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } } @Override public void outStart(Start node){ //Emit("END(001)", true); instructionWriter.close(); symbolWriter.close(); } @Override public void outAAssignmentExpr(AAssignmentExpr node) { super.outAAssignmentExpr(node); Emit("MOV(021) " + getNextDAddress(false) + " " + node.getLeft(), true); } @Override public void caseAArrayDefinition(AArrayDefinition node){ int size = Integer.parseInt(node.getNumber().getText()); // Reserver memory for array } @Override public void caseAArrayExpr(AArrayExpr node){ // TODO: currently only gets the values node.getExpr().apply(this); SymbolArray symbol = (SymbolArray) currentScope.getSymbolOrThrow(node.getName().getText(), node.getName()); int location = 0; // Get location in memory int size = 1; if (symbol.getContainedType().getType() == SymbolType.Type.Int || symbol.getContainedType().getType() == SymbolType.Type.Decimal) { size = 2; } node.getExpr().apply(this); int offset = size; // * Value of the expression location += offset; Emit("*(420) " + getNextDAddress(false) + " &" + size + " " + getNextDAddress(false), false); Emit("+(400) " + getNextDAddress(false) + " &" + location + " " + getNextDAddress(false), false); Emit("+(400) " + getNextDAddress(false) + " &" + node.getName() + " " + getNextDAddress(false), false); } @Override public void caseADeclaration(ADeclaration node){ super.caseADeclaration(node); } @Override public void outABreakStatement(ABreakStatement node){ super.outABreakStatement(node); Emit("BREAK(514)", true); } @Override public void outACaseStatement(ACaseStatement node){ //throw new NotImplementedException(); } @Override public void outAIncrementExpr(AIncrementExpr node) { super.outAIncrementExpr(node); Emit("++(590) " + getNextDAddress(false), true); } @Override public void outADecrementExpr(ADecrementExpr node) { super.outADecrementExpr(node); Emit("--(592) " + getNextDAddress(false), true); } @Override public void outACompareAndExpr(ACompareAndExpr node){ super.outACompareAndExpr(node); Emit("ANDW(034) D" + (nextDAddress - 4) + " " + getNextDAddress(false) + " " + getNextDAddress(true), true); } @Override public void outACompareOrExpr(ACompareOrExpr node){ super.outACompareOrExpr(node); Emit("ORW(035) D" + (nextDAddress - 4) + " " + getNextDAddress(false) + " " + getNextDAddress(true), true); } @Override public void outACompareEqualExpr(ACompareEqualExpr node){ super.outACompareEqualExpr(node); Emit("AND=(300) D" + nextDAddress + " " + getNextDAddress(false), true); Emit("SET " + getNextWAddress(true), true); } @Override public void outACompareGreaterExpr(ACompareGreaterExpr node){ super.outACompareGreaterExpr(node); Emit("AND>(320) D" + (nextDAddress - 4) + " " + getNextDAddress(false), true); Emit("SET " + getNextWAddress(true), true); } @Override public void outACompareGreaterOrEqualExpr(ACompareGreaterOrEqualExpr node){ super.outACompareGreaterOrEqualExpr(node); Emit("AND>=(325) D" + (nextDAddress - 4) + " " + getNextDAddress(false), true); Emit("SET " + getNextWAddress(true), true); } @Override public void outACompareLessExpr(ACompareLessExpr node){ super.outACompareLessExpr(node); Emit("AND<(310) D" + (nextDAddress - 4) + " " + getNextDAddress(false), true); Emit("SET " + getNextWAddress(true), true); } @Override public void outACompareLessOrEqualExpr(ACompareLessOrEqualExpr node) { super.outACompareLessOrEqualExpr(node); Emit("AND<=(315) D" + (nextDAddress - 4) + " " + getNextDAddress(false), true); Emit("SET " + getNextWAddress(true), true); } @Override public void outACompareNotEqualExpr(ACompareNotEqualExpr node) { super.outACompareNotEqualExpr(node); Emit("AND<>(305) D" + (nextDAddress - 4) + " " + getNextDAddress(false), true); Emit("SET " + getNextWAddress(true), true); } @Override public void outAContinueStatement(AContinueStatement node){ //throw new NotImplementedException(); } @Override public void outADeclaration(ADeclaration node) { Symbol symbol = currentScope.getSymbolOrThrow(node.getName().getText(), node); if (symbol.getType().equals(SymbolType.Boolean())) { Emit(node.getName().getText() + "\tBOOL\t" + getNextDAddress(true) + ".00\t\t0\t", false); } else if (symbol.getType().equals(SymbolType.Int())) { Emit(node.getName().getText() + "\tINT\t" + getNextDAddress(true) + "\t\t0\t", false); } else if (symbol.getType().equals(SymbolType.Char())) { } else if (symbol.getType().equals(SymbolType.Decimal())) { Emit(node.getName().getText() + "\tREAL\t" + getNextDAddress(true) + "\t\t0\t", false); } else if (symbol.getType().equals(SymbolType.Timer())) { Emit(node.getName().getText() + "\tTIMER\t" + getNextDAddress(true) + "\t\t0\t", false); } else if (symbol.getType().equals(SymbolType.Array())) { } else if (symbol.getType().equals(SymbolType.Void())){ // Method is a void function } else if (symbol.getType().equals(SymbolType.Type.Function)) { } else if (symbol.getType().equals(SymbolType.Type.Struct)) { } else { // throw new RuntimeException(); // TODO Need new Exception. Pretty unknown error though } } @Override public void outADefaultStatement(ADefaultStatement node){ //throw new NotImplementedException(); } @Override public void inAFunctionCallExpr(AFunctionCallExpr node){ SymbolFunction function = (SymbolFunction) currentScope.getSymbolOrThrow(node.getName().getText(), node); if (function.getReturnType().equals(SymbolType.Type.Void)) { Emit("SBS(091) " + getFunctionNumber(true), true); } else { Emit("MCRO(099) " + getFunctionNumber(true) + " " + getNextDAddress(true) + " " + getNextDAddress(true), true); } //Emit("SBS(091) " + getFunctionNumber(true), true); } @Override public void inAFunctionRootDeclaration(AFunctionRootDeclaration node){ super.inAFunctionRootDeclaration(node); Emit("SBN(092) " + getFunctionNumber(false), true); Emit("LD P_On", true); //returnlabel = getNextJump(); } @Override public void outAFunctionRootDeclaration(AFunctionRootDeclaration node) { super.outAFunctionRootDeclaration(node); //Emit("JME(005) #" + returnlabel, true); Emit("RET(093)", true); Emit("END(001)", true); } @Override public void outAIdentifierExpr(AIdentifierExpr node){ //throw new NotImplementedException(); } @Override public void outAMemberExpr(AMemberExpr node){ //throw new NotImplementedException(); } @Override public void outANegationExpr(ANegationExpr node){ super.outANegationExpr(node); Emit("NOT " + getNextDAddress(false), true); } @Override public void outAPortAnalogInputExpr(APortAnalogInputExpr node){ //throw new NotImplementedException(); } @Override public void outAPortAnalogOutputExpr(APortAnalogOutputExpr node){ //throw new NotImplementedException(); } @Override public void outAPortInputExpr(APortInputExpr node){ //throw new NotImplementedException(); } @Override public void outAPortMemoryExpr(APortMemoryExpr node){ //throw new NotImplementedException(); } @Override public void outAPortOutputExpr(APortOutputExpr node){ //throw new NotImplementedException(); } @Override public void outAReturnStatement(AReturnStatement node){ super.outAReturnStatement(node); //Emit("JMP(004) #" + returnlabel, true); //Emit("RET(093)", true); } @Override public void outASwitchStatement(ASwitchStatement node){ //throw new NotImplementedException(); } @Override public void outATrueExpr(ATrueExpr node){ super.outATrueExpr(node); Emit("MOV(021) #1 " + getNextDAddress(true), true); } @Override public void outAFalseExpr(AFalseExpr node){ super.outAFalseExpr(node); Emit("MOV(021) #0 " + getNextDAddress(true), true); } @Override public void outATypeCastExpr(ATypeCastExpr node){ //throw new NotImplementedException(); } @Override public void caseABranchStatement(ABranchStatement node) { //Do not call super as this function handles calls of the child classes if (node.getRight() != null) { // If - else statement int ifLabel = getNextJump(); int elseLabel = getNextJump(); node.getCondition().apply(this); Emit("CJP(510) #" + ifLabel, true); node.getRight().apply(this); Emit("JMP(004) #" + elseLabel, true); Emit("JME(005) #" + ifLabel, true); node.getLeft().apply(this); Emit("JME(005) #" + elseLabel, true); } else { // If statement int label = getNextJump(); node.getCondition().apply(this); Emit("CJPN(511) #" + label, true); node.getLeft().apply(this); Emit("JME(005) #" + label, true); } } @Override public void caseAForStatement(AForStatement node){ // Not needed since we convert For-loops til While-loops } @Override public void caseASwitchStatement(ASwitchStatement node){ //throw new NotImplementedException(); } @Override public void caseAWhileStatement(AWhileStatement node){ //Emit("LD b1", true); int jumpLabel = getNextJump(); int loopLabel = getNextJump(); node.getCondition().apply(this); Emit("LD W" + getNextWAddress(false), true); Emit("JMP(004) #" + jumpLabel, true); node.getStatement().apply(this); Emit("JME(005) #" + jumpLabel, true); } @Override public void outAIntegerExpr(AIntegerExpr node) { super.outAIntegerExpr(node); push(node.getIntegerLiteral()); } @Override public void outADecimalExpr(ADecimalExpr node) { super.outADecimalExpr(node); push(node.getDecimalLiteral()); } @Override public void outAAddExpr(AAddExpr node) { super.outAAddExpr(node); // TODO Different if float Emit("+(400) " + pop() + " " + pop() + " " + stackPointer(true), true); } @Override public void outADivExpr(ADivExpr node) { super.outADivExpr(node); // TODO Different if float Emit("/(430) " + pop() + " " + pop() + " " + stackPointer(true), true); } @Override public void outAMultiExpr(AMultiExpr node) { super.outAMultiExpr(node); // TODO Different if float Emit("*(420) " + pop() + " " + pop() + " " + stackPointer(true), true); } @Override public void outASubExpr(ASubExpr node) { super.outASubExpr(node); // TODO Different if float Emit("-(410) " + pop() + " " + pop() + " " + stackPointer(true), true); } private int getNextJump(){ jumpLabel = jumpLabel + 1; if(jumpLabel > 255) throw new IndexOutOfBoundsException(); return jumpLabel; } protected void Emit(String s, boolean instruction){ if (instruction == true) { // Write to InstructionList, if instruction instructionWriter.println(s); } else { // Otherwise it's a symbol, then write to SymbolList symbolWriter.println(s); } } }
package info.tehnut.xtones.client; import net.minecraft.client.Minecraft; import net.minecraft.client.renderer.block.model.ModelResourceLocation; import net.minecraft.client.settings.KeyBinding; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.util.EnumHand; import net.minecraft.util.ResourceLocation; import net.minecraftforge.client.event.ModelRegistryEvent; import net.minecraftforge.client.event.MouseEvent; import net.minecraftforge.client.model.ModelLoader; import net.minecraftforge.client.settings.KeyConflictContext; import net.minecraftforge.fml.client.registry.ClientRegistry; import net.minecraftforge.fml.common.Mod.EventBusSubscriber; import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; import org.checkerframework.checker.nullness.qual.MonotonicNonNull; import org.lwjgl.input.Keyboard; import info.tehnut.xtones.Tone; import info.tehnut.xtones.Xtones; import info.tehnut.xtones.config.XtonesConfig; import info.tehnut.xtones.item.XtoneBlockItem; import info.tehnut.xtones.network.XtonesNetwork; import java.util.Objects; @SideOnly(Side.CLIENT) @EventBusSubscriber(value = Side.CLIENT, modid = Xtones.ID) public final class XtonesClient { private static final KeyBinding SCROLL_MODIFIER = new KeyBinding( "key." + Xtones.ID + ".scroll", KeyConflictContext.IN_GAME, Keyboard.KEY_LSHIFT, Xtones.NAME ); static { ClientRegistry.registerKeyBinding(SCROLL_MODIFIER); } private static @MonotonicNonNull Boolean serverXtoneCycling = null; private XtonesClient() { } public static String getScrollModifierName() { return SCROLL_MODIFIER.getDisplayName(); } public static void setServerXtoneCycling(final boolean state) { if (serverXtoneCycling != null) { throw new IllegalStateException(); } serverXtoneCycling = state; } @SubscribeEvent static void registerModels(final ModelRegistryEvent event) { Xtones.items().forEach(item -> { for (int variant = 0; variant < Tone.VARIANTS; ++variant) { setCustomModelResourceLocation(item, variant, "variant=" + variant); } }); setCustomModelResourceLocation(Xtones.baseItem(), 0, "normal"); setCustomModelResourceLocation(Xtones.lampItem(), 0, "active=false,facing=up"); } @SubscribeEvent static void mousePolled(final MouseEvent event) { if (hasXtoneCycling() && event.getDwheel() != 0 && SCROLL_MODIFIER.isKeyDown()) { final Minecraft minecraft = Minecraft.getMinecraft(); final EntityPlayer player = minecraft.player; if (player != null && minecraft.currentScreen == null) { EnumHand hand = EnumHand.MAIN_HAND; if (!isXtone(player.getHeldItem(hand))) { hand = EnumHand.OFF_HAND; } if (isXtone(player.getHeldItem(hand))) { XtonesNetwork.cycleXtone(hand, event); event.setCanceled(true); } } } } private static void setCustomModelResourceLocation(final Item item, final int meta, final String variant) { final ResourceLocation name = Objects.requireNonNull(item.getRegistryName()); final ModelResourceLocation model = new ModelResourceLocation(name, variant); ModelLoader.setCustomModelResourceLocation(item, meta, model); } private static boolean hasXtoneCycling() { return XtonesConfig.hasXtoneCycling() && serverXtoneCycling != null && serverXtoneCycling; } private static boolean isXtone(final ItemStack stack) { return stack.getItem() instanceof XtoneBlockItem; } }
package info.u_team.u_team_core.util; import java.util.function.Function; import java.util.function.Supplier; import net.minecraft.core.BlockPos; import net.minecraft.nbt.CompoundTag; import net.minecraft.resources.ResourceKey; import net.minecraft.server.MinecraftServer; import net.minecraft.server.level.ServerLevel; import net.minecraft.server.level.ServerPlayer; import net.minecraft.server.level.TicketType; import net.minecraft.util.Mth; import net.minecraft.world.entity.Entity; import net.minecraft.world.entity.LivingEntity; import net.minecraft.world.entity.PathfinderMob; import net.minecraft.world.level.ChunkPos; import net.minecraft.world.level.ClipContext; import net.minecraft.world.level.ClipContext.Block; import net.minecraft.world.level.ClipContext.Fluid; import net.minecraft.world.level.Level; import net.minecraft.world.level.dimension.DimensionType; import net.minecraft.world.level.saveddata.SavedData; import net.minecraft.world.phys.HitResult; import net.minecraft.world.phys.Vec3; /** * Some utility methods for level interaction. * * @author HyCraftHD */ public class LevelUtil { /** * Raytrace from an entities look vector for collisions in range. Use default block mode {@link BlockMode#OUTLINE} and * fluid mode {@link FluidMode#NONE}. * * @param entity Entity from where we get the look vector * @param range Range in blocks * @return Raytrace result with information about the trace */ public static HitResult rayTraceServerSide(Entity entity, double range) { return rayTraceServerSide(entity, range, Block.OUTLINE, Fluid.NONE); } /** * Raytrace from an entities look vector for collisions in range. * * @param entity Entity from where we get the look vector * @param range Range in blocks * @param blockMode Mode for block collisions * @param fluidMode Mode for fluid collisions * @return Raytrace result with information about the trace */ public static HitResult rayTraceServerSide(Entity entity, double range, Block blockMode, Fluid fluidMode) { final Vec3 playerVector = entity.position().add(0, entity.getEyeHeight(), 0); final Vec3 lookVector = entity.getLookAngle(); final Vec3 locationVector = playerVector.add(lookVector.x * range, lookVector.y * range, lookVector.z * range); return entity.level.clip(new ClipContext(playerVector, locationVector, blockMode, fluidMode, entity)); } /** * Get a saved instance (own implementation) of {@link SavedData}. If it does not exist, a new one is created. * * @param <T> Custom level save data class * @param level Server level * @param name Name of this data * @param defaultData Function for creating an instance and for the default instance * @return An instance of <T> with the loaded data or default data. */ public static <T extends SavedData> T getSaveData(ServerLevel level, Function<CompoundTag, T> load, String name, Function<String, T> defaultData) { return getSaveData(level, name, load, () -> defaultData.apply(name)); } /** * Get a saved instance (own implementation) of {@link SavedData}. If it does not exist, a new one is created. * * @param <T> Custom level save data class * @param level Server level * @param name Name of this data * @param defaultData Supplier for creating an instance and for the default instance * @return An instance of <T> with the loaded data or default data. */ public static <T extends SavedData> T getSaveData(ServerLevel level, String name, Function<CompoundTag, T> load, Supplier<T> defaultData) { return level.getDataStorage().computeIfAbsent(load, defaultData, name); } /** * Get the {@link ServerLevel} from the {@link ResourceKey} * * @param entity An entity used to get the server instance with {@link Entity#getServer()} * @param key The dimension key * @return The server level for the given key */ public static ServerLevel getServerLevel(Entity entity, ResourceKey<Level> key) { return getServerLevel(entity.getServer(), key); } /** * Get the {@link ServerLevel} from the {@link ResourceKey} * * @param server The server instance * @param key The dimension key * @return The server level for the given key */ public static ServerLevel getServerLevel(MinecraftServer server, ResourceKey<Level> key) { return server.getLevel(key); } /** * Teleports any entity to a given location in a given {@link ServerLevel}. Don't change the yaw and pitch of the * entity. * * @param entity The entity to teleport * @param key The dimension key where the entity should be teleported. Can be the same as the current dimension key or a * different one * @param pos The position the entity should be teleported to * @return The teleported entity */ public static Entity teleportEntity(Entity entity, ResourceKey<Level> key, BlockPos pos) { return teleportEntity(entity, key, Vec3.atCenterOf(pos)); } /** * Teleports any entity to a given location in a given {@link ServerLevel}. Don't change the yaw and pitch of the * entity. * * @param entity The entity to teleport * @param key The dimension key where the entity should be teleported. Can be the same as the current dimension key or a * different one * @param pos The position the entity should be teleported to * @return The teleported entity */ public static Entity teleportEntity(Entity entity, ResourceKey<Level> key, Vec3 pos) { return teleportEntity(entity, getServerLevel(entity, key), pos); } /** * Teleports any entity to a given location in a given {@link ServerLevel}. Don't change the yaw and pitch of the * entity. * * @param entity The entity to teleport * @param level The server level where the entity should be teleported. Can be the same as the current level or a * different one * @param pos The position the entity should be teleported to * @return The teleported entity */ public static Entity teleportEntity(Entity entity, ServerLevel level, BlockPos pos) { return teleportEntity(entity, level, Vec3.atCenterOf(pos)); } /** * Teleports any entity to a given location in a given {@link ServerLevel}. Don't change the yaw and pitch of the * entity. * * @param entity The entity to teleport * @param level The server level where the entity should be teleported. Can be the same as the current level or a * different one * @param pos The position the entity should be teleported to * @return The teleported entity */ public static Entity teleportEntity(Entity entity, ServerLevel level, Vec3 pos) { return teleportEntity(entity, level, pos.x(), pos.y(), pos.z(), entity.getYRot(), entity.getXRot()); } /** * Teleports any entity to a given location in a given {@link DimensionType}. * * @param entity The entity to teleport * @param key The dimension key where the entity should be teleported. Can be the same as the current dimension key or a * different one * @param x X-Coordinate * @param y Y-Coordinate * @param z Z-Coordinate * @param yaw Yaw * @param pitch Pitch * @return The teleported entity */ public static Entity teleportEntity(Entity entity, ResourceKey<Level> key, double x, double y, double z, float yaw, float pitch) { return teleportEntity(entity, getServerLevel(entity, key), x, y, z, yaw, pitch); } /** * Teleports any entity to a given location in a given {@link ServerLevel}. * * @param entity The entity to teleport * @param level The server level where the entity should be teleported. Can be the same as the current level or a * different one * @param x X-Coordinate * @param y Y-Coordinate * @param z Z-Coordinate * @param yaw Yaw * @param pitch Pitch * @return The teleported entity */ public static Entity teleportEntity(Entity entity, ServerLevel level, double x, double y, double z, float yaw, float pitch) { return teleportEntity(entity, level, x, y, z, yaw, pitch, true); } /** * Teleports any entity to a given location in a given {@link ServerLevel}. * * @param entity The entity to teleport * @param level The server level where the entity should be teleported. Can be the same as the current level or a * different one * @param x X-Coordinate * @param y Y-Coordinate * @param z Z-Coordinate * @param yaw Yaw * @param pitch Pitch * @param detach Detach the entity * @return The teleported entity */ public static Entity teleportEntity(Entity entity, ServerLevel level, double x, double y, double z, float yaw, float pitch, boolean detach) { final float wrapedYaw = Mth.wrapDegrees(yaw); final float wrapedPitch = Mth.wrapDegrees(pitch); if (entity instanceof final ServerPlayer player) { level.getChunkSource().addRegionTicket(TicketType.POST_TELEPORT, new ChunkPos(new BlockPos(x, y, z)), 1, entity.getId()); if (detach) { player.stopRiding(); } if (player.isSleeping()) { player.stopSleepInBed(true, true); } if (level == entity.level) { player.connection.teleport(x, y, z, wrapedYaw, wrapedPitch); } else { player.teleportTo(level, x, y, z, wrapedYaw, wrapedPitch); } entity.setYHeadRot(wrapedYaw); } else { final float clampedPitch = Mth.clamp(wrapedPitch, -90F, 90F); if (level == entity.level) { entity.moveTo(x, y, z, wrapedYaw, clampedPitch); entity.setYHeadRot(wrapedYaw); } else { if (detach) { entity.unRide(); } final Entity entityOld = entity; entity = entity.getType().create(level); if (entity == null) { return null; } entity.restoreFrom(entityOld); entity.moveTo(x, y, z, wrapedYaw, clampedPitch); entity.setYHeadRot(wrapedYaw); entityOld.setRemoved(Entity.RemovalReason.CHANGED_DIMENSION); level.addDuringTeleport(entity); } } if (!(entity instanceof LivingEntity livingEntity) || !livingEntity.isFallFlying()) { entity.setDeltaMovement(entity.getDeltaMovement().multiply(1, 0, 1)); entity.setOnGround(true); } if (entity instanceof final PathfinderMob pathFinderMob) { pathFinderMob.getNavigation().stop(); } return entity; } }
package innovimax.mixthem.arguments; /** * <p>This is the representation of a parameter value.</p> * @author Innovimax * @version 1.0 */ public abstract class ParamValue { private static class ParamStringValue() { private final String text; private ParamStringValue(String text) { this.text = text; } @Override public String asString() { return this.text; } @Override public int asInt() { throw new UnsupportedOperationException("ParamStringValue does not have an int representation"); } @Override public String toString() { return this.text; } } private static class ParamIntValue() { private final int i; private ParamIntValue(int i) { this.i = i; } @Override public String asString() { throw new UnsupportedOperationException("ParamIntValue does not have a String representation"); } @Override public int asInt() { return this.i; } @Override public String toString() { return Integer.toString(i); } } /** * private Constructor */ public ParamValue() {} public static ParamValue createString(String str) { return new ParamStringValue(str); } public static ParamValue createInt(int i) { return new ParamIntValue(i); } /** * Returns the parameter value as a String. * @return The parameter value as a String */ public abstract String asString(); /** * Returns the parameter value as an Integer. * @return The parameter value as an Integer */ public abstract int asInt(); }
package io.irontest.resources; import com.fasterxml.jackson.core.JsonProcessingException; import io.irontest.db.EndpointDAO; import io.irontest.db.TeststepDAO; import io.irontest.models.Endpoint; import io.irontest.models.Properties; import io.irontest.models.SOAPTeststepProperties; import io.irontest.models.Teststep; import io.irontest.utils.WSDLParser; import javax.ws.rs.*; import javax.ws.rs.core.MediaType; @Path("/testcases/{testcaseId}/teststeps") @Produces({ MediaType.APPLICATION_JSON }) public class TeststepResource { private final TeststepDAO teststepDAO; private final EndpointDAO endpointDAO; public TeststepResource(TeststepDAO teststepDAO, EndpointDAO endpointDAO) { this.teststepDAO = teststepDAO; this.endpointDAO = endpointDAO; } @POST public Teststep create(Teststep teststep) throws JsonProcessingException { preCreationProcess(teststep); // create test step long id = teststepDAO.insert(teststep); teststep.setId(id); teststep.setRequest(null); // no need to bring request to client at this point return teststep; } // adding more info to the teststep object private void preCreationProcess(Teststep teststep) { Properties properties = teststep.getProperties(); // create sample request String sampleRequest = null; if (Teststep.TEST_STEP_TYPE_SOAP.equals(teststep.getType())) { sampleRequest = WSDLParser.getSampleRequest((SOAPTeststepProperties) properties); } else if (Teststep.TEST_STEP_TYPE_DB.equals(teststep.getType())){ sampleRequest = "select * from ? where ?"; } teststep.setRequest(sampleRequest); // create unmanaged endpoint Endpoint endpoint = new Endpoint(); if (Teststep.TEST_STEP_TYPE_SOAP.equals(teststep.getType())) { endpoint.setType(Endpoint.ENDPOINT_TYPE_SOAP); endpoint.setUrl(WSDLParser.getAdhocAddress((SOAPTeststepProperties) properties)); } else if (Teststep.TEST_STEP_TYPE_DB.equals(teststep.getType())) { endpoint.setType(Endpoint.TEST_STEP_TYPE_DB); } endpoint.setDescription("Unmanaged " + endpoint.getType() + " Endpoint"); long endpointId = endpointDAO.insertUnmanagedEndpoint(endpoint); endpoint.setId(endpointId); teststep.setEndpoint(endpoint); } // Find the teststep and its associated endpoint @GET @Path("{teststepId}") public Teststep findById(@PathParam("teststepId") long teststepId) { Teststep teststep = teststepDAO.findById(teststepId); Endpoint endpoint = endpointDAO.findById(teststep.getEndpoint().getId()); teststep.setEndpoint(endpoint); return teststep; } @PUT @Path("{teststepId}") public Teststep update(Teststep teststep) throws JsonProcessingException { Teststep oldTeststep = findById(teststep.getId()); teststepDAO.update(teststep); if (teststep.getEndpoint().getEnvironmentId() == null) { // this is an unmanaged endpoint, so update it endpointDAO.update(teststep.getEndpoint()); } else if (oldTeststep.getEndpoint().getEnvironmentId() == null) { // delete the old unmanaged endpoint when a managed endpoint is associated with the test step endpointDAO.deleteById(oldTeststep.getEndpoint().getId()); } return findById(teststep.getId()); } @DELETE @Path("{teststepId}") public void delete(@PathParam("teststepId") long teststepId) { Teststep teststep = findById(teststepId); teststepDAO.deleteById(teststepId); if (teststep.getEndpoint().getEnvironmentId() == null) { // delete the teststep's endpoint if it is unmanaged endpointDAO.deleteById(teststep.getEndpoint().getId()); } } }
package com.eucalyptus.tests.awssdk; import com.amazonaws.AmazonServiceException; import com.amazonaws.Request; import com.amazonaws.auth.AWSCredentials; import com.amazonaws.auth.AWSCredentialsProvider; import com.amazonaws.auth.BasicAWSCredentials; import com.amazonaws.handlers.AbstractRequestHandler; import com.amazonaws.internal.StaticCredentialsProvider; import com.amazonaws.services.autoscaling.AmazonAutoScaling; import com.amazonaws.services.autoscaling.AmazonAutoScalingClient; import com.amazonaws.services.autoscaling.model.*; import com.amazonaws.services.autoscaling.model.BlockDeviceMapping; import com.amazonaws.services.autoscaling.model.InstanceMonitoring; import com.amazonaws.services.autoscaling.model.Tag; import com.amazonaws.services.cloudwatch.AmazonCloudWatch; import com.amazonaws.services.cloudwatch.AmazonCloudWatchClient; import com.amazonaws.services.ec2.AmazonEC2; import com.amazonaws.services.ec2.AmazonEC2Client; import com.amazonaws.services.ec2.model.*; import com.amazonaws.services.ec2.model.Filter; import com.amazonaws.services.ec2.model.Instance; import com.amazonaws.services.elasticloadbalancing.AmazonElasticLoadBalancing; import com.amazonaws.services.elasticloadbalancing.AmazonElasticLoadBalancingClient; import com.amazonaws.services.elasticloadbalancing.model.*; import com.amazonaws.services.identitymanagement.model.*; import com.amazonaws.services.s3.AmazonS3; import com.amazonaws.services.s3.AmazonS3Client; import com.github.sjones4.youcan.youare.YouAre; import com.github.sjones4.youcan.youare.YouAreClient; import com.github.sjones4.youcan.youare.model.CreateAccountRequest; import com.github.sjones4.youcan.youare.model.DeleteAccountRequest; import org.apache.log4j.Logger; import java.io.IOException; import java.nio.charset.Charset; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.*; import java.util.concurrent.TimeUnit; class Eutester4j { static String eucarc = System.getProperty("eucarc"); static String endpointFile = System.getProperty("endpoints"); static Logger logger = Logger.getLogger(Eutester4j.class.getCanonicalName()); static String EC2_ENDPOINT = null; static String AS_ENDPOINT = null; static String ELB_ENDPOINT = null; static String IAM_ENDPOINT = null; static String CW_ENDPOINT = null; static String S3_ENDPOINT = null; static String TOKENS_ENDPOINT = null; static String SECRET_KEY = null; static String ACCESS_KEY = null; static String ACCOUNT_ID = null; static String CREDPATH = null; static String NAME_PREFIX; static String endpoints; static AmazonAutoScaling as; static AmazonEC2 ec2; static AmazonElasticLoadBalancing elb; static AmazonCloudWatch cw; static AmazonS3 s3; static YouAre youAre; static String IMAGE_ID = null; static String KERNEL_ID = null; static String RAMDISK_ID = null; static String AVAILABILITY_ZONE = null; static String INSTANCE_TYPE = "m1.small"; public static void getCloudInfo() throws Exception { if (eucarc != null) { CREDPATH = eucarc; } else { CREDPATH = "eucarc"; } if (endpointFile != null) { endpoints = endpointFile; } else { endpoints = "endpoints.xml"; } print("Getting cloud information from " + CREDPATH); EC2_ENDPOINT = parseEucarc(CREDPATH, "EC2_URL"); AS_ENDPOINT = parseEucarc(CREDPATH, "AWS_AUTO_SCALING_URL"); ELB_ENDPOINT = parseEucarc(CREDPATH, "AWS_ELB_URL"); CW_ENDPOINT = parseEucarc(CREDPATH, "AWS_CLOUDWATCH_URL"); IAM_ENDPOINT = parseEucarc(CREDPATH, "EUARE_URL"); S3_ENDPOINT = parseEucarc(CREDPATH, "S3_URL"); TOKENS_ENDPOINT = parseEucarc(CREDPATH, "TOKEN_URL"); SECRET_KEY = parseEucarc(CREDPATH, "EC2_SECRET_KEY").replace("'", ""); ACCESS_KEY = parseEucarc(CREDPATH, "EC2_ACCESS_KEY").replace("'", ""); ACCOUNT_ID = parseEucarc(CREDPATH,"EC2_ACCOUNT_NUMBER").replace("'", ""); print("Updating endpoints file"); updateEndpoints(endpoints, EC2_ENDPOINT, S3_ENDPOINT); print("Getting cloud connections"); as = getAutoScalingClient(ACCESS_KEY, SECRET_KEY, AS_ENDPOINT); ec2 = getEc2Client(ACCESS_KEY, SECRET_KEY, EC2_ENDPOINT); elb = getElbClient(ACCESS_KEY, SECRET_KEY, ELB_ENDPOINT); cw = getCwClient(ACCESS_KEY, SECRET_KEY, CW_ENDPOINT); s3 = getS3Client(ACCESS_KEY, SECRET_KEY, S3_ENDPOINT); youAre = getYouAreClient(ACCESS_KEY, SECRET_KEY, IAM_ENDPOINT); IMAGE_ID = findImage(); if (!isHVM()) { KERNEL_ID = findKernel(); RAMDISK_ID = findRamdisk(); } AVAILABILITY_ZONE = findAvailablityZone(); NAME_PREFIX = eucaUUID() + "-"; print("Using resource prefix for test: " + NAME_PREFIX); print("Cloud Discovery Complete"); } // Quick way to initialize just the S3 client without initializing other clients in getCloudInfo(). // For ease of use against AWS (mainly) as well as Eucalyptus public static void initS3Client() throws Exception { if (eucarc != null) { CREDPATH = eucarc; } else { CREDPATH = "eucarc"; } if (endpointFile != null) { endpoints = endpointFile; } else { endpoints = "endpoints.xml"; } print("Getting cloud information from " + CREDPATH); EC2_ENDPOINT = parseEucarc(CREDPATH, "EC2_URL"); S3_ENDPOINT = parseEucarc(CREDPATH, "S3_URL"); SECRET_KEY = parseEucarc(CREDPATH, "EC2_SECRET_KEY").replace("'", ""); ACCESS_KEY = parseEucarc(CREDPATH, "EC2_ACCESS_KEY").replace("'", ""); print("Updating endpoints file"); updateEndpoints(endpoints, EC2_ENDPOINT, S3_ENDPOINT); print("Initializing S3 connections"); s3 = getS3Client(ACCESS_KEY, SECRET_KEY, S3_ENDPOINT); print("S3 Discovery Complete"); } public static AmazonS3 initS3ClientWithNewAccount(String account, String user) throws Exception { // Initialize everything for the first time if (EC2_ENDPOINT == null || S3_ENDPOINT == null || IAM_ENDPOINT == null || ACCESS_KEY == null || SECRET_KEY == null) { if (eucarc != null) { CREDPATH = eucarc; } else { CREDPATH = "eucarc"; } if (endpointFile != null) { endpoints = endpointFile; } else { endpoints = "endpoints.xml"; } print("Getting cloud information from " + CREDPATH); EC2_ENDPOINT = parseEucarc(CREDPATH, "EC2_URL"); S3_ENDPOINT = parseEucarc(CREDPATH, "S3_URL"); IAM_ENDPOINT = parseEucarc(CREDPATH, "EUARE_URL"); ACCESS_KEY = parseEucarc(CREDPATH, "EC2_ACCESS_KEY").replace("'", ""); SECRET_KEY = parseEucarc(CREDPATH, "EC2_SECRET_KEY").replace("'", ""); print("Updating endpoints file"); updateEndpoints(endpoints, EC2_ENDPOINT, S3_ENDPOINT); youAre = getYouAreClient(ACCESS_KEY, SECRET_KEY, IAM_ENDPOINT); } // Create a new account if one does not exist try { createAccount(account); if (!user.equalsIgnoreCase("admin")) { createUser(account, user); } } catch (Exception e) { // Account may already exist, try getting the keys } Map<String, String> keyMap = getUserKeys(account, user); // Initialize the s3 client and return it return getS3Client(keyMap.get("ak"), keyMap.get("sk"), S3_ENDPOINT); } public static void testInfo(String testName) { print("*****TEST NAME: " + testName); } /** * create ec2 connection based with supplied accessKey and secretKey * * @param accessKey * @param secretKey */ public static AmazonEC2 getEc2Client(String accessKey, String secretKey, String endpoint) { AWSCredentials creds = new BasicAWSCredentials(accessKey, secretKey); final AmazonEC2 ec2 = new AmazonEC2Client(creds); ec2.setEndpoint(endpoint); return ec2; } public static AmazonAutoScaling getAutoScalingClient(String accessKey, String secretKey, String endpoint) { AWSCredentials creds = new BasicAWSCredentials(accessKey, secretKey); final AmazonAutoScaling as = new AmazonAutoScalingClient(creds); as.setEndpoint(endpoint); return as; } public static AmazonElasticLoadBalancing getElbClient(String accessKey, String secretKey, String endpoint) { AWSCredentials creds = new BasicAWSCredentials(accessKey, secretKey); final AmazonElasticLoadBalancing elb = new AmazonElasticLoadBalancingClient(creds); elb.setEndpoint(endpoint); return elb; } /** * The YouAre interface extends AmazonIdentityManagement so you have the * regular IAM actions plus (a few) Euare specific ones. */ public static YouAre getYouAreClient(String accessKey, String secretKey, String endpoint) { AWSCredentialsProvider awsCredentialsProvider = new StaticCredentialsProvider( new BasicAWSCredentials(accessKey, secretKey)); final YouAre youAre = new YouAreClient(awsCredentialsProvider); youAre.setEndpoint(endpoint); return youAre; } public static AmazonCloudWatch getCwClient(String accessKey, String secretKey, String endpoint) { AWSCredentials creds = new BasicAWSCredentials(accessKey, secretKey); final AmazonCloudWatch cw = new AmazonCloudWatchClient(creds); cw.setEndpoint(endpoint); return cw; } public static AmazonS3 getS3Client(String accessKey, String secretKey, String endpoint) { AWSCredentials creds = new BasicAWSCredentials(accessKey, secretKey); final AmazonS3 s3 = new AmazonS3Client(creds); s3.setEndpoint(endpoint); return s3; } /** * @param credpath * @param field * @return the value of the field from eucarc file * @throws IOException */ public static String parseEucarc(String credpath, String field) throws IOException { Charset charset = Charset.forName("UTF-8"); String creds = credpath; String result = null; try { List<String> lines = Files.readAllLines(Paths.get(creds), charset); CharSequence find = field; for (String line : lines) { if (line.contains(find)) { result = line.substring(line.lastIndexOf('=') + 1); break; } } } catch (IOException ioe) { ioe.printStackTrace(); } return result; } public static void updateEndpoints(String endpoints, String ec2Endpoint, String s3Endpoint) throws IOException { Path path = Paths.get(endpoints); Charset charset = Charset.forName("UTF-8"); String content = new String(Files.readAllBytes(path), charset); content = content.replaceAll("EC2_URL", ec2Endpoint); content = content.replaceAll("WALRUS_URL", s3Endpoint); Files.write(path, content.getBytes(charset)); } public static String eucaUUID() { return Long.toHexString(Double.doubleToLongBits(Math.random())); } public static void assertThat(boolean condition, String message) { assert condition : message; } public static void print(String text) { logger.info(text); } /** * helper method to pause execution * * @param secs time to sleep in seconds */ public static void sleep(int secs) { try { Thread.sleep(secs * 1000); } catch (InterruptedException e) { e.printStackTrace(); } } public static void verifyInstanceHealthStatus(final String instanceId, final String expectedStatus) { String healthStatus = getHealthStatus(instanceId); assertThat(expectedStatus.equals(healthStatus), "Expected " + expectedStatus + " health status"); } public static void waitForHealthStatus(final String instanceId, final String expectedStatus) throws Exception { final long startTime = System.currentTimeMillis(); final long timeout = TimeUnit.MINUTES.toMillis(5); boolean completed = false; while (!completed && (System.currentTimeMillis() - startTime) < timeout) { Thread.sleep(5000); final String healthStatus = getHealthStatus(instanceId); completed = expectedStatus.equals(healthStatus); } assertThat(completed, "Instances health status did not change to " + expectedStatus + " within the expected timeout"); print("Instance health status changed in " + (System.currentTimeMillis() - startTime) + "ms"); } public static String getHealthStatus(final String instanceId) { final DescribeAutoScalingInstancesResult instancesResult = as .describeAutoScalingInstances(new DescribeAutoScalingInstancesRequest().withInstanceIds(instanceId)); assertThat(instancesResult.getAutoScalingInstances().size() == 1, "Auto scaling instance found"); final AutoScalingInstanceDetails details = instancesResult.getAutoScalingInstances().get(0); final String healthStatus = details.getHealthStatus(); print("Health status: " + healthStatus); return healthStatus; } public static List<?> waitForInstances(final long timeout, final int expectedCount, final String groupName, final boolean asString) throws Exception { final long startTime = System.currentTimeMillis(); boolean completed = false; if (asString) { List<?> instanceIds = Collections.emptyList(); while (!completed && (System.currentTimeMillis() - startTime) < timeout) { Thread.sleep(5000); instanceIds = getInstancesForGroup(groupName, "running", true); completed = instanceIds.size() == expectedCount; } assertThat(completed, "Instances count did not change to " + expectedCount + " within the expected timeout"); print("Instance count changed in " + (System.currentTimeMillis() - startTime) + "ms"); return instanceIds; } else { List<?> instances = Collections.emptyList(); while (!completed && (System.currentTimeMillis() - startTime) < timeout) { Thread.sleep(5000); instances = getInstancesForGroup(groupName, "running", false); completed = instances.size() == expectedCount; } assertThat(completed, "Instances count did not change to " + expectedCount + " within the expected timeout"); print("Instance count changed in " + (System.currentTimeMillis() - startTime) + "ms"); return instances; } } public static List<?> getInstancesForGroup(final String groupName, final String status, final boolean asString) { final DescribeInstancesResult instancesResult = ec2 .describeInstances(new DescribeInstancesRequest() .withFilters(new Filter() .withName("tag:aws:autoscaling:groupName") .withValues(groupName))); if (asString) { final List<String> instanceIds = new ArrayList<String>(); for (final Reservation reservation : instancesResult.getReservations()) { for (final Instance instance : reservation.getInstances()) { if (status == null || instance.getState() == null || status.equals(instance.getState().getName())) { instanceIds.add(instance.getInstanceId()); } } } return instanceIds; } else { final List<Instance> instances = new ArrayList<Instance>(); for (final Reservation reservation : instancesResult.getReservations()) { for (final Instance instance : reservation.getInstances()) { if (status == null || instance.getState() == null || status.equals(instance.getState().getName())) { instances.add(instance); } } } return instances; } } /** * Wait for instance steady state (no PENDING, no STOPPING, no SHUTTING-DOWN) */ public static void waitForInstances(final long timeout) { final long startTime = System.currentTimeMillis(); withWhile: while (true) { if ((System.currentTimeMillis() - startTime) > timeout) { throw new IllegalStateException("Instance wait timed out"); } try { Thread.sleep(2000); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } DescribeInstancesResult result = ec2.describeInstances(); for (final Reservation reservation : result.getReservations()) { for (final Instance instance : reservation.getInstances()) { switch (instance.getState().getCode()) { case 0: case 32: case 64: continue withWhile; } } } break; } } /** * Wait for volume steady state (no creating, no deleting) */ public static void waitForVolumes(final long timeout) { final long startTime = System.currentTimeMillis(); withWhile: while (true) { if ((System.currentTimeMillis() - startTime) > timeout) { throw new IllegalStateException("Volume wait timed out"); } try { Thread.sleep(2000); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } final DescribeVolumesResult result = ec2.describeVolumes(); for (final Volume volume : result.getVolumes()) { if ("creating".equals(volume.getState()) || "deleting".equals(volume.getState())) continue withWhile; } break; } } /** * Wait for snapshot steady state (no pending) */ public static void waitForSnapshots(final long timeout) { final long startTime = System.currentTimeMillis(); withWhile: while (true) { if ((System.currentTimeMillis() - startTime) > timeout) { throw new IllegalStateException("Snapshot wait timed out"); } try { Thread.sleep(2000); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } final DescribeSnapshotsResult result = ec2.describeSnapshots(); for (final Snapshot snapshot : result.getSnapshots()) { if ("pending".equals(snapshot.getState())) continue withWhile; } break; } } public static String findImage() { // Find an appropriate image to launch final DescribeImagesResult imagesResult = ec2 .describeImages(new DescribeImagesRequest().withFilters( new Filter().withName("image-type").withValues( "machine"), new Filter().withName("root-device-type").withValues( "instance-store"), new Filter().withName("is-public").withValues( "true"))); assertThat(imagesResult.getImages().size() > 0, "Image not found"); final String imageId = imagesResult.getImages().get(0).getImageId(); print("Using image: " + imageId); return imageId; } public static boolean isHVM() { final DescribeImagesResult imagesResult = ec2 .describeImages(new DescribeImagesRequest().withFilters( new Filter().withName("image-id").withValues( findImage()), new Filter().withName("virtualization-type").withValues( "hvm"))); return (imagesResult.getImages().size() != 0); } public static String findKernel() { // Find an appropriate image to launch final DescribeImagesResult imagesResult = ec2 .describeImages(new DescribeImagesRequest() .withFilters( new Filter().withName("kernel-id").withValues( "eki-*"))); assertThat(imagesResult.getImages().size() > 0, "Kernel not found (image with explicit kernel and ramdisk required)"); print("Using kernel: " + imagesResult.getImages().get(0).getKernelId()); return imagesResult.getImages().get(0).getKernelId(); } public static String findRamdisk() { // Find an appropriate image to launch final DescribeImagesResult imagesResult = ec2 .describeImages(new DescribeImagesRequest() .withFilters( new Filter().withName("ramdisk-id").withValues( "eri-*"))); assertThat(imagesResult.getImages().size() > 0, "RamDisk not found (image with explicit kernel and ramdisk required)"); print("Using ramdisk: " + imagesResult.getImages().get(0).getRamdiskId()); return imagesResult.getImages().get(0).getRamdiskId(); } public static String findAvailablityZone() { // Find an AZ to use final DescribeAvailabilityZonesResult azResult = ec2 .describeAvailabilityZones(); assertThat(azResult.getAvailabilityZones().size() > 0, "Availability zone not found"); final String availabilityZone = azResult.getAvailabilityZones().get(0) .getZoneName(); print("Using availability zone: " + availabilityZone); return availabilityZone; } public static List<AvailabilityZone> getAZ() { // Find an AZ to use final DescribeAvailabilityZonesResult azResult = ec2 .describeAvailabilityZones(); assertThat(azResult.getAvailabilityZones().size() > 0, "Availability zone not found"); return azResult.getAvailabilityZones(); } /** * @param name * @param desc */ public static void createSecurityGroup(String name, String desc) { try { CreateSecurityGroupRequest securityGroupRequest = new CreateSecurityGroupRequest( name, desc); ec2.createSecurityGroup(securityGroupRequest); print("Created Security Group: " + name); } catch (AmazonServiceException ase) { // Likely this means that the group is already created, so ignore. print(ase.getMessage()); } } /** * @return list of security groups */ public static List<SecurityGroup> describeSecurityGroups() { DescribeSecurityGroupsResult securityGroupsResult = null; try { DescribeSecurityGroupsRequest describeSecurityGroupsRequest = new DescribeSecurityGroupsRequest(); securityGroupsResult = ec2 .describeSecurityGroups(describeSecurityGroupsRequest); } catch (AmazonServiceException ase) { // Likely this means that the group is already created, so ignore. print(ase.getMessage()); } return securityGroupsResult.getSecurityGroups(); } /** * @param groupName security group to delete */ public static void deleteSecurityGroup(String groupName) { try { DeleteSecurityGroupRequest deleteSecurityGroupRequest = new DeleteSecurityGroupRequest( groupName); ec2.deleteSecurityGroup(deleteSecurityGroupRequest); print("Deleted Security Group: " + groupName); } catch (AmazonServiceException ase) { print(ase.getMessage()); } } /** * @param emi * @param keyName * @param type * @param securityGroups */ public static void runInstances(String emi, String keyName, String type, List<String> securityGroups, int minCount, int maxCount) { RunInstancesRequest runInstancesRequest = new RunInstancesRequest() .withInstanceType(type).withImageId(emi).withMinCount(minCount) .withMaxCount(maxCount).withSecurityGroups(securityGroups) .withKeyName(keyName); ec2.runInstances(runInstancesRequest); print("Started instance: " + getLastlaunchedInstance().get(0).getInstanceId()); } /** * @param instanceIds */ public static void stopInstances(List<String> instanceIds) { StopInstancesRequest stopInstancesRequest = new StopInstancesRequest( instanceIds); ec2.stopInstances(stopInstancesRequest); for (String instance : instanceIds) { print("Stopped instance: " + instance); } } /** * @param instanceIds */ public static void startInstances(List<String> instanceIds) { StartInstancesRequest startInstancesRequest = new StartInstancesRequest( instanceIds); ec2.startInstances(startInstancesRequest); for (String instance : instanceIds) { print("Started instance: " + instance); } } /** * @param instanceIds */ public static void terminateInstances(List<String> instanceIds) { TerminateInstancesRequest terminateInstancesRequest = new TerminateInstancesRequest(instanceIds); ec2.terminateInstances(terminateInstancesRequest); for (String instance : instanceIds) { print("Terminated instance: " + instance); } } /** * @return # of reservations */ public static List<Reservation> getInstancesList() { DescribeInstancesResult describeInstancesRequest = ec2.describeInstances(); return describeInstancesRequest.getReservations(); } /** * @param keyName */ public static void createKeyPair(String keyName) { CreateKeyPairRequest createKeyPairRequest = new CreateKeyPairRequest( keyName); ec2.createKeyPair(createKeyPairRequest); print("Created keypair: " + keyName); } /** * @return */ public static int getKeyPairCount() { DescribeKeyPairsRequest describeKeyPairsRequest = new DescribeKeyPairsRequest(); DescribeKeyPairsResult describeKeyPairsResult = ec2 .describeKeyPairs(describeKeyPairsRequest); return describeKeyPairsResult.getKeyPairs().size(); } /** * @param keyName */ public static void deleteKeyPair(String keyName) { DeleteKeyPairRequest deleteKeyPairRequest = new DeleteKeyPairRequest( keyName); ec2.deleteKeyPair(deleteKeyPairRequest); print("Deleted keypair: " + keyName); } /** * Create a volume, returning the identifier. */ public static String createVolume(final String zone, final int size) { final String volumeId = ec2.createVolume( new CreateVolumeRequest() .withAvailabilityZone(zone) .withSize(size) ).getVolume().getVolumeId(); print("Created Volume: " + volumeId); return volumeId; } public static void deleteVolume(final String volumeId) { ec2.deleteVolume(new DeleteVolumeRequest().withVolumeId(volumeId)); print("Deleted Volume: " + volumeId); } /** * Create a snapshot, returning the identifier. */ public static String createSnapshot(final String volumeId, final String description) { final String snapshotId = ec2.createSnapshot( new CreateSnapshotRequest() .withVolumeId(volumeId) .withDescription(description) ).getSnapshot().getSnapshotId(); print("Created Snapshot: " + snapshotId); return snapshotId; } public static void deleteSnapshot(final String snapshotId) { ec2.deleteSnapshot(new DeleteSnapshotRequest().withSnapshotId(snapshotId)); print("Deleted Snapshot: " + snapshotId); } public static String allocateElasticIP() { final String ip = ec2.allocateAddress().getPublicIp(); print("Allocated Elastic IP: " + ip); return ip; } public static void releaseElasticIP(final String ip) { ec2.releaseAddress(new ReleaseAddressRequest().withPublicIp(ip)); print("Released Elastic IP: " + ip); } /** * @return */ public static List<Instance> getLastlaunchedInstance() { List<Instance> instanceList = null; List<Reservation> reservations = getInstancesList(); for (Reservation reservation : reservations) { instanceList = reservation.getInstances(); Collections.sort(instanceList, new Comparator<Instance>() { public int compare(Instance i1, Instance i2) { return i1.getLaunchTime().compareTo(i2.getLaunchTime()); } }); } return instanceList; } public static void createLaunchConfig(String launchConfig, String imageId, String instanceType, String keyName, String securityGroups, String kernelId, String ramdiskId, BlockDeviceMapping blockDeviceMapping, String iamInstanceProfile, InstanceMonitoring instanceMonitoring, String userData) { CreateLaunchConfigurationRequest createLaunchConfigurationRequest = new CreateLaunchConfigurationRequest() .withLaunchConfigurationName(launchConfig) .withImageId(imageId) .withInstanceType(instanceType) .withSecurityGroups(securityGroups) .withKeyName(keyName) .withKernelId(kernelId) .withRamdiskId(ramdiskId) .withBlockDeviceMappings(blockDeviceMapping) .withIamInstanceProfile(iamInstanceProfile) .withInstanceMonitoring(instanceMonitoring) .withUserData(userData); as.createLaunchConfiguration(createLaunchConfigurationRequest); print("Created Launch Configuration: " + launchConfig); } public static List<LaunchConfiguration> describeLaunchConfigs() { DescribeLaunchConfigurationsResult launchConfigurationsResult = null; try { DescribeLaunchConfigurationsRequest describeLaunchConfigurationsRequest = new DescribeLaunchConfigurationsRequest(); launchConfigurationsResult = as.describeLaunchConfigurations(describeLaunchConfigurationsRequest); } catch (AmazonServiceException ase) { print(ase.getMessage()); } return launchConfigurationsResult.getLaunchConfigurations(); } public static void deleteLaunchConfig(String launchConfigurationName) { try { DeleteLaunchConfigurationRequest deleteLaunchConfigurationRequest = new DeleteLaunchConfigurationRequest() .withLaunchConfigurationName(launchConfigurationName); as.deleteLaunchConfiguration(deleteLaunchConfigurationRequest); print("Deleted Launch Configuration: " + launchConfigurationName); } catch (AmazonServiceException ase) { print(ase.getMessage()); } } public static void createAutoScalingGroup(String groupName, String launchConfig, Integer minSize, Integer maxSize, Integer desiredCapacity, String availabilityZone, Integer cooldown, Integer healthCheckGracePeriod, String healthCheckType, String loadBalancer, Tag tag, String terminationPolicy) { CreateAutoScalingGroupRequest createAutoScalingGroupRequest = new CreateAutoScalingGroupRequest() .withAutoScalingGroupName(groupName) .withLaunchConfigurationName(launchConfig) .withMinSize(minSize) .withMaxSize(maxSize) .withDesiredCapacity(desiredCapacity) .withAvailabilityZones(availabilityZone) .withDefaultCooldown(cooldown) .withHealthCheckGracePeriod(healthCheckGracePeriod) .withHealthCheckType(healthCheckType) .withLoadBalancerNames(loadBalancer) .withTags(tag) .withTerminationPolicies(terminationPolicy); as.createAutoScalingGroup(createAutoScalingGroupRequest); print("Created Auto Scaling Group: " + groupName); } public static List<AutoScalingGroup> describeAutoScalingGroups() { DescribeAutoScalingGroupsResult autoScalingGroupsResult = null; try { DescribeAutoScalingGroupsRequest describeAutoScalingGroupsRequest = new DescribeAutoScalingGroupsRequest(); autoScalingGroupsResult = as.describeAutoScalingGroups(describeAutoScalingGroupsRequest); } catch (AmazonServiceException ase) { print(ase.getMessage()); } return autoScalingGroupsResult.getAutoScalingGroups(); } public static void deleteAutoScalingGroup(String autoScalingGroupName, boolean force) { try { DeleteAutoScalingGroupRequest deleteAutoScalingGroupRequest = new DeleteAutoScalingGroupRequest() .withAutoScalingGroupName(autoScalingGroupName) .withForceDelete(force); as.deleteAutoScalingGroup(deleteAutoScalingGroupRequest); print("Deleted Auto Scaling Group: " + autoScalingGroupName); } catch (AmazonServiceException ase) { print(ase.getMessage()); } } public static String getInstanceState(final String groupName) { final DescribeAutoScalingGroupsResult groupResult = as.describeAutoScalingGroups(new DescribeAutoScalingGroupsRequest().withAutoScalingGroupNames(groupName)); String state = null; for (final AutoScalingGroup group : groupResult.getAutoScalingGroups()) { assertThat(groupName.equals(group.getAutoScalingGroupName()), "Unexpected group: " + group.getAutoScalingGroupName()); assertThat(group.getInstances().size() < 2, "Unexpected instance count: " + group.getInstances().size()); for (final com.amazonaws.services.autoscaling.model.Instance instance : group.getInstances()) { state = instance.getLifecycleState(); } } return state; } public static void waitForInstances(final String state, final long timeout, final String groupName, final boolean allowEmpty) throws Exception { final long startTime = System.currentTimeMillis(); boolean completed = false; String instanceState = null; while (!completed && (System.currentTimeMillis() - startTime) < timeout) { instanceState = getInstanceState(groupName); completed = instanceState == null && allowEmpty || state.equals(instanceState); Thread.sleep(2500); } assertThat(completed, "Instance not found with state " + state + " within the expected timeout"); print("Instance found in " + (System.currentTimeMillis() - startTime) + "ms for state: " + state + (instanceState == null ? " (instance terminated before state detected)" : "")); } public static void deletePolicy(String policyName) { DeletePolicyRequest deletePolicyRequest = null; try { deletePolicyRequest = new DeletePolicyRequest().withPolicyName(policyName); as.deletePolicy(deletePolicyRequest); print("Deleted policy: " + policyName); } catch (AmazonServiceException ase) { print(ase.getMessage()); } } public static List<ScalingPolicy> describePolicies() { DescribePoliciesResult describePoliciesResult = null; try { DescribePoliciesRequest describePoliciesRequest = new DescribePoliciesRequest(); describePoliciesResult = as.describePolicies(describePoliciesRequest); } catch (AmazonServiceException ase) { print(ase.getMessage()); } return describePoliciesResult.getScalingPolicies(); } public static void createLoadBalancer(String loadBalancerName) { elb.createLoadBalancer(new CreateLoadBalancerRequest() .withLoadBalancerName(loadBalancerName) .withAvailabilityZones(AVAILABILITY_ZONE) .withListeners( new Listener().withInstancePort(80) .withLoadBalancerPort(80) .withProtocol("HTTP"))); print("Created load balancer: " + loadBalancerName); } public static void deleteLoadBlancer(String loadBalancerName) { try { elb.deleteLoadBalancer(new DeleteLoadBalancerRequest().withLoadBalancerName(loadBalancerName)); print("Deleted load balancer: " + loadBalancerName); } catch (AmazonServiceException ase) { print(ase.getMessage()); } } public static void waitForElbInstances(final String elbName, final long timeout, final List<String> instances) throws Exception { final long startTime = System.currentTimeMillis(); boolean completed = false; while (!completed && (System.currentTimeMillis() - startTime) < timeout) { final List<String> elbInstances = new ArrayList<String>(); final DescribeLoadBalancersResult balancersResult = elb.describeLoadBalancers(new DescribeLoadBalancersRequest().withLoadBalancerNames(elbName)); for (final LoadBalancerDescription description : balancersResult.getLoadBalancerDescriptions()) { for (final com.amazonaws.services.elasticloadbalancing.model.Instance instance : description.getInstances()) { elbInstances.add(instance.getInstanceId()); } } completed = elbInstances.containsAll(instances) && instances.containsAll(elbInstances); Thread.sleep(2500); } assertThat(completed, "Instance not found for load balancer " + elbName + " within the expected timeout"); print("Instance found in " + (System.currentTimeMillis() - startTime) + "ms for load balancer: " + elbName); } public static boolean isProfilePresent(final String profileName, final List<InstanceProfile> profiles) { boolean foundProfile = false; if (profiles != null) for (final InstanceProfile profile : profiles) { foundProfile = foundProfile || profileName.equals(profile.getInstanceProfileName()); } return foundProfile; } public static void createIAMPolicy(final String accountName, String userName, String policyName, String policyDocument) { AWSCredentialsProvider awsCredentialsProvider = new StaticCredentialsProvider( new BasicAWSCredentials(ACCESS_KEY, SECRET_KEY)); final YouAreClient youAre = new YouAreClient(awsCredentialsProvider); youAre.setEndpoint(IAM_ENDPOINT); youAre.addRequestHandler(new AbstractRequestHandler() { public void beforeRequest(final Request<?> request) { request.addParameter("DelegateAccount", accountName); } }); if (policyDocument == null) { policyDocument = "{\n" + "\"Statement\": [\n" + " {\n" + " \"Action\": \"*\",\n" + " \"Effect\": \"Allow\",\n" + " \"Resource\": \"*\"\n" + " }\n" + " ]\n" + "}"; } PutUserPolicyRequest putUserPolicyRequest = new PutUserPolicyRequest() .withPolicyName(policyName) .withPolicyDocument(policyDocument) .withUserName(userName); youAre.putUserPolicy(putUserPolicyRequest); print("Created policy: " + policyName); } public static AWSCredentials getUserCreds(final String accountName, String userName) { AWSCredentialsProvider awsCredentialsProvider = new StaticCredentialsProvider( new BasicAWSCredentials(ACCESS_KEY, SECRET_KEY)); final YouAreClient youAre = new YouAreClient(awsCredentialsProvider); youAre.setEndpoint(IAM_ENDPOINT); youAre.addRequestHandler(new AbstractRequestHandler() { public void beforeRequest(final Request<?> request) { request.addParameter("DelegateAccount", accountName); } }); CreateAccessKeyRequest createAccessKeyRequest = new CreateAccessKeyRequest().withUserName(userName); String newKeys = String.valueOf(youAre.createAccessKey(createAccessKeyRequest)); print("Created new access key for user " + userName); // get accesskey from key gen result request int start = newKeys.lastIndexOf("AccessKeyId:") + 13; int end = newKeys.lastIndexOf(",Status"); String accessKey = newKeys.substring(start, end); print("Access Key: " + accessKey); // get secretkey from key gen result request start = newKeys.lastIndexOf("SecretAccessKey:") + 17; end = newKeys.lastIndexOf(",CreateDate:"); String secretKey = newKeys.substring(start, end); print("Secret Key: " + secretKey); return new BasicAWSCredentials(accessKey, secretKey); } public static void createAccount(String accountName) { int numAccountsBefore = youAre.listAccounts().getAccounts().size(); CreateAccountRequest createAccountRequest = new CreateAccountRequest().withAccountName(accountName); youAre.createAccount(createAccountRequest); assertThat((numAccountsBefore < youAre.listAccounts().getAccounts().size()),"Failed to create account " + accountName); print("Created account: " + accountName); } public static void deleteAccount(String accountName){ int numAccountsBefore = youAre.listAccounts().getAccounts().size(); DeleteAccountRequest deleteAccountRequest = new DeleteAccountRequest().withAccountName(accountName).withRecursive(Boolean.TRUE); youAre.deleteAccount(deleteAccountRequest); assertThat((numAccountsBefore > youAre.listAccounts().getAccounts().size()),"Failed to delete account " + accountName); print("Deleted account: " + accountName); } public static void createUser(final String accountName, String userName){ AWSCredentialsProvider awsCredentialsProvider = new StaticCredentialsProvider( new BasicAWSCredentials(ACCESS_KEY, SECRET_KEY)); final YouAreClient youAre = new YouAreClient(awsCredentialsProvider); youAre.setEndpoint(IAM_ENDPOINT); youAre.addRequestHandler(new AbstractRequestHandler() { public void beforeRequest(final Request<?> request) { request.addParameter("DelegateAccount", accountName); } }); int numUsersBefore = youAre.listUsers().getUsers().size(); CreateUserRequest createUserRequest = new CreateUserRequest() .withUserName(userName) .withPath("/"); youAre.createUser(createUserRequest); assertThat((numUsersBefore < youAre.listUsers().getUsers().size()), "Failed to create user " + userName); print("Created new user " + userName + " in account " + accountName); } public static Map<String, String> getUserKeys(final String accountName, String userName){ Map<String, String> keys = new HashMap<>(); AWSCredentialsProvider awsCredentialsProvider = new StaticCredentialsProvider( new BasicAWSCredentials(ACCESS_KEY, SECRET_KEY)); final YouAreClient youAre = new YouAreClient(awsCredentialsProvider); youAre.setEndpoint(IAM_ENDPOINT); youAre.addRequestHandler(new AbstractRequestHandler() { public void beforeRequest(final Request<?> request) { request.addParameter("DelegateAccount", accountName); } }); CreateAccessKeyRequest createAccessKeyRequest = new CreateAccessKeyRequest().withUserName(userName); String newKeys = String.valueOf(youAre.createAccessKey(createAccessKeyRequest)); print("Created new access key for user " + userName); // get accesskey from key gen result request int start = newKeys.lastIndexOf("AccessKeyId:") + 13; int end = newKeys.lastIndexOf(",Status"); String accessKey = newKeys.substring(start, end); keys.put("ak", accessKey); // get secretkey from key gen result request start = newKeys.lastIndexOf("SecretAccessKey:") + 17; end = newKeys.lastIndexOf(",CreateDate:"); String secretKey = newKeys.substring(start, end); keys.put("sk", secretKey); return keys; } }
package ev3dev.utils; import mocks.MockBaseTest; import mocks.ev3dev.sensors.BatteryMock; import org.junit.Before; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.nio.file.Path; import java.nio.file.Paths; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; public class SysfsTest extends MockBaseTest { private static final Logger LOGGER = LoggerFactory.getLogger(SysfsTest.class); final String BATTERY_PATH = "power_supply"; final String BATTERY_EV3_SUBPATH = "legoev3-battery"; final String BATTERY_FIELD_VOLTAGE = "voltage_now"; final String BATTERY_FIELD_VOLTAGE_VALUE = "8042133"; String BATTERY_FIELD_VOLTAGE_SUFFIX; @Before public void onceExecutedBeforeAll() throws IOException { getGlobalPaths(); createEV3DevMocksPath(); } @Test public void existPathSuccessTest() throws IOException { String pathToAssert = JAVA_IO_TEMPDIR + JUNIT_PATH + "/"+ EV3DEV_PATH; assertThat(tempEV3DevFolder.getAbsolutePath(), is(pathToAssert)); assertThat(Sysfs.existPath(pathToAssert), is(true)); pathToAssert = JAVA_IO_TEMPDIR + JUNIT_PATH + "/"+ EV3DEV_PATH + "/"+ MOCKS_PATH; assertThat(tempMocksFolder.getAbsolutePath(), is(pathToAssert)); assertThat(Sysfs.existPath(pathToAssert), is(true)); } @Test public void existPathSuccessTest2() throws IOException { BatteryMock batteryMock = new BatteryMock(this.tempFolder); BATTERY_FIELD_VOLTAGE_SUFFIX = batteryMock.createEV3DevMocksEV3BrickPlatformPath(); final String pathToAssert = JAVA_IO_TEMPDIR + JUNIT_PATH + "/"+ EV3DEV_PATH + "/" + MOCKS_PATH + "/" + BATTERY_PATH + "/" + BATTERY_EV3_SUBPATH; //assertThat(tempEV3BatteryFolder.getAbsolutePath(), is(pathToAssert)); assertThat(Sysfs.existPath(pathToAssert), is(true)); } @Test public void readString() throws Exception { BatteryMock batteryMock = new BatteryMock(this.tempFolder); BATTERY_FIELD_VOLTAGE_SUFFIX = batteryMock.createEV3DevMocksEV3BrickPlatformPath(); String pathToAssert = JAVA_IO_TEMPDIR + JUNIT_PATH + "/"+ EV3DEV_PATH + "/" + MOCKS_PATH + "/" + BATTERY_PATH + "/" + BATTERY_EV3_SUBPATH + "/" + BATTERY_FIELD_VOLTAGE + BATTERY_FIELD_VOLTAGE_SUFFIX; assertThat(Sysfs.readString(pathToAssert), is(BATTERY_FIELD_VOLTAGE_VALUE)); } @Test public void readInteger() throws Exception { BatteryMock batteryMock = new BatteryMock(this.tempFolder); BATTERY_FIELD_VOLTAGE_SUFFIX = batteryMock.createEV3DevMocksEV3BrickPlatformPath(); String pathToAssert = JAVA_IO_TEMPDIR + JUNIT_PATH + "/"+ EV3DEV_PATH + "/" + MOCKS_PATH + "/" + BATTERY_PATH + "/" + BATTERY_EV3_SUBPATH + "/" + BATTERY_FIELD_VOLTAGE + BATTERY_FIELD_VOLTAGE_SUFFIX; LOGGER.trace(pathToAssert); assertThat(Sysfs.readInteger(pathToAssert), is(Integer.parseInt(BATTERY_FIELD_VOLTAGE_VALUE))); } @Test public void readFloat() throws Exception { BatteryMock batteryMock = new BatteryMock(this.tempFolder); BATTERY_FIELD_VOLTAGE_SUFFIX = batteryMock.createEV3DevMocksEV3BrickPlatformPath(); String pathToAssert = JAVA_IO_TEMPDIR + JUNIT_PATH + "/"+ EV3DEV_PATH + "/" + MOCKS_PATH + "/" + BATTERY_PATH + "/" + BATTERY_EV3_SUBPATH + "/" + BATTERY_FIELD_VOLTAGE + BATTERY_FIELD_VOLTAGE_SUFFIX; LOGGER.trace(pathToAssert); assertThat(Sysfs.readFloat(pathToAssert), is(Float.parseFloat(BATTERY_FIELD_VOLTAGE_VALUE))); } /* @Test public void getElements() throws Exception { String pathToAssert = JAVA_IO_TEMPDIR + JUNIT_PATH + "/"+ EV3DEV_PATH + "/" + MOCKS_PATH + "/" + BATTERY_PATH + "/" + BATTERY_EV3_SUBPATH; log.trace(pathToAssert); final List<File> fileList = new ArrayList<>(); fileList.add(batterySensor); assertThat(Sysfs.getElements(pathToAssert), is(fileList)); } */ @Test public void existFile() throws Exception { BatteryMock batteryMock = new BatteryMock(this.tempFolder); BATTERY_FIELD_VOLTAGE_SUFFIX = batteryMock.createEV3DevMocksEV3BrickPlatformPath(); LOGGER.debug(BATTERY_FIELD_VOLTAGE_SUFFIX); String pathToAssert = JAVA_IO_TEMPDIR + JUNIT_PATH + "/"+ EV3DEV_PATH + "/" + MOCKS_PATH + "/" + BATTERY_PATH + "/" + BATTERY_EV3_SUBPATH + "/" + BATTERY_FIELD_VOLTAGE + BATTERY_FIELD_VOLTAGE_SUFFIX; final Path path = Paths.get(pathToAssert); LOGGER.debug(path.toString()); assertThat(Sysfs.existFile(path), is(true)); } @Test public void notExistFile() throws Exception { BatteryMock batteryMock = new BatteryMock(this.tempFolder); BATTERY_FIELD_VOLTAGE_SUFFIX = batteryMock.createEV3DevMocksEV3BrickPlatformPath(); LOGGER.debug(BATTERY_FIELD_VOLTAGE_SUFFIX); String pathToAssert = JAVA_IO_TEMPDIR + JUNIT_PATH + "/"+ EV3DEV_PATH + "/" + "BAD_PATH"; final Path path = Paths.get(pathToAssert); LOGGER.debug(path.toString()); assertThat(Sysfs.existFile(path), is(false)); } @Test public void writeString() throws Exception { BatteryMock batteryMock = new BatteryMock(this.tempFolder); BATTERY_FIELD_VOLTAGE_SUFFIX = batteryMock.createEV3DevMocksEV3BrickPlatformPath(); String pathToAssert = JAVA_IO_TEMPDIR + JUNIT_PATH + "/"+ EV3DEV_PATH + "/" + MOCKS_PATH + "/" + BATTERY_PATH + "/" + BATTERY_EV3_SUBPATH + "/" + BATTERY_FIELD_VOLTAGE + BATTERY_FIELD_VOLTAGE_SUFFIX; Sysfs.writeString(pathToAssert, "10"); assertThat(Sysfs.readString(pathToAssert), is("10")); } @Test public void writeInteger() throws Exception { BatteryMock batteryMock = new BatteryMock(this.tempFolder); BATTERY_FIELD_VOLTAGE_SUFFIX = batteryMock.createEV3DevMocksEV3BrickPlatformPath(); String pathToAssert = JAVA_IO_TEMPDIR + JUNIT_PATH + "/"+ EV3DEV_PATH + "/" + MOCKS_PATH + "/" + BATTERY_PATH + "/" + BATTERY_EV3_SUBPATH + "/" + BATTERY_FIELD_VOLTAGE + BATTERY_FIELD_VOLTAGE_SUFFIX; Sysfs.writeInteger(pathToAssert, 10); assertThat(Sysfs.readInteger(pathToAssert), is(10)); } @Test(expected = RuntimeException.class) public void writeBytesTest() { int BUFFER_SIZE = 0; byte[] buf = new byte[BUFFER_SIZE]; final String FB_PATH = "/dev/MY_PERSONAL_PATH"; Sysfs.writeBytes(FB_PATH, buf); } }
package org.basex.query.func; import org.basex.query.*; import org.basex.query.expr.*; import org.basex.query.iter.*; import org.basex.query.value.*; import org.basex.query.value.item.*; import org.basex.query.value.seq.*; import org.basex.util.*; public abstract class FuncCall extends Arr { /** Tail-call flag. */ boolean tailCall; /** * Constructor. * @param ii input info * @param e sub-expressions */ FuncCall(final InputInfo ii, final Expr[] e) { super(ii, e); } /** * Evaluates and returns the function to be called. * @param ctx query context * @return the function * @throws QueryException query exception */ abstract XQFunction evalFunc(final QueryContext ctx) throws QueryException; /** * Evaluates and returns the arguments for this call. * @param ctx query context * @return the function * @throws QueryException query exception */ abstract Value[] evalArgs(final QueryContext ctx) throws QueryException; @Override public final void markTailCalls(final QueryContext ctx) { if (ctx != null) ctx.compInfo(QueryText.OPTTCE, this); tailCall = true; } @Override public final Item item(final QueryContext ctx, final InputInfo ii) throws QueryException { return tailCall ? (Item) invokeTail(evalFunc(ctx), evalArgs(ctx), true, ctx, info) : (Item) invoke(evalFunc(ctx), evalArgs(ctx), true, ctx, info); } @Override public final Value value(final QueryContext ctx) throws QueryException { return tailCall ? invokeTail(evalFunc(ctx), evalArgs(ctx), false, ctx, info) : invoke(evalFunc(ctx), evalArgs(ctx), false, ctx, info); } @Override public final Iter iter(final QueryContext ctx) throws QueryException { return value(ctx).iter(); } /** * Calls the given function with the given arguments and takes care of tail-calls. * @param fun function to call * @param arg arguments for the call * @param ctx query context * @param itm flag for requesting a single item * @param ii input info * @return result of the function call * @throws QueryException query exception */ private static Value invoke(final XQFunction fun, final Value[] arg, final boolean itm, final QueryContext ctx, final InputInfo ii) throws QueryException { XQFunction func = fun; Value[] args = arg; final int fp = ctx.stack.enterFrame(func.stackFrameSize()); try { while(true) { final Value ret = itm ? func.invItem(ctx, ii, args) : func.invValue(ctx, ii, args); func = ctx.pollTailCall(); if(func == null) return ret; ctx.stack.reuseFrame(func.stackFrameSize()); args = ctx.pollTailArgs(); } } catch(final QueryException ex) { ex.add(ii); throw ex; } finally { ctx.stack.exitFrame(fp); } } /** * Tail-calls the given function with the given arguments. * @param fun function to call * @param arg arguments for the call * @param ctx query context * @param itm flag for requesting a single item * @param ii input info * @return result of the function call * @throws QueryException query exception */ private static Value invokeTail(final XQFunction fun, final Value[] arg, final boolean itm, final QueryContext ctx, final InputInfo ii) throws QueryException { final int calls = ctx.tailCalls, max = ctx.maxCalls; if(max >= 0 && calls >= max) { // there are at least `ctx.maxCalls` tail-calls on the stack, eliminate them ctx.registerTailCall(fun, arg); return itm ? null : Empty.SEQ; } ctx.tailCalls++; final int fp = ctx.stack.enterFrame(fun.stackFrameSize()); try { return itm ? fun.invItem(ctx, ii, arg) : fun.invValue(ctx, ii, arg); } catch(final QueryException ex) { ex.add(ii); throw ex; } finally { ctx.tailCalls = calls; ctx.stack.exitFrame(fp); } } /** * Calls the given function with the given arguments, returning zero or one item. * This method takes care of tail calls. * @param fun function to call * @param arg arguments to the function * @param ctx query context * @param ii input info * @return the resulting item * @throws QueryException query exception */ public static Item item(final XQFunction fun, final Value[] arg, final QueryContext ctx, final InputInfo ii) throws QueryException { return (Item) invoke(fun, arg, true, ctx, ii); } /** * Calls the given function with the given arguments, returning zero or more items. * This method takes care of tail calls. * @param fun function to call * @param arg arguments to the function * @param ctx query context * @param ii input info * @return the resulting value * @throws QueryException query exception */ public static Value value(final XQFunction fun, final Value[] arg, final QueryContext ctx, final InputInfo ii) throws QueryException { return invoke(fun, arg, false, ctx, ii); } }
package integration; import com.codeborne.selenide.ex.FrameNotFoundException; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import static com.codeborne.selenide.Condition.name; import static com.codeborne.selenide.Condition.text; import static com.codeborne.selenide.WebDriverConditions.currentFrameUrl; import static com.codeborne.selenide.WebDriverConditions.urlContaining; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.junit.jupiter.api.Assumptions.assumeFalse; final class FramesTest extends ITest { @BeforeEach void openPage() { openFile("page_with_frames.html"); } @Test void canSwitchIntoInnerFrame() { assertThat(driver().title()).isEqualTo("Test::frames"); switchTo().innerFrame("parentFrame"); $("frame").shouldHave(name("childFrame_1")); driver().webdriver().shouldHave(currentFrameUrl(getBaseUrl() + "/page_with_parent_frame.html")); switchTo().innerFrame("parentFrame", "childFrame_1"); assertThat(driver().source()).contains("Hello, WinRar!"); driver().webdriver().shouldHave(currentFrameUrl(getBaseUrl() + "/hello_world.txt")); driver().webdriver().shouldHave(urlContaining("/page_with_frames.html")); switchTo().innerFrame("parentFrame", "childFrame_2"); $("frame").shouldHave(name("childFrame_2_1")); driver().webdriver().shouldHave(currentFrameUrl(getBaseUrl() + "/page_with_child_frame.html")); driver().webdriver().shouldHave(urlContaining("/page_with_frames.html")); switchTo().innerFrame("parentFrame", "childFrame_2", "childFrame_2_1"); assertThat(driver().source()).contains("This is last frame!"); driver().webdriver().shouldHave(currentFrameUrl(getBaseUrl() + "/child_frame.txt")); driver().webdriver().shouldHave(urlContaining("/page_with_frames.html")); switchTo().innerFrame("parentFrame"); $("frame").shouldHave(name("childFrame_1")); driver().webdriver().shouldHave(urlContaining("/page_with_frames.html")); assertThat(driver().getCurrentFrameUrl()).isEqualTo(getBaseUrl() + "/page_with_parent_frame.html"); } @Test void switchToInnerFrame_withoutParameters_switchesToDefaultContent() { switchTo().innerFrame("parentFrame"); $("frame").shouldHave(name("childFrame_1")); switchTo().innerFrame(); $("frame").shouldHave(name("topFrame")); } @Test void canSwitchBetweenFramesByTitle() { assertThat(driver().title()).isEqualTo("Test::frames"); switchTo().frame("topFrame"); assertThat(driver().source()).contains("Hello, WinRar!"); switchTo().defaultContent(); switchTo().frame("leftFrame"); $("h1").shouldHave(text("Page with dynamic select")); switchTo().defaultContent(); switchTo().frame("mainFrame"); $("h1").shouldHave(text("Page with JQuery")); } @Test void canSwitchBetweenFramesByIndex() { assumeFalse(browser().isChrome()); assertThat(driver().title()).isEqualTo("Test::frames"); switchTo().frame(0); assertThat(driver().source()).contains("Hello, WinRar!"); switchTo().defaultContent(); switchTo().frame(1); $("h1").shouldHave(text("Page with dynamic select")); switchTo().defaultContent(); switchTo().frame(2); $("h1").shouldHave(text("Page with JQuery")); } @Test void throwsNoSuchFrameExceptionWhenSwitchingToAbsentFrameByElement() { assertThat(driver().title()).isEqualTo("Test::frames"); assertThatThrownBy(() -> { switchTo().frame("mainFrame"); // $("#log") is present, but not frame. switchTo().frame($("#log")); }) .isInstanceOf(FrameNotFoundException.class) .hasMessageStartingWith("No frame found with element: <div id=\"log\" displayed:false></div>"); } @Test void throwsNoSuchFrameExceptionWhenSwitchingToAbsentFrameByTitle() { assertThat(driver().title()).isEqualTo("Test::frames"); assertThatThrownBy(() -> switchTo().frame("absentFrame")) .isInstanceOf(FrameNotFoundException.class) .hasMessageStartingWith("No frame found with id/name: absentFrame"); } @Test void throwsNoSuchFrameExceptionWhenSwitchingToAbsentFrameByIndex() { assertThat(driver().title()).isEqualTo("Test::frames"); assertThatThrownBy(() -> switchTo().frame(Integer.MAX_VALUE)) .isInstanceOf(FrameNotFoundException.class) .hasMessageStartingWith("No frame found with index: " + Integer.MAX_VALUE); } @Test void attachesScreenshotWhenCannotFrameNotFound() { assertThatThrownBy(() -> switchTo().frame(33)) .isInstanceOf(FrameNotFoundException.class) .hasMessageStartingWith("No frame found with index: 33") .hasMessageContaining("Screenshot: file:") .hasMessageContaining("Page source: file:") .hasMessageContaining("Caused by: TimeoutException:"); } }
package mho.qbar; import mho.haskellesque.iterables.ExhaustiveProvider; import mho.haskellesque.iterables.IterableProvider; import mho.haskellesque.iterables.RandomProvider; import mho.haskellesque.structures.Pair; import mho.haskellesque.structures.Triple; import java.math.BigInteger; import java.math.RoundingMode; import java.util.Random; import static mho.haskellesque.iterables.IterableUtils.*; public class RationalDemos { private static final boolean USE_RANDOM = true; private static final String NECESSARY_CHARS = "-/0123456789"; private static final int LIMIT = 10000; private static IterableProvider P; private static Iterable<Rational> RATIONALS; private static void initialize() { P = USE_RANDOM ? new RandomProvider(new Random(7706916639046193098L)) : new ExhaustiveProvider(); Iterable<Rational> RATIONALS = USE_RANDOM ? Rational.RATIONALS : Rational.RATIONALS; //todo } public static void ofBigIntegerBigIntegerDemo() { initialize(); Iterable<Pair<BigInteger, BigInteger>> it = filter( p -> !p.b.equals(BigInteger.ZERO), P.pairs(P.bigIntegers()) ); for (Pair<BigInteger, BigInteger> p : take(LIMIT, it)) { System.out.println("of(" + p.a + ", " + p.b + ") = " + Rational.of(p.a, p.b)); } } public static void ofIntIntDemo() { initialize(); Iterable<Pair<Integer, Integer>> it = filter(p -> p.b != 0, P.pairs(P.integers())); for (Pair<Integer, Integer> p : take(LIMIT, it)) { System.out.println("of(" + p.a + ", " + p.b + ") = " + Rational.of(p.a, p.b)); } } public static void ofBigIntegerDemo() { initialize(); for (BigInteger bi : take(LIMIT, P.bigIntegers())) { System.out.println("of(" + bi + ") = " + Rational.of(bi)); } } public static void ofIntDemo() { initialize(); for (int bi : take(LIMIT, P.integers())) { System.out.println("of(" + bi + ") = " + Rational.of(bi)); } } public static void ofFloatDemo() { initialize(); for (float f : take(LIMIT, P.floats())) { System.out.println("of(" + f + ") = " + Rational.of(f)); } } public static void ofDoubleDemo() { initialize(); for (double d : take(LIMIT, P.doubles())) { System.out.println("of(" + d + ") = " + Rational.of(d)); } } // public static void ofBigDecimalDemo() { // for (BigDecimal bd : Generators.bigDecimals().iterate(limit)) { // System.out.println("of(" + bd + ") = " + Rational.of(bd)); public static void negateDemo() { for (Rational r : take(LIMIT, RATIONALS)) { System.out.println("-(" + r + ") = " + r.negate()); } } public static void invertDemo() { for (Rational r : take(LIMIT, filter(s -> s != Rational.ZERO, RATIONALS))) { System.out.println("1/(" + r + ") = " + r.invert()); } } public static void absDemo() { for (Rational r : take(LIMIT, RATIONALS)) { System.out.println("|" + r + "| = " + r.abs()); } } public static void signumDemo() { for (Rational r : take(LIMIT, RATIONALS)) { System.out.println("sgn(" + r + ") = " + r.signum()); } } public static void addDemo() { for (Pair<Rational, Rational> p : take(LIMIT, P.pairs(RATIONALS))) { System.out.println(p.a + " + " + p.b + " = " + Rational.add(p.a, p.b)); } } public static void subtractDemo() { for (Pair<Rational, Rational> p : take(LIMIT, P.pairs(RATIONALS))) { System.out.println(p.a + " - " + p.b + " = " + Rational.subtract(p.a, p.b)); } } public static void multiplyRationalRationalDemo() { for (Pair<Rational, Rational> p : take(LIMIT, P.pairs(RATIONALS))) { System.out.println(p.a + " * " + p.b + " = " + Rational.multiply(p.a, p.b)); } } public static void multiplyBigIntegerDemo() { for (Pair<Rational, BigInteger> p : take(LIMIT, P.pairs(RATIONALS, P.bigIntegers()))) { assert p.a != null; assert p.b != null; System.out.println(p.a + " * " + p.b + " = " + p.a.multiply(p.b)); } } public static void multiplyIntDemo() { for (Pair<Rational, Integer> p : take(LIMIT, P.pairs(RATIONALS, P.integers()))) { assert p.a != null; assert p.b != null; System.out.println(p.a + " * " + p.b + " = " + p.a.multiply(p.b)); } } public static void divideRationalRationalDemo() { Iterable<Pair<Rational, Rational>> it = filter(p -> p.b != Rational.ZERO, P.pairs(RATIONALS)); for (Pair<Rational, Rational> p : take(LIMIT, it)) { System.out.println(p.a + " / " + p.b + " = " + Rational.divide(p.a, p.b)); } } public static void divideBigIntegerDemo() { Iterable<Pair<Rational, BigInteger>> it = P.pairs( RATIONALS, filter(bi -> !bi.equals(BigInteger.ZERO), P.bigIntegers()) ); for (Pair<Rational, BigInteger> p : take(LIMIT, it)) { assert p.a != null; assert p.b != null; System.out.println(p.a + " / " + p.b + " = " + p.a.divide(p.b)); } } public static void divideIntDemo() { for (Pair<Rational, Integer> p : take(LIMIT, P.pairs(RATIONALS, filter(i -> i != 0, P.integers())))) { assert p.a != null; assert p.b != null; System.out.println(p.a + " / " + p.b + " = " + p.a.divide(p.b)); } } public static void powDemo() { Iterable<Pair<Rational, Integer>> it = filter( p -> p.b >= 0 || p.a != Rational.ZERO, P.pairs(RATIONALS, P.integers()) ); for (Pair<Rational, Integer> p : take(LIMIT, it)) { assert p.a != null; assert p.b != null; System.out.println(p.a + " ^ " + p.b + " = " + p.a.pow(p.b)); } } public static void floorDemo() { for (Rational r : take(LIMIT, RATIONALS)) { System.out.println("floor(" + r + ") = " + r.floor()); } } public static void ceilingDemo() { for (Rational r : take(LIMIT, RATIONALS)) { System.out.println("ceil(" + r + ") = " + r.ceiling()); } } public static void fractionalPartDemo() { for (Rational r : take(LIMIT, RATIONALS)) { System.out.println("fractionalPart(" + r + ") = " + r.fractionalPart()); } } public static void roundDemo() { Iterable<Pair<Rational, RoundingMode>> it = filter( p -> p.b != RoundingMode.UNNECESSARY || p.a.getDenominator().equals(BigInteger.ONE), P.pairs(RATIONALS, P.roundingModes()) ); for (Pair<Rational, RoundingMode> p : take(LIMIT, it)) { System.out.println("round(" + p.a + ", " + p.b + ") = " + p.a.round(p.b)); } } public static void roundToDenominatorDemo() { Iterable<Triple<Rational, BigInteger, RoundingMode>> it = filter( p -> p.c != RoundingMode.UNNECESSARY || p.b.mod(p.a.getDenominator()).equals(BigInteger.ZERO), P.triples(RATIONALS, P.positiveBigIntegers(), P.roundingModes()) ); for (Triple<Rational, BigInteger, RoundingMode> t : take(LIMIT, it)) { System.out.println("round(" + t.a + ", " + t.b + ", " + t.c + ") = " + t.a.roundToDenominator(t.b, t.c)); } } public static void shiftLeftDemo() { for (Pair<Rational, Integer> p : take(LIMIT, P.pairs(RATIONALS, P.integers()))) { System.out.println(p.a + " << " + p.b + " = " + p.a.shiftLeft(p.b)); } } public static void shiftRightDemo() { for (Pair<Rational, Integer> p : take(LIMIT, P.pairs(RATIONALS, P.integers()))) { System.out.println(p.a + " >> " + p.b + " = " + p.a.shiftRight(p.b)); } } public static void binaryExponentDemo() { for (Rational r : take(LIMIT, Rational.POSITIVE_RATIONALS)) { System.out.println("binaryExponent(" + r + ") = " + r.binaryExponent()); } } public static void toFloatDemo() { for (Rational r : take(LIMIT, RATIONALS)) { System.out.println("toFloat(" + r + ") = " + r.toFloat()); } } public static void toFloatRoundingModeDemo() { Iterable<Pair<Rational, RoundingMode>> it = filter( p -> p.b != RoundingMode.UNNECESSARY || Rational.of(p.a.toFloat(RoundingMode.FLOOR)).equals(p.a), P.pairs(RATIONALS, P.roundingModes()) ); for (Pair<Rational, RoundingMode> p : take(LIMIT, it)) { System.out.println("toFloat(" + p.a + ", " + p.b + ") = " + p.a.toFloat(p.b)); } } public static void toDoubleDemo() { for (Rational r : take(LIMIT, RATIONALS)) { System.out.println("toDouble(" + r + ") = " + r.toDouble()); } } public static void toDoubleRoundingModeDemo() { Iterable<Pair<Rational, RoundingMode>> it = filter( p -> p.b != RoundingMode.UNNECESSARY || Rational.of(p.a.toFloat(RoundingMode.FLOOR)).equals(p.a), P.pairs(RATIONALS, P.roundingModes())); for (Pair<Rational, RoundingMode> p : take(LIMIT, it)) { System.out.println("toDouble(" + p.a + ", " + p.b + ") = " + p.a.toDouble(p.b)); } } public static void hasTerminatingDecimalExpansionDemo() { for (Rational r : take(LIMIT, RATIONALS)) { System.out.println("hasTerminatingDecimalExpansion(" + r + ") = " + r.hasTerminatingDecimalExpansion()); } } public static void toBigDecimalDemo() { Iterable<Rational> it = filter(Rational::hasTerminatingDecimalExpansion, RATIONALS); for (Rational r : take(LIMIT, it)) { System.out.println("toBigDecimal(" + r + ") = " + r.toBigDecimal()); } } // public static void toBigDecimalPrecisionDemo() { // Iterable<Pair<Rational, Integer>> g = filter( // new SubExponentialPairGenerator<>( // RATIONALS, // Generators.naturalIntegers() // p -> p.b != 0 || p.a.hasTerminatingDecimalExpansion()); // for (Pair<Rational, Integer> p : g.iterate(limit)) { // System.out.println("toBigDecimal(" + p.a + ", " + p.b + ") = " + p.a.toBigDecimal(p.b)); // public static void toBigDecimalPrecisionRoundingMode() { // Generator<Pair<Rational, Integer>> pg = new FilteredGenerator<Pair<Rational, Integer>>( // new SubExponentialPairGenerator<>( // RATIONALS, // Generators.naturalIntegers() // p -> p.b != 0 || p.a.hasTerminatingDecimalExpansion()); // Generator<Pair<Pair<Rational, Integer>, RoundingMode>> g = new FilteredGenerator<Pair<Pair<Rational,Integer>, RoundingMode>>( // pairs(pg, Generators.roundingModes()), // p -> p.b != RoundingMode.UNNECESSARY || // (p.a.a.hasTerminatingDecimalExpansion() && // p.a.b >= p.a.a.numberOfDecimalDigits())); // for (Pair<Pair<Rational, Integer>, RoundingMode> p : g.iterate(limit)) { // System.out.println("toBigDecimal(" + p.a.a + ", " + p.a.b + ", " + p.b + ") = " + // p.a.a.toBigDecimal(p.a.b, p.b)); public static void equalsRationalDemo() { for (Pair<Rational, Rational> p : take(LIMIT, P.pairs(RATIONALS))) { System.out.println("equals(" + p.a + ", " + p.b + ") = " + p.a.equals(p.b)); } } public static void equalsNullDemo() { for (Rational r : take(LIMIT, RATIONALS)) { //noinspection ObjectEqualsNull System.out.println("equals(" + r + ", null) = " + r.equals(null)); } } public static void hashCodeDemo() { for (Rational r : take(LIMIT, RATIONALS)) { System.out.println("hashCode(" + r + ") = " + r.hashCode()); } } public static void compareToDemo() { for (Pair<Rational, Rational> p : take(LIMIT, P.pairs(RATIONALS))) { System.out.println("compareTo(" + p.a + ", " + p.b + ") = " + p.a.compareTo(p.b)); } } public static void continuedFractionDemo() { for (Rational r : take(LIMIT, RATIONALS)) { System.out.println("continuedFraction(" + r + ") = " + r.continuedFraction()); } } // public static void fromContinuedFractionDemo() { // Iterable<List<BigInteger>> it = pairs( // P.bigIntegers(), // new ListGenerator<BigInteger>(POSITIVE_BIG_INTEGERS) // ).map( // List<BigInteger> bis = new ArrayList<>(); // bis.add(p.a); // bis.addAll(p.b); // return bis; // bis -> { // List<BigInteger> tail = new ArrayList<>(); // for (int i = 1; i < bis.size(); i++) { // tail.add(bis.get(i)); // return Pair.of(bis.get(0), tail); // bis -> { // if (bis.isEmpty()) return false; // for (int i = 1; i < bis.size(); i++) { // if (bis.get(i).signum() != 1) return false; // return true; // for (List<BigInteger> bis : bisg.iterate(limit)) { // String bisString = bis.toString(); // bisString = bisString.substring(1, bisString.length() - 1); // System.out.println("fromContinuedFraction(" + bisString + ") = " + Rational.fromContinuedFraction(bis)); public static void convergentsDemo() { for (Rational r : take(LIMIT, RATIONALS)) { System.out.println("convergents(" + r + ") = " + r.convergents()); } } // public static void positionalNotationDemo() { // Generator<BigInteger> big = new FilteredGenerator<>( // POSITIVE_BIG_INTEGERS, // bi -> bi.compareTo(BigInteger.ONE) > 0 // Generator<Pair<Rational, BigInteger>> g = new SubExponentialPairGenerator<>(Rational.nonnegativeRationals(), big); // for (Pair<Rational, BigInteger> p : g.iterate(limit)) { // System.out.println("positionalNotation(" + p.a + ", " + p.b + " = " + p.a.positionalNotation(p.b)); // public static void fromPositionalNotationDemo() { // Generator<BigInteger> big = new FilteredGenerator<>( // POSITIVE_BIG_INTEGERS, // bi -> bi.compareTo(BigInteger.ONE) > 0 // Generator<Triple<List<BigInteger>, List<BigInteger>, List<BigInteger>>> tg = new SameTripleGenerator<>(new ListGenerator<>(Generators.naturalBigIntegers())); // Generator<Pair<Triple<List<BigInteger>, List<BigInteger>, List<BigInteger>>, BigInteger>> g = new FilteredGenerator<>( // new SubExponentialPairGenerator<Triple<List<BigInteger>, List<BigInteger>, List<BigInteger>>, BigInteger>(tg, big), // if (p.a.c.isEmpty()) return false; // for (BigInteger digit : p.a.a) { // if (digit.compareTo(p.b) >= 0) return false; // for (BigInteger digit : p.a.b) { // if (digit.compareTo(p.b) >= 0) return false; // for (BigInteger digit : p.a.c) { // if (digit.compareTo(p.b) >= 0) return false; // return true; // for (Pair<Triple<List<BigInteger>, List<BigInteger>, List<BigInteger>>, BigInteger> t : g.iterate(limit)) { // System.out.println("fromPositionalNotation(" + t.b + ", " + t.a.a + ", " + t.a.b + ", " + t.a.c + ") = " + Rational.fromPositionalNotation(t.b, t.a.a, t.a.b, t.a.c)); // public static void digitsDemo() { // Generator<BigInteger> big = new FilteredGenerator<>( // POSITIVE_BIG_INTEGERS, // bi -> bi.compareTo(BigInteger.ONE) > 0 // Generator<Pair<Rational, BigInteger>> g = new SubExponentialPairGenerator<>(Rational.nonnegativeRationals(), big); // for (Pair<Rational, BigInteger> p : g.iterate(limit)) { // Pair<List<BigInteger>, Iterable<BigInteger>> digits = p.a.digits(p.b); // String beforeDecimalString = digits.a.toString(); // List<String> afterDecimalStrings = new ArrayList<>(); // int i = 0; // for (BigInteger digit : digits.b) { // if (i >= 20) { // afterDecimalStrings.add("..."); // break; // afterDecimalStrings.add(digit.toString()); // String resultString = "(" + beforeDecimalString + ", " + afterDecimalStrings + ")"; // System.out.println("digits(" + p.a + ", " + p.b + ") = " + resultString); // public static void readDemo() { // readDemo(limit, false, false); // public static void readDemo(, boolean necessaryChars, boolean skipNullResults) { // Generator<String> g = new FilteredGenerator<>( // (necessaryChars ? Generators.strings(NECESSARY_CHARS) : Generators.strings()), // s -> !s.endsWith("/0")); // for (String s : g.iterate(limit)) { // Rational r = Rational.read(s); // if (!skipNullResults || r != null) System.out.println("read(" + s + ") = " + r); }
package org.objectweb.proactive.ext.util; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.io.PrintStream; import java.util.ArrayList; import java.util.List; import javassist.ClassClassPath; import javassist.ClassPool; import org.objectweb.proactive.core.mop.JavassistByteCodeStubBuilder; import org.objectweb.proactive.core.mop.Utils; public class StubGenerator { public static void main(String[] args) { StubGenerator sg = new StubGenerator(args); sg.run(); } private File srcDir; private String pkg = ""; private File destDir; private String cl; private boolean verbose = false; public StubGenerator(String[] args) { ClassPool pool = ClassPool.getDefault(); pool.insertClassPath(new ClassClassPath(this.getClass())); int index = 0; while (index < args.length) { if (args[index].equals("-srcDir")) { srcDir = new File(args[index + 1]); index += 2; } else if (args[index].equals("-pkg")) { pkg = args[index + 1]; index += 2; } else if (args[index].equals("-destDir")) { destDir = new File(args[index + 1]); index += 2; } else if (args[index].equals("-class")) { cl = args[index + 1]; index += 2; } else if (args[index].equals("-verbose")) { verbose = true; index++; } else { usage(); System.exit(1); } } } public void usage() { System.out.println("Usage:"); System.out.println("\t-srcDir directory where to find source classes"); System.out.println("\t-destDir directory where to put generated stubs"); System.out.println("\t-pkg package name"); System.out.println("\t-class generate only a stub for this class"); System.out.println("\t-verbose enable verbose mode"); System.out.println(""); } public void logAndExit(String str) { System.err.println(str); System.exit(2); } public void run() { if (srcDir == null) { logAndExit("srcDir attribute is not set"); } if (!srcDir.exists()) { logAndExit("Invalid srcDir attribute: " + srcDir.toString() + " does not exist"); } if (!srcDir.isDirectory()) { logAndExit("Invalid srcDir attribute: " + srcDir.toString() + " is not a directory"); } if (pkg == null) { logAndExit("pkg attribute is not set"); } File pkgDir = new File(srcDir.toString() + File.separator + pkg.replace('.', File.separatorChar)); if (!pkgDir.exists()) { logAndExit("Invalid pkg attribute: " + pkgDir.toString() + " does not exist"); } if (destDir == null) { destDir = srcDir; } if (!destDir.isDirectory()) { logAndExit("Invalid dest attribute: " + destDir.toString() + " is not a directory"); } if (!destDir.isDirectory()) { logAndExit("Invalid src attribute: " + destDir.toString() + " is not a directory"); } List<File> files = new ArrayList<File>(); if (cl == null) { // Find all the classes in this package files.addAll(exploreDirectory(pkgDir)); } else { File file = new File(pkgDir + File.separator + cl + ".class"); if (!file.exists() || !file.isFile()) { logAndExit("Invalid pkg or class attribute: " + file.toString() + " does not exist"); } files.add(file); } PrintStream stderr = System.err; PrintStream mute = new PrintStream(new MuteOutputStream()); if (!verbose) { System.setErr(mute); } // ClassPool.releaseUnmodifiedClassFile = true; for (File file : files) { String str = file.toString().replaceFirst(srcDir.toString().replace("\\", "\\\\"), ""); try { if (!verbose) { System.setErr(mute); } StubGenerator.generateClass(str, destDir.toString() + File.separator); } catch (Throwable e) { System.out.println("Stub generation failed: " + str); } } if (!verbose) { System.setErr(stderr); } } private List<File> exploreDirectory(File dir) { List<File> files = new ArrayList<File>(); for (File file : dir.listFiles()) { if (file.isDirectory()) { files.addAll(exploreDirectory(file)); } if (!file.toString().endsWith(".class")) { continue; } files.add(file); } return files; } /** * @param arg * @param directoryName */ public static void generateClass(String arg, String directoryName) { String className = processClassName(arg); String fileName = null; String stubClassName = null; try { // Generates the bytecode for the class byte[] data; data = JavassistByteCodeStubBuilder.create(className, null); stubClassName = Utils.convertClassNameToStubClassName(className, null); char sep = File.separatorChar; fileName = directoryName + stubClassName.replace('.', sep) + ".class"; // And writes it to a file new File(fileName.substring(0, fileName.lastIndexOf(sep))).mkdirs(); // String fileName = directoryName + System.getProperty // ("file.separator") + File f = new File(fileName); FileOutputStream fos = new FileOutputStream(f); fos.write(data); fos.flush(); fos.close(); } catch (Exception e) { System.err.println("Cannot compute stub generation for class " + className); System.err.println("Reason is " + e); } } /** * Turn a file name into a class name if necessary. Remove the ending .class * and change all the '/' into '.' * * @param name */ protected static String processClassName(String name) { int i = name.indexOf(".class"); String tmp = name; if (i < 0) { return name; } tmp = name.substring(0, i); String tmp2 = tmp.replace(File.separatorChar, '.'); if (tmp2.indexOf('.') == 0) { return tmp2.substring(1); } return tmp2; } public class MuteOutputStream extends OutputStream { @Override public void write(int b) throws IOException { // Please shut up ! } } }
package org.op4j; import java.io.Serializable; import java.math.BigDecimal; import java.math.BigInteger; import java.math.RoundingMode; import java.text.DecimalFormat; import java.text.NumberFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Calendar; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Set; import junit.framework.TestCase; import org.apache.commons.lang.LocaleUtils; import org.apache.commons.lang.StringUtils; import org.javaruntype.type.Type; import org.javaruntype.type.Types; import org.junit.Before; import org.junit.Test; import org.op4j.exceptions.ExecutionException; import org.op4j.functions.Call; import org.op4j.functions.DecimalPoint; import org.op4j.functions.ExecCtx; import org.op4j.functions.Fn; import org.op4j.functions.FnArray; import org.op4j.functions.FnBigDecimal; import org.op4j.functions.FnBigInteger; import org.op4j.functions.FnBoolean; import org.op4j.functions.FnDouble; import org.op4j.functions.FnFloat; import org.op4j.functions.FnInteger; import org.op4j.functions.FnList; import org.op4j.functions.FnLong; import org.op4j.functions.FnNumber; import org.op4j.functions.FnSet; import org.op4j.functions.FnShort; import org.op4j.functions.FnString; import org.op4j.functions.Function; import org.op4j.functions.IFunction; import org.op4j.functions.FnString.AsciifyMode; import org.op4j.test.auto.TestOperation; public class AssortedTests extends TestCase { private AssortedTestsData testUtils; @Override @Before public void setUp() throws Exception { this.testUtils = new AssortedTestsData(); } @Test public void test1() { List<String> data = this.testUtils.getStringList(8); List<String> result = Op.onList(data) .forEach().exec(new IFunction<String, String>() { public String execute(String input, ExecCtx ctx) throws Exception { return ctx.getIndex() + " - " + input; } public Type<? extends String> getResultType( Type<? extends String> targetType) { return Types.STRING; } }).get(); assertEquals(data.size(), result.size()); for (int index = 0; index < data.size(); index++) { assertEquals(index + " - " + data.get(index), result.get(index)); } } @Test public void test2() { List<String> data1 = this.testUtils.getStringList(8); List<String> data2 = this.testUtils.getStringList(10); List<String> result = Op.onList(data1) .addAll(data2).removeAllNullOrFalse(new IFunction<String, Boolean>() { public Boolean execute(String input, ExecCtx ctx) throws Exception { return Boolean.valueOf(StringUtils.contains("a", input)); } public Type<? extends Boolean> getResultType( Type<? extends String> targetType) { return Types.BOOLEAN; } }).get(); List<String> aResult = new ArrayList<String>(); data1.addAll(data2); for (String string : data1) { if (string == null) { continue; } if (StringUtils.contains("a", string)) { aResult.add(string); } } assertEquals(aResult.size(), result.size()); for (int index = 0; index < aResult.size(); index++) { assertEquals(aResult.get(index), result.get(index)); } } @Test public void test8() { Map<Integer, String> data = this.testUtils.getMapOfIntegerString(5); Map<Integer, String> result = Op.onMap(data) .forEachEntry() .onValue() .replaceWith("abc") .get(); assertEquals(data.size(), result.size()); for (Map.Entry<Integer, String> entry : result.entrySet()) { assertEquals( "abc", entry.getValue()); } } @Test public void test14() { List<Integer> expectedListInt1 = Arrays.asList(new Integer[] { 234,12,231 }); List<Integer> expectedListInt2 = Arrays.asList(new Integer[] { 234,10 }); List<Integer> listInt1 = Op.onListFor(234,12,231).get(); List<Integer> listInt2 = Op.onListFor(234).addAll(10).get(); assertEquals(expectedListInt1, listInt1); assertEquals(expectedListInt2, listInt2); } @Test public void test16() { final Serializable[] expSerArray = new Serializable[] {"one", "two", "three", Integer.valueOf(3) }; final Serializable[] serArray = new String[] {"one", "two", "three" }; Serializable[] newArray = Op.onArrayOf(Types.SERIALIZABLE, serArray).add(Integer.valueOf(3)).get(); assertEquals(Serializable[].class, newArray.getClass()); assertEquals(Arrays.asList(expSerArray), Arrays.asList(newArray)); } @Test public void test17() { final Serializable[] expSerArray = new Serializable[] {"one", "two", "three", Integer.valueOf(3) }; final Serializable[] serArray = new String[] {"one", "two", "three" }; Serializable[] newArray = Op.onArrayOf(Types.SERIALIZABLE, serArray).ifNotNull(). execAsArray( new IFunction<Serializable[],Serializable[]>() { public Type<? extends Serializable[]> getResultType(Type<? extends Serializable[]> targetType) { return targetType; } public Serializable[] execute(final Serializable[] input, final ExecCtx ctx) throws Exception { final String[] result = new String[input.length]; for (int i = 0; i < input.length; i++) { result[i] = (String) input[i]; } return result; } }).endIf().add(Integer.valueOf(3)).get(); assertEquals(Serializable[].class, newArray.getClass()); assertEquals(Arrays.asList(expSerArray), Arrays.asList(newArray)); } @Test public void test18() { final Serializable[] expSerArray = new Serializable[] {"one", "two", "three", Integer.valueOf(3) }; final Serializable[] serArray = new String[] {"one", "two", "three" }; Serializable[] newArray = Op.onArrayOf(Types.SERIALIZABLE, serArray).replaceWith(serArray).add(Integer.valueOf(3)).get(); assertEquals(Serializable[].class, newArray.getClass()); assertEquals(Arrays.asList(expSerArray), Arrays.asList(newArray)); } @Test public void test19 () { final Serializable[] expSerArray = new Serializable[] {"one", "two", "three", Integer.valueOf(3) }; final Serializable[] serArray = new String[] {"one", "two", "three" }; Serializable[] newArray = Op.on(serArray).of(Types.SERIALIZABLE).add(Integer.valueOf(3)).get(); assertEquals(Serializable[].class, newArray.getClass()); assertEquals(Arrays.asList(expSerArray), Arrays.asList(newArray)); } @Test public void test20() { final List<String> stringList = this.testUtils.getStringList(10); try { Op.onList(stringList).forEach().exec(Call.methodForInteger("toUpperCase")).endFor().toArrayOf(Types.INTEGER).get(); } catch (ExecutionException e) { assertTrue(e.getCause().getMessage().startsWith("Result of calling method")); } } @Test public void test21() { final List<String> stringList = Arrays.asList(new String[] {"one", "two", "three"}); final List<String> stringUpperList = Arrays.asList(new String[] {"ONE", "TWO", "THREE"}); final List<String> result = Op.onList(stringList).map(FnString.toUpperCase()).get(); assertEquals(stringUpperList, result); } // @Test // @SuppressWarnings("unchecked") // public void test22() { // final List<List<String>> stringListOfList = Arrays.asList( // Arrays.asList(new String[] {"one", "two", "three", "four"}), // Arrays.asList(new String[] {"un", "dous", "tres", "catro"}) // final List<List<String>> stringUpperListOfList = Arrays.asList( // Arrays.asList(new String[] {"ONE", "TWO", "THREE", "FOUR"}), // Arrays.asList(new String[] {"UN", "DOUS", "TRES", "CATRO"}) // final List<List<String>> result = // Op.onListOfList(stringListOfList).mapMap(StringFuncs.toUpperCase()).get(); // assertEquals(stringUpperListOfList, result); @Test public void test24() { final List<String> stringList = Arrays.asList(new String[] {"one", "two", "three", null}); final List<String> stringUpperList = Arrays.asList(new String[] {"ONE", "TWO", "THREE", null}); final List<String> result = Op.onList(stringList).forEach().execIfNotNull(FnString.toUpperCase()).get(); assertEquals(stringUpperList, result); } @Test public void test25() { final List<String> stringList = Arrays.asList(new String[] {"one", "two", "three", null}); final List<String> stringUpperList = Arrays.asList(new String[] {"ONE", "TWO", "THREE", null}); final List<String> result = Op.onList(stringList).mapIfNotNull(FnString.toUpperCase()).get(); assertEquals(stringUpperList, result); } @Test public void test26() { final String[] stringArr = new String[] {"one", "two", "three", "three", null, null}; final String[] stringArrDist = new String[] {"one", "two", "three", null, "four"}; final String[] result = Op.onArrayOf(Types.STRING, stringArr). exec(FnArray.ofString().distinct()). exec(FnArray.ofString().add("four")). get(); assertEquals(String[].class, result.getClass()); assertEquals(Arrays.asList(stringArrDist), Arrays.asList(result)); } @SuppressWarnings("unchecked") @Test public void test27() { final List<Integer> integerList = Arrays.asList(new Integer[]{null, 23, 34, null, -34}); List<TestOperation> testOperations = new ArrayList<TestOperation>(); testOperations.add(new TestOperation("add", new Object[] {Integer.valueOf(2)})); testOperations.add(new TestOperation("forEach")); testOperations.add(new TestOperation("ifNotNull")); testOperations.add(new TestOperation("replaceWith", new Object[]{null})); testOperations.add(new TestOperation("endIf")); testOperations.add(new TestOperation("exec", new Object[]{FnNumber.toStr()})); testOperations.add(new TestOperation("get")); final List<Integer> listResult = (List<Integer>)org.op4j.test.auto.Test.testOnList(integerList, testOperations); assertEquals(Arrays.asList(new Integer[]{null, null, null, null, null, null}), listResult); // System.out.println("test27. Result testOnList: " + listResult); final Integer[] arrayResult = (Integer[])org.op4j.test.auto.Test.testOnArrayOf(Types.INTEGER, integerList.toArray(new Integer[]{}), testOperations); assertEquals(Arrays.asList(new Integer[]{null, null, null, null, null, null}), Arrays.asList(arrayResult)); // System.out.println("test27. Result testOnArray: " + ArrayUtils.toString(arrayResult)); } @Test public void test28() { final Integer[] integerArr = new Integer[]{null, 23, 34, null, -34}; final List<Integer> integerList = Arrays.asList(integerArr); final List<Integer> result = Op.on(integerArr).toList().get(); assertEquals(integerList, result); } @Test public void test30() throws Exception { final List<String> stringList = Arrays.asList(new String[] {"one", "two", "three", null}); final List<String> stringUpperList = Arrays.asList(new String[] {"ONE", "TWO", "THREE", null}); final Function<List<String>,List<String>> fn = Fn.onListOf(Types.STRING).map(FnString.toUpperCase()).get(); final List<String> result = fn.execute(stringList); assertEquals(stringUpperList, result); final List<String> result2 = Op.on(stringList).exec(fn).get(); assertEquals(stringUpperList, result2); } @Test public void test31() throws Exception { assertEquals(Integer.valueOf(4), Op.on(10).exec(FnInteger.divideBy(3,RoundingMode.CEILING)).get()); } @Test public void test34() { final List<Integer> integerList = Arrays.asList(new Integer[]{null, 23, 34, null, -34}); assertEquals(Arrays.asList(null, 27, 38, null, -30), Op.on(integerList).forEach().exec(FnInteger.add(4)).get()); } @Test public void test35() { final List<BigDecimal> list = Arrays.asList(new BigDecimal[]{null, BigDecimal.valueOf(23), BigDecimal.valueOf(34), null, BigDecimal.valueOf(-34)}); assertEquals(Arrays.asList(null, BigDecimal.valueOf(23).add(BigDecimal.valueOf(4)), BigDecimal.valueOf(34).add(BigDecimal.valueOf(4)), null, BigDecimal.valueOf(-34).add(BigDecimal.valueOf(4))), Op.on(list).forEach().exec(FnBigDecimal.add(BigDecimal.valueOf(4))).get()); } @Test public void test36() throws Exception { final List<Long> result = Arrays.asList(new Long[] { 53L, 430L }); List<Long> values = Arrays.asList(new Long[] { 6641L, 53L, 430L, 1245L }); { values = Op.on(values).removeAllTrue(FnLong.greaterThan(500)).get(); assertEquals(result, values); } } @Test public void test37() throws Exception { final Long[] values = new Long[] { 53L, 430L }; String[] keys = new String[] { "A", "A" }; { Map<String,Long[]> groupedMap = Op.on(keys).zipAndGroupValuesFrom(Types.LONG, values).get(); assertEquals(1, groupedMap.size()); assertEquals(Long[].class, groupedMap.get("A").getClass()); assertEquals(Arrays.asList(values), Arrays.asList(groupedMap.get("A"))); } } @Test public void test38() throws Exception { final String str = "Earth"; Boolean matches = Op.on(str).exec(FnString.matches("a")).get(); assertEquals(Boolean.FALSE, matches); matches = Op.on(str).exec(FnString.matches(".a.*h")).get(); assertEquals(Boolean.TRUE, matches); } @Test public void test39() throws Exception { final String str = "Earth"; Boolean matches = Op.on(str).exec(FnString.contains("a")).get(); assertEquals(Boolean.TRUE, matches); matches = Op.on(str).exec(FnString.contains("b")).get(); assertEquals(Boolean.FALSE, matches); matches = Op.on(str).exec(FnString.contains(".a.*h")).get(); assertEquals(Boolean.TRUE, matches); } @Test public void test40() throws Exception { final String str = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. " + "Fusce a lacus lectus, quis tristique nibh. Aenean sit amet dolor justo. " + "Morbi nibh urna, ornare non congue non, dignissim at nibh. Nulla euismod, " + "dui id consequat tempus, lacus velit sodales metus, non luctus ipsum " + "purus id neque. Ut eleifend vestibulum rutrum. Praesent quis dui urna, " + "quis cursus arcu. Aliquam interdum quam quis erat condimentum ullamcorper. " + "Nam eget massa eu tellus pulvinar blandit sed quis libero. Proin ut quam " + "nunc, id rutrum mi. Vestibulum ante ipsum primis in faucibus orci luctus " + "et ultrices posuere cubilia Curae;"; assertEquals(11, Op.on(str).exec(FnString.extractAll("qu..")).get().size()); assertEquals("quis", Op.on(str).exec(FnString.extractFirst("qu..")).get()); assertEquals("quam", Op.on(str).exec(FnString.extractLast("qu..")).get()); assertEquals("eleif", Op.on(str).exec(FnString.matchAndExtract("(.*?)(ele..)(.*?)", 2)).get()); assertEquals(Arrays.asList(new String[] {"eleif", "liq"}), Op.on(str).exec(FnString.matchAndExtractAll("(.*?)(ele..)(.*?)(li.)(.*?)", 2, 4)).get()); } @Test public void test41() throws Exception { String[] arr1 = new String[] { "one", "two", "three" }; String[] arr2 = new String[] { "one", "two", "three", "four" }; String[] arr3 = new String[] { "one", "two" }; String[] arr4 = new String[] { "one" }; String[] arr5 = new String[] { }; String[] arr1Res = new String[] { "three", "two", "one" }; String[] arr2Res = new String[] { "four", "three", "two", "one" }; String[] arr3Res = new String[] { "two", "one" }; String[] arr4Res = new String[] { "one" }; String[] arr5Res = new String[] { }; arr1 = Op.on(arr1).reverse().get(); arr2 = Op.on(arr2).reverse().get(); arr3 = Op.on(arr3).reverse().get(); arr4 = Op.on(arr4).reverse().get(); arr5 = Op.on(arr5).reverse().get(); assertEquals(Arrays.asList(arr1Res), Arrays.asList(arr1)); assertEquals(Arrays.asList(arr2Res), Arrays.asList(arr2)); assertEquals(Arrays.asList(arr3Res), Arrays.asList(arr3)); assertEquals(Arrays.asList(arr4Res), Arrays.asList(arr4)); assertEquals(Arrays.asList(arr5Res), Arrays.asList(arr5)); } @Test public void test42() throws Exception { List<String> list1 = Arrays.asList(new String[] { "one", "two", "three" }); List<String> list2 = Arrays.asList(new String[] { "one", "two", "three", "four" }); List<String> list3 = Arrays.asList(new String[] { "one", "two" }); List<String> list4 = Arrays.asList(new String[] { "one" }); List<String> list5 = Arrays.asList(new String[] { }); List<String> list1Res = Arrays.asList(new String[] { "three", "two", "one" }); List<String> list2Res = Arrays.asList(new String[] { "four", "three", "two", "one" }); List<String> list3Res = Arrays.asList(new String[] { "two", "one" }); List<String> list4Res = Arrays.asList(new String[] { "one" }); List<String> list5Res = Arrays.asList(new String[] { }); list1 = Op.on(list1).reverse().get(); list2 = Op.on(list2).reverse().get(); list3 = Op.on(list3).reverse().get(); list4 = Op.on(list4).reverse().get(); list5 = Op.on(list5).reverse().get(); assertEquals(list1Res, list1); assertEquals(list2Res, list2); assertEquals(list3Res, list3); assertEquals(list4Res, list4); assertEquals(list5Res, list5); } @Test public void test43() throws Exception { Set<String> set1 = new LinkedHashSet<String>(Arrays.asList(new String[] { "one", "two", "three" })); Set<String> set2 = new LinkedHashSet<String>(Arrays.asList(new String[] { "one", "two", "three", "four" })); Set<String> set3 = new LinkedHashSet<String>(Arrays.asList(new String[] { "one", "two" })); Set<String> set4 = new LinkedHashSet<String>(Arrays.asList(new String[] { "one" })); Set<String> set5 = new LinkedHashSet<String>(Arrays.asList(new String[] { })); Set<String> set1Res = new LinkedHashSet<String>(Arrays.asList(new String[] { "three", "two", "one" })); Set<String> set2Res = new LinkedHashSet<String>(Arrays.asList(new String[] { "four", "three", "two", "one" })); Set<String> set3Res = new LinkedHashSet<String>(Arrays.asList(new String[] { "two", "one" })); Set<String> set4Res = new LinkedHashSet<String>(Arrays.asList(new String[] { "one" })); Set<String> set5Res = new LinkedHashSet<String>(Arrays.asList(new String[] { })); set1 = Op.on(set1).reverse().get(); set2 = Op.on(set2).reverse().get(); set3 = Op.on(set3).reverse().get(); set4 = Op.on(set4).reverse().get(); set5 = Op.on(set5).reverse().get(); assertEquals(set1Res, set1); assertEquals(set2Res, set2); assertEquals(set3Res, set3); assertEquals(set4Res, set4); assertEquals(set5Res, set5); } @Test public void test44() throws Exception { Map<Integer, String> map0 = new LinkedHashMap<Integer, String>(); Map<Integer, String> map1 = new LinkedHashMap<Integer, String>(map0); map1.put(1, "one"); Map<Integer, String> map2 = new LinkedHashMap<Integer, String>(map1); map2.put(2, "two"); Map<Integer, String> map3 = new LinkedHashMap<Integer, String>(map2); map3.put(3, "three"); Map<Integer, String> map4 = new LinkedHashMap<Integer, String>(map3); map4.put(4, "four"); Map<Integer, String> map0Res = new LinkedHashMap<Integer, String>(); Map<Integer, String> map1Res = new LinkedHashMap<Integer, String>(); map1Res.put(1, "one"); Map<Integer, String> map2Res = new LinkedHashMap<Integer, String>(); map2Res.put(2, "two"); map2Res.put(1, "one"); Map<Integer, String> map3Res = new LinkedHashMap<Integer, String>(); map3Res.put(3, "three"); map3Res.put(2, "two"); map3Res.put(1, "one"); Map<Integer, String> map4Res = new LinkedHashMap<Integer, String>(); map4Res.put(4, "four"); map4Res.put(3, "three"); map4Res.put(2, "two"); map4Res.put(1, "one"); map0 = Op.on(map0).reverse().get(); map1 = Op.on(map1).reverse().get(); map2 = Op.on(map2).reverse().get(); map3 = Op.on(map3).reverse().get(); map4 = Op.on(map4).reverse().get(); assertEquals(map0Res, map0); assertEquals(map1Res, map1); assertEquals(map2Res, map2); assertEquals(map3Res, map3); assertEquals(map4Res, map4); } @Test public void test45() throws Exception { List<Boolean> result = Op.onListFor(BigDecimal.valueOf(34), Double.valueOf(34), BigDecimal.valueOf(34).setScale(4)) .forEach().exec(FnNumber.eqValue(BigDecimal.valueOf(34))).get(); assertTrue("BigDecimal.valueOf(34) equals to BigDecimal.valueOf(34)", result.get(0)); assertTrue("Double.valueOf(34) equals to BigDecimal.valueOf(34)", result.get(1)); assertTrue("BigDecimal.valueOf(34).setScale(4) equals to BigDecimal.valueOf(34)", result.get(2)); } @Test public void test46() throws Exception { List<Boolean> result = Op.onListFor(BigDecimal.valueOf(34), Double.valueOf(34), BigDecimal.valueOf(34).setScale(4)) .forEach().exec(FnNumber.notEqValue(BigDecimal.valueOf(34))).get(); assertFalse("BigDecimal.valueOf(34) notequals to BigDecimal.valueOf(34)", result.get(0)); assertFalse("Double.valueOf(34) notequals to BigDecimal.valueOf(34)", result.get(1)); assertFalse("BigDecimal.valueOf(34).setScale(4) notequals to BigDecimal.valueOf(34)", result.get(2)); } @Test public void test47() throws Exception { Boolean result = Op.on(Types.BIG_DECIMAL, null) .exec(FnNumber.notEq(null)).get(); assertFalse("null notequals to null", result); result = Op.on(Types.BIG_DECIMAL, null) .exec(FnNumber.eq(null)).get(); assertTrue("null equals to null", result); } @Test public void test48() throws Exception { Boolean result = Op.on(Types.BIG_DECIMAL, null) .exec(FnBigDecimal.notEq(null)).get(); assertFalse("null notequals to null", result); result = Op.on(Types.BIG_DECIMAL, null) .exec(FnBigDecimal.eq(null)).get(); assertTrue("null equals to null", result); } @Test public void test49() throws Exception { List<Boolean> result = Op.onListFor(BigDecimal.valueOf(34), BigDecimal.valueOf(34).setScale(10), BigDecimal.valueOf(34).setScale(4)) .forEach().exec(FnBigDecimal.eqValue(BigDecimal.valueOf(34))).get(); assertTrue("BigDecimal.valueOf(34) equals to BigDecimal.valueOf(34)", result.get(0)); assertTrue("BigDecimal.valueOf(34).setScale(10) equals to BigDecimal.valueOf(34)", result.get(1)); assertTrue("BigDecimal.valueOf(34).setScale(4) equals to BigDecimal.valueOf(34)", result.get(2)); } @Test public void test50() throws Exception { List<Boolean> result = Op.onListFor(BigDecimal.valueOf(34), BigDecimal.valueOf(34).setScale(10), BigDecimal.valueOf(34).setScale(4)) .forEach().exec(FnBigDecimal.notEqValue(BigDecimal.valueOf(34))).get(); assertFalse("BigDecimal.valueOf(34) notequals to BigDecimal.valueOf(34)", result.get(0)); assertFalse("BigDecimal.valueOf(34).setScale(10) notequals to BigDecimal.valueOf(34)", result.get(1)); assertFalse("BigDecimal.valueOf(34).setScale(4) notequals to BigDecimal.valueOf(34)", result.get(2)); } @Test public void test51() throws Exception { Boolean result = Op.on(Types.DOUBLE, null) .exec(FnDouble.notEq(null)).get(); assertFalse("null notequals to null", result); result = Op.on(Types.DOUBLE, null) .exec(FnDouble.eq(null)).get(); assertTrue("null equals to null", result); } @Test public void test52() throws Exception { List<Boolean> result = Op.onListFor(Double.valueOf(34), null) .forEach().exec(FnDouble.notEq(Double.valueOf(34))).get(); assertFalse("Double.valueOf(34) notequals to Double.valueOf(34)", result.get(0)); assertTrue("null notequals to Double.valueOf(34)", result.get(1)); Function<Double,Boolean> fn = FnBoolean.or(FnNumber.isNull(), FnDouble.isNull()); Op.on(13434d).exec(fn).get(); Op.on(13434d).exec(FnBoolean.or(FnNumber.isNull(), FnDouble.isNull())).get(); Function<Double,Boolean> fn1 = FnBoolean.or(FnDouble.isNull(), FnNumber.isNull()); Op.on(13434d).exec(fn1).get(); Op.on(13434d).exec(FnBoolean.or(FnDouble.isNull(), FnNumber.isNull())).get(); } @Test public void test53() throws Exception { assertTrue("Op.on(Double.valueOf(4)).exec(FnNumber.eqValue(4))", Op.on(Double.valueOf(4)) .exec(FnNumber.eqValue(4)).get()); assertTrue("Op.on(Double.valueOf(4)).exec(FnNumber.notEq(null))", Op.on(Double.valueOf(4)) .exec(FnNumber.notEq(null)).get()); assertTrue("Op.on(Double.valueOf(4)).exec(FnNumber.eqValue(BigDecimal.valueOf(4).setScale(6)))", Op.on(Double.valueOf(4)).exec(FnNumber.eqValue(BigDecimal.valueOf(4).setScale(6))).get()); assertFalse("Op.on(Double.valueOf(4)).exec(FnNumber.notEqValue(BigDecimal.valueOf(4).setScale(6)))", Op.on(Double.valueOf(4)).exec(FnNumber.notEqValue(BigDecimal.valueOf(4).setScale(6))).get()); assertFalse("Op.on(BigDecimal.valueOf(4)).exec(FnNumber.notEqValue(BigDecimal.valueOf(4).setScale(6)))", Op.on(BigDecimal.valueOf(4)).exec(FnNumber.notEqValue(BigDecimal.valueOf(4).setScale(6))).get()); assertFalse("Op.on(Integer.valueOf(4)).exec(FnNumber.notEqValue(BigDecimal.valueOf(4).setScale(6)))", Op.on(Integer.valueOf(4)).exec(FnNumber.notEqValue(BigDecimal.valueOf(4).setScale(6))).get()); assertTrue("Op.on(Integer.valueOf(4)).exec(FnNumber.eqValue(BigDecimal.valueOf(4).setScale(6)))", Op.on(Integer.valueOf(4)).exec(FnNumber.eqValue(BigDecimal.valueOf(4).setScale(6))).get()); assertTrue("Op.on(Integer.valueOf(4)).exec(FnNumber.notEqValue(BigDecimal.valueOf(4).setScale(6)))", Op.on(Double.valueOf(4.1)).exec(FnNumber.notEqValue(BigDecimal.valueOf(4).setScale(6))).get()); assertTrue("Op.on(Integer.valueOf(4)).exec(FnNumber.notEqValue(BigDecimal.valueOf(4.1).setScale(6)))", Op.on(Double.valueOf(4)).exec(FnNumber.notEqValue(BigDecimal.valueOf(4.1).setScale(6))).get()); assertTrue("Op.on(Short.valueOf((short)4)).exec(FnNumber.eqValue(BigDecimal.valueOf(4).setScale(6)))", Op.on(Short.valueOf((short)4)).exec(FnNumber.eqValue(BigDecimal.valueOf(4).setScale(6))).get()); assertFalse("Op.on(Long.valueOf(4)).exec(FnNumber.notEqValue(BigDecimal.valueOf(4).setScale(6)))", Op.on(Long.valueOf(4)).exec(FnNumber.notEqValue(BigDecimal.valueOf(4).setScale(6))).get()); assertTrue("Op.on(Double.valueOf(4)).exec(FnNumber.eq(4))", Op.on(Double.valueOf(4)) .exec(FnNumber.eq((double)4)).get()); assertFalse("Op.on(Double.valueOf(4)).exec(FnNumber.eq(Integer.valueOf(4)))", Op.on(Double.valueOf(4)) .exec(FnNumber.eq(Integer.valueOf(4))).get()); assertFalse("Op.on(Double.valueOf(4)).exec(FnNumber.eq(BigDecimal.valueOf(4).setScale(6)))", Op.on(Double.valueOf(4)) .exec(FnNumber.eq(BigDecimal.valueOf(4).setScale(6))).get()); assertTrue("Op.on(BigDecimal.valueOf(4)).exec(FnNumber.notEq(BigDecimal.valueOf(4).setScale(6)))", Op.on(BigDecimal.valueOf(4)).exec(FnNumber.notEq(BigDecimal.valueOf(4).setScale(6))).get()); } @Test public void test54() throws Exception { assertEquals( Op.on(new Object[] {4.5, "hello", BigDecimal.valueOf(45.78)}) .exec(FnString.joinArray(",")).get(), "4.5,hello,45.78"); assertEquals( Op.on(new Object[] {4.5, "hello", BigDecimal.valueOf(45.78)}) .exec(FnString.joinArray("*")).get(), "4.5*hello*45.78"); assertEquals(Op.on("Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday") .exec(FnString.split(",")).castToListOf(Types.STRING).forEach().exec(FnString.trim()).get(), Op.onListFor("Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday").get()); } @Test public void test55() throws Exception { Calendar cal1 = Calendar.getInstance(); assertEquals( Op.on(new Object[] {4.5, "hello", cal1}) .exec(FnString.joinArray(",")).get(), "4.5,hello," + cal1.toString()); assertEquals( Op.on(new Object[] {4.5, "hello", cal1}) .exec(FnString.joinArray()).get(), "4.5hello" + cal1.toString()); assertEquals( Op.on("hello*goodbye") .exec(FnString.splitAsArray("*")).castToArrayOf(Types.STRING).toList().get(), Op.onArrayFor("hello", "goodbye").toList().get()); assertNull( Op.on(Types.ARRAY_OF_STRING, null) .exec(FnString.joinArray(",")).get()); assertNull( Op.on(Types.STRING, null) .exec(FnString.split()).get()); } @Test public void test56() throws Exception { final String testStr1 = "\u00DF\u00DF \u00DF\u00DF a \u00DF\u00DF nu\u00DF NU\u00DF nu\u00DF\u00DF NU\u00DF\u00DF \u00DF\u00DF"; final String testStr2 = "\u00DF\u00DF"; final String testStr3 = "LO E \u00C7\u00C0 I\u00D1\u00C6 N\u00DC\u00DF \u00DEOR! a\u00F1e\u00E7\u00E1\u00ED\u00E9\u00F3\u00FA \u00E4\u00EB\u00EF\u00F6\u00FC\u00C4\u00CB\u00CF\u00D6\u00DC"; final String testStr4 = "LO E \u00C7\u00C0 I\u00D1\u00C6 N\u00DC\u00DF\u00DF"; final String testStr5 = "LO E \u00C7\u00C0 I\u00D1\u00C6 N\u00DC\u00DF\u00DF "; final String testStr6 = "LO E \u00C7\u00C0 I\u00D1\u00C6 N\u00DC\u00DF\u00DF \u00DF"; final String testStr7 = "LO E \u00C7\u00C0 I\u00D1\u00C6 Nu\u00DF\u00DF \u00DF"; final String testStr8 = "LO E \u00C7\u00C0 I\u00D1\u00C6 N\u00DC\u00DF\u00DF a"; final String testStr9 = "M\u00DCNCHEN"; final String testStr10 = "M\u00DCNCHEN \u00E4\u00EB\u00EF\u00F6\u00FC\u00C4\u00CB\u00CF\u00D6\u00DC"; assertEquals("SSSS SSSS a ssss nuss NUSS nussss NUSSSS SSSS", Op.on(testStr1).exec(FnString.asciify()).get()); assertEquals("SSSS", Op.on(testStr2).exec(FnString.asciify()).get()); assertEquals("LO E CA INAE NUSS THOR! anecaieou aeiouAEIOU", Op.on(testStr3).exec(FnString.asciify()).get()); assertEquals("LO E CA INAE NUSSSS", Op.on(testStr4).exec(FnString.asciify()).get()); assertEquals("LO E CA INAE NUSSSS ", Op.on(testStr5).exec(FnString.asciify()).get()); assertEquals("LO E CA INAE NUSSSS SS", Op.on(testStr6).exec(FnString.asciify()).get()); assertEquals("LO E CA INAE Nussss ss", Op.on(testStr7).exec(FnString.asciify()).get()); assertEquals("LO E CA INAE NUSSSS a", Op.on(testStr8).exec(FnString.asciify()).get()); assertEquals("MUENCHEN", Op.on(testStr9).exec(FnString.asciify(AsciifyMode.UMLAUT_E)).get()); assertEquals("MUENCHEN aeeioeueAEEIOEUE", Op.on(testStr10).exec(FnString.asciify(AsciifyMode.UMLAUT_E)).get()); } @Test public void test57() throws Exception { Short b = Short.valueOf((short)10); Short c = Short.valueOf((short)-3); assertEquals(Op.on(c).exec(FnShort.module(b.intValue())).get(), Short.valueOf(BigInteger.valueOf(c.longValue()) .mod(BigInteger.valueOf(b.longValue())).shortValue())); assertEquals(Op.on(c).exec(FnShort.remainder(b.intValue())).get(), Short.valueOf(BigInteger.valueOf(c.longValue()) .remainder(BigInteger.valueOf(b.longValue())).shortValue())); assertNotSame(Op.on(c).exec(FnShort.remainder(b.intValue())).get(), Short.valueOf(BigInteger.valueOf(c.longValue()) .mod(BigInteger.valueOf(b.longValue())).shortValue())); } @Test public void test58() throws Exception { Long b = Long.valueOf(56756710); Long c = Long.valueOf(-38799); assertEquals(Op.on(c).exec(FnLong.module(b.intValue())).get(), Long.valueOf(BigInteger.valueOf(c.longValue()) .mod(BigInteger.valueOf(b.longValue())).longValue())); assertEquals(Op.on(c).exec(FnLong.remainder(b.intValue())).get(), Long.valueOf(BigInteger.valueOf(c.longValue()) .remainder(BigInteger.valueOf(b.longValue())).longValue())); assertNotSame(Op.on(c).exec(FnLong.remainder(b.intValue())).get(), Long.valueOf(BigInteger.valueOf(c.longValue()) .mod(BigInteger.valueOf(b.longValue())).longValue())); assertEquals(Op.on(c).exec(FnLong.remainder(Double.valueOf(4.5))).get(), Long.valueOf(BigInteger.valueOf(c.longValue()) .remainder(BigInteger.valueOf(Double.valueOf(4.5).longValue())).longValue())); assertEquals(Op.on(c).exec(FnLong.remainder((short)56)).get(), Long.valueOf(BigInteger.valueOf(c.longValue()) .remainder(BigInteger.valueOf(56)).longValue())); } @Test public void test59() throws Exception { Integer b = Integer.valueOf(56756710); Integer c = Integer.valueOf(-38799); assertEquals(Op.on(c).exec(FnInteger.module(b.intValue())).get(), Integer.valueOf(BigInteger.valueOf(c.longValue()) .mod(BigInteger.valueOf(b.longValue())).intValue())); assertEquals(Op.on(c).exec(FnInteger.remainder(b.intValue())).get(), Integer.valueOf(BigInteger.valueOf(c.longValue()) .remainder(BigInteger.valueOf(b.longValue())).intValue())); assertNotSame(Op.on(c).exec(FnInteger.remainder(b.intValue())).get(), Integer.valueOf(BigInteger.valueOf(c.longValue()) .mod(BigInteger.valueOf(b.longValue())).intValue())); assertEquals(Op.on(c).exec(FnInteger.remainder(Long.valueOf(33))).get(), Integer.valueOf(BigInteger.valueOf(c.longValue()) .remainder(BigInteger.valueOf(33)).intValue())); } @Test public void test60() throws Exception { Float b = Float.valueOf(56756710.34f); Float c = Float.valueOf(-3856799.134f); assertEquals(Op.on(c).exec(FnFloat.remainder(b.floatValue())).get(), Float.valueOf(BigDecimal.valueOf(c.doubleValue()) .remainder(BigDecimal.valueOf(b.doubleValue())).floatValue())); assertEquals(Op.on(c).exec(FnFloat.remainder(b.floatValue())).get(), Float.valueOf(BigDecimal.valueOf(c.doubleValue()) .remainder(BigDecimal.valueOf(b.doubleValue())).floatValue())); assertEquals(Op.on(c).exec(FnFloat.remainder(b)).get(), Float.valueOf(BigDecimal.valueOf(c.doubleValue()) .remainder(BigDecimal.valueOf(b.doubleValue())).floatValue())); assertNotSame(Op.on(c).exec(FnFloat.remainder(b.doubleValue())).get(), Float.valueOf(BigDecimal.valueOf(c.doubleValue()) .remainder(BigDecimal.valueOf(b.doubleValue())).floatValue())); } @Test public void test61() throws Exception { Double b = Double.valueOf(56756.710); Double c = Double.valueOf(-3856.9799); assertEquals(Op.on(c).exec(FnDouble.remainder(b.doubleValue())).get(), Double.valueOf(BigDecimal.valueOf(c.doubleValue()) .remainder(BigDecimal.valueOf(b.doubleValue())).doubleValue())); } @Test public void test62() throws Exception { BigInteger b = BigInteger.valueOf(56756710); BigInteger c = BigInteger.valueOf(-3856799); assertEquals(Op.on(c).exec(FnBigInteger.module(b)).get(), BigInteger.valueOf(c.longValue()) .mod(BigInteger.valueOf(b.longValue()))); assertEquals(Op.on(c).exec(FnBigInteger.remainder(b.intValue())).get(), c.remainder(b)); assertNotSame(Op.on(c).exec(FnBigInteger.remainder(b.intValue())).get(), c.mod(b)); } @Test public void test63() throws Exception { assertFalse(Op.on("67e").exec(FnString.isBigDecimal()).get().booleanValue()); assertTrue(Op.on("67.5").exec(FnString.isBigDecimal(Locale.ENGLISH)).get().booleanValue()); assertTrue(Op.on("6997.89").exec(FnString.isBigDecimal(Locale.ENGLISH)).get().booleanValue()); assertTrue(Op.on("6,8989898989898989898989898989898989898989898").exec(FnString .isBigDecimal(LocaleUtils.toLocale("es"))).get().booleanValue()); assertFalse(Op.on("6,9.9.7.89fgfd").exec(FnString .isBigDecimal(LocaleUtils.toLocale("es"))).get().booleanValue()); assertTrue(Op.on("6.9.97,89").exec(FnString .isBigDecimal(LocaleUtils.toLocale("es"))).get().booleanValue()); assertFalse(Op.on("6,997.89").exec(FnString .isBigDecimal(LocaleUtils.toLocale("es"))).get().booleanValue()); assertTrue(Op.on("6.997,89").exec(FnString .isBigDecimal(LocaleUtils.toLocale("es"))).get().booleanValue()); assertTrue(Op.on("6.9.9.7,89").exec(FnString .isBigDecimal(LocaleUtils.toLocale("es"))).get().booleanValue()); assertTrue(Op.on("69,9").exec(FnString .isBigDecimal(DecimalPoint.IS_COMMA)).get().booleanValue()); assertTrue(Op.on("69.9").exec(FnString .isBigDecimal(DecimalPoint.IS_POINT)).get().booleanValue()); assertTrue(Op.on("69,9").exec(FnString .isBigDecimal(DecimalPoint.CAN_BE_POINT_OR_COMMA)).get().booleanValue()); assertTrue(Op.on("69.9").exec(FnString .isBigDecimal(DecimalPoint.CAN_BE_POINT_OR_COMMA)).get().booleanValue()); assertFalse(Op.on("69-9").exec(FnString .isBigDecimal(DecimalPoint.CAN_BE_POINT_OR_COMMA)).get().booleanValue()); } @Test public void test64() throws Exception { try { Op.on("19800805shouldnotwork").exec(FnString.toCalendar("yyyyMMdd")).get(); fail("Should not reach this point. 19800805shouldnotwork has been converted to Calendar"); } catch (ExecutionException e) { // Do nothing } Calendar result = Op.on("19800805").exec(FnString.toCalendar("yyyyMMdd")).get(); Calendar correct = Calendar.getInstance(); correct.clear(); correct.set(Calendar.YEAR, 1980); correct.set(Calendar.MONTH, 7); correct.set(Calendar.DAY_OF_MONTH, 5); assertEquals(result, correct); } @Test public void test65() throws Exception { DecimalFormat nf = (DecimalFormat) NumberFormat.getInstance(Locale.US); nf.setParseBigDecimal(true); assertFalse(Op.on("67e").exec(FnString.isBigInteger()).get().booleanValue()); try { Op.on("67e").exec(FnString.toBigInteger()).get(); fail("Value was not expected to be converted into a BigInteger"); } catch (ExecutionException e) { // Do nothing } assertTrue(Op.on("67.5").exec(FnString.isBigInteger(Locale.ENGLISH)).get().booleanValue()); assertEquals(Op.on("67.5").exec(FnString.toBigInteger(Locale.ENGLISH)).get(), BigInteger.valueOf(nf.parse("67.5").longValue())); assertTrue(Op.on("6997.89").exec(FnString.isBigInteger(Locale.ENGLISH)).get().booleanValue()); assertEquals(Op.on("6997.89").exec(FnString.toBigInteger(Locale.ENGLISH)).get(), BigInteger.valueOf(nf.parse("6997.89").longValue())); assertFalse(Op.on("6.7,5").exec(FnString.isBigInteger(Locale.ENGLISH)).get().booleanValue()); try { Op.on("6.7,5").exec(FnString.toBigInteger(Locale.ENGLISH)).get(); fail("Value was not expected to be converted into a BigInteger"); } catch (ExecutionException e) { // Do nothing } assertTrue(Op.on("6,8989898989898989898989898989898989898989898").exec(FnString .isBigInteger(LocaleUtils.toLocale("es"))).get().booleanValue()); assertEquals(Op.on("6,8989898989898989898989898989898989898989898").exec(FnString .toBigInteger(LocaleUtils.toLocale("es"))).get(), BigInteger.valueOf(nf.parse("6.8989898989898989898989898989898989898989898").longValue())); assertFalse(Op.on("6,9.9.7.89fgfd").exec(FnString .isBigInteger(LocaleUtils.toLocale("es"))).get().booleanValue()); try { Op.on("6,9.9.7.89fgfd").exec(FnString .toBigInteger(LocaleUtils.toLocale("es"))).get(); fail("Value was not expected to be converted into a BigInteger"); } catch (ExecutionException e) { // Do nothing } assertTrue(Op.on("6.9.97,89").exec(FnString .isBigInteger(LocaleUtils.toLocale("es"))).get().booleanValue()); assertEquals(Op.on("6.9.97,89").exec(FnString .toBigInteger(LocaleUtils.toLocale("es"))).get(), BigInteger.valueOf(nf.parse("6,9,97.89").longValue())); assertFalse(Op.on("6,997.89").exec(FnString .isBigInteger(LocaleUtils.toLocale("es"))).get().booleanValue()); try { Op.on("6,997.89").exec(FnString .toBigInteger(LocaleUtils.toLocale("es"))).get(); fail("Value was not expected to be converted into a BigInteger"); } catch (ExecutionException e) { // Do nothing } assertTrue(Op.on("6.997,89").exec(FnString .isBigInteger(LocaleUtils.toLocale("es"))).get().booleanValue()); assertEquals(Op.on("6.997,89").exec(FnString .toBigInteger(LocaleUtils.toLocale("es"))).get(), BigInteger.valueOf(nf.parse("6,997.89").longValue())); assertTrue(Op.on("6.9.9.7,89").exec(FnString .isBigInteger(LocaleUtils.toLocale("es"))).get().booleanValue()); assertEquals(Op.on("6.9.9.7,89").exec(FnString .toBigInteger(LocaleUtils.toLocale("es"))).get(), BigInteger.valueOf(nf.parse("6,9,9,7.89").longValue())); assertFalse(Op.on("67e").exec(FnString.isBigDecimal()).get().booleanValue()); try { Op.on("67e").exec(FnString.toBigDecimal()).get(); fail("Value was not expected to be converted into a BigDecimal"); } catch (ExecutionException e) { // Do nothing } assertTrue(Op.on("67.5").exec(FnString.isBigDecimal(Locale.ENGLISH)).get().booleanValue()); assertEquals(Op.on("67.5").exec(FnString.toBigDecimal(Locale.ENGLISH)).get(), BigDecimal.valueOf(nf.parse("67.5").doubleValue())); assertTrue(Op.on("6997.89").exec(FnString.isBigDecimal(Locale.ENGLISH)).get().booleanValue()); assertEquals(Op.on("6997.89").exec(FnString.toBigDecimal(Locale.ENGLISH)).get(), BigDecimal.valueOf(nf.parse("6997.89").doubleValue())); assertFalse(Op.on("6.7,5").exec(FnString.isBigDecimal(Locale.ENGLISH)).get().booleanValue()); try { Op.on("6.7,5").exec(FnString.toBigDecimal(Locale.ENGLISH)).get(); fail("Value was not expected to be converted into a BigDecimal"); } catch (ExecutionException e) { // Do nothing } assertTrue(Op.on("6,8989898989898989898989898989898989898989898").exec(FnString .isBigDecimal(LocaleUtils.toLocale("es"))).get().booleanValue()); assertEquals(Op.on("6,8989898989898989898989898989898989898989898").exec(FnString .toBigDecimal(LocaleUtils.toLocale("es"))).get(), nf.parse("6.8989898989898989898989898989898989898989898")); assertFalse(Op.on("6,9.9.7.89fgfd").exec(FnString .isBigDecimal(LocaleUtils.toLocale("es"))).get().booleanValue()); try { Op.on("6,9.9.7.89fgfd").exec(FnString .toBigDecimal(LocaleUtils.toLocale("es"))).get(); fail("Value was not expected to be converted into a BigDecimal"); } catch (ExecutionException e) { // Do nothing } assertTrue(Op.on("6.9.97,89").exec(FnString .isBigDecimal(LocaleUtils.toLocale("es"))).get().booleanValue()); assertEquals(Op.on("6.9.97,89").exec(FnString .toBigDecimal(LocaleUtils.toLocale("es"))).get(), BigDecimal.valueOf(nf.parse("6,9,97.89").doubleValue())); assertFalse(Op.on("6,997.89").exec(FnString .isBigDecimal(LocaleUtils.toLocale("es"))).get().booleanValue()); try { Op.on("6,997.89").exec(FnString .toBigDecimal(LocaleUtils.toLocale("es"))).get(); fail("Value was not expected to be converted into a BigDecimal"); } catch (ExecutionException e) { // Do nothing } assertTrue(Op.on("6.997,89").exec(FnString .isBigDecimal(LocaleUtils.toLocale("es"))).get().booleanValue()); assertEquals(Op.on("6.997,89").exec(FnString .toBigDecimal(LocaleUtils.toLocale("es"))).get(), BigDecimal.valueOf(nf.parse("6,997.89").doubleValue())); assertTrue(Op.on("6.9.9.7,89").exec(FnString .isBigDecimal(LocaleUtils.toLocale("es"))).get().booleanValue()); assertEquals(Op.on("6.9.9.7,89").exec(FnString .toBigDecimal(LocaleUtils.toLocale("es"))).get(), BigDecimal.valueOf(nf.parse("6,9,9,7.89").doubleValue())); assertFalse(Op.on("67e").exec(FnString.isDouble()).get().booleanValue()); try { Op.on("67e").exec(FnString.toDouble()).get(); fail("Value was not expected to be converted into a Double"); } catch (ExecutionException e) { // Do nothing } assertTrue(Op.on("67.5").exec(FnString.isDouble(Locale.ENGLISH)).get().booleanValue()); assertEquals(Op.on("67.5").exec(FnString.toDouble(Locale.ENGLISH)).get(), Double.valueOf(nf.parse("67.5").doubleValue())); assertTrue(Op.on("6997.89").exec(FnString.isDouble(Locale.ENGLISH)).get().booleanValue()); assertEquals(Op.on("6997.89").exec(FnString.toDouble(Locale.ENGLISH)).get(), Double.valueOf(nf.parse("6997.89").doubleValue())); assertFalse(Op.on("6.7,5").exec(FnString.isDouble(Locale.ENGLISH)).get().booleanValue()); try { Op.on("6.7,5").exec(FnString.toDouble(Locale.ENGLISH)).get(); fail("Value was not expected to be converted into a Double"); } catch (ExecutionException e) { // Do nothing } assertTrue(Op.on("6,8989898989898989898989898989898989898989898").exec(FnString .isDouble(LocaleUtils.toLocale("es"))).get().booleanValue()); assertEquals(Op.on("6,8989898989898989898989898989898989898989898").exec(FnString .toDouble(LocaleUtils.toLocale("es"))).get(), Double.valueOf(nf.parse("6.8989898989898989898989898989898989898989898").doubleValue())); assertFalse(Op.on("6,9.9.7.89fgfd").exec(FnString .isDouble(LocaleUtils.toLocale("es"))).get().booleanValue()); try { Op.on("6,9.9.7.89fgfd").exec(FnString .toDouble(LocaleUtils.toLocale("es"))).get(); fail("Value was not expected to be converted into a Double"); } catch (ExecutionException e) { // Do nothing } assertTrue(Op.on("6.9.97,89").exec(FnString .isDouble(LocaleUtils.toLocale("es"))).get().booleanValue()); assertEquals(Op.on("6.9.97,89").exec(FnString .toDouble(LocaleUtils.toLocale("es"))).get(), Double.valueOf(nf.parse("6,9,97.89").doubleValue())); assertFalse(Op.on("6,997.89").exec(FnString .isDouble(LocaleUtils.toLocale("es"))).get().booleanValue()); try { Op.on("6,997.89").exec(FnString .toDouble(LocaleUtils.toLocale("es"))).get(); fail("Value was not expected to be converted into a Double"); } catch (ExecutionException e) { // Do nothing } assertTrue(Op.on("6.997,89").exec(FnString .isDouble(LocaleUtils.toLocale("es"))).get().booleanValue()); assertEquals(Op.on("6.997,89").exec(FnString .toDouble(LocaleUtils.toLocale("es"))).get(), Double.valueOf(nf.parse("6,997.89").doubleValue())); assertTrue(Op.on("6.9.9.7,89").exec(FnString .isDouble(LocaleUtils.toLocale("es"))).get().booleanValue()); assertEquals(Op.on("6.9.9.7,89").exec(FnString .toDouble(LocaleUtils.toLocale("es"))).get(), Double.valueOf(nf.parse("6,9,9,7.89").doubleValue())); assertFalse(Op.on("67e").exec(FnString.isFloat()).get().booleanValue()); try { Op.on("67e").exec(FnString.toFloat()).get(); fail("Value was not expected to be converted into a Float"); } catch (ExecutionException e) { // Do nothing } assertTrue(Op.on("67.5").exec(FnString.isFloat(Locale.ENGLISH)).get().booleanValue()); assertEquals(Op.on("67.5").exec(FnString.toFloat(Locale.ENGLISH)).get(), Float.valueOf(nf.parse("67.5").floatValue())); assertTrue(Op.on("6997.89").exec(FnString.isFloat(Locale.ENGLISH)).get().booleanValue()); assertEquals(Op.on("6997.89").exec(FnString.toFloat(Locale.ENGLISH)).get(), Float.valueOf(nf.parse("6997.89").floatValue())); assertFalse(Op.on("6.7,5").exec(FnString.isFloat(Locale.ENGLISH)).get().booleanValue()); try { Op.on("6.7,5").exec(FnString.toFloat(Locale.ENGLISH)).get(); fail("Value was not expected to be converted into a Float"); } catch (ExecutionException e) { // Do nothing } assertTrue(Op.on("6,8989898989898989898989898989898989898989898").exec(FnString .isFloat(LocaleUtils.toLocale("es"))).get().booleanValue()); assertEquals(Op.on("6,8989898989898989898989898989898989898989898").exec(FnString .toFloat(LocaleUtils.toLocale("es"))).get(), Float.valueOf(nf.parse("6.8989898989898989898989898989898989898989898").floatValue())); assertFalse(Op.on("6,9.9.7.89fgfd").exec(FnString .isFloat(LocaleUtils.toLocale("es"))).get().booleanValue()); try { Op.on("6,9.9.7.89fgfd").exec(FnString .toFloat(LocaleUtils.toLocale("es"))).get(); fail("Value was not expected to be converted into a Float"); } catch (ExecutionException e) { // Do nothing } assertTrue(Op.on("6.9.97,89").exec(FnString .isFloat(LocaleUtils.toLocale("es"))).get().booleanValue()); assertEquals(Op.on("6.9.97,89").exec(FnString .toFloat(LocaleUtils.toLocale("es"))).get(), Float.valueOf(nf.parse("6,9,97.89").floatValue())); assertFalse(Op.on("6,997.89").exec(FnString .isFloat(LocaleUtils.toLocale("es"))).get().booleanValue()); try { Op.on("6,997.89").exec(FnString .toFloat(LocaleUtils.toLocale("es"))).get(); fail("Value was not expected to be converted into a Float"); } catch (ExecutionException e) { // Do nothing } assertTrue(Op.on("6.997,89").exec(FnString .isFloat(LocaleUtils.toLocale("es"))).get().booleanValue()); assertEquals(Op.on("6.997,89").exec(FnString .toFloat(LocaleUtils.toLocale("es"))).get(), Float.valueOf(nf.parse("6,997.89").floatValue())); assertTrue(Op.on("6.9.9.7,89").exec(FnString .isFloat(LocaleUtils.toLocale("es"))).get().booleanValue()); assertEquals(Op.on("6.9.9.7,89").exec(FnString .toFloat(LocaleUtils.toLocale("es"))).get(), Float.valueOf(nf.parse("6,9,9,7.89").floatValue())); assertFalse(Op.on("67e").exec(FnString.isLong()).get().booleanValue()); try { Op.on("67e").exec(FnString.toLong()).get(); fail("Value was not expected to be converted into a Long"); } catch (ExecutionException e) { // Do nothing } assertTrue(Op.on("67.5").exec(FnString.isLong(Locale.ENGLISH)).get().booleanValue()); assertEquals(Op.on("67.5").exec(FnString.toLong(Locale.ENGLISH)).get(), Long.valueOf(nf.parse("67.5").longValue())); assertTrue(Op.on("6997.89").exec(FnString.isLong(Locale.ENGLISH)).get().booleanValue()); assertEquals(Op.on("6997.89").exec(FnString.toLong(Locale.ENGLISH)).get(), Long.valueOf(nf.parse("6997.89").longValue())); assertFalse(Op.on("6.7,5").exec(FnString.isLong(Locale.ENGLISH)).get().booleanValue()); try { Op.on("6.7,5").exec(FnString.toLong(Locale.ENGLISH)).get(); fail("Value was not expected to be converted into a Long"); } catch (ExecutionException e) { // Do nothing } assertTrue(Op.on("6,8989898989898989898989898989898989898989898").exec(FnString .isLong(LocaleUtils.toLocale("es"))).get().booleanValue()); assertEquals(Op.on("6,8989898989898989898989898989898989898989898").exec(FnString .toLong(LocaleUtils.toLocale("es"))).get(), Long.valueOf(nf.parse("6.8989898989898989898989898989898989898989898").longValue())); assertFalse(Op.on("6,9.9.7.89fgfd").exec(FnString .isLong(LocaleUtils.toLocale("es"))).get().booleanValue()); try { Op.on("6,9.9.7.89fgfd").exec(FnString .toLong(LocaleUtils.toLocale("es"))).get(); fail("Value was not expected to be converted into a Long"); } catch (ExecutionException e) { // Do nothing } assertTrue(Op.on("6.9.97,89").exec(FnString .isLong(LocaleUtils.toLocale("es"))).get().booleanValue()); assertEquals(Op.on("6.9.97,89").exec(FnString .toLong(LocaleUtils.toLocale("es"))).get(), Long.valueOf(nf.parse("6,9,97.89").longValue())); assertFalse(Op.on("6,997.89").exec(FnString .isLong(LocaleUtils.toLocale("es"))).get().booleanValue()); try { Op.on("6,997.89").exec(FnString .toLong(LocaleUtils.toLocale("es"))).get(); fail("Value was not expected to be converted into a Long"); } catch (ExecutionException e) { // Do nothing } assertTrue(Op.on("6.997,89").exec(FnString .isLong(LocaleUtils.toLocale("es"))).get().booleanValue()); assertEquals(Op.on("6.997,89").exec(FnString .toLong(LocaleUtils.toLocale("es"))).get(), Long.valueOf(nf.parse("6,997.89").longValue())); assertTrue(Op.on("6.9.9.7,89").exec(FnString .isLong(LocaleUtils.toLocale("es"))).get().booleanValue()); assertEquals(Op.on("6.9.9.7,89").exec(FnString .toLong(LocaleUtils.toLocale("es"))).get(), Long.valueOf(nf.parse("6,9,9,7.89").longValue())); assertFalse(Op.on("67e").exec(FnString.isInteger()).get().booleanValue()); try { Op.on("67e").exec(FnString.toInteger()).get(); fail("Value was not expected to be converted into an Integer"); } catch (ExecutionException e) { // Do nothing } assertTrue(Op.on("67.5").exec(FnString.isInteger(Locale.ENGLISH)).get().booleanValue()); assertEquals(Op.on("67.5").exec(FnString.toInteger(Locale.ENGLISH)).get(), Integer.valueOf(nf.parse("67.5").intValue())); assertTrue(Op.on("6997.89").exec(FnString.isInteger(Locale.ENGLISH)).get().booleanValue()); assertEquals(Op.on("6997.89").exec(FnString.toInteger(Locale.ENGLISH)).get(), Integer.valueOf(nf.parse("6997.89").intValue())); assertFalse(Op.on("6.7,5").exec(FnString.isInteger(Locale.ENGLISH)).get().booleanValue()); try { Op.on("6.7,5").exec(FnString.toInteger(Locale.ENGLISH)).get(); fail("Value was not expected to be converted into an Integer"); } catch (ExecutionException e) { // Do nothing } assertTrue(Op.on("6,8989898989898989898989898989898989898989898").exec(FnString .isInteger(LocaleUtils.toLocale("es"))).get().booleanValue()); assertEquals(Op.on("6,8989898989898989898989898989898989898989898").exec(FnString .toInteger(LocaleUtils.toLocale("es"))).get(), Integer.valueOf(nf.parse("6.8989898989898989898989898989898989898989898").intValue())); assertFalse(Op.on("6,9.9.7.89fgfd").exec(FnString .isInteger(LocaleUtils.toLocale("es"))).get().booleanValue()); try { Op.on("6,9.9.7.89fgfd").exec(FnString .toInteger(LocaleUtils.toLocale("es"))).get(); fail("Value was not expected to be converted into an Integer"); } catch (ExecutionException e) { // Do nothing } assertTrue(Op.on("6.9.97,89").exec(FnString .isInteger(LocaleUtils.toLocale("es"))).get().booleanValue()); assertEquals(Op.on("6.9.97,89").exec(FnString .toInteger(LocaleUtils.toLocale("es"))).get(), Integer.valueOf(nf.parse("6,9,97.89").intValue())); assertFalse(Op.on("6,997.89").exec(FnString .isInteger(LocaleUtils.toLocale("es"))).get().booleanValue()); try { Op.on("6,997.89").exec(FnString .toInteger(LocaleUtils.toLocale("es"))).get(); fail("Value was not expected to be converted into an Integer"); } catch (ExecutionException e) { // Do nothing } assertTrue(Op.on("6.997,89").exec(FnString .isInteger(LocaleUtils.toLocale("es"))).get().booleanValue()); assertEquals(Op.on("6.997,89").exec(FnString .toInteger(LocaleUtils.toLocale("es"))).get(), Integer.valueOf(nf.parse("6,997.89").intValue())); assertTrue(Op.on("6.9.9.7,89").exec(FnString .isInteger(LocaleUtils.toLocale("es"))).get().booleanValue()); assertEquals(Op.on("6.9.9.7,89").exec(FnString .toInteger(LocaleUtils.toLocale("es"))).get(), Integer.valueOf(nf.parse("6,9,9,7.89").intValue())); assertFalse(Op.on("67e").exec(FnString.isShort()).get().booleanValue()); try { Op.on("67e").exec(FnString.toShort()).get(); fail("Value was not expected to be converted into a Short"); } catch (ExecutionException e) { // Do nothing } assertTrue(Op.on("67.5").exec(FnString.isShort(Locale.ENGLISH)).get().booleanValue()); assertEquals(Op.on("67.5").exec(FnString.toShort(Locale.ENGLISH)).get(), Short.valueOf(nf.parse("67.5").shortValue())); assertTrue(Op.on("6997.89").exec(FnString.isShort(Locale.ENGLISH)).get().booleanValue()); assertEquals(Op.on("6997.89").exec(FnString.toShort(Locale.ENGLISH)).get(), Short.valueOf(nf.parse("6997.89").shortValue())); assertFalse(Op.on("6.7,5").exec(FnString.isShort(Locale.ENGLISH)).get().booleanValue()); try { Op.on("6.7,5").exec(FnString.toShort(Locale.ENGLISH)).get(); fail("Value was not expected to be converted into a Short"); } catch (ExecutionException e) { // Do nothing } assertTrue(Op.on("6,8989898989898989898989898989898989898989898").exec(FnString .isShort(LocaleUtils.toLocale("es"))).get().booleanValue()); assertEquals(Op.on("6,8989898989898989898989898989898989898989898").exec(FnString .toShort(LocaleUtils.toLocale("es"))).get(), Short.valueOf(nf.parse("6.8989898989898989898989898989898989898989898").shortValue())); assertFalse(Op.on("6,9.9.7.89fgfd").exec(FnString .isShort(LocaleUtils.toLocale("es"))).get().booleanValue()); try { Op.on("6,9.9.7.89fgfd").exec(FnString .toShort(LocaleUtils.toLocale("es"))).get(); fail("Value was not expected to be converted into a Short"); } catch (ExecutionException e) { // Do nothing } assertTrue(Op.on("6.9.97,89").exec(FnString .isShort(LocaleUtils.toLocale("es"))).get().booleanValue()); assertEquals(Op.on("6.9.97,89").exec(FnString .toShort(LocaleUtils.toLocale("es"))).get(), Short.valueOf(nf.parse("6,9,97.89").shortValue())); assertFalse(Op.on("6,997.89").exec(FnString .isShort(LocaleUtils.toLocale("es"))).get().booleanValue()); try { Op.on("6,997.89").exec(FnString .toShort(LocaleUtils.toLocale("es"))).get(); fail("Value was not expected to be converted into a Short"); } catch (ExecutionException e) { // Do nothing } assertTrue(Op.on("6.997,89").exec(FnString .isShort(LocaleUtils.toLocale("es"))).get().booleanValue()); assertEquals(Op.on("6.997,89").exec(FnString .toShort(LocaleUtils.toLocale("es"))).get(), Short.valueOf(nf.parse("6,997.89").shortValue())); assertTrue(Op.on("6.9.9.7,89").exec(FnString .isShort(LocaleUtils.toLocale("es"))).get().booleanValue()); assertEquals(Op.on("6.9.9.7,89").exec(FnString .toShort(LocaleUtils.toLocale("es"))).get(), Short.valueOf(nf.parse("6,9,9,7.89").shortValue())); assertTrue(Op.on("688").exec(FnString .isShort(9)).get().booleanValue()); assertEquals(Op.on("688").exec(FnString .toShort(9)).get(), Short.valueOf("688", 9)); assertFalse(Op.on("662.1").exec(FnString .isShort(7)).get().booleanValue()); try { Op.on("662.1").exec(FnString .toShort(7)).get(); fail("Value was not expected to be converted into a Short"); } catch (ExecutionException e) { // Do nothing } assertFalse(Op.on("67e").exec(FnString.isByte()).get().booleanValue()); try { Op.on("67e").exec(FnString.toByte()).get(); fail("Value was not expected to be converted into a Byte"); } catch (ExecutionException e) { // Do nothing } assertTrue(Op.on("67.5").exec(FnString.isByte(Locale.ENGLISH)).get().booleanValue()); assertEquals(Op.on("67.5").exec(FnString.toByte(Locale.ENGLISH)).get(), Byte.valueOf(nf.parse("67.5").byteValue())); assertTrue(Op.on("6.9").exec(FnString.isByte(Locale.ENGLISH)).get().booleanValue()); assertEquals(Op.on("6.9").exec(FnString.toByte(Locale.ENGLISH)).get(), Byte.valueOf(nf.parse("6.9").byteValue())); assertFalse(Op.on("6.7,5").exec(FnString.isByte(Locale.ENGLISH)).get().booleanValue()); try { Op.on("6.7,5").exec(FnString.toByte(Locale.ENGLISH)).get(); fail("Value was not expected to be converted into a Byte"); } catch (ExecutionException e) { // Do nothing } assertTrue(Op.on("6,8989898989898989898989898989898989898989898").exec(FnString .isByte(LocaleUtils.toLocale("es"))).get().booleanValue()); assertEquals(Op.on("6,8989898989898989898989898989898989898989898").exec(FnString .toByte(LocaleUtils.toLocale("es"))).get(), Byte.valueOf(nf.parse("6.8989898989898989898989898989898989898989898").byteValue())); assertFalse(Op.on("6,9.9.7.89fgfd").exec(FnString .isByte(LocaleUtils.toLocale("es"))).get().booleanValue()); try { Op.on("6,9.9.7.89fgfd").exec(FnString .toByte(LocaleUtils.toLocale("es"))).get(); fail("Value was not expected to be converted into a Byte"); } catch (ExecutionException e) { // Do nothing } assertTrue(Op.on("6.9").exec(FnString .isByte(LocaleUtils.toLocale("es"))).get().booleanValue()); assertEquals(Op.on("6.9").exec(FnString .toByte(LocaleUtils.toLocale("es"))).get(), Byte.valueOf(nf.parse("6,9").byteValue())); assertFalse(Op.on("6,997.89").exec(FnString .isByte(LocaleUtils.toLocale("es"))).get().booleanValue()); try { Op.on("6,997.89").exec(FnString .toByte(LocaleUtils.toLocale("es"))).get(); fail("Value was not expected to be converted into a Byte"); } catch (ExecutionException e) { // Do nothing } assertTrue(Op.on("6.9,89").exec(FnString .isByte(LocaleUtils.toLocale("es"))).get().booleanValue()); assertEquals(Op.on("6.9,89").exec(FnString .toByte(LocaleUtils.toLocale("es"))).get(), Byte.valueOf(nf.parse("6,9.89").byteValue())); assertTrue(Op.on("9.7,89").exec(FnString .isByte(LocaleUtils.toLocale("es"))).get().booleanValue()); assertEquals(Op.on("9.7,89").exec(FnString .toByte(LocaleUtils.toLocale("es"))).get(), Byte.valueOf(nf.parse("9,7.89").byteValue())); assertTrue(Op.on("68").exec(FnString .isByte(9)).get().booleanValue()); assertEquals(Op.on("68").exec(FnString.toByte(9)).get(), Byte.valueOf("68", 9)); } @Test public void test66() throws Exception { Double minDouble = Double.valueOf(Double.MIN_VALUE); Double maxDouble = Double.valueOf(Double.MAX_VALUE); Float minFloat = Float.valueOf(Float.MIN_VALUE); Float maxFloat = Float.valueOf(Float.MAX_VALUE); Long minLong = Long.valueOf(Long.MIN_VALUE); Long maxLong = Long.valueOf(Long.MAX_VALUE); Integer minInteger = Integer.valueOf(Integer.MIN_VALUE); Integer maxInteger = Integer.valueOf(Integer.MAX_VALUE); Short minShort = Short.valueOf(Short.MIN_VALUE); Short maxShort = Short.valueOf(Short.MAX_VALUE); Byte minByte = Byte.valueOf(Byte.MIN_VALUE); Byte maxByte = Byte.valueOf(Byte.MAX_VALUE); System.out.println( "Byte -> " + minByte + " to " + maxByte + "\n" + "Short -> " + minShort + " to " + maxShort + "\n" + "Integer -> " + minInteger + " to " + maxInteger + "\n" + "Long -> " + minLong + " to " + maxLong + "\n" + "Float -> " + minFloat + " to " + maxFloat + "\n" + "Double -> " + minDouble + " to " + maxDouble); String number = String.valueOf(BigInteger.valueOf(maxInteger) .add(BigInteger.valueOf(1))); assertFalse(Op.on(number).exec(FnString .isInteger()).get().booleanValue()); try { Op.on(number).exec(FnString .toInteger()).get(); fail("Value was not expected to be converted into an Integer"); } catch (ExecutionException e) { // Do nothing } number = String.valueOf(BigDecimal.valueOf(maxInteger) .add(BigDecimal.valueOf(0.5))); assertTrue(Op.on(number).exec(FnString .isInteger()).get().booleanValue()); assertEquals(Op.on(number).exec(FnString .toInteger()).get(), maxInteger); number = String.valueOf(BigDecimal.valueOf(maxLong) .add(BigDecimal.valueOf(4.5))); assertTrue(Op.on(number).exec(FnString .isBigInteger()).get().booleanValue()); assertEquals(Op.on(number).exec(FnString .toBigInteger()).get(), BigDecimal.valueOf(maxLong).add(BigDecimal.valueOf(4.5)).toBigInteger()); assertTrue(Op.on(number).exec(FnString .isBigDecimal()).get().booleanValue()); assertEquals(Op.on(number).exec(FnString .toBigDecimal()).get(), BigDecimal.valueOf(maxLong).add(BigDecimal.valueOf(4.5))); assertFalse(Op.on(number).exec(FnString .isLong()).get().booleanValue()); try { Op.on(number).exec(FnString .toLong()).get(); fail("Value was not expected to be converted into an Integer"); } catch (ExecutionException e) { // Do nothing } number = String.valueOf(BigDecimal.valueOf(minShort) .add(BigDecimal.valueOf(-1))); assertFalse(Op.on(number).exec(FnString .isShort()).get().booleanValue()); assertTrue(Op.on(number).exec(FnString .isLong()).get().booleanValue()); assertFalse(Op.on(number).exec(FnString .isByte()).get().booleanValue()); number = String.valueOf(maxShort); assertTrue(Op.on(number).exec(FnString .isShort()).get().booleanValue()); assertTrue(Op.on(number).exec(FnString .isLong()).get().booleanValue()); assertFalse(Op.on(number).exec(FnString .isByte()).get().booleanValue()); number = String.valueOf(minByte); assertTrue(Op.on(number).exec(FnString .isShort()).get().booleanValue()); assertTrue(Op.on(number).exec(FnString .isLong()).get().booleanValue()); assertTrue(Op.on(number).exec(FnString .isByte()).get().booleanValue()); number = String.valueOf(BigDecimal.valueOf(minDouble) .subtract(BigDecimal.valueOf(1))); assertTrue(Op.on(number).exec(FnString .isShort()).get().booleanValue()); assertFalse(Op.on(number).exec(FnString .isFloat()).get().booleanValue()); assertFalse(Op.on(number).exec(FnString .isDouble()).get().booleanValue()); number = String.valueOf(BigDecimal.valueOf(minFloat) .subtract(BigDecimal.valueOf(1))); assertTrue(Op.on(number).exec(FnString .isShort()).get().booleanValue()); assertFalse(Op.on(number).exec(FnString .isFloat()).get().booleanValue()); assertFalse(Op.on(number).exec(FnString .isDouble()).get().booleanValue()); number = String.valueOf(BigDecimal.valueOf(maxDouble) .add(BigDecimal.valueOf(4.5))); assertTrue(Op.on(number).exec(FnString .isBigInteger()).get().booleanValue()); assertTrue(Op.on(number).exec(FnString .isBigDecimal()).get().booleanValue()); assertFalse(Op.on(number).exec(FnString .isLong()).get().booleanValue()); assertFalse(Op.on(number).exec(FnString .isFloat()).get().booleanValue()); number = String.valueOf(BigDecimal.valueOf(maxFloat) .add(BigDecimal.valueOf(4.5))); assertTrue(Op.on(number).exec(FnString .isBigInteger()).get().booleanValue()); assertTrue(Op.on(number).exec(FnString .isBigDecimal()).get().booleanValue()); assertTrue(Op.on(number).exec(FnString .isDouble()).get().booleanValue()); assertFalse(Op.on(number).exec(FnString .isLong()).get().booleanValue()); assertFalse(Op.on(number).exec(FnString .isFloat()).get().booleanValue()); number = String.valueOf(BigDecimal.valueOf(minLong) .add(BigDecimal.valueOf(-1))); assertFalse(Op.on(number).exec(FnString .isShort()).get().booleanValue()); assertFalse(Op.on(number).exec(FnString .isLong()).get().booleanValue()); assertFalse(Op.on(number).exec(FnString .isByte()).get().booleanValue()); number = String.valueOf(BigDecimal.valueOf(minInteger) .subtract(BigDecimal.valueOf(1))); assertFalse(Op.on(number).exec(FnString .isShort()).get().booleanValue()); assertTrue(Op.on(number).exec(FnString .isLong()).get().booleanValue()); assertFalse(Op.on(number).exec(FnString .isByte()).get().booleanValue()); number = String.valueOf(BigDecimal.valueOf(maxInteger) .add(BigDecimal.valueOf(0.5))); assertTrue(Op.on(number).exec(FnString .isInteger()).get().booleanValue()); assertEquals(Op.on(number).exec(FnString .toInteger()).get(), maxInteger); number = String.valueOf(BigDecimal.valueOf(maxByte) .add(BigDecimal.valueOf(0.5))); assertTrue(Op.on(number).exec(FnString .isInteger()).get().booleanValue()); assertTrue(Op.on(number).exec(FnString .isByte()).get().booleanValue()); number = String.valueOf(BigDecimal.valueOf(maxByte) .add(BigDecimal.valueOf(1.5))); assertFalse(Op.on(number).exec(FnString .isByte()).get().booleanValue()); number = String.valueOf(BigDecimal.valueOf(maxByte) + ",4"); assertTrue(Op.on(number).exec(FnString .isByte(DecimalPoint.IS_COMMA)).get().booleanValue()); number = String.valueOf(BigDecimal.valueOf(maxByte) + ",9"); assertTrue(Op.on(number).exec(FnString .isByte(DecimalPoint.IS_COMMA)).get().booleanValue()); number = String.valueOf(BigDecimal.valueOf(maxByte) .add(BigDecimal.valueOf(1))); assertFalse(Op.on(number).exec(FnString .isByte()).get().booleanValue()); assertTrue(Op.on("4,5,4.4").exec(FnString .isLong(Locale.UK)).get().booleanValue()); assertTrue(Op.on("123").exec(FnString .isByte(5)).get().booleanValue()); assertFalse(Op.on("5").exec(FnString .isByte(5)).get().booleanValue()); } @Test public void test67() throws Exception { String[] array = new String[] {"first", "second", "third"}; assertEquals(array.length, Op.on(array).exec(FnArray.ofString().count()) .get().intValue()); List<Integer> list = Op.onListFor(Integer.valueOf(4)).get(); assertEquals(list.size(), Op.on(list).exec(FnList.ofInteger().count()) .get().intValue()); Set<Calendar> set = Op.onSetFor(Calendar.getInstance(), Calendar.getInstance()).get(); assertEquals(set.size(), Op.on(set).exec(FnSet.ofCalendar().count()) .get().intValue()); } @Test public void test68() throws Exception { assertEquals("asd", Op.on("<>asd<>").exec(FnString.substringBetween("<>")) .get()); assertEquals("", Op.on("<>asd<>").exec(FnString.substringBefore("<>")) .get()); assertEquals("<>asd", Op.on("<>asd<>").exec(FnString.substringBeforeLast("<>")) .get()); assertEquals("as", Op.on("<>asd<>").exec(FnString.substringBetween(">", "d")) .get()); } }
package loadster.sdk.client; import feign.*; import feign.jackson.JacksonDecoder; import feign.jackson.JacksonEncoder; import loadster.sdk.exceptions.ApiException; import loadster.sdk.types.*; import java.io.IOException; import java.io.InputStream; import java.util.List; /** * Simplified client interface for the Workbench API. */ public class WorkbenchApiClient { private WorkbenchApi jsonApi; public WorkbenchApiClient(final String host, final int port, final String apiKey) { jsonApi = Feign.builder().decoder(new JacksonDecoder()).encoder(new JacksonEncoder()).requestInterceptor(new RequestInterceptor() { @Override public void apply(RequestTemplate requestTemplate) { requestTemplate.query("apiKey", apiKey); } }).target(WorkbenchApi.class, "http://" + host + ":" + port); } /** * Lists all projects. */ public List<Reference> listProjects() throws ApiException, IOException { return jsonApi.listProjects(); } /** * Gets details on a project. */ public Project getProject(String id) throws ApiException, IOException { return jsonApi.getProject(id); } /** * Gets details on a scenario. */ public Scenario getScenario(String projectId, String scenarioId) throws ApiException, IOException { return jsonApi.getScenario(projectId, scenarioId); } /** * Gets details on a script. */ public Script getScript(String projectId, String scriptId) throws ApiException, IOException { return jsonApi.getScript(projectId, scriptId); } /** * Gets details on a data set. */ public DataSet getDataSet(String projectId, String dataSetId) throws ApiException, IOException { return jsonApi.getDataSet(projectId, dataSetId); } /** * Gets details on a test. */ public Test getTest(String projectId, String scenarioId, String testId) throws ApiException, IOException { return jsonApi.getTest(projectId, scenarioId, testId); } /** * Attempts to start a test for a scenario. */ public Test startTest(Scenario scenario) throws ApiException, IOException { return jsonApi.startTest(scenario.getProjectId(), scenario.getId()); } /** * Gets up-to-date status on a test. */ public TestStatus getTestStatus(Test test) throws ApiException, IOException { return jsonApi.getTestStatus(test.getProjectId(), test.getScenarioId(), test.getId()); } /** * Fetches an HTML test report for a test. The test has to be finished or this will fail. */ public InputStream getTestReport(Test test) throws ApiException, IOException { return jsonApi.getTestReport(test.getProjectId(), test.getScenarioId(), test.getId()).body().asInputStream(); } /** * Fetches statistics for a test. The test has to be finished or this will fail. */ public TestStatistics getTestStatistics(Test test) throws ApiException, IOException { return jsonApi.getTestStatistics(test.getProjectId(), test.getScenarioId(), test.getId()); } private interface WorkbenchApi { @RequestLine("GET /projects") @Headers("Accept: application/json") List<Reference> listProjects(); @RequestLine("GET /projects/{projectId}") @Headers("Accept: application/json") Project getProject(@Param("projectId") String projectId); @RequestLine("GET /projects/{projectId}/scenarios/{scenarioId}") @Headers("Accept: application/json") Scenario getScenario(@Param("projectId") String projectId, @Param("scenarioId") String scenarioId); @RequestLine("GET /projects/{projectId}/scripts/{scriptId}") @Headers("Accept: application/json") Script getScript(@Param("projectId") String projectId, @Param("scriptId") String scriptId); @RequestLine("GET /projects/{projectId}/datasets/{dataSetId}") @Headers("Accept: application/json") DataSet getDataSet(@Param("projectId") String projectId, @Param("dataSetId") String dataSetId); @RequestLine("GET /projects/{projectId}/scenarios/{scenarioId}/tests/{testId}") @Headers("Accept: application/json") Test getTest(@Param("projectId") String projectId, @Param("scenarioId") String scenarioId, @Param("testId") String testId); @RequestLine("POST /projects/{projectId}/scenarios/{scenarioId}/tests") @Headers("Accept: application/json") Test startTest(@Param("projectId") String projectId, @Param("scenarioId") String scenarioId); @RequestLine("GET /projects/{projectId}/scenarios/{scenarioId}/tests/{testId}/status") @Headers("Accept: application/json") TestStatus getTestStatus(@Param("projectId") String projectId, @Param("scenarioId") String scenarioId, @Param("testId") String testId); @RequestLine("GET /projects/{projectId}/scenarios/{scenarioId}/tests/{testId}/report") @Headers("Accept: application/json") TestStatistics getTestStatistics(@Param("projectId") String projectId, @Param("scenarioId") String scenarioId, @Param("testId") String testId); @RequestLine("GET /projects/{projectId}/scenarios/{scenarioId}/tests/{testId}/report") @Headers("Accept: text/html") Response getTestReport(@Param("projectId") String projectId, @Param("scenarioId") String scenarioId, @Param("testId") String testId); } }
package qiniu.happydns; import org.junit.Assert; import org.junit.Test; import qiniu.happydns.http.IHosts; import qiniu.happydns.local.*; import java.io.IOException; import java.net.InetAddress; import java.net.UnknownHostException; public class DnsTest { private boolean flag = false; @Test public void testDns() throws IOException { IResolver[] resolvers = new IResolver[2]; resolvers[0] = new Resolver(InetAddress.getByName(SystemDnsServer.getByUnixConf()[0])); resolvers[1] = new Resolver(InetAddress.getByName("119.29.29.29")); DnsClient dns = new DnsClient(resolvers); String[] ips = dns.query("www.qiniu.com"); Assert.assertNotNull(ips); Assert.assertTrue(ips.length > 0); } @Test public void testTtl() throws IOException { IResolver[] resolvers = new IResolver[2]; resolvers[0] = new Resolver(InetAddress.getByName(SystemDnsServer.getByUnixConf()[0])); resolvers[1] = new HijackingDetectWrapper( new Resolver(InetAddress.getByName("119.29.29.29"))); IHosts h = new Hosts(); h.put("hello.qiniu.com", "1.1.1.1"); h.put("hello.qiniu.com", "2.2.2.2"); h.put("qiniu.com", "3.3.3.3"); DnsClient dns = new DnsClient(resolvers, h); Domain d = new Domain("qiniu.com", false, false, 10); String[] r = dns.query(d); Assert.assertEquals(1, r.length); Assert.assertEquals("3.3.3.3", r[0]); d = new Domain("qiniu.com", false, false, 1000); r = dns.query(d); Assert.assertEquals(1, r.length); Assert.assertTrue(!"3.3.3.3".equals(r[0])); } public void testCname() throws IOException { IResolver[] resolvers = new IResolver[2]; resolvers[0] = new Resolver(InetAddress.getByName(SystemDnsServer.getByUnixConf()[0])); resolvers[1] = new HijackingDetectWrapper( new Resolver(InetAddress.getByName("114.114.115.115"))); IHosts h = new Hosts(); h.put("hello.qiniu.com", "1.1.1.1"); h.put("hello.qiniu.com", "2.2.2.2"); h.put("qiniu.com", "3.3.3.3"); DnsClient dns = new DnsClient(resolvers, h); Domain d = new Domain("qiniu.com", true); String[] r = dns.query(d); Assert.assertEquals(1, r.length); Assert.assertEquals("3.3.3.3", r[0]); d = new Domain("qiniu.com", false); r = dns.query(d); Assert.assertEquals(1, r.length); Assert.assertTrue(!"3.3.3.3".equals(r[0])); } public void testNull() throws UnknownHostException { IResolver[] resolvers = new IResolver[1]; resolvers[0] = new Resolver(InetAddress.getByName(SystemDnsServer.getByUnixConf()[0])); DnsClient dns = new DnsClient(resolvers); IOException e = null; try { dns.query((String) null); } catch (IOException ex) { ex.printStackTrace(); e = ex; } Assert.assertNotNull(e); e = null; try { dns.query((Domain) null); } catch (IOException ex) { ex.printStackTrace(); e = ex; } Assert.assertNotNull(e); e = null; try { dns.query(""); } catch (IOException ex) { ex.printStackTrace(); e = ex; } Assert.assertNotNull(e); } public void testIp() throws IOException { IResolver[] resolvers = new IResolver[1]; resolvers[0] = new Resolver(InetAddress.getByName(SystemDnsServer.getByUnixConf()[0])); DnsClient dns = new DnsClient(resolvers); String[] ips = dns.query("1.1.1.1"); Assert.assertEquals(ips.length, 1); Assert.assertEquals(ips[0], "1.1.1.1"); } }
package ml.duncte123.skybot.objects; import java.util.Collections; import java.util.HashMap; import java.util.Map; public class Primitives { public static Class<?> unwrap(Class<?> type) { return (wrapperToPrimitives.get(type) == null) ? type : wrapperToPrimitives.get(type); } public static Class<?> wrap(Class<?> type) { return (primitivesToWrapper.get(type) == null) ? type : primitivesToWrapper.get(type); } private static final Map<Class<?>, Class<?>> primitivesToWrapper; private static final Map<Class<?>, Class<?>> wrapperToPrimitives; static { Map<Class<?>, Class<?>> p = new HashMap<>(16); Map<Class<?>, Class<?>> w = new HashMap<>(16); put(p, w, boolean.class, Boolean.class); put(p, w, byte.class, Byte.class); put(p, w, char.class, Character.class); put(p, w, double.class, Double.class); put(p, w, float.class, Float.class); put(p, w, int.class, Integer.class); put(p, w, long.class, Long.class); put(p, w, short.class, Short.class); put(p, w, void.class, Void.class); primitivesToWrapper = Collections.unmodifiableMap(p); wrapperToPrimitives = Collections.unmodifiableMap(w); } private static void put(Map<Class<?>, Class<?>> first, Map<Class<?>, Class<?>> second, Class<?> primitive, Class<?> wrapper) { first.put(primitive, wrapper); second.put(wrapper, primitive); } }
package water; import hex.*; import hex.deeplearning.DropoutTest; import hex.deeplearning.NeuronsTest; import org.junit.internal.TextListener; import org.junit.runner.Description; import org.junit.runner.JUnitCore; import org.junit.runner.Result; import org.junit.runner.notification.Failure; import water.deploy.NodeCL; import water.fvec.*; import water.util.Log; import water.util.Utils; import java.util.ArrayList; import java.util.List; public class JUnitRunnerDebug { public static final int NODES = 1; public static void main(String[] args) throws Exception { int[] ports = new int[NODES]; for( int i = 0; i < ports.length; i++ ) ports[i] = 54321 + i * 2; String flat = ""; for( int i = 0; i < ports.length; i++ ) flat += "127.0.0.1:" + ports[i] + "\n"; flat = Utils.writeFile(flat).getAbsolutePath(); for( int i = 0; i < ports.length; i++ ) { Class c = i == 0 ? UserCode.class : H2O.class; new NodeCL(c, ("-ip 127.0.0.1 -port " + ports[i] + " -flatfile " + flat).split(" ")).start(); } } public static class UserCode { public static void userMain(String[] args) { H2O.main(args); TestUtil.stall_till_cloudsize(NODES); List<Class> tests = new ArrayList<Class>(); // Classes to test: // tests = JUnitRunner.all(); // Neural Net - deprecated // tests.add(NeuralNetSpiralsTest.class); //compare NeuralNet vs reference // tests.add(NeuralNetIrisTest.class); //compare NeuralNet vs reference // Deep Learning tests // tests.add(DeepLearningVsNeuralNet.class); //only passes for NODES=1, not clear why // tests.add(DeepLearningAutoEncoderTest.class); //test Deep Learning convergence // tests.add(DeepLearningAutoEncoderCategoricalTest.class); //test Deep Learning convergence // tests.add(DeepLearningSpiralsTest.class); //test Deep Learning convergence // tests.add(DeepLearningIrisTest.Short.class); //compare Deep Learning vs reference // tests.add(DeepLearningIrisTest.Long.class); //compare Deep Learning vs reference // tests.add(DeepLearningProstateTest.Short.class); //test Deep Learning // tests.add(DeepLearningProstateTest.Long.class); //test Deep Learning // tests.add(NeuronsTest.class); //test Deep Learning // tests.add(MRUtilsTest.class); //test MR sampling/rebalancing // tests.add(DropoutTest.class); //test NN Dropput // Chunk tests tests.add(C0LChunkTest.class); tests.add(C0DChunkTest.class); tests.add(C1ChunkTest.class); tests.add(C1NChunkTest.class); tests.add(C1SChunkTest.class); tests.add(C2ChunkTest.class); tests.add(C2SChunkTest.class); tests.add(C4ChunkTest.class); tests.add(C4SChunkTest.class); tests.add(C8ChunkTest.class); tests.add(C8DChunkTest.class); tests.add(CBSChunkTest.class); tests.add(CX0ChunkTest.class); tests.add(CXIChunkTest.class); tests.add(CXDChunkTest.class); // tests.add(GLMTest2.class); // tests.add(DRFTest.class); // tests.add(GBMTest.class); // tests.add(KMeans2Test.class); // tests.add(PCATest.class); // Uncomment this to sleep here and use the browser. // try { Thread.sleep(10000000); } catch (Exception _) {} JUnitCore junit = new JUnitCore(); junit.addListener(new LogListener()); Result result = junit.run(tests.toArray(new Class[0])); if( result.getFailures().size() == 0 ) { Log.info("SUCCESS!"); System.exit(0); } else { Log.info("FAIL!"); System.exit(1); } } } static class LogListener extends TextListener { LogListener() { super(System.out); } @Override public void testRunFinished(Result result) { printHeader(result.getRunTime()); printFailures(result); printFooter(result); } @Override public void testStarted(Description description) { Log.info(""); Log.info("Starting test " + description); } @Override public void testFailure(Failure failure) { Log.info("Test failed " + failure); } @Override public void testIgnored(Description description) { Log.info("Ignoring test " + description); } } }
package net.darkhax.bookshelf.util; import java.util.HashSet; import java.util.List; import java.util.Set; import net.minecraft.entity.Entity; import net.minecraft.entity.LivingEntity; import net.minecraft.entity.MobEntity; import net.minecraft.entity.SharedMonsterAttributes; import net.minecraft.entity.ai.attributes.IAttribute; import net.minecraft.inventory.EquipmentSlotType; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.potion.Effect; import net.minecraft.potion.EffectInstance; import net.minecraft.potion.Effects; import net.minecraft.util.Direction; import net.minecraft.util.math.AxisAlignedBB; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.RayTraceContext; import net.minecraft.util.math.RayTraceContext.BlockMode; import net.minecraft.util.math.RayTraceContext.FluidMode; import net.minecraft.util.math.RayTraceResult; import net.minecraft.util.math.Vec3d; import net.minecraft.world.World; public final class EntityUtils { /** * Calculates the distance between two entities. * * @param firstEntity The first entity to use. * @param secondEntity The second entity to use. * @return double The distance between the two entities passed. */ public static double getDistanceFromEntity (Entity firstEntity, Entity secondEntity) { return MathsUtils.getDistanceBetweenPoints(firstEntity.getPositionVector(), secondEntity.getPositionVector()); } /** * Calculates the distance between an entity and a BlockPos. * * @param entity The Entity to use for the first position. * @param pos The BlockPos to use for the second position. * @return double The distance between the Entity and the BlockPos. */ public static double getDistaceFromPos (Entity entity, BlockPos pos) { return MathsUtils.getDistanceBetweenPoints(entity.getPositionVector(), new Vec3d(pos)); } /** * Pushes an entity towards a specific direction. * * @param entityToMove The entity that you want to push. * @param direction The direction to push the entity. * @param force The amount of force to push the entity with. */ public static void pushTowards (Entity entityToMove, Direction direction, double force) { pushTowards(entityToMove, entityToMove.getPosition().offset(direction.getOpposite(), 1), force); } /** * Pushes an Entity towards a BlockPos. * * @param entityToMove The entity that you want to push. * @param pos The BlockPos to push the entity towards. * @param force The amount of force to push the entity with. */ public static void pushTowards (Entity entityToMove, BlockPos pos, double force) { final BlockPos entityPos = entityToMove.getPosition(); final double distanceX = (double) pos.getX() - entityPos.getX(); final double distanceY = (double) pos.getY() - entityPos.getY(); final double distanceZ = (double) pos.getZ() - entityPos.getZ(); final double distance = Math.sqrt(distanceX * distanceX + distanceY * distanceY + distanceZ * distanceZ); if (distance > 0) { entityToMove.setMotion(new Vec3d(distanceX / distance * force, distanceY / distance * force, distanceZ / distance * force)); } } /** * Pushes an entity towards another one. * * @param entityToMove The entity that should be pushed towards the other entity. * @param destination The destination entity, that the entity to move should be pushed * towards. * @param force The amount of force to push the entityToMove with. */ public static void pushTowards (Entity entityToMove, Entity destination, double force) { final double distanceX = destination.getPosX() - entityToMove.getPosX(); final double distanceY = destination.getPosY() - entityToMove.getPosY(); final double distanceZ = destination.getPosZ() - entityToMove.getPosZ(); final double distance = Math.sqrt(distanceX * distanceX + distanceY * distanceY + distanceZ * distanceZ); if (distance > 0) { entityToMove.setMotion(new Vec3d(distanceX / distance * force, distanceY / distance * force, distanceZ / distance * force)); } } /** * Creates a Vec3d that represents the additional motion that would be needed to push an * entity towards a destination. * * @param entityToMove The entity to push. * @param direction The direction to push the entity. * @param force The amount of force to use. * */ public static void pushTowardsDirection (Entity entityToMove, Direction direction, double force) { final BlockPos entityPos = entityToMove.getPosition(); final BlockPos destination = entityToMove.getPosition().offset(direction.getOpposite(), 1); final double distanceX = (double) destination.getX() - entityPos.getX(); final double distanceY = (double) destination.getY() - entityPos.getY(); final double distanceZ = (double) destination.getZ() - entityPos.getZ(); final double distance = Math.sqrt(distanceX * distanceX + distanceY * distanceY + distanceZ * distanceZ); if (distance > 0) { entityToMove.setMotion(new Vec3d(distanceX / distance * force, distanceY / distance * force, distanceZ / distance * force)); } } /** * Checks if two entities are close enough together. * * @param firstEntity The first entity to check. * @param secondEntity The second entity to check. * @param maxDistance The maximum distance that the entities can be apart. * @return boolean True if the distance between the entities are within range of the * maxDistance. */ public static boolean areEntitiesCloseEnough (Entity firstEntity, Entity secondEntity, double maxDistance) { return getDistanceFromEntity(firstEntity, secondEntity) < maxDistance * maxDistance; } /** * Gets a List of entities that are within the provided area. * * @param <T> The type of entities to look for. * @param entityClass The type of entity you are looking for. * @param world The world to search in. * @param pos The position to start the search around. * @param range The range of the search. * @return A List containing all entities of the specified type that are within the range. */ public static <T extends Entity> List<T> getEntitiesInArea (Class<T> entityClass, World world, BlockPos pos, int range) { return getEntitiesInArea(entityClass, world, pos, (float) range); } /** * Gets a List of entities that are within the provided area. * * @param <T> The type of entities to look for. * @param entityClass The type of entity you are looking for. * @param world The world to search in. * @param pos The position to start the search around. * @param range The range of the search. * @return A List containing all entities of the specified type that are within the range. */ public static <T extends Entity> List<T> getEntitiesInArea (Class<T> entityClass, World world, BlockPos pos, float range) { return world.getEntitiesWithinAABB(entityClass, new AxisAlignedBB(pos.add(-range, -range, -range), pos.add(range + 1, range + 1, range + 1))); } /** * A check to see if an entity is wearing a full suit of the armor. This check is based on * the class names of armor. * * @param living: The living entity to check the armor of. * @param armorClass: The class of the armor to check against. * @return boolean: True if every piece of armor the entity is wearing are the same class * as the provied armor class. */ public static boolean isWearingFullSet (MobEntity living, Class<Item> armorClass) { for (final EquipmentSlotType slot : EquipmentSlotType.values()) { if (slot.getSlotType().equals(EquipmentSlotType.Group.ARMOR)) { final ItemStack armor = living.getItemStackFromSlot(slot); if (armor.isEmpty() || !armor.getItem().getClass().equals(armorClass)) { return false; } } } return true; } /** * Gets the max health value of an entity. * * @param entity The entity to get the value from. * @return The value of the attribute. */ public static double getMaxHealth (MobEntity entity) { return entity.getAttribute(SharedMonsterAttributes.MAX_HEALTH).getValue(); } /** * Gets the follow/tracking range value of an entity. * * @param entity The entity to get the value from. * @return The value of the attribute. */ public static double getFollowRange (MobEntity entity) { return entity.getAttribute(SharedMonsterAttributes.FOLLOW_RANGE).getValue(); } /** * Gets the knockback resistance value of an entity. * * @param entity The entity to get the value from. * @return The value of the attribute. */ public static double getKnockbackResistance (MobEntity entity) { return entity.getAttribute(SharedMonsterAttributes.KNOCKBACK_RESISTANCE).getValue(); } /** * Gets the movement speed value of an entity. * * @param entity The entity to get the value from. * @return The value of the attribute. */ public static double getMovementSpeed (MobEntity entity) { return entity.getAttribute(SharedMonsterAttributes.MOVEMENT_SPEED).getValue(); } /** * Gets the attack value of an entity. * * @param entity The entity to get the value from. * @return The value of the attribute. */ public static double getAttackDamage (MobEntity entity) { return entity.getAttribute(SharedMonsterAttributes.ATTACK_DAMAGE).getValue(); } /** * Gets the attack speed value of an entity. * * @param entity The entity to get the value from. * @return The value of the attribute. */ public static double getAttackSpeed (MobEntity entity) { return entity.getAttribute(SharedMonsterAttributes.ATTACK_SPEED).getValue(); } /** * Gets the armor value of an entity. * * @param entity The entity to get the value from. * @return The value of the attribute. */ public static double getArmor (MobEntity entity) { return entity.getAttribute(SharedMonsterAttributes.ARMOR).getValue(); } /** * Gets the armor toughness value of an entity. * * @param entity The entity to get the value from. * @return The value of the attribute. */ public static double getArmorToughness (MobEntity entity) { return entity.getAttribute(SharedMonsterAttributes.ARMOR_TOUGHNESS).getValue(); } /** * Gets the luck value of an entity. * * @param entity The entity to get the value from. * @return The value of the attribute. */ public static double getLuck (MobEntity entity) { return entity.getAttribute(SharedMonsterAttributes.LUCK).getValue(); } /** * Gets a value of an attribute for an entity. * * @param entity The entity to get the value of. * @param attribute The attribute to get the value of. * @return The value of the attribute. */ public static double getValue (MobEntity entity, IAttribute attribute) { return entity.getAttribute(attribute).getValue(); } /** * Performs a ray trace for the look vector of an entity. * * @param entity The entity to perform a ray trace on. * @param length The distance to cast the rays. * @param blockMode The mode used when detecting blocks. * @param fluidMode The mode used when detecting fluids. * @return An object containing the results of the ray trace. */ public static RayTraceResult rayTrace (LivingEntity entity, double length, BlockMode blockMode, FluidMode fluidMode) { final Vec3d startingPosition = new Vec3d(entity.getPosX(), entity.getPosY() + entity.getEyeHeight(), entity.getPosZ()); final Vec3d lookVector = entity.getLookVec(); final Vec3d endingPosition = startingPosition.add(lookVector.x * length, lookVector.y * length, lookVector.z * length); return entity.world.rayTraceBlocks(new RayTraceContext(startingPosition, endingPosition, blockMode, fluidMode, entity)); } /** * Checks if an entity can be affected by fire. While fire immune entities can already * negate the effects of fire doing prechecks using this method can be used to avoid * rendering flickers or filter out these types of entities. * * @param toCheck The entity to check. * @return Whether or not this entity can be affected by fire. */ public static boolean isAffectedByFire (LivingEntity toCheck) { return !toCheck.isImmuneToFire() && !toCheck.isPotionActive(Effects.FIRE_RESISTANCE); } /** * Clears potion effect from an entity based on whether or not the effects are positive or * negative. * * @param entity The entity to remove effects from. * @param removePositive Should positive effects be cleared? * @param removeNegative Should negative effects be cleared? */ public static void clearEffects (LivingEntity entity, boolean removePositive, boolean removeNegative) { final Set<Effect> toClear = new HashSet<>(); for (final EffectInstance effect : entity.getActivePotionEffects()) { final boolean isGood = effect.getPotion().isBeneficial(); if (isGood && removePositive || !isGood && removeNegative) { toClear.add(effect.getPotion()); } } for (final Effect effect : toClear) { entity.removePotionEffect(effect); } } }
package water; import hex.*; import hex.nn.Dropout; import org.junit.internal.TextListener; import org.junit.runner.Description; import org.junit.runner.JUnitCore; import org.junit.runner.Result; import org.junit.runner.notification.Failure; import water.deploy.NodeCL; import water.util.Log; import water.util.Utils; import java.util.ArrayList; import java.util.List; public class JUnitRunnerDebug { public static final int NODES = 3; public static void main(String[] args) throws Exception { int[] ports = new int[NODES]; for( int i = 0; i < ports.length; i++ ) ports[i] = 54321 + i * 2; String flat = ""; for( int i = 0; i < ports.length; i++ ) flat += "127.0.0.1:" + ports[i] + "\n"; flat = Utils.writeFile(flat).getAbsolutePath(); for( int i = 0; i < ports.length; i++ ) { Class c = i == 0 ? UserCode.class : H2O.class; new NodeCL(c, ("-ip 127.0.0.1 -port " + ports[i] + " -flatfile " + flat).split(" ")).start(); } } public static class UserCode { public static void userMain(String[] args) { H2O.main(args); TestUtil.stall_till_cloudsize(NODES); List<Class> tests = new ArrayList<Class>(); // Classes to test: // tests = JUnitRunner.all(); // tests.add(NNvsNeuralNet.class); //only passes for NODES=1, not clear why tests.add(NeuralNetSpiralsTest.class); //compare NeuralNet vs reference tests.add(NeuralNetIrisTest.class); //compare NeuralNet vs reference tests.add(NeuralNetSpiralsTest2.class); //compare NN vs reference tests.add(NeuralNetIrisTest2.class); //compare NN vs reference tests.add(Dropout.class); //test NN Dropput // Uncomment this to sleep here and use the browser. // try { Thread.sleep(10000000); } catch (Exception _) {} JUnitCore junit = new JUnitCore(); junit.addListener(new LogListener()); Result result = junit.run(tests.toArray(new Class[0])); if( result.getFailures().size() == 0 ) { Log.info("SUCCESS!"); System.exit(0); } else { Log.info("FAIL!"); System.exit(1); } } } static class LogListener extends TextListener { LogListener() { super(System.out); } @Override public void testRunFinished(Result result) { printHeader(result.getRunTime()); printFailures(result); printFooter(result); } @Override public void testStarted(Description description) { Log.info(""); Log.info("Starting test " + description); } @Override public void testFailure(Failure failure) { Log.info("Test failed " + failure); } @Override public void testIgnored(Description description) { Log.info("Ignoring test " + description); } } }
package net.finmath.functions; import java.util.Calendar; import net.finmath.rootfinder.NewtonsMethod; import net.finmath.stochastic.RandomVariable; import net.finmath.stochastic.Scalar; /** * This class implements some functions as static class methods. * * It provides functions like * <ul> * <li>the Black-Scholes formula, * <li>the inverse of the Back-Scholes formula with respect to (implied) volatility, * <li>the Bachelier formula, * <li>the inverse of the Bachelier formula with respect to (implied) volatility, * <li>the corresponding functions (versions) for caplets and swaptions, * <li>analytic approximation for European options under the SABR model, * <li>some convexity adjustments. * </ul> * * @author Christian Fries * @version 1.10 * @date 27.04.2012 */ public class AnalyticFormulas { /** * Preventing instantiation of this class. */ private AnalyticFormulas() { // This constructor will never be invoked } /** * Calculates the Black-Scholes option value of a call, i.e., the payoff max(S(T)-K,0) P, where S follows a log-normal process with constant log-volatility. * * The method also handles cases where the forward and/or option strike is negative * and some limit cases where the forward and/or the option strike is zero. * * @param forward The forward of the underlying. * @param volatility The Black-Scholes volatility. * @param optionMaturity The option maturity T. * @param optionStrike The option strike. If the option strike is &le; 0.0 the method returns the value of the forward contract paying S(T)-K in T. * @param payoffUnit The payoff unit (e.g., the discount factor) * @return Returns the value of a European call option under the Black-Scholes model. */ public static double blackScholesGeneralizedOptionValue( final double forward, final double volatility, final double optionMaturity, final double optionStrike, final double payoffUnit) { if(optionMaturity < 0) { return 0; } else if(forward < 0) { // We use max(X,0) = X + max(-X,0) return (forward - optionStrike) * payoffUnit + blackScholesGeneralizedOptionValue(-forward, volatility, optionMaturity, -optionStrike, payoffUnit); } else if((forward == 0) || (optionStrike <= 0.0) || (volatility <= 0.0) || (optionMaturity <= 0.0)) { // Limit case (where dPlus = +/- infty) return Math.max(forward - optionStrike,0) * payoffUnit; } else { // Calculate analytic value final double dPlus = (Math.log(forward / optionStrike) + 0.5 * volatility * volatility * optionMaturity) / (volatility * Math.sqrt(optionMaturity)); final double dMinus = dPlus - volatility * Math.sqrt(optionMaturity); final double valueAnalytic = (forward * NormalDistribution.cumulativeDistribution(dPlus) - optionStrike * NormalDistribution.cumulativeDistribution(dMinus)) * payoffUnit; return valueAnalytic; } } /** * Calculates the Black-Scholes option value of a call, i.e., the payoff max(S(T)-K,0) P, where S follows a log-normal process with constant log-volatility. * * The model specific quantities are considered to be random variable, i.e., * the function may calculate an per-path valuation in a single call. * * @param forward The forward of the underlying. * @param volatility The Black-Scholes volatility. * @param optionMaturity The option maturity T. * @param optionStrike The option strike. If the option strike is &le; 0.0 the method returns the value of the forward contract paying S(T)-K in T. * @param payoffUnit The payoff unit (e.g., the discount factor) * @return Returns the value of a European call option under the Black-Scholes model. */ public static RandomVariable blackScholesGeneralizedOptionValue( final RandomVariable forward, final RandomVariable volatility, final double optionMaturity, final double optionStrike, final RandomVariable payoffUnit) { if(optionMaturity < 0) { return forward.mult(0.0); } else { final RandomVariable dPlus = forward.div(optionStrike).log().add(volatility.squared().mult(0.5 * optionMaturity)).div(volatility).div(Math.sqrt(optionMaturity)); final RandomVariable dMinus = dPlus.sub(volatility.mult(Math.sqrt(optionMaturity))); final RandomVariable valueAnalytic = dPlus.apply(NormalDistribution::cumulativeDistribution).mult(forward).sub(dMinus.apply(NormalDistribution::cumulativeDistribution).mult(optionStrike)).mult(payoffUnit); return valueAnalytic; } } /** * Calculates the Black-Scholes option value of a call, i.e., the payoff max(S(T)-K,0), where S follows a log-normal process with constant log-volatility. * * @param initialStockValue The spot value of the underlying. * @param riskFreeRate The risk free rate r (df = exp(-r T)). * @param volatility The Black-Scholes volatility. * @param optionMaturity The option maturity T. * @param optionStrike The option strike. If the option strike is &le; 0.0 the method returns the value of the forward contract paying S(T)-K in T. * @return Returns the value of a European call option under the Black-Scholes model. */ public static double blackScholesOptionValue( final double initialStockValue, final double riskFreeRate, final double volatility, final double optionMaturity, final double optionStrike) { return blackScholesGeneralizedOptionValue( initialStockValue * Math.exp(riskFreeRate * optionMaturity), // forward volatility, optionMaturity, optionStrike, Math.exp(-riskFreeRate * optionMaturity) // payoff unit ); } /** * Calculates the Black-Scholes option value of a call, i.e., the payoff max(S(T)-K,0), where S follows a log-normal process with constant log-volatility. * * @param initialStockValue The spot value of the underlying. * @param riskFreeRate The risk free rate r (df = exp(-r T)). * @param volatility The Black-Scholes volatility. * @param optionMaturity The option maturity T. * @param optionStrike The option strike. If the option strike is &le; 0.0 the method returns the value of the forward contract paying S(T)-K in T. * @return Returns the value of a European call option under the Black-Scholes model. */ public static RandomVariable blackScholesOptionValue( final RandomVariable initialStockValue, final RandomVariable riskFreeRate, final RandomVariable volatility, final double optionMaturity, final double optionStrike) { return blackScholesGeneralizedOptionValue( initialStockValue.mult(riskFreeRate.mult(optionMaturity).exp()), // forward volatility, optionMaturity - 0.0, optionStrike, riskFreeRate.mult(-optionMaturity).exp() // payoff unit ); } /** * Calculates the Black-Scholes option value of a call, i.e., the payoff max(S(T)-K,0), where S follows a log-normal process with constant log-volatility. * * @param initialStockValue The spot value of the underlying. * @param riskFreeRate The risk free rate r (df = exp(-r T)). * @param volatility The Black-Scholes volatility. * @param optionMaturity The option maturity T. * @param optionStrike The option strike. If the option strike is &le; 0.0 the method returns the value of the forward contract paying S(T)-K in T. * @return Returns the value of a European call option under the Black-Scholes model. */ public static RandomVariable blackScholesOptionValue( final RandomVariable initialStockValue, final double riskFreeRate, final double volatility, final double optionMaturity, final double optionStrike) { return blackScholesGeneralizedOptionValue( initialStockValue.mult(Math.exp(riskFreeRate*optionMaturity)), // forward new Scalar(volatility), optionMaturity - 0.0, optionStrike, new Scalar(Math.exp(-riskFreeRate*optionMaturity)) // payoff unit ); } /** * Calculates the Black-Scholes option value of a call, i.e., the payoff max(S(T)-K,0), or a put, i.e., the payoff max(K-S(T),0), where S follows a log-normal process with constant log-volatility. * * @param initialStockValue The spot value of the underlying. * @param riskFreeRate The risk free rate r (df = exp(-r T)). * @param volatility The Black-Scholes volatility. * @param optionMaturity The option maturity T. * @param optionStrike The option strike. If the option strike is &le; 0.0 the method returns the value of the forward contract paying S(T)-K in T for the call and zero for the put. * @param isCall If true, the value of a call is calculated, if false, the value of a put is calculated. * @return Returns the value of a European call/put option under the Black-Scholes model. */ public static double blackScholesOptionValue( final double initialStockValue, final double riskFreeRate, final double volatility, final double optionMaturity, final double optionStrike, final boolean isCall) { final double callValue = blackScholesOptionValue(initialStockValue, riskFreeRate, volatility, optionMaturity, optionStrike); if(isCall) { return callValue; } else { final double putValue = callValue - (initialStockValue-optionStrike * Math.exp(-riskFreeRate * optionMaturity)); return putValue; } } /** * Calculates the Black-Scholes option value of an atm call option. * * @param volatility The Black-Scholes volatility. * @param optionMaturity The option maturity T. * @param forward The forward, i.e., the expectation of the index under the measure associated with payoff unit. * @param payoffUnit The payoff unit, i.e., the discount factor or the anuity associated with the payoff. * @return Returns the value of a European at-the-money call option under the Black-Scholes model */ public static double blackScholesATMOptionValue( final double volatility, final double optionMaturity, final double forward, final double payoffUnit) { if(optionMaturity < 0) { return 0.0; } // Calculate analytic value final double dPlus = 0.5 * volatility * Math.sqrt(optionMaturity); final double dMinus = -dPlus; final double valueAnalytic = (NormalDistribution.cumulativeDistribution(dPlus) - NormalDistribution.cumulativeDistribution(dMinus)) * forward * payoffUnit; return valueAnalytic; } /** * Calculates the delta of a call option under a Black-Scholes model * * The method also handles cases where the forward and/or option strike is negative * and some limit cases where the forward or the option strike is zero. * In the case forward = option strike = 0 the method returns 1.0. * * @param initialStockValue The initial value of the underlying, i.e., the spot. * @param riskFreeRate The risk free rate of the bank account numerarie. * @param volatility The Black-Scholes volatility. * @param optionMaturity The option maturity T. * @param optionStrike The option strike. * @return The delta of the option */ public static double blackScholesOptionDelta( final double initialStockValue, final double riskFreeRate, final double volatility, final double optionMaturity, final double optionStrike) { if(optionMaturity < 0) { return 0; } else if(initialStockValue < 0) { // We use Indicator(S>K) = 1 - Indicator(-S>-K) return 1 - blackScholesOptionDelta(-initialStockValue, riskFreeRate, volatility, optionMaturity, -optionStrike); } else if(initialStockValue == 0) { // Limit case (where dPlus = +/- infty) if(optionStrike < 0) { return 1.0; // dPlus = +infinity } else if(optionStrike > 0) { return 0.0; // dPlus = -infinity } else { return 1.0; // Matter of definition of continuity of the payoff function } } else if((optionStrike <= 0.0) || (volatility <= 0.0) || (optionMaturity <= 0.0)) // (and initialStockValue > 0) { // The Black-Scholes model does not consider it being an option return 1.0; } else { // Calculate delta final double dPlus = (Math.log(initialStockValue / optionStrike) + (riskFreeRate + 0.5 * volatility * volatility) * optionMaturity) / (volatility * Math.sqrt(optionMaturity)); final double delta = NormalDistribution.cumulativeDistribution(dPlus); return delta; } } /** * Calculates the delta of a call option under a Black-Scholes model * * The method also handles cases where the forward and/or option strike is negative * and some limit cases where the forward or the option strike is zero. * In the case forward = option strike = 0 the method returns 1.0. * * @param initialStockValue The initial value of the underlying, i.e., the spot. * @param riskFreeRate The risk free rate of the bank account numerarie. * @param volatility The Black-Scholes volatility. * @param optionMaturity The option maturity T. * @param optionStrike The option strike. * @return The delta of the option */ public static RandomVariable blackScholesOptionDelta( final RandomVariable initialStockValue, final RandomVariable riskFreeRate, final RandomVariable volatility, final double optionMaturity, final double optionStrike) { if(optionMaturity < 0) { return initialStockValue.mult(0.0); } else { // Calculate delta final RandomVariable dPlus = initialStockValue.div(optionStrike).log().add(volatility.squared().mult(0.5).add(riskFreeRate).mult(optionMaturity)).div(volatility).div(Math.sqrt(optionMaturity)); final RandomVariable delta = dPlus.apply(NormalDistribution::cumulativeDistribution); return delta; } } /** * Calculates the delta of a call option under a Black-Scholes model * * The method also handles cases where the forward and/or option strike is negative * and some limit cases where the forward or the option strike is zero. * In the case forward = option strike = 0 the method returns 1.0. * * @param initialStockValue The initial value of the underlying, i.e., the spot. * @param riskFreeRate The risk free rate of the bank account numerarie. * @param volatility The Black-Scholes volatility. * @param optionMaturity The option maturity T. * @param optionStrike The option strike. * @return The delta of the option */ public static RandomVariable blackScholesOptionDelta( final RandomVariable initialStockValue, final double riskFreeRate, final double volatility, final double optionMaturity, final double optionStrike) { return blackScholesOptionDelta(initialStockValue, new Scalar(riskFreeRate), new Scalar(volatility), optionMaturity, optionStrike); } /** * Calculates the delta of a call option under a Black-Scholes model * * The method also handles cases where the forward and/or option strike is negative * and some limit cases where the forward or the option strike is zero. * In the case forward = option strike = 0 the method returns 1.0. * * @param initialStockValue The initial value of the underlying, i.e., the spot. * @param riskFreeRate The risk free rate of the bank account numerarie. * @param volatility The Black-Scholes volatility. * @param optionMaturity The option maturity T. * @param optionStrike The option strike. * @return The delta of the option */ public static RandomVariable blackScholesOptionDelta( final RandomVariable initialStockValue, final RandomVariable riskFreeRate, final RandomVariable volatility, final double optionMaturity, final RandomVariable optionStrike) { if(optionMaturity < 0) { return initialStockValue.mult(0.0); } else { // Calculate delta final RandomVariable dPlus = initialStockValue.div(optionStrike).log().add(volatility.squared().mult(0.5).add(riskFreeRate).mult(optionMaturity)).div(volatility).div(Math.sqrt(optionMaturity)); final RandomVariable delta = dPlus.apply(NormalDistribution::cumulativeDistribution); return delta; } } /** * This static method calculated the gamma of a call option under a Black-Scholes model * * @param initialStockValue The initial value of the underlying, i.e., the spot. * @param riskFreeRate The risk free rate of the bank account numerarie. * @param volatility The Black-Scholes volatility. * @param optionMaturity The option maturity T. * @param optionStrike The option strike. * @return The gamma of the option */ public static double blackScholesOptionGamma( final double initialStockValue, final double riskFreeRate, final double volatility, final double optionMaturity, final double optionStrike) { if(optionStrike <= 0.0 || optionMaturity <= 0.0) { // The Black-Scholes model does not consider it being an option return 0.0; } else { // Calculate gamma final double dPlus = (Math.log(initialStockValue / optionStrike) + (riskFreeRate + 0.5 * volatility * volatility) * optionMaturity) / (volatility * Math.sqrt(optionMaturity)); final double gamma = Math.exp(-0.5*dPlus*dPlus) / (Math.sqrt(2.0 * Math.PI * optionMaturity) * initialStockValue * volatility); return gamma; } } /** * This static method calculated the gamma of a call option under a Black-Scholes model * * @param initialStockValue The initial value of the underlying, i.e., the spot. * @param riskFreeRate The risk free rate of the bank account numerarie. * @param volatility The Black-Scholes volatility. * @param optionMaturity The option maturity T. * @param optionStrike The option strike. * @return The gamma of the option */ public static RandomVariable blackScholesOptionGamma( final RandomVariable initialStockValue, final RandomVariable riskFreeRate, final RandomVariable volatility, final double optionMaturity, final double optionStrike) { if(optionStrike <= 0.0 || optionMaturity <= 0.0) { // The Black-Scholes model does not consider it being an option return initialStockValue.mult(0.0); } else { // Calculate gamma final RandomVariable dPlus = initialStockValue.div(optionStrike).log().add(volatility.squared().mult(0.5).add(riskFreeRate).mult(optionMaturity)).div(volatility).div(Math.sqrt(optionMaturity)); final RandomVariable gamma = dPlus.squared().mult(-0.5).exp().div(initialStockValue.mult(volatility).mult(Math.sqrt(2.0 * Math.PI * optionMaturity))); return gamma; } } /** * This static method calculated the gamma of a call option under a Black-Scholes model * * @param initialStockValue The initial value of the underlying, i.e., the spot. * @param riskFreeRate The risk free rate of the bank account numerarie. * @param volatility The Black-Scholes volatility. * @param optionMaturity The option maturity T. * @param optionStrike The option strike. * @return The gamma of the option */ public static RandomVariable blackScholesOptionGamma( final RandomVariable initialStockValue, final double riskFreeRate, final double volatility, final double optionMaturity, final double optionStrike) { return blackScholesOptionGamma(initialStockValue, new Scalar(riskFreeRate), new Scalar(volatility), optionMaturity, optionStrike); } /** * Calculates the vega of a call, i.e., the payoff max(S(T)-K,0) P, where S follows a * normal process with constant volatility, i.e., a Black-Scholes model * \[ * \mathrm{d} S(t) = r S(t) \mathrm{d} t + \sigma S(t)\mathrm{d}W(t) * \] * * @param initialStockValue The initial value of the underlying, i.e., the spot. * @param riskFreeRate The risk free rate of the bank account numerarie. * @param volatility The Black-Scholes volatility. * @param optionMaturity The option maturity T. * @param optionStrike The option strike. * @return The vega of the option */ public static double blackScholesOptionVega( final double initialStockValue, final double riskFreeRate, final double volatility, final double optionMaturity, final double optionStrike) { if(optionStrike <= 0.0 || optionMaturity <= 0.0) { // The Black-Scholes model does not consider it being an option return 0.0; } else { // Calculate vega final double dPlus = (Math.log(initialStockValue / optionStrike) + (riskFreeRate + 0.5 * volatility * volatility) * optionMaturity) / (volatility * Math.sqrt(optionMaturity)); final double vega = Math.exp(-0.5*dPlus*dPlus) / Math.sqrt(2.0 * Math.PI) * initialStockValue * Math.sqrt(optionMaturity); return vega; } } /** * Calculates the vega of a call, i.e., the payoff max(S(T)-K,0) P, where S follows a * normal process with constant volatility, i.e., a Black-Scholes model * \[ * \mathrm{d} S(t) = r S(t) \mathrm{d} t + \sigma S(t)\mathrm{d}W(t) * \] * * @param initialStockValue The initial value of the underlying, i.e., the spot. * @param riskFreeRate The risk free rate of the bank account numerarie. * @param volatility The Black-Scholes volatility. * @param optionMaturity The option maturity T. * @param optionStrike The option strike. * @return The vega of the option */ public static RandomVariable blackScholesOptionVega( final RandomVariable initialStockValue, final RandomVariable riskFreeRate, final RandomVariable volatility, final double optionMaturity, final double optionStrike) { if(optionStrike <= 0.0 || optionMaturity <= 0.0) { // The Black-Scholes model does not consider it being an option return initialStockValue.mult(0.0); } else { // Calculate vega final RandomVariable dPlus = initialStockValue.div(optionStrike).log().add(volatility.squared().mult(0.5).add(riskFreeRate).mult(optionMaturity)).div(volatility).div(Math.sqrt(optionMaturity)); final RandomVariable vega = dPlus.squared().mult(-0.5).exp().div(Math.sqrt(2.0 * Math.PI * optionMaturity)).mult(initialStockValue).mult(volatility); return vega; } } /** * Calculates the vega of a call, i.e., the payoff max(S(T)-K,0) P, where S follows a * normal process with constant volatility, i.e., a Black-Scholes model * \[ * \mathrm{d} S(t) = r S(t) \mathrm{d} t + \sigma S(t)\mathrm{d}W(t) * \] * * @param initialStockValue The initial value of the underlying, i.e., the spot. * @param riskFreeRate The risk free rate of the bank account numerarie. * @param volatility The Black-Scholes volatility. * @param optionMaturity The option maturity T. * @param optionStrike The option strike. * @return The vega of the option */ public static RandomVariable blackScholesOptionVega( final RandomVariable initialStockValue, final double riskFreeRate, final double volatility, final double optionMaturity, final double optionStrike) { return blackScholesOptionVega(initialStockValue, new Scalar(riskFreeRate), new Scalar(volatility), optionMaturity, optionStrike); } /** * This static method calculated the vega of a call option under a Black-Scholes model * * @param initialStockValue The initial value of the underlying, i.e., the spot. * @param riskFreeRate The risk free rate of the bank account numerarie. * @param volatility The Black-Scholes volatility. * @param optionMaturity The option maturity T. * @param optionStrike The option strike. * @return The vega of the option */ public static double blackScholesOptionTheta( final double initialStockValue, final double riskFreeRate, final double volatility, final double optionMaturity, final double optionStrike) { if(optionStrike <= 0.0 || optionMaturity <= 0.0) { // The Black-Scholes model does not consider it being an option return 0.0; } else { // Calculate theta final double dPlus = (Math.log(initialStockValue / optionStrike) + (riskFreeRate + 0.5 * volatility * volatility) * optionMaturity) / (volatility * Math.sqrt(optionMaturity)); final double dMinus = dPlus - volatility * Math.sqrt(optionMaturity); final double theta = -volatility * Math.exp(-0.5*dPlus*dPlus) / Math.sqrt(2.0 * Math.PI) / Math.sqrt(optionMaturity) / 2 * initialStockValue - riskFreeRate * optionStrike * Math.exp(-riskFreeRate * optionMaturity) * NormalDistribution.cumulativeDistribution(dMinus); return theta; } } /** * This static method calculated the rho of a call option under a Black-Scholes model * * @param initialStockValue The initial value of the underlying, i.e., the spot. * @param riskFreeRate The risk free rate of the bank account numerarie. * @param volatility The Black-Scholes volatility. * @param optionMaturity The option maturity T. * @param optionStrike The option strike. * @return The rho of the option */ public static double blackScholesOptionRho( final double initialStockValue, final double riskFreeRate, final double volatility, final double optionMaturity, final double optionStrike) { if(optionStrike <= 0.0 || optionMaturity <= 0.0) { // The Black-Scholes model does not consider it being an option return 0.0; } else { // Calculate rho final double dMinus = (Math.log(initialStockValue / optionStrike) + (riskFreeRate - 0.5 * volatility * volatility) * optionMaturity) / (volatility * Math.sqrt(optionMaturity)); final double rho = optionStrike * optionMaturity * Math.exp(-riskFreeRate * optionMaturity) * NormalDistribution.cumulativeDistribution(dMinus); return rho; } } /** * Calculates the Black-Scholes option implied volatility of a call, i.e., the payoff * <p><i>max(S(T)-K,0)</i></p>, where <i>S</i> follows a log-normal process with constant log-volatility. * The admissible values for <code>optionValue</code> are between <code>forward * payoffUnit - optionStrike</code> (the inner value) and <code>forward * payoffUnit</code>. * * @param forward The forward of the underlying (which is equal to S(0) / payoffUnit, given the spot value S(0)). * @param optionMaturity The option maturity T. * @param optionStrike The option strike. If the option strike is &le; 0.0 the method returns the value of the forward contract paying S(T)-K in T. * @param payoffUnit The payoff unit (e.g., the discount factor), (which is equal to exp(-maturity * r), given the interest rate r). * @param optionValue The option value. The admissible values for <code>optionValue</code> are between <code>forward * payoffUnit - optionStrike</code> (the inner value) and <code>forward * payoffUnit</code>. * @return Returns the implied volatility of a European call option under the Black-Scholes model. */ public static double blackScholesOptionImpliedVolatility( final double forward, final double optionMaturity, final double optionStrike, final double payoffUnit, final double optionValue) { // Limit the maximum number of iterations, to ensure this calculation returns fast, e.g. in cases when there is no such thing as an implied vol // TODO An exception should be thrown, when there is no implied volatility for the given value. final int maxIterations = 500; final double maxAccuracy = 1E-15; if(optionStrike <= 0.0) { // Actually it is not an option return 0.0; } else { // Calculate an lower and upper bound for the volatility final double p = NormalDistribution.inverseCumulativeDistribution((optionValue/payoffUnit+optionStrike)/(forward+optionStrike)) / Math.sqrt(optionMaturity); final double q = 2.0 * Math.abs(Math.log(forward/optionStrike)) / optionMaturity; final double volatilityLowerBound = p + Math.sqrt(Math.max(p * p - q, 0.0)); final double volatilityUpperBound = p + Math.sqrt( p * p + q ); // If strike is close to forward the two bounds are close to the analytic solution if(Math.abs(volatilityLowerBound - volatilityUpperBound) < maxAccuracy) { return (volatilityLowerBound+volatilityUpperBound) / 2.0; } // Solve for implied volatility final NewtonsMethod solver = new NewtonsMethod(0.5*(volatilityLowerBound+volatilityUpperBound) /* guess */); while(solver.getAccuracy() > maxAccuracy && !solver.isDone() && solver.getNumberOfIterations() < maxIterations) { final double volatility = solver.getNextPoint(); // Calculate analytic value final double dPlus = (Math.log(forward / optionStrike) + 0.5 * volatility * volatility * optionMaturity) / (volatility * Math.sqrt(optionMaturity)); final double dMinus = dPlus - volatility * Math.sqrt(optionMaturity); final double valueAnalytic = (forward * NormalDistribution.cumulativeDistribution(dPlus) - optionStrike * NormalDistribution.cumulativeDistribution(dMinus)) * payoffUnit; final double derivativeAnalytic = forward * Math.sqrt(optionMaturity) * Math.exp(-0.5*dPlus*dPlus) / Math.sqrt(2.0*Math.PI) * payoffUnit; final double error = valueAnalytic - optionValue; solver.setValueAndDerivative(error,derivativeAnalytic); } return solver.getBestPoint(); } } /** * Calculates the Black-Scholes option value of a digital call option. * * @param initialStockValue The initial value of the underlying, i.e., the spot. * @param riskFreeRate The risk free rate of the bank account numerarie. * @param volatility The Black-Scholes volatility. * @param optionMaturity The option maturity T. * @param optionStrike The option strike. * @return Returns the value of a European call option under the Black-Scholes model */ public static double blackScholesDigitalOptionValue( final double initialStockValue, final double riskFreeRate, final double volatility, final double optionMaturity, final double optionStrike) { if(optionStrike <= 0.0) { // The Black-Scholes model does not consider it being an option return 1.0; } else { // Calculate analytic value final double dPlus = (Math.log(initialStockValue / optionStrike) + (riskFreeRate + 0.5 * volatility * volatility) * optionMaturity) / (volatility * Math.sqrt(optionMaturity)); final double dMinus = dPlus - volatility * Math.sqrt(optionMaturity); final double valueAnalytic = Math.exp(- riskFreeRate * optionMaturity) * NormalDistribution.cumulativeDistribution(dMinus); return valueAnalytic; } } /** * Calculates the delta of a digital option under a Black-Scholes model * * @param initialStockValue The initial value of the underlying, i.e., the spot. * @param riskFreeRate The risk free rate of the bank account numerarie. * @param volatility The Black-Scholes volatility. * @param optionMaturity The option maturity T. * @param optionStrike The option strike. * @return The delta of the digital option */ public static double blackScholesDigitalOptionDelta( final double initialStockValue, final double riskFreeRate, final double volatility, final double optionMaturity, final double optionStrike) { if(optionStrike <= 0.0 || optionMaturity <= 0.0) { // The Black-Scholes model does not consider it being an option return 0.0; } else { // Calculate delta final double dPlus = (Math.log(initialStockValue / optionStrike) + (riskFreeRate + 0.5 * volatility * volatility) * optionMaturity) / (volatility * Math.sqrt(optionMaturity)); final double dMinus = dPlus - volatility * Math.sqrt(optionMaturity); final double delta = Math.exp(-riskFreeRate * optionMaturity) * Math.exp(-0.5*dMinus*dMinus) / (Math.sqrt(2.0 * Math.PI * optionMaturity) * initialStockValue * volatility); return delta; } } /** * Calculates the vega of a digital option under a Black-Scholes model * * @param initialStockValue The initial value of the underlying, i.e., the spot. * @param riskFreeRate The risk free rate of the bank account numerarie. * @param volatility The Black-Scholes volatility. * @param optionMaturity The option maturity T. * @param optionStrike The option strike. * @return The vega of the digital option */ public static double blackScholesDigitalOptionVega( final double initialStockValue, final double riskFreeRate, final double volatility, final double optionMaturity, final double optionStrike) { if(optionStrike <= 0.0 || optionMaturity <= 0.0) { // The Black-Scholes model does not consider it being an option return 0.0; } else { // Calculate vega final double dPlus = (Math.log(initialStockValue / optionStrike) + (riskFreeRate + 0.5 * volatility * volatility) * optionMaturity) / (volatility * Math.sqrt(optionMaturity)); final double dMinus = dPlus - volatility * Math.sqrt(optionMaturity); final double vega = - Math.exp(-riskFreeRate * optionMaturity) * Math.exp(-0.5*dMinus*dMinus) / Math.sqrt(2.0 * Math.PI) * dPlus / volatility; return vega; } } /** * Calculates the rho of a digital option under a Black-Scholes model * * @param initialStockValue The initial value of the underlying, i.e., the spot. * @param riskFreeRate The risk free rate of the bank account numerarie. * @param volatility The Black-Scholes volatility. * @param optionMaturity The option maturity T. * @param optionStrike The option strike. * @return The rho of the digital option */ public static double blackScholesDigitalOptionRho( final double initialStockValue, final double riskFreeRate, final double volatility, final double optionMaturity, final double optionStrike) { if(optionMaturity <= 0.0) { // The Black-Scholes model does not consider it being an option return 0.0; } else if(optionStrike <= 0.0) { final double rho = - optionMaturity * Math.exp(-riskFreeRate * optionMaturity); return rho; } else { // Calculate rho final double dMinus = (Math.log(initialStockValue / optionStrike) + (riskFreeRate - 0.5 * volatility * volatility) * optionMaturity) / (volatility * Math.sqrt(optionMaturity)); final double rho = - optionMaturity * Math.exp(-riskFreeRate * optionMaturity) * NormalDistribution.cumulativeDistribution(dMinus) + Math.sqrt(optionMaturity)/volatility * Math.exp(-riskFreeRate * optionMaturity) * Math.exp(-0.5*dMinus*dMinus) / Math.sqrt(2.0 * Math.PI); return rho; } } /** * Calculate the value of a caplet assuming the Black'76 model. * * @param forward The forward (spot). * @param volatility The Black'76 volatility. * @param optionMaturity The option maturity * @param optionStrike The option strike. * @param periodLength The period length of the underlying forward rate. * @param discountFactor The discount factor corresponding to the payment date (option maturity + period length). * @return Returns the value of a caplet under the Black'76 model */ public static double blackModelCapletValue( final double forward, final double volatility, final double optionMaturity, final double optionStrike, final double periodLength, final double discountFactor) { // May be interpreted as a special version of the Black-Scholes Formula return AnalyticFormulas.blackScholesGeneralizedOptionValue(forward, volatility, optionMaturity, optionStrike, periodLength * discountFactor); } /** * Calculate the implied volatility of a caplet assuming the Black'76 model. * * @param forward The forward (spot). * @param optionMaturity The option maturity * @param optionStrike The option strike. * @param periodLength The period length of the underlying forward rate. * @param discountFactor The discount factor corresponding to the payment date (option maturity + period length). * @param value The value of the caplet. * @return Returns the value of a caplet under the Black'76 model */ public static double blackModelCapletImpliedVolatility( final double forward, final double optionMaturity, final double optionStrike, final double periodLength, final double discountFactor, final double value) { // May be interpreted as a special version of the Black-Scholes Formula return AnalyticFormulas.blackScholesOptionImpliedVolatility(forward, optionMaturity, optionStrike, periodLength * discountFactor, value); } /** * Calculate the value of a digital caplet assuming the Black'76 model. * * @param forward The forward (spot). * @param volatility The Black'76 volatility. * @param periodLength The period length of the underlying forward rate. * @param discountFactor The discount factor corresponding to the payment date (option maturity + period length). * @param optionMaturity The option maturity * @param optionStrike The option strike. * @return Returns the price of a digital caplet under the Black'76 model */ public static double blackModelDigitalCapletValue( final double forward, final double volatility, final double periodLength, final double discountFactor, final double optionMaturity, final double optionStrike) { // May be interpreted as a special version of the Black-Scholes Formula return AnalyticFormulas.blackScholesDigitalOptionValue(forward, 0.0, volatility, optionMaturity, optionStrike) * periodLength * discountFactor; } /** * Calculate the delta of a digital caplet assuming the Black'76 model. * * @param forward The forward (spot). * @param volatility The Black'76 volatility. * @param periodLength The period length of the underlying forward rate. * @param discountFactor The discount factor corresponding to the payment date (option maturity + period length). * @param optionMaturity The option maturity * @param optionStrike The option strike. * @return Returns the price of a digital caplet under the Black'76 model */ public static double blackModelDigitalCapletDelta( final double forward, final double volatility, final double periodLength, final double discountFactor, final double optionMaturity, final double optionStrike) { // May be interpreted as a special version of the Black-Scholes Formula return AnalyticFormulas.blackScholesDigitalOptionDelta(forward, 0.0, volatility, optionMaturity, optionStrike) * periodLength * discountFactor; } /** * Calculate the value of a digital caplet assuming the Black'76 model. * * This method exists for backward compatibility due to a typo in an earlier version. * * @param forward The forward (spot). * @param volatility The Black'76 volatility. * @param periodLength The period length of the underlying forward rate. * @param discountFactor The discount factor corresponding to the payment date (option maturity + period length). * @param optionMaturity The option maturity * @param optionStrike The option strike. * @return Returns the price of a digital caplet under the Black'76 model */ public static double blackModelDgitialCapletValue( final double forward, final double volatility, final double periodLength, final double discountFactor, final double optionMaturity, final double optionStrike) { return AnalyticFormulas.blackModelDigitalCapletValue(forward, volatility, periodLength, discountFactor, optionMaturity, optionStrike); } /** * Calculate the value of a swaption assuming the Black'76 model. * * @param forwardSwaprate The forward (spot) * @param volatility The Black'76 volatility. * @param optionMaturity The option maturity. * @param optionStrike The option strike. * @param swapAnnuity The swap annuity corresponding to the underlying swap. * @return Returns the value of a Swaption under the Black'76 model */ public static double blackModelSwaptionValue( final double forwardSwaprate, final double volatility, final double optionMaturity, final double optionStrike, final double swapAnnuity) { // May be interpreted as a special version of the Black-Scholes Formula return AnalyticFormulas.blackScholesGeneralizedOptionValue(forwardSwaprate, volatility, optionMaturity, optionStrike, swapAnnuity); } /** * Calculates the value of an Exchange option under a generalized Black-Scholes model, i.e., the payoff \( max(S_{1}(T)-S_{2}(T),0) \), * where \( S_{1} \) and \( S_{2} \) follow a log-normal process with constant log-volatility and constant instantaneous correlation. * * The method also handles cases where the forward and/or option strike is negative * and some limit cases where the forward and/or the option strike is zero. * * @param spot1 Value of \( S_{1}(0) \) * @param spot2 Value of \( S_{2}(0) \) * @param volatility1 Volatility of \( \log(S_{1}(t)) \) * @param volatility2 Volatility of \( \log(S_{2}(t)) \) * @param correlation Instantaneous correlation of \( \log(S_{1}(t)) \) and \( \log(S_{2}(t)) \) * @param optionMaturity The option maturity \( T \). * @return Returns the value of a European exchange option under the Black-Scholes model. */ public static double margrabeExchangeOptionValue( final double spot1, final double spot2, final double volatility1, final double volatility2, final double correlation, final double optionMaturity) { final double volatility = Math.sqrt(volatility1*volatility1 + volatility2*volatility2 - 2.0 * volatility1*volatility2*correlation); return blackScholesGeneralizedOptionValue(spot1, volatility, optionMaturity, spot2, 1.0); } /* * Some functions for the Bachelier model. For more see BachelierModel class. */ /** * Calculates the option value of a call, i.e., the payoff max(S(T)-K,0), where S follows a * normal process with numeraire scaled volatility, i.e., a homogeneous Bachelier model * \[ * \mathrm{d} S(t) = r S(t) \mathrm{d} t + \sigma exp(-r (T-t)) \mathrm{d}W(t) * \] * * Considering the numeraire \( N(t) = exp(-r (T-t)) \), this implies that \( F(t) = S(t)/N(t) \) follows * \[ * \mathrm{d} F(t) = \sigma \mathrm{d}W(t) \text{.} * \] * * @param forward The forward of the underlying \( F(0) = S(0)/N(0) = S(0) \exp(r T) \). * @param volatility The Bachelier volatility \( \sigma \) of the forward process. * @param optionMaturity The option maturity T. * @param optionStrike The option strike K. * @param payoffUnit The payoff unit (e.g., the discount factor \( N(0)/N(T) = exp(-r T) \)) * @return Returns the value of a European call option under the Bachelier model. */ public static double bachelierOptionValue( final double forward, final double volatility, final double optionMaturity, final double optionStrike, final double payoffUnit) { return BachelierModel.bachelierOptionValue(forward, volatility, optionMaturity, optionStrike, payoffUnit); } /** * Calculates the option value of a call, i.e., the payoff max(S(T)-K,0), where S follows a * normal process with numeraire scaled volatility, i.e., a homogeneous Bachelier model * \[ * \mathrm{d} S(t) = r S(t) \mathrm{d} t + \sigma exp(-r (T-t)) \mathrm{d}W(t) * \] * Considering the numeraire \( N(t) = exp(-r (T-t)) \), this implies that \( F(t) = S(t)/N(t) \) follows * \[ * \mathrm{d} F(t) = \sigma \mathrm{d}W(t) \text{.} * \] * * @param forward The forward of the underlying \( F(0) = S(0)/N(0) = S(0) \exp(r T) \). * @param volatility The Bachelier volatility \( \sigma \) of the forward process. * @param optionMaturity The option maturity T. * @param optionStrike The option strike K. * @param payoffUnit The payoff unit (e.g., the discount factor \( N(0)/N(T) = exp(-r T) \)) * @return Returns the value of a European call option under the Bachelier model. */ public static RandomVariable bachelierOptionValue( final RandomVariable forward, final RandomVariable volatility, final double optionMaturity, final double optionStrike, final RandomVariable payoffUnit) { return BachelierModel.bachelierOptionValue(forward, volatility, optionMaturity, optionStrike, payoffUnit); } /** * Calculates the Bachelier option implied volatility of a call, i.e., the payoff max(S(T)-K,0), where S follows a * normal process with numeraire scaled volatility, i.e., a homogeneous Bachelier model * \[ * \mathrm{d} S(t) = r S(t) \mathrm{d} t + \sigma exp(-r (T-t)) \mathrm{d}W(t) * \] * Considering the numeraire \( N(t) = exp(-r (T-t)) \), this implies that \( F(t) = S(t)/N(t) \) follows * \[ * \mathrm{d} F(t) = \sigma \mathrm{d}W(t) \text{.} * \] * * @param forward The forward of the underlying. * @param optionMaturity The option maturity T. * @param optionStrike The option strike. If the option strike is &le; 0.0 the method returns the value of the forward contract paying S(T)-K in T. * @param payoffUnit The payoff unit (e.g., the discount factor) * @param optionValue The option value. * @return Returns the implied volatility of a European call option under the Bachelier model. */ public static double bachelierOptionImpliedVolatility( final double forward, final double optionMaturity, final double optionStrike, final double payoffUnit, final double optionValue) { return BachelierModel.bachelierOptionImpliedVolatility(forward, optionMaturity, optionStrike, payoffUnit, optionValue); } /** * Calculates the option delta dV(0)/dS(0) of a call option, i.e., the payoff V(T)=max(S(T)-K,0), where S follows a * normal process with numeraire scaled volatility, i.e., a homogeneous Bachelier model * \[ * \mathrm{d} S(t) = r S(t) \mathrm{d} t + \sigma exp(-r (T-t)) \mathrm{d}W(t) * \] * Considering the numeraire \( N(t) = exp(-r (T-t)) \), this implies that \( F(t) = S(t)/N(t) \) follows * \[ * \mathrm{d} F(t) = \sigma \mathrm{d}W(t) \text{.} * \] * * @param forward The forward of the underlying \( F(0) = S(0)/N(0) = S(0) \exp(r T) \). * @param volatility The Bachelier volatility \( \sigma \) of the forward process. * @param optionMaturity The option maturity T. * @param optionStrike The option strike K. * @param payoffUnit The payoff unit (e.g., the discount factor \( N(0)/N(T) = exp(-r T) \)) * @return Returns the value of the option delta (dV/dS(0)) of a European call option under the Bachelier model. */ public static double bachelierOptionDelta( final double forward, final double volatility, final double optionMaturity, final double optionStrike, final double payoffUnit) { return BachelierModel.bachelierOptionDelta(forward, volatility, optionMaturity, optionStrike, payoffUnit); } /* * CMS Options */ /** * Calculate the value of a CMS option using the Black-Scholes model for the swap rate together with * the Hunt-Kennedy convexity adjustment. * * @param forwardSwaprate The forward swap rate * @param volatility Volatility of the log of the swap rate * @param swapAnnuity The swap annuity * @param optionMaturity The option maturity * @param swapMaturity The swap maturity * @param payoffUnit The payoff unit, e.g., the discount factor corresponding to the payment date * @param optionStrike The option strike * @return Value of the CMS option */ public static double huntKennedyCMSOptionValue( final double forwardSwaprate, final double volatility, final double swapAnnuity, final double optionMaturity, final double swapMaturity, final double payoffUnit, final double optionStrike) { final double a = 1.0/swapMaturity; final double b = (payoffUnit / swapAnnuity - a) / forwardSwaprate; final double convexityAdjustment = Math.exp(volatility*volatility*optionMaturity); final double valueUnadjusted = blackModelSwaptionValue(forwardSwaprate, volatility, optionMaturity, optionStrike, swapAnnuity); final double valueAdjusted = blackModelSwaptionValue(forwardSwaprate * convexityAdjustment, volatility, optionMaturity, optionStrike, swapAnnuity); return a * valueUnadjusted + b * forwardSwaprate * valueAdjusted; } /** * Calculate the value of a CMS strike using the Black-Scholes model for the swap rate together with * the Hunt-Kennedy convexity adjustment. * * @param forwardSwaprate The forward swap rate * @param volatility Volatility of the log of the swap rate * @param swapAnnuity The swap annuity * @param optionMaturity The option maturity * @param swapMaturity The swap maturity * @param payoffUnit The payoff unit, e.g., the discount factor corresponding to the payment date * @param optionStrike The option strike * @return Value of the CMS strike */ public static double huntKennedyCMSFloorValue( final double forwardSwaprate, final double volatility, final double swapAnnuity, final double optionMaturity, final double swapMaturity, final double payoffUnit, final double optionStrike) { final double huntKennedyCMSOptionValue = huntKennedyCMSOptionValue(forwardSwaprate, volatility, swapAnnuity, optionMaturity, swapMaturity, payoffUnit, optionStrike); // A floor is an option plus the strike (max(X,K) = max(X-K,0) + K) return huntKennedyCMSOptionValue + optionStrike * payoffUnit; } /** * Calculate the adjusted forward swaprate corresponding to a change of payoff unit from the given swapAnnuity to the given payoffUnit * using the Black-Scholes model for the swap rate together with the Hunt-Kennedy convexity adjustment. * * @param forwardSwaprate The forward swap rate * @param volatility Volatility of the log of the swap rate * @param swapAnnuity The swap annuity * @param optionMaturity The option maturity * @param swapMaturity The swap maturity * @param payoffUnit The payoff unit, e.g., the discount factor corresponding to the payment date * @return Convexity adjusted forward rate */ public static double huntKennedyCMSAdjustedRate( final double forwardSwaprate, final double volatility, final double swapAnnuity, final double optionMaturity, final double swapMaturity, final double payoffUnit) { final double a = 1.0/swapMaturity; final double b = (payoffUnit / swapAnnuity - a) / forwardSwaprate; final double convexityAdjustment = Math.exp(volatility*volatility*optionMaturity); final double rateUnadjusted = forwardSwaprate; final double rateAdjusted = forwardSwaprate * convexityAdjustment; return (a * rateUnadjusted + b * forwardSwaprate * rateAdjusted) * swapAnnuity / payoffUnit; } /** * Calculated the approximation to the lognormal Black volatility using the * standard SABR model and the standard Hagan approximation. * * @param alpha initial value of the stochastic volatility process of the SABR model. * @param beta CEV parameter of the SABR model. * @param rho Correlation (leverages) of the stochastic volatility. * @param nu Volatility of the stochastic volatility (vol-of-vol). * @param underlying Underlying (spot) value. * @param strike Strike. * @param maturity Maturity. * @return Implied lognormal Black volatility. */ public static double sabrHaganLognormalBlackVolatilityApproximation(final double alpha, final double beta, final double rho, final double nu, final double underlying, final double strike, final double maturity) { return sabrHaganLognormalBlackVolatilityApproximation(alpha, beta, rho, nu, 0.0, underlying, strike, maturity); } /** * Calculated the approximation to the lognormal Black volatility using the * standard SABR model and the standard Hagan approximation. * * @param alpha initial value of the stochastic volatility process of the SABR model. * @param beta CEV parameter of the SABR model. * @param rho Correlation (leverages) of the stochastic volatility. * @param nu Volatility of the stochastic volatility (vol-of-vol). * @param displacement The displacement parameter d. * @param underlying Underlying (spot) value. * @param strike Strike. * @param maturity Maturity. * @return Implied lognormal Black volatility. */ public static double sabrHaganLognormalBlackVolatilityApproximation(final double alpha, final double beta, final double rho, final double nu, final double displacement, double underlying, double strike, final double maturity) { if(alpha <= 0) { throw new IllegalArgumentException("&alpha; must be greater than 0."); } if(rho > 1 || rho < -1) { throw new IllegalArgumentException("&rho; must be between -1 and 1."); } if(nu <= 0) { throw new IllegalArgumentException("&nu; must be greater than 0."); } if(underlying <= 0) { throw new IllegalArgumentException("Approximation not definied for non-positive underlyings."); } // Apply displacement. Displaced model is just a shift on underlying and strike. underlying += displacement; strike += displacement; if(Math.abs(underlying - strike) < 0.0001 * (1+Math.abs(underlying))) { /* * ATM case - we assume underlying = strike */ final double term1 = alpha / (Math.pow(underlying,1-beta)); final double term2 = Math.pow(1-beta,2)/24 * Math.pow(alpha,2)/Math.pow(underlying,2*(1-beta)) + rho*beta*alpha*nu/(4*Math.pow(underlying,1-beta)) + (2-3*rho*rho)*nu*nu/24; return term1 * (1+ term2 * maturity); } else{ /* * General non-ATM case no prob with log(F/K) */ final double forwardTimesStrike = underlying * strike; final double z = nu/alpha * Math.pow(forwardTimesStrike, (1-beta)/2) * Math.log(underlying / strike); final double x = Math.log((Math.sqrt(1- 2*rho * z + z*z) + z - rho)/(1 - rho)); final double term1 = alpha / Math.pow(forwardTimesStrike,(1-beta)/2) / (1 + Math.pow(1-beta,2)/24*Math.pow(Math.log(underlying/strike),2) + Math.pow(1-beta,4)/1920 * Math.pow(Math.log(underlying/strike),4)); final double term2 = (Math.abs(x-z) < 1E-10) ? 1 : z / x; final double term3 = 1 + (Math.pow(1 - beta,2)/24 *Math.pow(alpha, 2)/Math.pow(forwardTimesStrike, 1-beta) + rho*beta*nu*alpha / 4 / Math.pow(forwardTimesStrike, (1-beta)/2) + (2-3*rho*rho)/24 * nu*nu) *maturity; return term1 * term2 * term3; } } /** * Return the implied normal volatility (Bachelier volatility) under a SABR model using the * approximation of Berestycki. * * @param alpha initial value of the stochastic volatility process of the SABR model. * @param beta CEV parameter of the SABR model. * @param rho Correlation (leverages) of the stochastic volatility. * @param nu Volatility of the stochastic volatility (vol-of-vol). * @param displacement The displacement parameter d. * @param underlying Underlying (spot) value. * @param strike Strike. * @param maturity Maturity. * @return The implied normal volatility (Bachelier volatility) */ public static double sabrBerestyckiNormalVolatilityApproximation(final double alpha, final double beta, final double rho, final double nu, final double displacement, double underlying, double strike, final double maturity) { // Apply displacement. Displaced model is just a shift on underlying and strike. underlying += displacement; strike += displacement; final double forwardStrikeAverage = (underlying+strike) / 2.0; // Original paper uses a geometric average here double z; if(beta < 1.0) { z = nu / alpha * (Math.pow(underlying, 1.0-beta) - Math.pow(strike, 1.0-beta)) / (1.0-beta); } else { z = nu / alpha * Math.log(underlying/strike); } final double x = Math.log((Math.sqrt(1.0 - 2.0*rho*z + z*z) + z - rho) / (1.0-rho)); double term1; if(Math.abs(underlying - strike) < 1E-10 * (1+Math.abs(underlying))) { // ATM case - we assume underlying = strike term1 = alpha * Math.pow(underlying, beta); } else if(x == 0) { // x ~ z for z small if(beta < 1.0) { term1 = (underlying-strike) * alpha / (Math.pow(underlying, 1.0-beta) - Math.pow(strike, 1.0-beta)) / (1.0-beta); } else { term1 = (underlying-strike) * alpha / Math.log(underlying/strike); } } else { term1 = nu * (underlying-strike) / x; } final double sigma = term1 * (1.0 + maturity * ((-beta*(2-beta)*alpha*alpha)/(24*Math.pow(forwardStrikeAverage,2.0*(1.0-beta))) + beta*alpha*rho*nu / (4*Math.pow(forwardStrikeAverage,(1.0-beta))) + (2.0 -3.0*rho*rho)*nu*nu/24)); return Math.max(sigma, 0.0); } /** * Return the implied normal volatility (Bachelier volatility) under a SABR model using the * approximation of Hagan. * * @param alpha initial value of the stochastic volatility process of the SABR model. * @param beta CEV parameter of the SABR model. * @param rho Correlation (leverages) of the stochastic volatility. * @param nu Volatility of the stochastic volatility (vol-of-vol). * @param displacement The displacement parameter d. * @param underlying Underlying (spot) value. * @param strike Strike. * @param maturity Maturity. * @return The implied normal volatility (Bachelier volatility) */ public static double sabrNormalVolatilityApproximation(final double alpha, final double beta, final double rho, final double nu, final double displacement, double underlying, double strike, final double maturity) { // Apply displacement. Displaced model is just a shift on underlying and strike. underlying += displacement; strike += displacement; final double forwardStrikeAverage = (underlying+strike) / 2.0; final double z = nu / alpha * (underlying-strike) / Math.pow(forwardStrikeAverage, beta); final double x = Math.log((Math.sqrt(1.0 - 2.0*rho*z + z*z) + z - rho) / (1.0-rho)); double term1; if(Math.abs(underlying - strike) < 1E-8 * (1+Math.abs(underlying))) { // ATM case - we assume underlying = strike term1 = alpha * Math.pow(underlying, beta); } else { final double z2 = (1.0 - beta) / (Math.pow(underlying, 1.0-beta) - Math.pow(strike, 1.0-beta)); term1 = alpha * z2 * z * (underlying-strike) / x; } final double sigma = term1 * (1.0 + maturity * ((-beta*(2-beta)*alpha*alpha)/(24*Math.pow(forwardStrikeAverage,2.0*(1.0-beta))) + beta*alpha*rho*nu / (4*Math.pow(forwardStrikeAverage,(1.0-beta))) + (2.0 -3.0*rho*rho)*nu*nu/24)); return Math.max(sigma, 0.0); } /** * Return the parameter alpha (initial value of the stochastic vol process) of a SABR model using the * to match the given at-the-money volatility. * * @param normalVolatility ATM volatility to match. * @param beta CEV parameter of the SABR model. * @param rho Correlation (leverages) of the stochastic volatility. * @param nu Volatility of the stochastic volatility (vol-of-vol). * @param displacement The displacement parameter d. * @param underlying Underlying (spot) value. * @param maturity Maturity. * @return The implied normal volatility (Bachelier volatility) */ public static double sabrAlphaApproximation(final double normalVolatility, final double beta, final double rho, final double nu, final double displacement, double underlying, final double maturity) { // Apply displacement. Displaced model is just a shift on underlying and strike. underlying += displacement; // ATM case. final double forwardStrikeAverage = underlying; final double guess = normalVolatility/Math.pow(underlying, beta); final NewtonsMethod search = new NewtonsMethod(guess); while(!search.isDone() && search.getAccuracy() > 1E-16 && search.getNumberOfIterations() < 100) { final double alpha = search.getNextPoint(); final double term1 = alpha * Math.pow(underlying, beta); final double term2 = (1.0 + maturity * ((-beta*(2-beta)*alpha*alpha)/(24*Math.pow(forwardStrikeAverage,2.0*(1.0-beta))) + beta*alpha*rho*nu / (4*Math.pow(forwardStrikeAverage,(1.0-beta))) + (2.0 -3.0*rho*rho)*nu*nu/24)); final double derivativeTerm1 = Math.pow(underlying, beta); final double derivativeTerm2 = maturity * (2*(-beta*(2-beta)*alpha)/(24*Math.pow(forwardStrikeAverage,2.0*(1.0-beta))) + beta*rho*nu / (4*Math.pow(forwardStrikeAverage,(1.0-beta)))); final double sigma = term1 * term2; final double derivative = derivativeTerm1 * term2 + term1 * derivativeTerm2; search.setValueAndDerivative(sigma-normalVolatility, derivative); } return search.getBestPoint(); } /** * Return the skew of the implied normal volatility (Bachelier volatility) under a SABR model using the * approximation of Berestycki. The skew is the first derivative of the implied vol w.r.t. the strike, * evaluated at the money. * * @param alpha initial value of the stochastic volatility process of the SABR model. * @param beta CEV parameter of the SABR model. * @param rho Correlation (leverages) of the stochastic volatility. * @param nu Volatility of the stochastic volatility (vol-of-vol). * @param displacement The displacement parameter d. * @param underlying Underlying (spot) value. * @param maturity Maturity. * @return The skew of the implied normal volatility (Bachelier volatility) */ public static double sabrNormalVolatilitySkewApproximation(final double alpha, final double beta, final double rho, final double nu, final double displacement, double underlying, final double maturity) { final double sigma = sabrBerestyckiNormalVolatilityApproximation(alpha, beta, rho, nu, displacement, underlying, underlying, maturity); // Apply displacement. Displaced model is just a shift on underlying and strike. underlying += displacement; final double a = alpha/Math.pow(underlying, 1-beta); final double c = 1.0/24*Math.pow(a, 3)*beta*(1.0-beta); final double skew = + (rho*nu/a + beta) * (1.0/2.0*sigma/underlying) - maturity*c*(3.0*rho*nu/a + beta - 2.0); // Some alternative representations // double term1dterm21 = (beta*(2-beta)*alpha*alpha*alpha)/24*Math.pow(underlying,-3.0*(1.0-beta)) * (1.0-beta); // double term1dterm22 = beta*alpha*alpha*rho*nu / 4 * Math.pow(underlying,-2.0*(1.0-beta)) * -(1.0-beta) * 0.5; // skew = + 1.0/2.0*sigma/underlying*(rho*nu/alpha * Math.pow(underlying, 1-beta) + beta) + maturity * (term1dterm21+term1dterm22); // skew = + (rho*nu/a + beta) * (1.0/2.0*sigma/underlying - maturity*3.0*c) + maturity*2.0*c*(1+beta); // skew = + (rho*nu/a + beta) * (1.0/2.0*sigma/underlying - maturity*c) - maturity*c*(2.0*rho*nu/a - 2.0); // The follwoing may be used as approximations (for beta=0 the approximation is exact). // double approximation = (rho*nu/a + beta) * (1.0/2.0*sigma/underlying); // double residual = skew - approximation; return skew; } /** * Return the curvature of the implied normal volatility (Bachelier volatility) under a SABR model using the * approximation of Berestycki. The curvatures is the second derivative of the implied vol w.r.t. the strike, * evaluated at the money. * * @param alpha initial value of the stochastic volatility process of the SABR model. * @param beta CEV parameter of the SABR model. * @param rho Correlation (leverages) of the stochastic volatility. * @param nu Volatility of the stochastic volatility (vol-of-vol). * @param displacement The displacement parameter d. * @param underlying Underlying (spot) value. * @param maturity Maturity. * @return The curvature of the implied normal volatility (Bachelier volatility) */ public static double sabrNormalVolatilityCurvatureApproximation(final double alpha, final double beta, final double rho, final double nu, final double displacement, double underlying, final double maturity) { final double sigma = sabrBerestyckiNormalVolatilityApproximation(alpha, beta, rho, nu, displacement, underlying, underlying, maturity); // Apply displacement. Displaced model is just a shift on underlying and strike. underlying += displacement; /* double d1xdz1 = 1.0; double d2xdz2 = rho; double d3xdz3 = 3.0*rho*rho-1.0; double d1zdK1 = -nu/alpha * Math.pow(underlying, -beta); double d2zdK2 = + nu/alpha * beta * Math.pow(underlying, -beta-1.0); double d3zdK3 = - nu/alpha * beta * (1.0+beta) * Math.pow(underlying, -beta-2.0); double d1xdK1 = d1xdz1*d1zdK1; double d2xdK2 = d2xdz2*d1zdK1*d1zdK1 + d1xdz1*d2zdK2; double d3xdK3 = d3xdz3*d1zdK1*d1zdK1*d1zdK1 + 3.0*d2xdz2*d2zdK2*d1zdK1 + d1xdz1*d3zdK3; double term1 = alpha * Math.pow(underlying, beta) / nu; */ final double d2Part1dK2 = nu * ((1.0/3.0 - 1.0/2.0 * rho * rho) * nu/alpha * Math.pow(underlying, -beta) + (1.0/6.0 * beta*beta - 2.0/6.0 * beta) * alpha/nu*Math.pow(underlying, beta-2)); final double d0BdK0 = (-1.0/24.0 *beta*(2-beta)*alpha*alpha*Math.pow(underlying, 2*beta-2) + 1.0/4.0 * beta*alpha*rho*nu*Math.pow(underlying, beta-1.0) + (2.0 -3.0*rho*rho)*nu*nu/24); final double d1BdK1 = (-1.0/48.0 *beta*(2-beta)*(2*beta-2)*alpha*alpha*Math.pow(underlying, 2*beta-3) + 1.0/8.0 * beta*(beta-1.0)*alpha*rho*nu*Math.pow(underlying, beta-2)); final double d2BdK2 = (-1.0/96.0 *beta*(2-beta)*(2*beta-2)*(2*beta-3)*alpha*alpha*Math.pow(underlying, 2*beta-4) + 1.0/16.0 * beta*(beta-1)*(beta-2)*alpha*rho*nu*Math.pow(underlying, beta-3)); final double curvatureApproximation = nu/alpha * ((1.0/3.0 - 1.0/2.0 * rho * rho) * sigma*nu/alpha * Math.pow(underlying, -2*beta)); final double curvaturePart1 = nu/alpha * ((1.0/3.0 - 1.0/2.0 * rho * rho) * sigma*nu/alpha * Math.pow(underlying, -2*beta) + (1.0/6.0 * beta*beta - 2.0/6.0 * beta) * sigma*alpha/nu*Math.pow(underlying, -2)); final double curvatureMaturityPart = (rho*nu + alpha*beta*Math.pow(underlying, beta-1))*d1BdK1 + alpha*Math.pow(underlying, beta)*d2BdK2; return (curvaturePart1 + maturity * curvatureMaturityPart); } public static double volatilityConversionLognormalATMtoNormalATM(final double forward, final double displacement, final double optionMaturity, final double lognormalVolatility) { final double x = lognormalVolatility * Math.sqrt(optionMaturity / 8); final double y = org.apache.commons.math3.special.Erf.erf(x); final double normalVol = Math.sqrt(2*Math.PI / optionMaturity) * (forward+displacement) * y; return normalVol; } /** * Numerical conversion of displaced lognormal volatility to normal volatility. * * @param forward The forward. * @param displacement The displacement (considering a displaced lognormal model, otherwise 0. * @param optionMaturity The maturity. * @param optionStrike The strike. * @param lognormalVolatility The (implied) lognormal volatility. * @return The (implied) normal volatility. */ public static double volatilityConversionLognormalToNormal(final double forward, final double displacement, final double optionMaturity, final double optionStrike, final double lognormalVolatility) { final double payoffUnit = 1.0; // does not matter in this conversion final double optionValue = blackScholesGeneralizedOptionValue(forward+displacement, lognormalVolatility, optionMaturity, optionStrike+displacement, payoffUnit); final double impliedNormalVolatility = bachelierOptionImpliedVolatility(forward, optionMaturity, optionStrike, payoffUnit, optionValue); return impliedNormalVolatility; } /** * Re-implementation of the Excel PRICE function (a rather primitive bond price formula). * The re-implementation is not exact, because this function does not consider daycount conventions. * * @param settlementDate Valuation date. * @param maturityDate Maturity date of the bond. * @param coupon Coupon payment. * @param yield Yield (discount factor, using frequency: 1/(1 + yield/frequency). * @param redemption Redemption (notional repayment). * @param frequency Frequency (1,2,4). * @return price Clean price. */ public static double price( final java.util.Date settlementDate, final java.util.Date maturityDate, final double coupon, final double yield, final double redemption, final int frequency) { double price = 0.0; if(maturityDate.after(settlementDate)) { price += redemption; } final Calendar paymentDate = Calendar.getInstance(); paymentDate.setTime(maturityDate); while(paymentDate.after(settlementDate)) { price += coupon; // Discount back price /= 1.0 + yield / frequency; paymentDate.add(Calendar.MONTH, -12/frequency); } final Calendar periodEndDate = (Calendar)paymentDate.clone(); periodEndDate.add(Calendar.MONTH, +12/frequency); // Accrue running period final double accrualPeriod = (paymentDate.getTimeInMillis() - settlementDate.getTime()) / (periodEndDate.getTimeInMillis() - paymentDate.getTimeInMillis()); price *= Math.pow(1.0 + yield / frequency, accrualPeriod); price -= coupon * accrualPeriod; return price; } /** * Re-implementation of the Excel PRICE function (a rather primitive bond price formula). * The re-implementation is not exact, because this function does not consider daycount conventions. * We assume we have (int)timeToMaturity/frequency future periods and the running period has * an accrual period of timeToMaturity - frequency * ((int)timeToMaturity/frequency). * * @param timeToMaturity The time to maturity. * @param coupon Coupon payment. * @param yield Yield (discount factor, using frequency: 1/(1 + yield/frequency). * @param redemption Redemption (notional repayment). * @param frequency Frequency (1,2,4). * @return price Clean price. */ public static double price( final double timeToMaturity, final double coupon, final double yield, final double redemption, final int frequency) { double price = 0.0; if(timeToMaturity > 0) { price += redemption; } double paymentTime = timeToMaturity; while(paymentTime > 0) { price += coupon; // Discount back price = price / (1.0 + yield / frequency); paymentTime -= 1.0 / frequency; } // Accrue running period final double accrualPeriod = 0.0- paymentTime; price *= Math.pow(1.0 + yield / frequency, accrualPeriod); price -= coupon * accrualPeriod; return price; } /** * Calculates the vega of a call, i.e., the payoff max(S(T)-K,0) P, where S follows a * normal process with constant volatility, i.e., a Bachelier model * \[ * \mathrm{d} S(t) = r S(t) \mathrm{d} t + \sigma \mathrm{d}W(t) * \] * * @param forward The forward of the underlying \( F = S(0) \exp(r T) \). * @param volatility The Bachelier volatility \( \sigma \). * @param optionMaturity The option maturity T. * @param optionStrike The option strike. * @param payoffUnit The payoff unit (e.g., the discount factor) * @return Returns the vega of a European call option under the Bachelier model. */ public static double bachelierGeneralizedOptionVega( final double forward, final double volatility, final double optionMaturity, final double optionStrike, final double payoffUnit) { if(optionMaturity < 0) { return 0; } else if(forward == optionStrike) { return Math.sqrt(optionMaturity / (Math.PI * 2.0)) * payoffUnit; } else { // Calculate analytic value final double dPlus = (forward - optionStrike) / (volatility * Math.sqrt(optionMaturity)); final double vegaAnalytic = Math.sqrt(optionMaturity) * NormalDistribution.density(dPlus) * payoffUnit; return vegaAnalytic; } } /** * Calculates the vega of a call, i.e., the payoff max(S(T)-K,0) P, where S follows a * normal process with constant volatility, i.e., a Black-Scholes model * \[ * \mathrm{d} S(t) = r S(t) \mathrm{d} t + \sigma S(t)\mathrm{d}W(t) * \] * * @param forward The forward of the underlying \( F = S(0) \exp(r T) \). * @param volatility The Black-Scholes volatility \( \sigma \). * @param optionMaturity The option maturity T. * @param optionStrike The option strike. * @param payoffUnit The payoff unit (e.g., the discount factor) * @return Returns the vega of a European call option under the Black-Scholes model. */ public static double blackScholesGeneralizedOptionVega( final double forward, final double volatility, final double optionMaturity, final double optionStrike, final double payoffUnit) { if(optionStrike <= 0.0 || optionMaturity <= 0.0) { // The Black-Scholes model does not consider it being an option return 0.0; } else { // Calculate vega final double dPlus = (Math.log(forward / optionStrike) + (0.5 * volatility * volatility) * optionMaturity) / (volatility * Math.sqrt(optionMaturity)); final double vega = payoffUnit * NormalDistribution.density(dPlus) * forward * Math.sqrt(optionMaturity); return vega; } } /** * Calculates the CEV option value of a call, i.e., the payoff max(S(T)-K,0), where S follows a CEV process. * Formula is from 2007 - Hsu Lin Lee - 'Constant Elasticity of Variance Option Pricing Model'. * CEV exponent must be between 0 and 1. * * @author Ralph Rudd * * @param initialStockValue The spot value of the underlying. * @param riskFreeRate The risk free rate r (df = exp(-r T)). * @param volatility The CEV volatility (NOT the log-normal volatility). * @param exponent The exponent of S in the diffusion term. * @param optionMaturity The option maturity T. * @param optionStrike The option strike. * @param isCall If true, the value of a call is calculated, if false, the value of a put is calculated. * @return Returns the value of a European call option under the CEV model. */ public static double constantElasticityOfVarianceOptionValue( double initialStockValue, double riskFreeRate, double volatility, double exponent, double optionMaturity, double optionStrike, boolean isCall) { final double kappa = 2 * riskFreeRate / (Math.pow(volatility, 2) * (1 - exponent) * (Math.exp(2 * riskFreeRate * (1 - exponent) * optionMaturity) - 1)); final double z = 2 + 1 / (1 - exponent); final double y = kappa * Math.pow(optionStrike, 2 * (1 - exponent)); final double x = kappa * Math.pow(initialStockValue, 2 * (1 - exponent)) * Math.exp(2 * riskFreeRate * (1 - exponent) * optionMaturity); final NonCentralChiSquaredDistribution P1 = new NonCentralChiSquaredDistribution(z, x); final NonCentralChiSquaredDistribution P2 = new NonCentralChiSquaredDistribution(z - 2, y); if (isCall) { return initialStockValue * (1 - P1.cumulativeDistribution(y)) - optionStrike * Math.exp(-riskFreeRate * optionMaturity) * P2.cumulativeDistribution(x); } else { return -initialStockValue * P1.cumulativeDistribution(y) + optionStrike * Math.exp(-riskFreeRate * optionMaturity) * (1 - P2.cumulativeDistribution(x)); } } }
package ca.ualberta.papaya; import android.app.Activity; import android.content.Intent; import android.graphics.Bitmap; import android.os.Bundle; import android.provider.MediaStore; import android.support.v7.app.ActionBar; import android.support.v7.widget.Toolbar; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import com.google.android.gms.maps.model.LatLng; import ca.ualberta.papaya.controllers.AddThingController; public class AddPictureActivity extends AbstractPapayaActivity { private Intent intent; private Bitmap picture; private Bitmap undoPicture; private MenuItem takePicture; private MenuItem save; private MenuItem delete; private ImageView image; private int UNDO = 0; public static final String PICTURE_EXTRA = "ca.papaya.ualberta.edit.Picture"; private static final int REQUEST_CAPTURING_IMAGE = 1234; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_add_picture); image = (ImageView) findViewById(R.id.picture); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); ActionBar actionBar = getSupportActionBar(); if (actionBar != null) { actionBar.setDisplayHomeAsUpEnabled(true); actionBar.setDisplayShowTitleEnabled(false); } toolbar.setNavigationIcon(R.drawable.ic_action_home); intent = getIntent(); picture = intent.getParcelableExtra(PICTURE_EXTRA); updateView(); } // Button for saving the current picture to the selected thing void savePic() { Intent returnIntent = new Intent(); returnIntent.putExtra(PICTURE_EXTRA, picture); setResult(Activity.RESULT_OK, returnIntent); finish(); } // Button for taking a new picture void takePic() { Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); if (intent.resolveActivity(getPackageManager()) != null) { startActivityForResult(intent, REQUEST_CAPTURING_IMAGE); } } // button for deleting the picture // may put in a undo feature void deletePic() { if (UNDO == 0) { //delete undoPicture = picture; picture = null; //updateView(); UNDO = 1; delete.setTitle("Undo"); } else { //redo picture = undoPicture; undoPicture = null; //updateView(); UNDO = 0; delete.setTitle("Delete"); } //picture = null; updateView(); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_add_picture, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.takePicture: // EITHER CALL THE METHOD HERE OR DO THE FUNCTION DIRECTLY takePic(); return true; case R.id.saveButton: savePic(); return true; case R.id.deleteButton: deletePic(); return true; default: return super.onOptionsItemSelected(item); } } // @Override // public boolean onPrepareOptionsMenu(Menu menu) { // super.onPrepareOptionsMenu(menu); // takePicture = menu.findItem(R.id.takePicture); // takePicture.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() { // @Override // public boolean onMenuItemClick(MenuItem item) { // takePic(); // return true; // save = menu.findItem(R.id.saveButton); // save.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() { // @Override // public boolean onMenuItemClick(MenuItem item) { // savePic(); // return true; // delete = menu.findItem(R.id.deleteButton); // delete.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() { // @Override // public boolean onMenuItemClick(MenuItem item) { // deletePic(); // return true; // return true; @Override protected void onStart() { super.onStart(); intent = getIntent(); if(picture == null) { picture = intent.getParcelableExtra(PICTURE_EXTRA); } updateView(); } private void updateView(){ if(picture != null){ image.setImageBitmap(picture); } else { image.setImageResource(android.R.color.transparent); } } //save the newly taken picture and update the view @Override protected void onActivityResult( int requestCode, int resultCode, Intent data){ if(requestCode == REQUEST_CAPTURING_IMAGE && resultCode == RESULT_OK){ Bundle extras = intent.getExtras(); picture = (Bitmap) extras.get("data"); updateView(); } } }
package net.liquidpineapple.pang.screens; import net.liquidpineapple.pang.Application; import net.liquidpineapple.pang.gui.Board; import net.liquidpineapple.pang.gui.NumberToken; import net.liquidpineapple.pang.gui.ScoreSystem; import net.liquidpineapple.pang.gui.TimeSystem; import net.liquidpineapple.pang.objects.Ball; import net.liquidpineapple.pang.objects.BallMovement; import net.liquidpineapple.pang.objects.GameObject; import net.liquidpineapple.pang.objects.Player; import net.liquidpineapple.pang.objects.playerschemes.Player1; import net.liquidpineapple.pang.objects.playerschemes.Player2; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; import java.awt.Graphics2D; import java.awt.image.ImageObserver; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.LinkedList; import javax.imageio.ImageIO; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; /** * Class that represents a level. * @author Govert de Gans * @date 2016-09-07 */ public class Level extends Screen { private LinkedList<GameObject> hudObjectList; public Level() { super(); hudObjectList = new LinkedList<GameObject>(); } /** * Method that parses a XML-file into a level. * * @param xmlFile - path/filename of the XML-file that should be parsed. * @return - returns a new level. */ public static Level createFromXml(String xmlFile) throws IOException, ParserConfigurationException, SAXException { Level output = new Level(); if (createFileReader(xmlFile) != null) { Document doc = createFileReader(xmlFile); String backgroundPath = "/sprites/" + doc.getElementsByTagName("background").item(0).getTextContent(); output.backgroundImage = ImageIO.read(Level.class.getResource(backgroundPath)); for (Ball ball : loadBalls(doc.getElementsByTagName("ball"))) { output.objectList.add(ball); } for (Player player : loadPlayer(doc.getElementsByTagName("player"))) { output.objectList.add(player); } TimeSystem.resetTime(loadTime(doc)); for (NumberToken token : TimeSystem.getTimePlaces()) { output.hudObjectList.add(token); } } for (NumberToken token : ScoreSystem.getPlaces()) { output.hudObjectList.add(token); } Application.lifeSystem.updateLifes(); output.hudObjectList.add(Application.lifeSystem); return output; } /** * Method that reads the balls from the XML-file and parses them into Ball objects. * * @param ballList - NodeList of the different balls to be parsed. * @return - Arraylist with Ball objects. */ public static ArrayList<Ball> loadBalls(NodeList ballList) { ArrayList<Ball> ballArray = new ArrayList<>(); for (int i = 0; i < ballList.getLength(); i++) { Node ballNode = ballList.item(i); Element ballElement = (Element) ballNode; int intXpos = Integer.parseInt(ballElement.getElementsByTagName("x") .item(0).getTextContent()); int intYpos = Integer.parseInt(ballElement.getElementsByTagName("y") .item(0).getTextContent()); int size = Integer.parseInt(ballElement.getElementsByTagName("size").item(0) .getTextContent()); String direction = ballElement.getElementsByTagName("direction").item(0).getTextContent(); BallMovement ballMovement = BallMovement.valueOf(direction); Ball ball = new Ball(intXpos, intYpos, ballMovement, size); ballArray.add(ball); } return ballArray; } /** * Method that reads the players from the XML-file and parses them into Player objects. * Simular to the loadBalls method * * @param playerlist - NodeList of the players that should be parsed. * @return - ArrayList of Player objects. */ public static ArrayList<Player> loadPlayer(NodeList playerlist) { ArrayList<Player> playerArray = new ArrayList<>(); for (int i = 0; i < playerlist.getLength(); i++) { Node playernode = playerlist.item(i); Element playerElement = (Element) playernode; int intXpos = Integer.parseInt(playerElement.getElementsByTagName("x") .item(0).getTextContent()); int intYpos = Integer.parseInt(playerElement.getElementsByTagName("y") .item(0).getTextContent()); if (i == 0) { playerArray.add(new Player(intXpos, intYpos, new Player1())); } else if (i == 1 && Application.multiplayer) { playerArray.add(new Player(intXpos, intYpos, new Player2())); } } return playerArray; } /** * Method to read time form an XML-file. * * @param doc {@link Document} to be read from * @return - returns an int contained in the {@code <time></time>} */ public static int loadTime(Document doc) { return Integer.parseInt(doc.getElementsByTagName("time").item(0).getTextContent()); } /** * Method to create a FileReader to read the XML-file. * * @param xmlFile - Path/name of the XML-file to be parsed. * @return - returns a new FileReader if no exception is thrown, else it will return null. */ public static Document createFileReader(String xmlFile) throws ParserConfigurationException, SAXException { InputStream in = Level.class.getResourceAsStream(xmlFile); DocumentBuilder documentBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); try { return documentBuilder.parse(in); } catch (IOException | IllegalArgumentException ex) { //TODO Fix this shit ex.printStackTrace(); return null; } } @Override /** * Update method for the level class. * Checks if the level is completed and if so, it loads a new level. * Updates all components in level when the level is not ended. */ public void doUpdate() { boolean levelEnded = true; for (GameObject object : objectList) { if (object instanceof Ball) { levelEnded = false; } } if (levelEnded) { try { nextLevel(); } catch (ParserConfigurationException | SAXException ex) { ex.printStackTrace(); } } else { new ArrayList<>(objectList).forEach(GameObject::doUpdate); } } /** * Attempst to load the new level (WIP). */ private void nextLevel() throws ParserConfigurationException, SAXException { Board currentBoard = Application.getBoard(); currentBoard.setLevelCount(currentBoard.getLevelCount() + 1); Screen newScreen = null; String levelLocation = "/levels/level" + currentBoard.getLevelCount() + ".xml"; if (createFileReader(levelLocation) != null) { try { newScreen = Level.createFromXml("/levels/level" + currentBoard.getLevelCount() + ".xml"); } catch (IOException ex) { ex.printStackTrace(); } } else { //set behaviour when all levels have been completed here. newScreen = new WinScreen(); } currentBoard.changeScreen(newScreen); } @Override public void doDrawing(Graphics2D graphics2D, ImageObserver imageObserver) { super.doDrawing(graphics2D, imageObserver); for (GameObject hudObject : hudObjectList) { hudObject.doDrawing(graphics2D, imageObserver); } } }
package net.openhft.chronicle.map; import net.openhft.chronicle.hash.ChronicleHash; import net.openhft.chronicle.hash.function.SerializableFunction; import net.openhft.chronicle.hash.serialization.BytesReader; import net.openhft.lang.io.Bytes; import net.openhft.lang.io.serialization.BytesMarshaller; import net.openhft.lang.model.Byteable; import org.jetbrains.annotations.NotNull; import java.io.Closeable; import java.io.File; import java.io.IOException; import java.io.Serializable; import java.util.Map; import java.util.concurrent.ConcurrentMap; /** * Extension of {@link ConcurrentMap} interface, stores the data off-heap. * * <p>For information on <ul> <li>how to construct a {@code ChronicleMap}</li> <li>{@code * ChronicleMap} flavors and properties</li> <li>available configurations</li> </ul> see {@link * ChronicleMapBuilder} documentation. * * <p>Functionally this interface defines some methods supporting garbage-free off-heap programming: * {@link #getUsing(Object, Object)}, {@link #acquireUsing(Object, Object)}. * * <p>Roughly speaking, {@code ChronicleMap} compares keys and values by their binary serialized * form, that shouldn't necessary be the same equality relation as defined by built-in {@link * Object#equals(Object)} method, which is prescribed by general {@link Map} contract. * * <p>Note that {@code ChronicleMap} extends {@link Closeable}, don't forget to {@linkplain #close() * close} map when it is no longer needed. * * @param <K> the map key type * @param <V> the map value type */ public interface ChronicleMap<K, V> extends ConcurrentMap<K, V>, ChronicleHash<K, MapEntry<K, V>, MapSegmentContext<K, V, ?>, ExternalMapQueryContext<K, V, ?>> { /** * Delegates to {@link ChronicleMapBuilder#of(Class, Class)} for convenience. * * @param keyClass class of the key type of the Chronicle Map to create * @param valueClass class of the value type of the Chronicle Map to create * @param <K> the key type of the Chronicle Map to create * @param <V> the value type of the Chronicle Map to create * @return a new {@code ChronicleMapBuilder} for the given key and value classes */ static <K, V> ChronicleMapBuilder<K, V> of(Class<K> keyClass, Class<V> valueClass) { return ChronicleMapBuilder.of(keyClass, valueClass); } /** * Returns the value to which the specified key is mapped, or {@code null} if this map contains * no mapping for the key. * * <p>If the value class allows reusing, particularly if it is a {@link Byteable} subclass, * consider {@link #getUsing(Object, Object)} method instead of this to reduce garbage * creation. * * @param key the key whose associated value is to be returned * @return the value to which the specified key is mapped after this method call, or {@code * null} if no value is mapped * @see #getUsing(Object, Object) */ @Override V get(Object key); /** * Returns the value to which the specified key is mapped, read to the provided {@code value} * object, if possible, or returns {@code null}, if this map contains no mapping for the key. * * <p>If the specified key is present in the map, the value data is read to the provided {@code * value} object via value marshaller's {@link BytesMarshaller#read(Bytes, Object) read(Bytes, * value)} or value reader's {@link BytesReader#read(Bytes, long, Object) read(Bytes, size, * value)} method, depending on what deserialization strategy is configured on the builder, * using which this map was constructed. If the value deserializer is able to reuse the given * {@code value} object, calling this method instead of {@link #get(Object)} could help to * reduce garbage creation. * * <p>The provided {@code value} object is allowed to be {@code null}, in this case {@code * map.getUsing(key, null)} call is semantically equivalent to simple {@code map.get(key)} * call. * * @param key the key whose associated value is to be returned * @param usingValue the object to read value data in, if possible * @return the value to which the specified key is mapped, or {@code null} if this map contains * no mapping for the key * @see #get(Object) * @see #acquireUsing(Object, Object) * @see ChronicleMapBuilder#valueMarshaller(BytesMarshaller) */ V getUsing(K key, V usingValue); /** * Acquire a value for a key, creating if absent. * * <p>If the specified key is absent in the map, {@linkplain ChronicleMapBuilder#defaultValue( * Object) default value} is taken or {@linkplain ChronicleMapBuilder#defaultValueProvider( * DefaultValueProvider) default value provider} is called. Then this object is put to this map * for the specified key. * * <p>Then, either if the key was initially absent in the map or already present, the value is * deserialized just as during {@link #getUsing(Object, Object) getUsing(key, usingValue)} call, * passed the same {@code key} and {@code usingValue} as into this method call. This means, as * in {@link #getUsing}, {@code usingValue} could safely be {@code null}, in this case a new * value instance is created to deserialize the data. * * <p>In code, {@code acquireUsing} is specified as : * <pre>{@code * V acquireUsing(K key, V usingValue) { * if (!containsKey(key)) * put(key, defaultValue(key)); * return getUsing(key, usingValue); * }}</pre> * * * <p>Where {@code defaultValue(key)} returns either {@linkplain ChronicleMapBuilder#defaultValue(Object) * default value} or {@link ChronicleMapBuilder#defaultValueProvider(DefaultValueProvider) * defaultValueProvider.} * * <p>If the {@code ChronicleMap} is off-heap updatable, i. e. created via {@link * ChronicleMapBuilder} builder (values are {@link Byteable}), there is one more option of what * to do if the key is absent in the map. By default, value bytes are just zeroed out, no * default value, either provided for key or constant, is put for the absent key. * * @param key the key whose associated value is to be returned * @param usingValue the object to read value data in, if present. Can not be null * @return value to which the given key is mapping after this call, either found or created * @see #getUsing(Object, Object) */ V acquireUsing(@NotNull K key, V usingValue); @NotNull net.openhft.chronicle.core.io.Closeable acquireContext(@NotNull K key, @NotNull V usingValue); /** * Returns the result of application of the given function to the value to which the given key * is mapped. If there is no mapping for the key, {@code null} is returned from {@code * getMapped()} call without application of the given function. This method is primarily useful * when accessing {@code ChronicleMap} implementation which delegates it's requests to some * remote node (server) and pulls the result through serialization/deserialization path, and * probably network. In this case, when you actually need only a part of the map value's state * (e. g. a single field) it's cheaper to extract it on the server side and transmit lesser * bytes. * * @param key the key whose associated value is to be queried * @param function a function to transform the value to the actually needed result, * which should be smaller than the map value * @param <R> the result type * @return the result of applying the function to the mapped value, or {@code null} if there * is no mapping for the key */ <R> R getMapped(K key, @NotNull SerializableFunction<? super V, R> function); /** * Exports all the entries to a {@link File} storing them in JSON format, an attempt is * made where possible to use standard java serialisation and keep the data human readable, data * serialized using the custom serialises are converted to a binary format which is not human * readable but this is only done if the Keys or Values are not {@link Serializable}. * This method can be used in conjunction with {@link ChronicleMap#putAll(File)} and is * especially useful if you wish to import/export entries from one chronicle map into another. * This import and export of the entries can be performed even when the versions of ChronicleMap * differ. This method is not performant and as such we recommend it is not used in performance * sensitive code. * * @param toFile the file to store all the entries to, the entries will be stored in JSON * format * @throws IOException its not possible store the data to {@code toFile} * @see ChronicleMap#putAll(File) */ void getAll(File toFile) throws IOException; /** * Imports all the entries from a {@link File}, the {@code fromFile} must be created * using or the same format as {@link ChronicleMap#get(Object)}, this method behaves * similar to {@link Map#put(Object, Object)} where existing * entries are overwritten. A write lock is only held while each individual entry is inserted * into the map, not over all the entries in the {@link File} * * @param fromFile the file containing entries ( in JSON format ) which will be deserialized and * {@link Map#put(Object, Object)} into the map * @throws IOException its not possible read the {@code fromFile} * @see ChronicleMap#getAll(File) */ void putAll(File fromFile) throws IOException; /** * Creates an empty value instance, which can be used with the * following methods : * * {@link ChronicleMap#getUsing(Object, Object) } * {@link ChronicleMap#acquireUsing(Object, Object) } * {@link ChronicleMap#acquireContext(Object, Object)} * * for example like this : * * <pre>{@code * V value = map.newValueInstance(); * try (ReadMapContext rc = map.getUsingLocked(key, value)) { * // add your logic here * } // the read lock is released here * }</pre> * * * @return a new empty instance based on the Value type * @see ChronicleMap#getUsing(Object, Object) * @see ChronicleMap#acquireUsing(Object, Object) * @see ChronicleMap#acquireContext(Object, Object) */ V newValueInstance(); /** * Creates an empty value instance, which can be used with the * following methods : * * {@link ChronicleMap#getUsing(Object, Object) } * {@link ChronicleMap#acquireUsing(Object, Object)} * {@link ChronicleMap#acquireContext(Object, Object)} * * for example like this : * * <pre>{@code * K key = map.newKeyInstance(); * key.setMyStringField("some key"); * * try (ReadMapContext rc = map.getUsingLocked(key, value)) { * // add your logic here * } // the read lock is released here * }</pre> * * * @return a new empty instance based on the Key type * @see ChronicleMap#getUsing(Object, Object) * @see ChronicleMap#acquireUsing(Object, Object) * @see ChronicleMap#acquireContext(Object, Object) */ K newKeyInstance(); /** * @return the class of {@code <V>} */ Class<V> valueClass(); }
package nl.wiegman.home.service; import java.math.BigDecimal; import java.math.RoundingMode; import java.util.ArrayList; import java.util.Calendar; import java.util.Collections; import java.util.Date; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.stream.Collectors; import org.apache.commons.lang3.time.DateUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationEventPublisher; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Service; import nl.wiegman.home.model.Klimaat; import nl.wiegman.home.model.KlimaatSensor; import nl.wiegman.home.model.SensorType; import nl.wiegman.home.realtime.UpdateEvent; import nl.wiegman.home.repository.KlimaatRepos; import nl.wiegman.home.repository.KlimaatSensorRepository; @Service public class KlimaatService { private static final Logger LOG = LoggerFactory.getLogger(KlimaatService.class); private static final String EVERY_15_MINUTES_PAST_THE_HOUR = "0 0/15 * * * ?"; private static final int TEMPERATURE_SCALE = 2; private static final int HUMIDITY_SCALE = 1; private final Map<String, List<Klimaat>> receivedInLastQuarter = new ConcurrentHashMap<>(); @Autowired KlimaatServiceCached klimaatServiceCached; @Autowired KlimaatRepos klimaatRepository; @Autowired KlimaatSensorRepository klimaatSensorRepository; @Autowired ApplicationEventPublisher eventPublisher; @Scheduled(cron = EVERY_15_MINUTES_PAST_THE_HOUR) public void save() { LOG.debug("Running " + this.getClass().getSimpleName() + ".save()"); Date now = new Date(); now = DateUtils.truncate(now, Calendar.MINUTE); for (Map.Entry<String, List<Klimaat>> receivedItem : receivedInLastQuarter.entrySet()) { List<BigDecimal> validTemperaturesFromLastQuarter = getValidTemperaturesFromLastQuarter(receivedItem.getKey()); List<BigDecimal> validHumiditiesFromLastQuarter = getValidHumiditiesFromLastQuarter(receivedItem.getKey()); KlimaatSensor klimaatSensor = receivedItem.getValue().get(0).getKlimaatSensor(); BigDecimal averageTemperature = getAverage(validTemperaturesFromLastQuarter); if (averageTemperature != null) { averageTemperature = averageTemperature.setScale(TEMPERATURE_SCALE, RoundingMode.CEILING); } BigDecimal averageHumidity = getAverage(validHumiditiesFromLastQuarter); if (averageHumidity != null) { averageHumidity = averageHumidity.setScale(HUMIDITY_SCALE, RoundingMode.CEILING); } if (averageTemperature != null || averageHumidity != null) { Klimaat klimaatToSave = new Klimaat(); klimaatToSave.setDatumtijd(now); klimaatToSave.setTemperatuur(averageTemperature); klimaatToSave.setLuchtvochtigheid(averageHumidity); klimaatToSave.setKlimaatSensor(klimaatSensor); klimaatRepository.save(klimaatToSave); } } receivedInLastQuarter.clear(); } public KlimaatSensor getKlimaatSensorByCode(String code) { return klimaatSensorRepository.findFirstByCode(code); } public List<Klimaat> getInPeriod(Date from, Date to) { if (to.before(new Date())) { return klimaatServiceCached.getInPeriod(from, to); } else { return klimaatRepository.findByDatumtijdBetweenOrderByDatumtijd(from, to); } } public BigDecimal getAverage(SensorType sensortype, Date from, Date to) { switch (sensortype) { case TEMPERATUUR: return klimaatRepository.getAverageTemperatuur(from, to); case LUCHTVOCHTIGHEID: return klimaatRepository.getAverageLuchtvochtigheid(from, to); default: return null; } } public Klimaat getMostRecent() { LOG.info("getMostRecent()"); return klimaatRepository.getMostRecent(); } public void add(Klimaat klimaat) { LOG.info("Recieved klimaat"); if (!receivedInLastQuarter.containsKey(klimaat.getKlimaatSensor().getCode())) { receivedInLastQuarter.put(klimaat.getKlimaatSensor().getCode(), new ArrayList<>()); } receivedInLastQuarter.get(klimaat.getKlimaatSensor().getCode()).add(klimaat); eventPublisher.publishEvent(new UpdateEvent(klimaat)); } public List<BigDecimal> getValidHumiditiesFromLastQuarter(String sensorId) { return receivedInLastQuarter.get(sensorId).stream() .filter(klimaat -> klimaat.getLuchtvochtigheid() != null && !BigDecimal.ZERO.equals(klimaat.getLuchtvochtigheid())) .map(klimaat -> klimaat.getLuchtvochtigheid()) .collect(Collectors.toList()); } public List<Klimaat> getHighest(SensorType sensortype, Date from, Date to, int limit) { switch (sensortype) { case TEMPERATUUR: return getHighestTemperature(from, to, limit); case LUCHTVOCHTIGHEID: return getHighestHumidity(from, to, limit); default: return Collections.emptyList(); } } public List<Klimaat> getLowest(SensorType sensortype, Date from, Date to, int limit) { switch (sensortype) { case TEMPERATUUR: return getLowestTemperature(from, to, limit); case LUCHTVOCHTIGHEID: return getLowestHumidity(from, to, limit); default: return null; } } private List<BigDecimal> getValidTemperaturesFromLastQuarter(String sensorId) { return receivedInLastQuarter.get(sensorId).stream() .filter(klimaat -> klimaat.getTemperatuur() != null && !BigDecimal.ZERO.equals(klimaat.getTemperatuur())) .map(klimaat -> klimaat.getTemperatuur()) .collect(Collectors.toList()); } private List<Klimaat> getLowestTemperature(Date from, Date to, int limit) { return klimaatRepository.getPeakLowTemperatureDates(from, to, limit) .stream() .map(date -> klimaatRepository.firstLowestTemperatureOnDay(date)) .collect(Collectors.toList()); } private List<Klimaat> getLowestHumidity(Date from, Date to, int limit) { return klimaatRepository.getPeakLowHumidityDates(from, to, limit) .stream() .map(date -> klimaatRepository.firstLowestHumidityOnDay(date)) .collect(Collectors.toList()); } private BigDecimal getAverage(List<BigDecimal> decimals) { BigDecimal average = null; if (!decimals.isEmpty()) { BigDecimal total = decimals.stream().reduce(BigDecimal.ZERO, BigDecimal::add); average = total.divide(BigDecimal.valueOf(decimals.size()), RoundingMode.CEILING); } return average; } private List<Klimaat> getHighestTemperature(Date from, Date to, int limit) { return klimaatRepository.getPeakHighTemperatureDates(from, to, limit) .stream() .map(date -> klimaatRepository.firstHighestTemperatureOnDay(date)) .collect(Collectors.toList()); } private List<Klimaat> getHighestHumidity(Date from, Date to, int limit) { return klimaatRepository.getPeakHighHumidityDates(from, to, limit) .stream() .map(date -> klimaatRepository.firstHighestHumidityOnDay(date)) .collect(Collectors.toList()); } }
package org.apdplat.superword.tools; import org.apache.commons.dbcp2.*; import org.apache.commons.lang.StringUtils; import org.apache.commons.pool2.ObjectPool; import org.apache.commons.pool2.impl.GenericObjectPool; import org.apdplat.superword.model.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.sql.DataSource; import java.sql.*; import java.util.ArrayList; import java.util.List; /** * * @author */ public class MySQLUtils { private static final Logger LOG = LoggerFactory.getLogger(MySQLUtils.class); private static final String DRIVER = "com.mysql.jdbc.Driver"; private static final String URL = "jdbc:mysql://127.0.0.1:3306/superword?useUnicode=true&characterEncoding=utf8"; private static final String USER = "root"; private static final String PASSWORD = "root"; private static DataSource dataSource = null; static { try { Class.forName(DRIVER); dataSource = setupDataSource(URL, USER, PASSWORD); } catch (ClassNotFoundException e) { LOG.error("MySQL", e); } } private MySQLUtils() { } public static boolean deleteWordDefinition(String word) { String sql = "delete from word_definition where word=?"; Connection con = getConnection(); if(con == null){ return false; } PreparedStatement pst = null; ResultSet rs = null; try { pst = con.prepareStatement(sql); pst.setString(1, word); return pst.execute(); } catch (SQLException e) { LOG.error("", e); } finally { close(con, pst, rs); } return false; } public static String getWordDefinition(String word, String dictionary) { String sql = "select definition from word_definition where word=? and dictionary=?"; Connection con = getConnection(); if(con == null){ return ""; } PreparedStatement pst = null; ResultSet rs = null; try { pst = con.prepareStatement(sql); pst.setString(1, word); pst.setString(2, dictionary); rs = pst.executeQuery(); if (rs.next()) { return rs.getString(1); } } catch (SQLException e) { LOG.error("", e); } finally { close(con, pst, rs); } return ""; } public static void saveWordDefinition(String word, String dictionary, String definition) { String sql = "insert into word_definition (word, dictionary, definition) values (?, ?, ?)"; Connection con = getConnection(); if(con == null){ return ; } PreparedStatement pst = null; ResultSet rs = null; try { pst = con.prepareStatement(sql); pst.setString(1, word); pst.setString(2, dictionary); pst.setString(3, definition); pst.executeUpdate(); } catch (SQLException e) { LOG.error("", e); } finally { close(con, pst, rs); } } public static boolean existUser(User user, String table){ String sql = "select id from "+table+" where user_name=?"; Connection con = getConnection(); if(con == null){ return false; } PreparedStatement pst = null; ResultSet rs = null; try { pst = con.prepareStatement(sql); pst.setString(1, user.getUserName()); rs = pst.executeQuery(); if (rs.next()) { return true; } } catch (SQLException e) { LOG.error("", e); } finally { close(con, pst, rs); } return false; } public static boolean login(User user){ String sql = "select password from user where user_name=?"; Connection con = getConnection(); if(con == null){ return false; } PreparedStatement pst = null; ResultSet rs = null; try { pst = con.prepareStatement(sql); pst.setString(1, user.getUserName()); rs = pst.executeQuery(); if (rs.next()) { String password = rs.getString(1); if(StringUtils.isNotBlank(user.getPassword()) && user.getPassword().equals(password)){ return true; } } } catch (SQLException e) { LOG.error("", e); } finally { close(con, pst, rs); } return false; } public static boolean register(User user) { String sql = "insert into user (user_name, password, date_time) values (?, ?, ?)"; Connection con = getConnection(); if(con == null){ return false; } PreparedStatement pst = null; ResultSet rs = null; try { pst = con.prepareStatement(sql); pst.setString(1, user.getUserName()); pst.setString(2, user.getPassword()); pst.setTimestamp(3, new Timestamp(user.getDateTime().getTime())); pst.executeUpdate(); return true; } catch (SQLException e) { e.printStackTrace(); LOG.error("", e); } finally { close(con, pst, rs); } return false; } public static UserText getUseTextFromDatabase(int id) { String sql = "select id,text,date_time,user_name from user_text where id=?"; Connection con = getConnection(); if(con == null){ return null; } PreparedStatement pst = null; ResultSet rs = null; try { pst = con.prepareStatement(sql); pst.setInt(1, id); rs = pst.executeQuery(); if (rs.next()) { int _id = rs.getInt(1); String text = rs.getString(2); Timestamp timestamp = rs.getTimestamp(3);; String user_name = rs.getString(4); UserText userText = new UserText(); userText.setId(id); userText.setText(text); userText.setDateTime(new java.util.Date(timestamp.getTime())); userText.setUserName(user_name); return userText; } } catch (SQLException e) { LOG.error("", e); } finally { close(con, pst, rs); } return null; } public static List<UserDynamicPrefix> getHistoryUserDynamicPrefixesFromDatabase(String userName) { List<UserDynamicPrefix> userDynamicPrefixes = new ArrayList<>(); String sql = "select id,dynamic_prefix,date_time from user_dynamic_prefix where user_name=?"; Connection con = getConnection(); if(con == null){ return userDynamicPrefixes; } PreparedStatement pst = null; ResultSet rs = null; try { pst = con.prepareStatement(sql); pst.setString(1, userName); rs = pst.executeQuery(); while (rs.next()) { int id = rs.getInt(1); String dynamicPrefix = rs.getString(2); Timestamp timestamp = rs.getTimestamp(3); UserDynamicPrefix userDynamicPrefix = new UserDynamicPrefix(); userDynamicPrefix.setId(id); userDynamicPrefix.setDynamicPrefix(dynamicPrefix); userDynamicPrefix.setDateTime(new java.util.Date(timestamp.getTime())); userDynamicPrefix.setUserName(userName); userDynamicPrefixes.add(userDynamicPrefix); } } catch (SQLException e) { LOG.error("", e); } finally { close(con, pst, rs); } return userDynamicPrefixes; } public static List<UserDynamicSuffix> getHistoryUserDynamicSuffixesFromDatabase(String userName) { List<UserDynamicSuffix> userDynamicSuffixes = new ArrayList<>(); String sql = "select id,dynamic_suffix,date_time from user_dynamic_suffix where user_name=?"; Connection con = getConnection(); if(con == null){ return userDynamicSuffixes; } PreparedStatement pst = null; ResultSet rs = null; try { pst = con.prepareStatement(sql); pst.setString(1, userName); rs = pst.executeQuery(); while (rs.next()) { int id = rs.getInt(1); String dynamicSuffix = rs.getString(2); Timestamp timestamp = rs.getTimestamp(3); UserDynamicSuffix userDynamicSuffix = new UserDynamicSuffix(); userDynamicSuffix.setId(id); userDynamicSuffix.setDynamicSuffix(dynamicSuffix); userDynamicSuffix.setDateTime(new java.util.Date(timestamp.getTime())); userDynamicSuffix.setUserName(userName); userDynamicSuffixes.add(userDynamicSuffix); } } catch (SQLException e) { LOG.error("", e); } finally { close(con, pst, rs); } return userDynamicSuffixes; } public static List<UserSimilarWord> getHistoryUserSimilarWordsFromDatabase(String userName) { List<UserSimilarWord> userSimilarWords = new ArrayList<>(); String sql = "select id,similar_word,date_time from user_similar_word where user_name=?"; Connection con = getConnection(); if(con == null){ return userSimilarWords; } PreparedStatement pst = null; ResultSet rs = null; try { pst = con.prepareStatement(sql); pst.setString(1, userName); rs = pst.executeQuery(); while (rs.next()) { int id = rs.getInt(1); String similarWord = rs.getString(2); Timestamp timestamp = rs.getTimestamp(3); UserSimilarWord userSimilarWord = new UserSimilarWord(); userSimilarWord.setId(id); userSimilarWord.setSimilarWord(similarWord); userSimilarWord.setDateTime(new java.util.Date(timestamp.getTime())); userSimilarWord.setUserName(userName); userSimilarWords.add(userSimilarWord); } } catch (SQLException e) { LOG.error("", e); } finally { close(con, pst, rs); } return userSimilarWords; } public static List<UserBook> getHistoryUserBooksFromDatabase(String userName) { List<UserBook> userBooks = new ArrayList<>(); String sql = "select id,book,date_time from user_book where user_name=?"; Connection con = getConnection(); if(con == null){ return userBooks; } PreparedStatement pst = null; ResultSet rs = null; try { pst = con.prepareStatement(sql); pst.setString(1, userName); rs = pst.executeQuery(); while (rs.next()) { int id = rs.getInt(1); String book = rs.getString(2); Timestamp timestamp = rs.getTimestamp(3); UserBook userBook = new UserBook(); userBook.setId(id); userBook.setBook(book); userBook.setDateTime(new java.util.Date(timestamp.getTime())); userBook.setUserName(userName); userBooks.add(userBook); } } catch (SQLException e) { LOG.error("", e); } finally { close(con, pst, rs); } return userBooks; } public static List<UserUrl> getHistoryUserUrlsFromDatabase(String userName) { List<UserUrl> userUrls = new ArrayList<>(); String sql = "select id,url,date_time from user_url where user_name=?"; Connection con = getConnection(); if(con == null){ return userUrls; } PreparedStatement pst = null; ResultSet rs = null; try { pst = con.prepareStatement(sql); pst.setString(1, userName); rs = pst.executeQuery(); while (rs.next()) { int id = rs.getInt(1); String url = rs.getString(2); Timestamp timestamp = rs.getTimestamp(3); UserUrl userUrl = new UserUrl(); userUrl.setId(id); userUrl.setUrl(url); userUrl.setDateTime(new java.util.Date(timestamp.getTime())); userUrl.setUserName(userName); userUrls.add(userUrl); } } catch (SQLException e) { LOG.error("", e); } finally { close(con, pst, rs); } return userUrls; } public static List<UserText> getHistoryUserTextsFromDatabase(String userName) { List<UserText> userTexts = new ArrayList<>(); String sql = "select id,text,date_time from user_text where user_name=?"; Connection con = getConnection(); if(con == null){ return userTexts; } PreparedStatement pst = null; ResultSet rs = null; try { pst = con.prepareStatement(sql); pst.setString(1, userName); rs = pst.executeQuery(); while (rs.next()) { int id = rs.getInt(1); String text = rs.getString(2); Timestamp timestamp = rs.getTimestamp(3); UserText userText = new UserText(); userText.setId(id); userText.setText(text); userText.setDateTime(new java.util.Date(timestamp.getTime())); userText.setUserName(userName); userTexts.add(userText); } } catch (SQLException e) { LOG.error("", e); } finally { close(con, pst, rs); } return userTexts; } public static List<UserWord> getHistoryUserWordsFromDatabase(String userName) { List<UserWord> userWords = new ArrayList<>(); String sql = "select id,word,dictionary,date_time from user_word where user_name=?"; Connection con = getConnection(); if(con == null){ return userWords; } PreparedStatement pst = null; ResultSet rs = null; try { pst = con.prepareStatement(sql); pst.setString(1, userName); rs = pst.executeQuery(); while (rs.next()) { int id = rs.getInt(1); String word = rs.getString(2); String dictionary = rs.getString(3); Timestamp timestamp = rs.getTimestamp(4); UserWord userWord = new UserWord(); userWord.setId(id); userWord.setWord(word); userWord.setDictionary(dictionary); userWord.setDateTime(new java.util.Date(timestamp.getTime())); userWord.setUserName(userName); userWords.add(userWord); } } catch (SQLException e) { LOG.error("", e); } finally { close(con, pst, rs); } return userWords; } public static void saveUserSimilarWordToDatabase(UserSimilarWord userSimilarWord) { String sql = "insert into user_similar_word (user_name, similar_word, md5, date_time) values (?, ?, ?, ?)"; Connection con = getConnection(); if(con == null){ return ; } PreparedStatement pst = null; ResultSet rs = null; try { pst = con.prepareStatement(sql); pst.setString(1, userSimilarWord.getUserName()); pst.setString(2, userSimilarWord.getSimilarWord()); pst.setString(3, MD5(userSimilarWord.getUserName()+userSimilarWord.getSimilarWord())); pst.setTimestamp(4, new Timestamp(userSimilarWord.getDateTime().getTime())); pst.executeUpdate(); } catch (SQLException e) { LOG.error("", e); } finally { close(con, pst, rs); } } public static void saveUserDynamicPrefixToDatabase(UserDynamicPrefix userDynamicPrefix) { String sql = "insert into user_dynamic_prefix (user_name, dynamic_prefix, md5, date_time) values (?, ?, ?, ?)"; Connection con = getConnection(); if(con == null){ return ; } PreparedStatement pst = null; ResultSet rs = null; try { pst = con.prepareStatement(sql); pst.setString(1, userDynamicPrefix.getUserName()); pst.setString(2, userDynamicPrefix.getDynamicPrefix()); pst.setString(3, MD5(userDynamicPrefix.getUserName()+userDynamicPrefix.getDynamicPrefix())); pst.setTimestamp(4, new Timestamp(userDynamicPrefix.getDateTime().getTime())); pst.executeUpdate(); } catch (SQLException e) { LOG.error("", e); } finally { close(con, pst, rs); } } public static void saveUserDynamicSuffixToDatabase(UserDynamicSuffix userDynamicSuffix) { String sql = "insert into user_dynamic_suffix (user_name, dynamic_suffix, md5, date_time) values (?, ?, ?, ?)"; Connection con = getConnection(); if(con == null){ return ; } PreparedStatement pst = null; ResultSet rs = null; try { pst = con.prepareStatement(sql); pst.setString(1, userDynamicSuffix.getUserName()); pst.setString(2, userDynamicSuffix.getDynamicSuffix()); pst.setString(3, MD5(userDynamicSuffix.getUserName()+userDynamicSuffix.getDynamicSuffix())); pst.setTimestamp(4, new Timestamp(userDynamicSuffix.getDateTime().getTime())); pst.executeUpdate(); } catch (SQLException e) { LOG.error("", e); } finally { close(con, pst, rs); } } public static void saveUserBookToDatabase(UserBook userBook) { String sql = "insert into user_book (user_name, book, md5, date_time) values (?, ?, ?, ?)"; Connection con = getConnection(); if(con == null){ return ; } PreparedStatement pst = null; ResultSet rs = null; try { pst = con.prepareStatement(sql); pst.setString(1, userBook.getUserName()); pst.setString(2, userBook.getBook()); pst.setString(3, MD5(userBook.getUserName()+userBook.getBook())); pst.setTimestamp(4, new Timestamp(userBook.getDateTime().getTime())); pst.executeUpdate(); } catch (SQLException e) { LOG.error("", e); } finally { close(con, pst, rs); } } public static void saveUserUrlToDatabase(UserUrl userUrl) { String sql = "insert into user_url (user_name, url, md5, date_time) values (?, ?, ?, ?)"; Connection con = getConnection(); if(con == null){ return ; } PreparedStatement pst = null; ResultSet rs = null; try { pst = con.prepareStatement(sql); pst.setString(1, userUrl.getUserName()); pst.setString(2, userUrl.getUrl()); pst.setString(3, MD5(userUrl.getUserName()+userUrl.getUrl())); pst.setTimestamp(4, new Timestamp(userUrl.getDateTime().getTime())); pst.executeUpdate(); } catch (SQLException e) { LOG.error("", e); } finally { close(con, pst, rs); } } public static void saveUserTextToDatabase(UserText userText) { String sql = "insert into user_text (user_name, text, md5, date_time) values (?, ?, ?, ?)"; Connection con = getConnection(); if(con == null){ return ; } PreparedStatement pst = null; ResultSet rs = null; try { pst = con.prepareStatement(sql); pst.setString(1, userText.getUserName()); pst.setString(2, userText.getText()); pst.setString(3, MD5(userText.getUserName() + userText.getText())); pst.setTimestamp(4, new Timestamp(userText.getDateTime().getTime())); pst.executeUpdate(); } catch (SQLException e) { LOG.error("", e); } finally { close(con, pst, rs); } } public static void saveUserWordToDatabase(UserWord userWord) { String sql = "insert into user_word (user_name, word, dictionary, date_time) values (?, ?, ?, ?)"; Connection con = getConnection(); if(con == null){ return ; } PreparedStatement pst = null; ResultSet rs = null; try { pst = con.prepareStatement(sql); pst.setString(1, userWord.getUserName()); pst.setString(2, userWord.getWord()); pst.setString(3, userWord.getDictionary()); pst.setTimestamp(4, new Timestamp(userWord.getDateTime().getTime())); pst.executeUpdate(); } catch (SQLException e) { LOG.error("", e); } finally { close(con, pst, rs); } } public static Connection getConnection() { Connection con = null; try { con = dataSource.getConnection(); } catch (Exception e) { LOG.error("MySQL", e); } return con; } private static DataSource setupDataSource(String connectUri, String uname, String passwd) { // First, we'll create a ConnectionFactory that the // pool will use to create Connections. // We'll use the DriverManagerConnectionFactory, // using the connect string passed in the command line // arguments. ConnectionFactory connectionFactory = new DriverManagerConnectionFactory(connectUri, uname, passwd); // Next we'll create the PoolableConnectionFactory, which wraps // the classes that implement the pooling functionality. PoolableConnectionFactory poolableConnectionFactory = new PoolableConnectionFactory(connectionFactory, null); // Now we'll need a ObjectPool that serves as the // actual pool of connections. // We'll use a GenericObjectPool instance, although // any ObjectPool implementation will suffice. ObjectPool<PoolableConnection> connectionPool = new GenericObjectPool<>(poolableConnectionFactory); // Set the factory's pool property to the owning pool poolableConnectionFactory.setPool(connectionPool); // Finally, we create the PoolingDriver itself, // passing in the object pool we created. PoolingDataSource<PoolableConnection> dataSource = new PoolingDataSource<>(connectionPool); return dataSource; } public static void close(Statement st) { close(null, st, null); } public static void close(Statement st, ResultSet rs) { close(null, st, rs); } public static void close(Connection con, Statement st, ResultSet rs) { try { if (rs != null) { rs.close(); rs = null; } if (st != null) { st.close(); st = null; } if (con != null) { con.close(); con = null; } } catch (SQLException e) { LOG.error("", e); } } public static void close(Connection con, Statement st) { close(con, st, null); } public static void close(Connection con) { close(con, null, null); } public static String MD5(String md5) { try { java.security.MessageDigest md = java.security.MessageDigest.getInstance("MD5"); byte[] array = md.digest(md5.getBytes()); StringBuffer sb = new StringBuffer(); for (int i = 0; i < array.length; ++i) { sb.append(Integer.toHexString((array[i] & 0xFF) | 0x100).substring(1,3)); } return sb.toString(); } catch (java.security.NoSuchAlgorithmException e) { } return null; } public static void main(String[] args) throws Exception { UserWord userWord = new UserWord(); userWord.setDateTime(new Date(System.currentTimeMillis())); userWord.setWord("fabulous"); userWord.setUserName("ysc"); MySQLUtils.saveUserWordToDatabase(userWord); System.out.println(MySQLUtils.getHistoryUserWordsFromDatabase("ysc")); } public static boolean processQQUser(QQUser qqUser) { if(qqUser.getUserName() == null){ return false; } qqUser.setPassword(""); if(!existUser(qqUser, "user")){ register(qqUser); } if(!existUser(qqUser, "user_qq")){ saveQQUser(qqUser); } return true; } private static void saveQQUser(QQUser user) { String sql = "insert into user_qq (user_name, password, nickname, gender, birthday, location, avatarURL30, avatarURL50, avatarURL100, date_time) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"; Connection con = getConnection(); if(con == null){ return ; } PreparedStatement pst = null; ResultSet rs = null; try { pst = con.prepareStatement(sql); pst.setString(1, user.getUserName()); pst.setString(2, user.getPassword()); pst.setString(3, user.getNickname()); pst.setString(4, user.getGender()); pst.setString(5, user.getBirthday()); pst.setString(6, user.getLocation()); pst.setString(7, user.getAvatarURL30()); pst.setString(8, user.getAvatarURL50()); pst.setString(9, user.getAvatarURL100()); pst.setTimestamp(10, new Timestamp(user.getDateTime().getTime())); pst.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); LOG.error("", e); } finally { close(con, pst, rs); } } }
package edu.umd.cs.findbugs.detect; import java.util.*; import org.apache.bcel.Constants; import org.apache.bcel.classfile.*; import org.apache.bcel.generic.*; import edu.umd.cs.findbugs.*; import edu.umd.cs.daveho.ba.*; import edu.umd.cs.daveho.ba.bcp.*; public class BCPMethodReturnCheck extends ByteCodePatternDetector { private BugReporter bugReporter; private static final ByteCodePattern pattern = new ByteCodePattern() .add(new MatchAny(new PatternElement[] { new Invoke("/^java\\.lang\\.(String|Byte|Boolean|Character|Short|Integer|Long|Float|Double)$", "/.*", "/.*", Invoke.ORDINARY_METHOD), new Invoke("+java.security.MessageDigest", "digest", "([B)[B", Invoke.INSTANCE), new Invoke("+java.net.InetAddress", "/.*", "/.*", Invoke.ORDINARY_METHOD), new Invoke("/^java\\.math\\.BigDecimal$", "/.*", "/.*", Invoke.ORDINARY_METHOD), new Invoke("/^java\\.math\\.BigInteger$", "/.*", "/.*", Invoke.ORDINARY_METHOD), }).label("call")) .add(new Opcode(Constants.POP)); public BCPMethodReturnCheck(BugReporter bugReporter) { this.bugReporter = bugReporter; } public ByteCodePattern getPattern() { return pattern; } public boolean prescreen(Method method, ClassContext classContext) { // Pre-screen for methods with a POP bytecode. // This gives us a 4X speedup. BitSet bytecodeSet = classContext.getBytecodeSet(method); return bytecodeSet.get(Constants.POP); } public void reportMatch(MethodGen methodGen, ByteCodePatternMatch match) { InstructionHandle call = match.getLabeledInstruction("call"); bugReporter.reportBug(new BugInstance("RV_RETURN_VALUE_IGNORED", NORMAL_PRIORITY) .addClassAndMethod(methodGen) .addCalledMethod(methodGen, (InvokeInstruction) call.getInstruction()) .addSourceLine(methodGen, call)); } } // vim:ts=4
package org.databene.commons.ui.swing; import java.awt.Canvas; import java.awt.Color; import java.awt.Component; import java.awt.Font; import java.awt.FontMetrics; import java.awt.Graphics; import javax.swing.Icon; import javax.swing.UIManager; /** * {@link Icon} implementation that renders a text.<br/><br/> * Created: 13.12.2013 08:28:56 * @since 0.5.25 * @author Volker Bergmann */ public class TextIcon implements Icon { private String text; private Font font; private Color background; private Color foreground; private int iconWidth; private int iconHeight; private int textWidth; private int ascent; public TextIcon(String text) { this(text, Color.BLACK, null); } public TextIcon(String text, Color foreground, Color background) { this(text, UIManager.getDefaults().getFont("Table.font"), foreground, background); } public TextIcon(String text, Font font, Color foreground, Color background) { this.text = text; this.font = font; FontMetrics metrics = new Canvas().getFontMetrics(font); this.textWidth = metrics.stringWidth(text); this.iconWidth = textWidth; this.iconHeight = font.getSize() + 2; this.ascent = metrics.getAscent(); this.background = background; this.foreground = foreground; } @Override public int getIconHeight() { return iconHeight; } public void setIconHeight(int iconHeight) { this.iconHeight = iconHeight; } @Override public int getIconWidth() { return iconWidth; } public void setIconWidth(int iconWidth) { this.iconWidth = iconWidth; } @Override public void paintIcon(Component c, Graphics g, int x, int y) { g.setColor(background); g.fillRect(x, y, iconWidth, iconHeight); g.setColor(foreground); Font origFont = g.getFont(); g.setFont(font); g.drawString(text, x + (iconWidth - textWidth) / 2, y + ascent - 1); g.setFont(origFont); } }
package com.fullmetalgalaxy.client.game.board; import com.fullmetalgalaxy.client.game.GameEngine; import com.fullmetalgalaxy.model.EnuZoom; import com.fullmetalgalaxy.model.MapShape; import com.fullmetalgalaxy.model.persist.AnBoardPosition; import com.fullmetalgalaxy.model.persist.AnPair; import com.fullmetalgalaxy.model.persist.Game; import com.google.gwt.user.client.ui.AbsolutePanel; import com.google.gwt.user.client.ui.Image; import com.google.gwt.user.client.ui.Widget; /** * @author Vincent Legendre * */ public class WgtBoardLayerBase extends AbsolutePanel implements BoardLayer { // these variable are here to keep track of the visible area of widget in pixel. protected int m_leftPix = 0; protected int m_topPix = 0; protected int m_botomPix = 0; protected int m_rightPix = 0; // private AnPair hexPositionLeftTop = new AnPair( 0, 0 ); // private AnPair hexPositionRightBotom = new AnPair( 900, 900 ); // cropped area in hexagon protected int m_cropLeftHex = 0; protected int m_cropTopHex = 0; protected int m_cropBotomHex = 10; protected int m_cropRightHex = 10; public WgtBoardLayerBase() { } /* (non-Javadoc) * @see com.fullmetalgalaxy.client.board.test.BoardLayer#hide() */ @Override public void hide() { } /** * you usually don't need to override this method (override redraw() instead) */ @Override public void redraw(int p_left, int p_top, int p_right, int p_botom) { m_topPix = p_top; m_botomPix = p_botom; if( m_botomPix > getOffsetHeight() ) { m_botomPix = getOffsetHeight(); } m_leftPix = p_left; m_rightPix = p_right; if( m_rightPix > getOffsetWidth() ) { m_rightPix = getOffsetWidth(); } // save currently visible map area for isHexVisible method /* the following optimization doesn't work since torus map :( AnPair pixPositionLeftTop = new AnPair( m_leftPix, m_topPix ); AnPair pixPositionRightBotom = new AnPair( m_rightPix, m_botomPix ); hexPositionLeftTop = convertPixPositionToHexPosition( pixPositionLeftTop ); hexPositionLeftTop.setX( Math.max( m_cropLeftHex - 1, hexPositionLeftTop.getX() - 2 ) ); hexPositionLeftTop.setY( Math.max( m_cropTopHex - 1, hexPositionLeftTop.getY() - 2 ) ); hexPositionRightBotom = convertPixPositionToHexPosition( pixPositionRightBotom ); hexPositionRightBotom.setX( Math.min( m_cropRightHex + 1, hexPositionRightBotom.getX() + 2 ) ); hexPositionRightBotom.setY( Math.min( m_cropBotomHex + 1, hexPositionRightBotom.getY() + 2 ) ); */ redraw(); } /** * override this method to redraw a little part of the widget after dragging board. */ public void redraw() { } private long m_lastGameId = 0; public void onModelChange(boolean p_forceRedraw) { Game game = GameEngine.model().getGame(); if( (game.getId() != m_lastGameId) || (p_forceRedraw) ) { resetPixelSize(); m_lastGameId = game.getId(); } } /* (non-Javadoc) * @see com.fullmetalgalaxy.client.board.test.BoardLayer#onModelChange() */ @Override public final void onModelChange() { onModelChange( false ); } /* (non-Javadoc) * @see com.fullmetalgalaxy.client.board.test.BoardLayer#show() */ @Override public void show() { } /* (non-Javadoc) * @see com.fullmetalgalaxy.client.board.test.BoardLayer#setZoom(com.fullmetalgalaxy.model.EnuZoom) */ @Override public void setZoom(EnuZoom p_zoom) { resetPixelSize(); } /** * recompute and set widget size in pixel */ protected void resetPixelSize() { int width = m_cropRightHex - m_cropLeftHex; int height = m_cropBotomHex - m_cropTopHex; int pxW = BoardConvert.landWidthHex2Pix( width, getZoom() ); int pxH = BoardConvert.landHeightHex2Pix( height, getZoom() ); setPixelSize( pxW, pxH ); } protected WgtBoard getWgtBoard() { return (WgtBoard)getParent().getParent(); } public EnuZoom getZoom() { return GameEngine.model().getZoomDisplayed(); } /** * the following method doesn't work since torus map shape * @param p_wgtHexPosition position in hexagon * @return true if a part of the given hexagon is visible. */ protected boolean isHexVisible(AnPair p_wgtHexPosition) { return true; /*boolean isXVisible = false; if( hexPositionLeftTop.getX() < hexPositionRightBotom.getX() ) { isXVisible = (p_wgtHexPosition.getX() > hexPositionLeftTop.getX()) && (p_wgtHexPosition.getX() < hexPositionRightBotom.getX()); } else { isXVisible = (p_wgtHexPosition.getX() > hexPositionLeftTop.getX()) || (p_wgtHexPosition.getX() < hexPositionRightBotom.getX()); } boolean isYVisible = false; if( hexPositionLeftTop.getY() < hexPositionRightBotom.getY() ) { isYVisible = (p_wgtHexPosition.getY() > hexPositionLeftTop.getY()) && (p_wgtHexPosition.getY() < hexPositionRightBotom.getY()); } else { isYVisible = (p_wgtHexPosition.getY() > hexPositionLeftTop.getY()) || (p_wgtHexPosition.getY() < hexPositionRightBotom.getY()); } return isXVisible && isYVisible;*/ } /** * @param p_wgtPixPosition position in pixel * @return true if the given position is visible. */ protected boolean isPixVisible(AnPair p_wgtPixPosition) { return (p_wgtPixPosition.getX() > m_leftPix) && (p_wgtPixPosition.getX() < m_rightPix) && (p_wgtPixPosition.getY() > m_topPix) && (p_wgtPixPosition.getY() < m_botomPix); } /** * set position of a widget as the widget is centered on an hexagon. * @param p_w * @param p_wgtHexPosition position in hexagon */ public void setWidgetHexPosition(Widget p_w, AnPair p_wgtHexPosition) { AnPair wgtPxPosition = convertHexPositionToPixPosition( p_wgtHexPosition ); setWidgetPixPosition( p_w, wgtPxPosition ); } /** * set position of a widget as the widget is centered on an hexagon. * @param p_w * @param p_wgtHexPosition position in hexagon */ protected void setWidgetHexPosition(Widget p_w, AnPair p_wgtHexPosition, int p_heightPixOffset) { AnPair wgtPxPosition = convertHexPositionToPixPosition( p_wgtHexPosition ); wgtPxPosition.setY( wgtPxPosition.getY() + p_heightPixOffset ); setWidgetPixPosition( p_w, wgtPxPosition ); } /** * set position of a widget as the widget is centered on the given position. * @param p_w * @param p_wgtPixPosition position in pixel */ private void setWidgetPixPosition(Widget p_w, AnPair p_wgtPixPosition) { super.setWidgetPosition( p_w, p_wgtPixPosition.getX() - p_w.getOffsetWidth() / 2, p_wgtPixPosition.getY() - p_w.getOffsetHeight() / 2 ); // p_w.setVisible( true ); } /** * set position of a widget as the widget is centered on the given position. * @param p_w * @param p_wgtPixPosition position in pixel */ public void setWidgetPixPosition(Image p_w, AnPair p_wgtPixPosition) { super.setWidgetPosition( p_w, p_wgtPixPosition.getX() - p_w.getWidth() / 2, p_wgtPixPosition .getY() - p_w.getHeight() / 2 ); // p_w.setVisible( true ); } public AnPair convertHexPositionToPixPosition(AnPair p_wgtHexPosition) { AnPair wgtHexPosition = p_wgtHexPosition; if( GameEngine.game().getMapShape() != MapShape.Flat ) { wgtHexPosition = new AnPair( p_wgtHexPosition ); } if( GameEngine.game().getMapShape().isEWLinked() ) { if( wgtHexPosition.getX() < m_cropLeftHex ) { wgtHexPosition.setX( p_wgtHexPosition.getX() + GameEngine.game().getLandWidth() ); } } if( GameEngine.game().getMapShape().isNSLinked() ) { if( wgtHexPosition.getY() < m_cropTopHex ) { wgtHexPosition.setY( p_wgtHexPosition.getY() + GameEngine.game().getLandHeight() ); } } return BoardConvert.convertHexPositionToPixPosition( wgtHexPosition, getZoom(), new AnPair(m_cropLeftHex,m_cropTopHex) ); } protected AnBoardPosition convertPixPositionToHexPosition(AnPair p_pixPosition) { return GameEngine .game() .getCoordinateSystem() .normalizePosition( BoardConvert.convertPixPositionToHexPosition( p_pixPosition, getZoom(), new AnPair( m_cropLeftHex, m_cropTopHex ) ) ); } @Override public void cropDisplay(int p_cropLeftHex, int p_cropTopHex, int p_cropRightHex, int p_cropBotomHex) { m_cropLeftHex = p_cropLeftHex; if( m_cropLeftHex < 0 ) m_cropLeftHex = 0; m_cropTopHex = p_cropTopHex; if( m_cropTopHex < 0 ) m_cropTopHex = 0; m_cropBotomHex = p_cropBotomHex; m_cropRightHex = p_cropRightHex; } @Override public AnPair getCropTopLeft() { return new AnPair(m_cropLeftHex,m_cropTopHex); } }