lang
stringclasses
2 values
license
stringclasses
13 values
stderr
stringlengths
0
343
commit
stringlengths
40
40
returncode
int64
0
128
repos
stringlengths
6
87.7k
new_contents
stringlengths
0
6.23M
new_file
stringlengths
3
311
old_contents
stringlengths
0
6.23M
message
stringlengths
6
9.1k
old_file
stringlengths
3
311
subject
stringlengths
0
4k
git_diff
stringlengths
0
6.31M
Java
apache-2.0
49e4c995797bb9332dded6d92c2bede11b074018
0
wuxinshui/spring-boot-samples,wuxinshui/spring-boot-samples,wuxinshui/spring-boot-samples,wuxinshui/spring-boot-samples
package com.wxs.quartz.conf; import org.quartz.Scheduler; import org.quartz.SchedulerException; import org.quartz.SchedulerFactory; import org.quartz.impl.StdSchedulerFactory; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; /** * @ClassName: JobConfig * @author: [Wuxinshui] * @CreateDate: 2017/8/7 18:02 * @UpdateUser: [Wuxinshui] * @UpdateDate: 2017/8/7 18:02 * @UpdateRemark: [说明本次修改内容] * @Description: [TODO(用一句话描述该文件做什么)] * @version: [V1.0] */ @Configuration public class QuartzConfig { @Bean(name = "scheduler") public Scheduler scheduler() throws SchedulerException { SchedulerFactory sf = new StdSchedulerFactory(); Scheduler scheduler = sf.getScheduler(); scheduler.start(); return scheduler; } //@Bean(name = "scheduler") //public Scheduler scheduler(CronTrigger cronTrigger) throws SchedulerException { // // SchedulerFactory sf = new StdSchedulerFactory(); // Scheduler scheduler = sf.getScheduler(); // // SchedulerFactoryBean factoryBean = new SchedulerFactoryBean(); // factoryBean.setSchedulerFactoryClass(StdSchedulerFactory.class); // factoryBean.setTriggers(cronTrigger); // Scheduler scheduler = null; // try { // factoryBean.afterPropertiesSet(); // scheduler = factoryBean.getScheduler(); // //scheduler.startDelayed(60); // scheduler.start(); // } catch (Exception e) { // e.printStackTrace(); // } // return scheduler; //} // //@Bean(name = "cronTrigger") //public CronTrigger cronTrigger(JobDetail jobDetail) throws ParseException { // CronTriggerFactoryBean cronTriggerFactoryBean = new CronTriggerFactoryBean(); // cronTriggerFactoryBean.setJobDetail(jobDetail); // cronTriggerFactoryBean.setName("InitJobTrigger"); // cronTriggerFactoryBean.setGroup("Default"); // cronTriggerFactoryBean.setCronExpression("0/1 * * * * ?"); // cronTriggerFactoryBean.afterPropertiesSet(); // CronTrigger cronTrigger = cronTriggerFactoryBean.getObject(); // return cronTrigger; //} // //@Bean(name = "jobDetail") //public JobDetail jobDetail() { // JobDetailFactoryBean jobDetailFactoryBean = new JobDetailFactoryBean(); // jobDetailFactoryBean.setGroup("Default"); // jobDetailFactoryBean.setName("InitJob"); // jobDetailFactoryBean.setJobClass(InitJob.class); // jobDetailFactoryBean.afterPropertiesSet(); // return jobDetailFactoryBean.getObject(); //} }
spring-boot-sample-quartz/src/main/java/com/wxs/quartz/conf/QuartzConfig.java
package com.wxs.quartz.conf; import com.wxs.quartz.job.InitJob; import org.quartz.*; import org.quartz.impl.StdSchedulerFactory; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.scheduling.quartz.CronTriggerFactoryBean; import org.springframework.scheduling.quartz.JobDetailFactoryBean; import org.springframework.scheduling.quartz.SchedulerFactoryBean; import java.text.ParseException; /** * @ClassName: JobConfig * @author: [Wuxinshui] * @CreateDate: 2017/8/7 18:02 * @UpdateUser: [Wuxinshui] * @UpdateDate: 2017/8/7 18:02 * @UpdateRemark: [说明本次修改内容] * @Description: [TODO(用一句话描述该文件做什么)] * @version: [V1.0] */ @Configuration public class QuartzConfig { @Bean(name = "scheduler") public Scheduler scheduler(CronTrigger cronTrigger) throws SchedulerException { //SchedulerFactory sf = new StdSchedulerFactory(); //Scheduler scheduler = sf.getScheduler(); SchedulerFactoryBean factoryBean = new SchedulerFactoryBean(); factoryBean.setSchedulerFactoryClass(StdSchedulerFactory.class); factoryBean.setTriggers(cronTrigger); Scheduler scheduler = null; try { factoryBean.afterPropertiesSet(); scheduler = factoryBean.getScheduler(); scheduler.startDelayed(60); //scheduler.start(); } catch (Exception e) { e.printStackTrace(); } return scheduler; } @Bean(name = "cronTrigger") public CronTrigger cronTrigger(JobDetail jobDetail) throws ParseException { CronTriggerFactoryBean cronTriggerFactoryBean = new CronTriggerFactoryBean(); cronTriggerFactoryBean.setJobDetail(jobDetail); cronTriggerFactoryBean.setName("InitJobTrigger"); cronTriggerFactoryBean.setGroup("Default"); cronTriggerFactoryBean.setCronExpression("0/1 * * * * ?"); cronTriggerFactoryBean.afterPropertiesSet(); CronTrigger cronTrigger = cronTriggerFactoryBean.getObject(); return cronTrigger; } @Bean(name = "jobDetail") public JobDetail jobDetail() { JobDetailFactoryBean jobDetailFactoryBean = new JobDetailFactoryBean(); jobDetailFactoryBean.setGroup("Default"); jobDetailFactoryBean.setName("InitJob"); jobDetailFactoryBean.setJobClass(InitJob.class); jobDetailFactoryBean.afterPropertiesSet(); return jobDetailFactoryBean.getObject(); } }
init schedule no job SchedulerFactory sf = new StdSchedulerFactory(); Scheduler scheduler = sf.getScheduler(); scheduler.start(); return scheduler;
spring-boot-sample-quartz/src/main/java/com/wxs/quartz/conf/QuartzConfig.java
init schedule no job SchedulerFactory sf = new StdSchedulerFactory(); Scheduler scheduler = sf.getScheduler(); scheduler.start(); return scheduler;
<ide><path>pring-boot-sample-quartz/src/main/java/com/wxs/quartz/conf/QuartzConfig.java <ide> package com.wxs.quartz.conf; <ide> <del>import com.wxs.quartz.job.InitJob; <del>import org.quartz.*; <add>import org.quartz.Scheduler; <add>import org.quartz.SchedulerException; <add>import org.quartz.SchedulerFactory; <ide> import org.quartz.impl.StdSchedulerFactory; <ide> import org.springframework.context.annotation.Bean; <ide> import org.springframework.context.annotation.Configuration; <del>import org.springframework.scheduling.quartz.CronTriggerFactoryBean; <del>import org.springframework.scheduling.quartz.JobDetailFactoryBean; <del>import org.springframework.scheduling.quartz.SchedulerFactoryBean; <del> <del>import java.text.ParseException; <ide> <ide> /** <ide> * @ClassName: JobConfig <ide> @Configuration <ide> public class QuartzConfig { <ide> <del> @Bean(name = "scheduler") <del> public Scheduler scheduler(CronTrigger cronTrigger) throws SchedulerException { <add> @Bean(name = "scheduler") <add> public Scheduler scheduler() throws SchedulerException { <ide> <del> //SchedulerFactory sf = new StdSchedulerFactory(); <del> //Scheduler scheduler = sf.getScheduler(); <add> SchedulerFactory sf = new StdSchedulerFactory(); <add> Scheduler scheduler = sf.getScheduler(); <add> scheduler.start(); <add> return scheduler; <add> } <ide> <del> SchedulerFactoryBean factoryBean = new SchedulerFactoryBean(); <del> factoryBean.setSchedulerFactoryClass(StdSchedulerFactory.class); <del> factoryBean.setTriggers(cronTrigger); <del> Scheduler scheduler = null; <del> try { <del> factoryBean.afterPropertiesSet(); <del> scheduler = factoryBean.getScheduler(); <del> scheduler.startDelayed(60); <del> //scheduler.start(); <del> } catch (Exception e) { <del> e.printStackTrace(); <del> } <del> return scheduler; <del> } <del> <del> @Bean(name = "cronTrigger") <del> public CronTrigger cronTrigger(JobDetail jobDetail) throws ParseException { <del> CronTriggerFactoryBean cronTriggerFactoryBean = new CronTriggerFactoryBean(); <del> cronTriggerFactoryBean.setJobDetail(jobDetail); <del> cronTriggerFactoryBean.setName("InitJobTrigger"); <del> cronTriggerFactoryBean.setGroup("Default"); <del> cronTriggerFactoryBean.setCronExpression("0/1 * * * * ?"); <del> cronTriggerFactoryBean.afterPropertiesSet(); <del> CronTrigger cronTrigger = cronTriggerFactoryBean.getObject(); <del> return cronTrigger; <del> } <del> <del> @Bean(name = "jobDetail") <del> public JobDetail jobDetail() { <del> JobDetailFactoryBean jobDetailFactoryBean = new JobDetailFactoryBean(); <del> jobDetailFactoryBean.setGroup("Default"); <del> jobDetailFactoryBean.setName("InitJob"); <del> jobDetailFactoryBean.setJobClass(InitJob.class); <del> jobDetailFactoryBean.afterPropertiesSet(); <del> return jobDetailFactoryBean.getObject(); <del> } <add> //@Bean(name = "scheduler") <add> //public Scheduler scheduler(CronTrigger cronTrigger) throws SchedulerException { <add> // <add> // SchedulerFactory sf = new StdSchedulerFactory(); <add> // Scheduler scheduler = sf.getScheduler(); <add> // <add> // SchedulerFactoryBean factoryBean = new SchedulerFactoryBean(); <add> // factoryBean.setSchedulerFactoryClass(StdSchedulerFactory.class); <add> // factoryBean.setTriggers(cronTrigger); <add> // Scheduler scheduler = null; <add> // try { <add> // factoryBean.afterPropertiesSet(); <add> // scheduler = factoryBean.getScheduler(); <add> // //scheduler.startDelayed(60); <add> // scheduler.start(); <add> // } catch (Exception e) { <add> // e.printStackTrace(); <add> // } <add> // return scheduler; <add> //} <add> // <add> //@Bean(name = "cronTrigger") <add> //public CronTrigger cronTrigger(JobDetail jobDetail) throws ParseException { <add> // CronTriggerFactoryBean cronTriggerFactoryBean = new CronTriggerFactoryBean(); <add> // cronTriggerFactoryBean.setJobDetail(jobDetail); <add> // cronTriggerFactoryBean.setName("InitJobTrigger"); <add> // cronTriggerFactoryBean.setGroup("Default"); <add> // cronTriggerFactoryBean.setCronExpression("0/1 * * * * ?"); <add> // cronTriggerFactoryBean.afterPropertiesSet(); <add> // CronTrigger cronTrigger = cronTriggerFactoryBean.getObject(); <add> // return cronTrigger; <add> //} <add> // <add> //@Bean(name = "jobDetail") <add> //public JobDetail jobDetail() { <add> // JobDetailFactoryBean jobDetailFactoryBean = new JobDetailFactoryBean(); <add> // jobDetailFactoryBean.setGroup("Default"); <add> // jobDetailFactoryBean.setName("InitJob"); <add> // jobDetailFactoryBean.setJobClass(InitJob.class); <add> // jobDetailFactoryBean.afterPropertiesSet(); <add> // return jobDetailFactoryBean.getObject(); <add> //} <ide> }
Java
unlicense
225b7ef7a0ade6f4aedbc82b8d708a7733822094
0
SkyLandTW/JXTN,AqD/JXTN,SkyLandTW/JXTN
/* * This is free and unencumbered software released into the public domain. * * Anyone is free to copy, modify, publish, use, compile, sell, or * distribute this software, either in source code form or as a compiled * binary, for any purpose, commercial or non-commercial, and by any * means. * * In jurisdictions that recognize copyright laws, the author or authors * of this software dedicate any and all copyright interest in the * software to the public domain. We make this dedication for the benefit * of the public at large and to the detriment of our heirs and * successors. We intend this dedication to be an overt act of * relinquishment in perpetuity of all present and future rights to this * software under copyright law. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. * * For more information, please refer to <http://unlicense.org/> */ package java.util; import java.lang.reflect.Array; import java.util.function.BiFunctionEx; import java.util.function.ConsumerEx; import java.util.function.Function; import java.util.function.FunctionEx; import java.util.function.Predicate; import java.util.function.PredicateEx; import java.util.function.ToDoubleFunctionEx; import java.util.function.ToIntFunctionEx; import java.util.function.ToLongFunctionEx; import jxtn.core.axi.collections.AfterConditionIterator; import jxtn.core.axi.collections.BeforeConditionIterator; import jxtn.core.axi.collections.ConcatedIterator; import jxtn.core.axi.collections.ExpandedIterator; import jxtn.core.axi.collections.FilteredIterator; import jxtn.core.axi.collections.IndexedItem; import jxtn.core.axi.collections.IndexedIterator; import jxtn.core.axi.collections.LinkLineIterator; import jxtn.core.axi.collections.LinkTreeIterator; import jxtn.core.axi.collections.MappedIterator; import jxtn.core.axi.collections.SkippedIterator; import jxtn.core.axi.comparators.MemberComparators; /** * {@link Iterator}的延伸功能。 * <p> * 添加延伸時應同步更新{@link java.lang.IterableExt}。 * </p> * * @author AqD * @param <E> 列舉項目型態 */ public interface IteratorExt<E> { /** * 結合多個列舉器。 * * @param <T> 列舉項目型態 * @param iterators 要結合的列舉器集合 * @return 結合的列舉器 */ @SafeVarargs public static <T> Iterator<T> concatAll(Iterator<? extends T>... iterators) { return new ConcatedIterator<>(Arrays.asList(iterators).iterator()); } /** * 結合多個列舉器。 * * @param <T> 列舉項目型態 * @param iteratorIterable 要結合的列舉器的列舉 * @return 結合的列舉器 */ public static <T> Iterator<T> concatAll(Iterable<Iterator<? extends T>> iteratorIterable) { return new ConcatedIterator<>(iteratorIterable.iterator()); } /** * 結合多個列舉器。 * * @param <T> 列舉項目型態 * @param iteratorIterator 要結合的列舉器的列舉器 * @return 結合的列舉器 */ public static <T> Iterator<T> concatAll(Iterator<Iterator<? extends T>> iteratorIterator) { return new ConcatedIterator<>(iteratorIterator); } /** * 建立線性結構的串接列舉器。 * * @param <T> 列舉項目型態 * @param item 初始項目 * @param getNext 取得每個項目的下一個項目的函數,傳回null表示結尾 * @return 串接列舉器 */ public static <T> Iterator<T> linkLine(T item, Function<? super T, ? extends T> getNext) { return new LinkLineIterator<>(item, getNext); } /** * 建立樹狀結構的串接列舉器。 * * @param <T> 列舉項目型態 * @param item 初始項目;根結點 * @param getChildren 取得每個項目的子項目集合,傳回null表示結尾 * @return 串接列舉器 */ public static <T> Iterator<T> linkTree(T item, Function<? super T, ? extends Iterator<? extends T>> getChildren) { return new LinkTreeIterator<>(item, getChildren); } /** * 針對每個項目執行指定動作 * * @param <TException> 動作可拋出的例外型態 * @param action 要執行的動作 * @throws TException 表示{@code action}丟出例外 */ default <TException extends Exception> void forEachEx(ConsumerEx<? super E, ? extends TException> action) throws TException { Objects.requireNonNull(action); Iterator<E> thiz = (Iterator<E>) this; while (thiz.hasNext()) { action.acceptEx(thiz.next()); } } ////////////////////////////////////////////////////////////////////////// // 條件測試 // /** * 檢查是否所有剩餘項目皆符合指定條件。 * <p> * 結束後列舉器會停在結尾。 * </p> * * @param <TException> 測試條件可拋出的例外型態 * @param condition 條件測試的函數 * @return true表示符合,或沒有項目可測試false表示任一項目不符合 * @throws TException 表示{@code condition}丟出例外 */ default <TException extends Exception> boolean all(PredicateEx<? super E, ? extends TException> condition) throws TException { Iterator<E> thiz = (Iterator<E>) this; while (thiz.hasNext()) { E item = thiz.next(); if (!condition.testEx(item)) { return false; } } return true; } /** * 檢查是否有任一項目符合指定條件。 * <p> * 結束後列舉器會停在第一筆符合項目之後或是結尾。 * </p> * * @param <TException> 測試條件可拋出的例外型態 * @param condition 條件測試的函數 * @return true表示符合false表示所有項目皆不符合,或沒有項目可測試 * @throws TException 表示{@code condition}丟出例外 */ default <TException extends Exception> boolean any(PredicateEx<? super E, ? extends TException> condition) throws TException { Iterator<E> thiz = (Iterator<E>) this; while (thiz.hasNext()) { E item = thiz.next(); if (condition.testEx(item)) { return true; } } return false; } ////////////////////////////////////////////////////////////////////////// // 列舉轉換 // /** * 將目前列舉器作為指定項目型態的列舉器傳回。 * * @param <V> 傳回項目型態 * @return 指定項目型態的列舉器(物件仍為目前列舉器) */ @SuppressWarnings("unchecked") default <V> Iterator<V> as() { return (Iterator<V>) this; } /** * 結合多個項目到結尾。 * * @param tailItems 要結合在結尾的其他項目 * @return 目前列舉及{@code tailItems}的結合 */ @SuppressWarnings("unchecked") default Iterator<E> append(E... tailItems) { List<Iterator<? extends E>> list = Arrays.asList( (Iterator<E>) this, Arrays.asList(tailItems).iterator()); return new ConcatedIterator<>(list.iterator()); } /** * 結合多個項目到開頭。 * * @param headItems 要結合在開頭的其他項目 * @return 目前列舉及{@code tailItems}的結合 */ @SuppressWarnings("unchecked") default Iterator<E> prepend(E... headItems) { List<Iterator<? extends E>> list = Arrays.asList( Arrays.asList(headItems).iterator(), (Iterator<E>) this); return new ConcatedIterator<>(list.iterator()); } /** * 結合多個列舉器。 * * @param iterators 要結合在後面的其他列舉器 * @return 目前列舉器及{@code iterators}的結合 */ @SuppressWarnings("unchecked") default Iterator<E> concat(Iterator<? extends E>... iterators) { List<Iterator<? extends E>> list = new ArrayList<>(iterators.length + 1); list.add((Iterator<E>) this); for (Iterator<? extends E> other : iterators) list.add(other); return new ConcatedIterator<>(list.iterator()); } /** * 依照展開函數建立展開列舉器。 * * @param <R> 展開項目型態 * @param expander 展開項目的函數 * @return 展開列舉器,依賴原有的列舉器 */ default <R> Iterator<R> expand(Function<? super E, Iterator<R>> expander) { Iterator<E> thiz = (Iterator<E>) this; return new ExpandedIterator<>(thiz, expander); } /** * 依照條件建立過濾列舉器。 * * @param condition 過濾條件 * @return 過濾列舉器,依賴原有的列舉器 */ default Iterator<E> filter(Predicate<? super E> condition) { Iterator<E> thiz = (Iterator<E>) this; return new FilteredIterator<>(thiz, condition); } /** * 依照條件建立剔除開頭的列舉器。 * <p> * 列舉內容只保留第一個符合條件後的所有項目(包含該項目)。 * </p> * * @param condition 過濾條件 * @return 過濾列舉器,依賴原有的列舉器 */ default Iterator<E> after(Predicate<? super E> condition) { Iterator<E> thiz = (Iterator<E>) this; return new AfterConditionIterator<>(thiz, condition); } /** * 依照條件建立剔除結尾的列舉器。 * <p> * 列舉內容只保留第一個符合條件前的所有項目(不含該項目)。 * </p> * * @param condition 過濾條件 * @return 過濾列舉器,依賴原有的列舉器 */ default Iterator<E> before(Predicate<? super E> condition) { Iterator<E> thiz = (Iterator<E>) this; return new BeforeConditionIterator<>(thiz, condition); } /** * 建立加上索引的列舉器。 * * @return 加上索引的列舉器,依賴原有的列舉器 */ default Iterator<IndexedItem<E>> indexed() { Iterator<E> thiz = (Iterator<E>) this; return new IndexedIterator<>(thiz); } /** * 依照對照函數建立對照列舉器。 * * @param <R> 對照項目型態 * @param mapper 對照項目的函數 * @return 對照列舉器,依賴原有的列舉器 */ default <R> Iterator<R> map(Function<? super E, ? extends R> mapper) { Iterator<E> thiz = (Iterator<E>) this; return new MappedIterator<>(thiz, mapper); } /** * 建立只包含指定型態項目的列舉器。 * * @param <R> 要取得項目的型態 * @param type 要取得項目的型態 * @return 只包含{@code type}型態項目的列舉 */ @SuppressWarnings("unchecked") default <R> Iterator<R> ofType(Class<? extends R> type) { Iterator<E> thiz = (Iterator<E>) this; return thiz.filter(type::isInstance).map(e -> (R) e); } /** * 建立跳過指定項目數量的列舉器。 * * @param count 要跳過的項目數量 * @return 跳過指定數量的列舉器,依賴原有的列舉器 */ default Iterator<E> skip(int count) { Iterator<E> thiz = (Iterator<E>) this; return new SkippedIterator<>(thiz, count); } ////////////////////////////////////////////////////////////////////////// // 項目挑選 // /** * 取得符合條件的下一筆項目。 * <p> * 結束後列舉器會停在第一筆符合項目之後或是結尾。 * </p> * * @param <TException> 測試條件可拋出的例外型態 * @param condition 取得項目的條件測試函數 * @return 下一筆項目 * @throws NoSuchElementException 沒有下一筆或符合條件的項目 * @throws TException 表示{@code condition}丟出例外 */ default <TException extends Exception> E next(PredicateEx<? super E, ? extends TException> condition) throws TException { Iterator<E> thiz = (Iterator<E>) this; while (thiz.hasNext()) { E item = thiz.next(); if (condition.testEx(item)) { return item; } } throw new NoSuchElementException(); } /** * 取得符合條件的下一筆項目。 * <p> * 結束後列舉器會停在第一筆符合項目之後或是結尾。 * </p> * * @return 下一筆項目,或null表示沒有下一筆或符合條件的項目 */ default E nextOrNull() { Iterator<E> thiz = (Iterator<E>) this; if (thiz.hasNext()) { return thiz.next(); } return null; } /** * 取得符合條件的下一筆項目。 * <p> * 結束後列舉器會停在第一筆符合項目之後或是結尾。 * </p> * * @param <TException> 測試條件可拋出的例外型態 * @param condition 取得項目的條件測試函數 * @return 下一筆項目,或null表示沒有下一筆或符合條件的項目 * @throws TException 表示{@code condition}丟出例外 */ default <TException extends Exception> E nextOrNull(PredicateEx<? super E, ? extends TException> condition) throws TException { Iterator<E> thiz = (Iterator<E>) this; while (thiz.hasNext()) { E item = thiz.next(); if (condition.testEx(item)) { return item; } } return null; } /** * 取得第N筆項目。 * * @param position 位置(相對於目前位置) * @return 第N筆項目 * @throws NoSuchElementException 沒有第N筆項目 */ default E nextNth(int position) { Iterator<E> thiz = (Iterator<E>) this; for (int i = 0; i < position; i++) { thiz.next(); } return thiz.next(); } /** * 取得第N筆項目。 * * @param position 位置(相對於目前位置) * @return 第N筆項目,或null表示沒有第N筆項目 */ default E nextNthOrNull(int position) { Iterator<E> thiz = (Iterator<E>) this; for (int i = 0; i < position; i++) { if (!thiz.hasNext()) return null; thiz.next(); } if (!thiz.hasNext()) return null; return thiz.next(); } /** * 取得下一個可計算出最大數值的項目。 * * @param <TException> 計算數值函數可拋出的例外型態 * @param <V> 數值型態 * @param getValue 計算項目數值的函數 * @return 下一個計算出最大數值的項目(跳過NULL數值) * @throws NoSuchElementException 沒有下一筆項目 * @throws TException 表示{@code getValue}丟出例外 */ default <V extends Comparable<? super V>, TException extends Exception> E nextOfMax(FunctionEx<? super E, ? extends V, ? extends TException> getValue) throws TException { Iterator<E> thiz = (Iterator<E>) this; if (!thiz.hasNext()) throw new NoSuchElementException(); E maxE = thiz.next(); V maxV = getValue.applyEx(maxE); while (thiz.hasNext()) { E curE = thiz.next(); V curV = getValue.applyEx(curE); if (maxV == null || maxV.compareTo(curV) < 0) { maxV = curV; maxE = curE; } } return maxE; } /** * 取得下一個可計算出最大數值的項目。 * * @param <TException> 計算數值函數可拋出的例外型態 * @param getValue 計算項目數值的函數 * @return 下一個計算出最大數值的項目 * @throws NoSuchElementException 沒有下一筆項目 * @throws TException 表示{@code getValue}丟出例外 */ default <TException extends Exception> E nextOfMaxDouble(ToDoubleFunctionEx<? super E, ? extends TException> getValue) throws TException { Iterator<E> thiz = (Iterator<E>) this; if (!thiz.hasNext()) throw new NoSuchElementException(); E maxE = thiz.next(); double maxV = getValue.applyAsDoubleEx(maxE); while (thiz.hasNext()) { E curE = thiz.next(); double curV = getValue.applyAsDoubleEx(curE); if (maxV < curV) { maxV = curV; maxE = curE; } } return maxE; } /** * 取得下一個可計算出最大數值的項目。 * * @param <TException> 計算數值函數可拋出的例外型態 * @param getValue 計算項目數值的函數 * @return 下一個計算出最大數值的項目 * @throws NoSuchElementException 沒有下一筆項目 * @throws TException 表示{@code getValue}丟出例外 */ default <TException extends Exception> E nextOfMaxInt(ToIntFunctionEx<? super E, ? extends TException> getValue) throws TException { Iterator<E> thiz = (Iterator<E>) this; if (!thiz.hasNext()) throw new NoSuchElementException(); E maxE = thiz.next(); int maxV = getValue.applyAsIntEx(maxE); while (thiz.hasNext()) { E curE = thiz.next(); int curV = getValue.applyAsIntEx(curE); if (maxV < curV) { maxV = curV; maxE = curE; } } return maxE; } /** * 取得下一個可計算出最大數值的項目。 * * @param <TException> 計算數值函數可拋出的例外型態 * @param getValue 計算項目數值的函數 * @return 下一個計算出最大數值的項目 * @throws NoSuchElementException 沒有下一筆項目 * @throws TException 表示{@code getValue}丟出例外 */ default <TException extends Exception> E nextOfMaxLong(ToLongFunctionEx<? super E, ? extends TException> getValue) throws TException { Iterator<E> thiz = (Iterator<E>) this; if (!thiz.hasNext()) throw new NoSuchElementException(); E maxE = thiz.next(); long maxV = getValue.applyAsLongEx(maxE); while (thiz.hasNext()) { E curE = thiz.next(); long curV = getValue.applyAsLongEx(curE); if (maxV < curV) { maxV = curV; maxE = curE; } } return maxE; } /** * 取得下一個可計算出最小數值的項目。 * * @param <TException> 計算數值函數可拋出的例外型態 * @param <V> 數值型態 * @param getValue 計算項目數值的函數 * @return 下一個計算出最小數值的項目(跳過NULL數值) * @throws NoSuchElementException 沒有下一筆項目 * @throws TException 表示{@code getValue}丟出例外 */ default <V extends Comparable<? super V>, TException extends Exception> E nextOfMin(FunctionEx<? super E, ? extends V, ? extends TException> getValue) throws TException { Iterator<E> thiz = (Iterator<E>) this; if (!thiz.hasNext()) throw new NoSuchElementException(); E minE = thiz.next(); V minV = getValue.applyEx(minE); while (thiz.hasNext()) { E curE = thiz.next(); V curV = getValue.applyEx(curE); if (minV == null || minV.compareTo(curV) > 0) { minV = curV; minE = curE; } } return minE; } /** * 取得下一個可計算出最小數值的項目。 * * @param <TException> 計算數值函數可拋出的例外型態 * @param getValue 計算項目數值的函數 * @return 下一個計算出最小數值的項目 * @throws NoSuchElementException 沒有下一筆項目 * @throws TException 表示{@code getValue}丟出例外 */ default <TException extends Exception> E nextOfMinDouble(ToDoubleFunctionEx<? super E, ? extends TException> getValue) throws TException { Iterator<E> thiz = (Iterator<E>) this; if (!thiz.hasNext()) throw new NoSuchElementException(); E minE = thiz.next(); double minV = getValue.applyAsDoubleEx(minE); while (thiz.hasNext()) { E curE = thiz.next(); double curV = getValue.applyAsDoubleEx(curE); if (minV > curV) { minV = curV; minE = curE; } } return minE; } /** * 取得下一個可計算出最小數值的項目。 * * @param <TException> 計算數值函數可拋出的例外型態 * @param getValue 計算項目數值的函數 * @return 下一個計算出最小數值的項目 * @throws NoSuchElementException 沒有下一筆項目 * @throws TException 表示{@code getValue}丟出例外 */ default <TException extends Exception> E nextOfMinInt(ToIntFunctionEx<? super E, ? extends TException> getValue) throws TException { Iterator<E> thiz = (Iterator<E>) this; if (!thiz.hasNext()) throw new NoSuchElementException(); E minE = thiz.next(); int minV = getValue.applyAsIntEx(minE); while (thiz.hasNext()) { E curE = thiz.next(); int curV = getValue.applyAsIntEx(curE); if (minV > curV) { minV = curV; minE = curE; } } return minE; } /** * 取得下一個可計算出最小數值的項目。 * * @param <TException> 計算數值函數可拋出的例外型態 * @param getValue 計算項目數值的函數 * @return 下一個計算出最小數值的項目 * @throws NoSuchElementException 沒有下一筆項目 * @throws TException 表示{@code getValue}丟出例外 */ default <TException extends Exception> E nextOfMinLong(ToLongFunctionEx<? super E, ? extends TException> getValue) throws TException { Iterator<E> thiz = (Iterator<E>) this; if (!thiz.hasNext()) throw new NoSuchElementException(); E minE = thiz.next(); long minV = getValue.applyAsLongEx(minE); while (thiz.hasNext()) { E curE = thiz.next(); long curV = getValue.applyAsLongEx(curE); if (minV > curV) { minV = curV; minE = curE; } } return minE; } ////////////////////////////////////////////////////////////////////////// // 項目統整 // /** * 用目前項目值建立陣列。 * * @param type 陣列項目型態 * @return 包含目前項目的陣列 */ @SuppressWarnings("unchecked") default E[] toArray(Class<E> type) { Iterator<E> thiz = (Iterator<E>) this; ArrayList<E> list = thiz.toArrayList(); E[] array = (E[]) Array.newInstance(type, list.size()); return list.toArray(array); } /** * 用目前項目值建立{@link ArrayList}。 * * @return 包含目前項目的{@link ArrayList} */ default ArrayList<E> toArrayList() { Iterator<E> thiz = (Iterator<E>) this; ArrayList<E> coll = new ArrayList<>(); while (thiz.hasNext()) { coll.add(thiz.next()); } return coll; } /** * 用目前項目值建立{@link ArrayList},依照條件做過濾。 * * @param <TException> 測試條件可拋出的例外型態 * @param condition 取得項目的條件測試函數 * @return 包含符合條件項目的{@link ArrayList} * @throws TException 表示{@code mapper}丟出例外 */ default <TException extends Exception> ArrayList<E> toArrayListFiltered(PredicateEx<? super E, ? extends TException> condition) throws TException { Iterator<E> thiz = (Iterator<E>) this; ArrayList<E> coll = new ArrayList<>(); while (thiz.hasNext()) { E e = thiz.next(); if (condition.testEx(e)) coll.add(e); } return coll; } /** * 用目前項目值建立{@link ArrayList},依照函數做對照。 * * @param <R> 對照項目型態 * @param <TException> 對照函數可拋出的例外型態 * @param mapper 對照項目的函數 * @return 包含目前項目對照結果的{@link ArrayList} * @throws TException 表示{@code mapper}丟出例外 */ default <R, TException extends Exception> ArrayList<R> toArrayListMapped(FunctionEx<? super E, ? extends R, ? extends TException> mapper) throws TException { Iterator<E> thiz = (Iterator<E>) this; ArrayList<R> coll = new ArrayList<>(); while (thiz.hasNext()) { coll.add(mapper.applyEx(thiz.next())); } return coll; } /** * 用目前項目值建立{@link ArrayList},依照鍵值做排序。 * * @param <V> 鍵值型態 * @param getKey 計算每個項目的鍵值 * @return 包含目前項目的{@link ArrayList},已排序 */ default <V extends Comparable<?>> ArrayList<E> toArrayListSorted(Function<? super E, ? extends V> getKey) { Iterator<E> thiz = (Iterator<E>) this; ArrayList<E> sorted = thiz.toArrayList(); sorted.sort(MemberComparators.byComparable(getKey)); return sorted; } /** * 用目前項目值建立{@link ArrayList},依照比較器做排序。 * * @param comparator 項目的比較器 * @return 包含目前項目的{@link ArrayList},已排序 */ default ArrayList<E> toArrayListSorted(Comparator<? super E> comparator) { Iterator<E> thiz = (Iterator<E>) this; ArrayList<E> sorted = thiz.toArrayList(); sorted.sort(comparator); return sorted; } /** * 用目前項目值建立{@link HashMap}。 * * @param <K> {@link HashMap}鍵值型態 * @param <KException> 計算鍵值函數可拋出的例外型態 * @param getKey 計算項目於新{@link HashMap}內的鍵值 * @return 包含目前項目對照結果的{@link HashMap} * @throws KException 表示{@code getKey}丟出例外 */ default <K, KException extends Exception> HashMap<K, E> toHashMap(FunctionEx<? super E, ? extends K, ? extends KException> getKey) throws KException { Iterator<E> thiz = (Iterator<E>) this; HashMap<K, E> coll = new HashMap<>(); while (thiz.hasNext()) { E item = thiz.next(); K k = getKey.applyEx(item); coll.put(k, item); } return coll; } /** * 用目前項目值建立{@link HashMap}。 * * @param <K> {@link HashMap}鍵值型態 * @param <V> {@link HashMap}項目值型態 * @param <KException> 計算鍵值函數可拋出的例外型態 * @param <VException> 計算項目值函數可拋出的例外型態 * @param getKey 計算項目於新{@link HashMap}內的鍵值 * @param getValue 計算項目於新{@link HashMap}內的項目值 * @return 包含目前項目對照結果的{@link HashMap} * @throws KException 表示{@code getKey}丟出例外 * @throws VException 表示{@code getValue}丟出例外 */ default <K, V, KException extends Exception, VException extends Exception> HashMap<K, V> toHashMap( FunctionEx<? super E, ? extends K, ? extends KException> getKey, FunctionEx<? super E, ? extends V, ? extends VException> getValue) throws KException, VException { Iterator<E> thiz = (Iterator<E>) this; HashMap<K, V> coll = new HashMap<>(); while (thiz.hasNext()) { E item = thiz.next(); K k = getKey.applyEx(item); V v = getValue.applyEx(item); coll.put(k, v); } return coll; } /** * 用目前項目值建立{@link HashMap},依照鍵值做分群。 * * @param <K> 分群鍵值型態 * @param <KException> 計算鍵值函數可拋出的例外型態 * @param getKey 計算每個項目的鍵值 * @return 包含目前項目分群組的{@link HashMap} * @throws KException 表示{@code getKey}丟出例外 */ default <K, KException extends Exception> HashMap<K, ArrayList<E>> toHashMapGrouped(FunctionEx<? super E, ? extends K, ? extends KException> getKey) throws KException { Iterator<E> thiz = (Iterator<E>) this; HashMap<K, ArrayList<E>> result = new HashMap<>(); while (thiz.hasNext()) { E item = thiz.next(); K key = getKey.applyEx(item); ArrayList<E> list = result.get(key); if (list == null) { list = new ArrayList<>(); result.put(key, list); } list.add(item); } return result; } /** * 用目前項目值建立{@link HashMap},依照鍵值做分群。 * * @param <K> 群組鍵值型態 * @param <V> 項目值型態 * @param <KException> 計算鍵值函數可拋出的例外型態 * @param <VException> 計算項目值函數可拋出的例外型態 * @param getKey 計算每個項目做分組的鍵值 * @param getValue 計算項目於新{@link HashMap}內的項目值 * @return 包含目前項目分群組的{@link HashMap} * @throws KException 表示{@code getKey}丟出例外 * @throws VException 表示{@code getValue}丟出例外 */ default <K, V, KException extends Exception, VException extends Exception> HashMap<K, ArrayList<V>> toHashMapGrouped( FunctionEx<? super E, ? extends K, ? extends KException> getKey, FunctionEx<? super E, ? extends V, ? extends VException> getValue) throws KException, VException { Iterator<E> thiz = (Iterator<E>) this; HashMap<K, ArrayList<V>> result = new HashMap<>(); while (thiz.hasNext()) { E item = thiz.next(); K key = getKey.applyEx(item); ArrayList<V> list = result.get(key); if (list == null) { list = new ArrayList<>(); result.put(key, list); } V value = getValue.applyEx(item); list.add(value); } return result; } /** * 用目前項目值建立{@link HashSet}。 * <p> * 重複值會被重疊覆蓋,後面的優先。 * </p> * * @return 包含目前項目的{@link HashSet} */ default HashSet<E> toHashSet() { Iterator<E> thiz = (Iterator<E>) this; HashSet<E> coll = new HashSet<>(); while (thiz.hasNext()) { coll.add(thiz.next()); } return coll; } /** * 用目前項目值建立{@link TreeMap}。 * * @param <K> {@link TreeMap}鍵值型態 * @param <KException> 計算鍵值函數可拋出的例外型態 * @param getKey 計算項目於新{@link TreeMap}內的鍵值 * @return 包含目前項目對照結果的{@link TreeMap} * @throws KException 表示{@code getKey}丟出例外 */ default <K, KException extends Exception> TreeMap<K, E> toTreeMap(FunctionEx<? super E, ? extends K, ? extends KException> getKey) throws KException { Iterator<E> thiz = (Iterator<E>) this; TreeMap<K, E> coll = new TreeMap<>(); while (thiz.hasNext()) { E item = thiz.next(); K k = getKey.applyEx(item); coll.put(k, item); } return coll; } /** * 用目前項目值建立{@link TreeMap}。 * * @param <K> {@link TreeMap}鍵值型態 * @param <V> {@link TreeMap}項目值型態 * @param <KException> 計算鍵值函數可拋出的例外型態 * @param <VException> 計算項目值函數可拋出的例外型態 * @param getKey 計算項目於新{@link TreeMap}內的鍵值 * @param getValue 計算項目於新{@link TreeMap}內的項目值 * @return 包含目前項目對照結果的{@link TreeMap} * @throws KException 表示{@code getKey}丟出例外 * @throws VException 表示{@code getValue}丟出例外 */ default <K, V, KException extends Exception, VException extends Exception> TreeMap<K, V> toTreeMap( FunctionEx<? super E, ? extends K, ? extends KException> getKey, FunctionEx<? super E, ? extends V, ? extends VException> getValue) throws KException, VException { Iterator<E> thiz = (Iterator<E>) this; TreeMap<K, V> coll = new TreeMap<>(); while (thiz.hasNext()) { E item = thiz.next(); K k = getKey.applyEx(item); V v = getValue.applyEx(item); coll.put(k, v); } return coll; } /** * 用目前項目值建立{@link TreeMap},依照鍵值做分群。 * * @param <K> 分群鍵值型態 * @param <KException> 計算鍵值函數可拋出的例外型態 * @param getKey 計算每個項目的鍵值 * @return 包含目前項目分群組的{@link TreeMap} * @throws KException 表示{@code getKey}丟出例外 */ default <K, KException extends Exception> TreeMap<K, ArrayList<E>> toTreeMapGrouped(FunctionEx<? super E, ? extends K, ? extends KException> getKey) throws KException { Iterator<E> thiz = (Iterator<E>) this; TreeMap<K, ArrayList<E>> result = new TreeMap<>(); while (thiz.hasNext()) { E item = thiz.next(); K key = getKey.applyEx(item); ArrayList<E> list = result.get(key); if (list == null) { list = new ArrayList<>(); result.put(key, list); } list.add(item); } return result; } /** * 用目前項目值建立{@link TreeMap},依照鍵值做分群。 * * @param <K> 群組鍵值型態 * @param <V> 項目值型態 * @param <KException> 計算鍵值函數可拋出的例外型態 * @param <VException> 計算項目值函數可拋出的例外型態 * @param getKey 計算每個項目做分組的鍵值 * @param getValue 計算項目於新{@link TreeMap}內的項目值 * @return 包含目前項目分群組的{@link TreeMap} * @throws KException 表示{@code getKey}丟出例外 * @throws VException 表示{@code getValue}丟出例外 */ default <K, V, KException extends Exception, VException extends Exception> TreeMap<K, ArrayList<V>> toTreeMapGrouped( FunctionEx<? super E, ? extends K, ? extends KException> getKey, FunctionEx<? super E, ? extends V, ? extends VException> getValue) throws KException, VException { Iterator<E> thiz = (Iterator<E>) this; TreeMap<K, ArrayList<V>> result = new TreeMap<>(); while (thiz.hasNext()) { E item = thiz.next(); K key = getKey.applyEx(item); ArrayList<V> list = result.get(key); if (list == null) { list = new ArrayList<>(); result.put(key, list); } V value = getValue.applyEx(item); list.add(value); } return result; } ////////////////////////////////////////////////////////////////////////// // 數學統計 // /** * 進行歸約動作 * * @param <U> 歸約結果型態 * @param <TException> 累加函數可拋出的例外型態 * @param identity 初始值 * @param accumulator 累加函數 * @return 歸約結果 * @throws TException 表示{@code accumulator}丟出例外 */ default <U, TException extends Exception> U reduce( U identity, BiFunctionEx<U, ? super E, U, TException> accumulator) throws TException { Iterator<E> thiz = (Iterator<E>) this; U result = identity; while (thiz.hasNext()) { E e = thiz.next(); result = accumulator.applyEx(result, e); } return result; } /** * 統計符合條件的項目數量。 * * @param <TException> 過濾條件函數可拋出的例外型態 * @param condition 過濾條件的函數 * @return 符合條件的項目數量 * @throws TException 表示{@code condition}丟出例外 */ default <TException extends Exception> int count(PredicateEx<? super E, ? extends TException> condition) throws TException { Iterator<E> thiz = (Iterator<E>) this; int count = 0; while (thiz.hasNext()) { E e = thiz.next(); if (condition.testEx(e)) count += 1; } return count; } /** * 計算項目代表數值的平均。 * * @param <TException> 計算數值函數可拋出的例外型態 * @param getValue 計算項目數值的函數 * @return 項目代表數值的平均,或null表示沒有項目 * @throws TException 表示{@code getValue}丟出例外 */ default <TException extends Exception> Double avgDouble(ToDoubleFunctionEx<? super E, ? extends TException> getValue) throws TException { Iterator<E> thiz = (Iterator<E>) this; double total = 0; double count = 0; while (thiz.hasNext()) { E e = thiz.next(); double v = getValue.applyAsDoubleEx(e); total += v; count += 1; } if (count > 0) { return total / count; } else { return null; } } /** * 計算項目代表數值的平均。 * * @param <TException> 計算數值函數可拋出的例外型態 * @param getValue 計算項目數值的函數 * @return 項目代表數值的平均,或null表示沒有項目 * @throws TException 表示{@code getValue}丟出例外 */ default <TException extends Exception> Integer avgInt(ToIntFunctionEx<? super E, ? extends TException> getValue) throws TException { Iterator<E> thiz = (Iterator<E>) this; double total = 0; double count = 0; while (thiz.hasNext()) { E e = thiz.next(); int v = getValue.applyAsIntEx(e); total += v; count += 1; } if (count > 0) { return Math.round((float) (total / count)); } else { return null; } } /** * 計算項目代表數值的平均。 * * @param <TException> 計算數值函數可拋出的例外型態 * @param getValue 計算項目數值的函數 * @return 項目代表數值的平均,或null表示沒有項目 * @throws TException 表示{@code getValue}丟出例外 */ default <TException extends Exception> Long avgLong(ToLongFunctionEx<? super E, ? extends TException> getValue) throws TException { Iterator<E> thiz = (Iterator<E>) this; double total = 0; double count = 0; while (thiz.hasNext()) { E e = thiz.next(); long v = getValue.applyAsLongEx(e); total += v; count += 1; } if (count > 0) { return Math.round(total / count); } else { return null; } } /** * 計算項目代表數值的最大值。 * * @param <TException> 計算數值函數可拋出的例外型態 * @param getValue 計算項目數值的函數 * @return 項目代表數值的最大值,或null表示沒有項目 * @throws TException 表示{@code getValue}丟出例外 */ default <TException extends Exception> Double maxDouble(ToDoubleFunctionEx<? super E, ? extends TException> getValue) throws TException { Iterator<E> thiz = (Iterator<E>) this; Double maxValue = null; while (thiz.hasNext()) { E e = thiz.next(); double v = getValue.applyAsDoubleEx(e); if (maxValue == null || maxValue < v) { maxValue = v; } } return maxValue; } /** * 計算項目代表數值的最大值。 * * @param <TException> 計算數值函數可拋出的例外型態 * @param getValue 計算項目數值的函數 * @return 項目代表數值的最大值,或null表示沒有項目 * @throws TException 表示{@code getValue}丟出例外 */ default <TException extends Exception> Integer maxInt(ToIntFunctionEx<? super E, ? extends TException> getValue) throws TException { Iterator<E> thiz = (Iterator<E>) this; Integer maxValue = null; while (thiz.hasNext()) { E e = thiz.next(); int v = getValue.applyAsIntEx(e); if (maxValue == null || maxValue < v) { maxValue = v; } } return maxValue; } /** * 計算項目代表數值的最大值。 * * @param <TException> 計算數值函數可拋出的例外型態 * @param getValue 計算項目數值的函數 * @return 項目代表數值的最大值,或null表示沒有項目 * @throws TException 表示{@code getValue}丟出例外 */ default <TException extends Exception> Long maxLong(ToLongFunctionEx<? super E, ? extends TException> getValue) throws TException { Iterator<E> thiz = (Iterator<E>) this; Long maxValue = null; while (thiz.hasNext()) { E e = thiz.next(); long v = getValue.applyAsLongEx(e); if (maxValue == null || maxValue < v) { maxValue = v; } } return maxValue; } /** * 計算項目代表數值的最小值。 * * @param <TException> 計算數值函數可拋出的例外型態 * @param getValue 計算項目數值的函數 * @return 項目代表數值的最小值,或null表示沒有項目 * @throws TException 表示{@code getValue}丟出例外 */ default <TException extends Exception> Double minDouble(ToDoubleFunctionEx<? super E, ? extends TException> getValue) throws TException { Iterator<E> thiz = (Iterator<E>) this; Double minValue = null; while (thiz.hasNext()) { E e = thiz.next(); double v = getValue.applyAsDoubleEx(e); if (minValue == null || minValue > v) { minValue = v; } } return minValue; } /** * 計算項目代表數值的最小值。 * * @param <TException> 計算數值函數可拋出的例外型態 * @param getValue 計算項目數值的函數 * @return 項目代表數值的最小值,或null表示沒有項目 * @throws TException 表示{@code getValue}丟出例外 */ default <TException extends Exception> Integer minInt(ToIntFunctionEx<? super E, ? extends TException> getValue) throws TException { Iterator<E> thiz = (Iterator<E>) this; Integer minValue = null; while (thiz.hasNext()) { E e = thiz.next(); int v = getValue.applyAsIntEx(e); if (minValue == null || minValue > v) { minValue = v; } } return minValue; } /** * 計算項目代表數值的最小值。 * * @param <TException> 計算數值函數可拋出的例外型態 * @param getValue 計算項目數值的函數 * @return 項目代表數值的最小值,或null表示沒有項目 * @throws TException 表示{@code getValue}丟出例外 */ default <TException extends Exception> Long minLong(ToLongFunctionEx<? super E, ? extends TException> getValue) throws TException { Iterator<E> thiz = (Iterator<E>) this; Long minValue = null; while (thiz.hasNext()) { E e = thiz.next(); long v = getValue.applyAsLongEx(e); if (minValue == null || minValue > v) { minValue = v; } } return minValue; } /** * 計算項目代表數值的總和。 * * @param <TException> 計算數值函數可拋出的例外型態 * @param getValue 計算項目數值的函數 * @return 項目代表數值的總和,或null表示沒有項目 * @throws TException 表示{@code getValue}丟出例外 */ default <TException extends Exception> double sumDouble(ToDoubleFunctionEx<? super E, ? extends TException> getValue) throws TException { Iterator<E> thiz = (Iterator<E>) this; double sumValue = 0; while (thiz.hasNext()) { E e = thiz.next(); sumValue += getValue.applyAsDoubleEx(e); } return sumValue; } /** * 計算項目代表數值的總和。 * * @param <TException> 計算數值函數可拋出的例外型態 * @param getValue 計算項目數值的函數 * @return 項目代表數值的總和 * @throws TException 表示{@code getValue}丟出例外 */ default <TException extends Exception> int sumInt(ToIntFunctionEx<? super E, ? extends TException> getValue) throws TException { Iterator<E> thiz = (Iterator<E>) this; int sumValue = 0; while (thiz.hasNext()) { E e = thiz.next(); sumValue += getValue.applyAsIntEx(e); } return sumValue; } /** * 計算項目代表數值的總和。 * * @param <TException> 計算數值函數可拋出的例外型態 * @param getValue 計算項目數值的函數 * @return 項目代表數值的總和 * @throws TException 表示{@code getValue}丟出例外 */ default <TException extends Exception> long sumLong(ToIntFunctionEx<? super E, ? extends TException> getValue) throws TException { Iterator<E> thiz = (Iterator<E>) this; long sumValue = 0; while (thiz.hasNext()) { E e = thiz.next(); sumValue += getValue.applyAsIntEx(e); } return sumValue; } /** * 計算項目代表數值的總和。 * * @param <TException> 計算數值函數可拋出的例外型態 * @param getValue 計算項目數值的函數 * @return 項目代表數值的總和 * @throws TException 表示{@code getValue}丟出例外 */ default <TException extends Exception> long sumLong(ToLongFunctionEx<? super E, ? extends TException> getValue) throws TException { Iterator<E> thiz = (Iterator<E>) this; long sumValue = 0; while (thiz.hasNext()) { E e = thiz.next(); sumValue += getValue.applyAsLongEx(e); } return sumValue; } }
jxtn.core.axi/src/java/util/IteratorExt.java
/* * This is free and unencumbered software released into the public domain. * * Anyone is free to copy, modify, publish, use, compile, sell, or * distribute this software, either in source code form or as a compiled * binary, for any purpose, commercial or non-commercial, and by any * means. * * In jurisdictions that recognize copyright laws, the author or authors * of this software dedicate any and all copyright interest in the * software to the public domain. We make this dedication for the benefit * of the public at large and to the detriment of our heirs and * successors. We intend this dedication to be an overt act of * relinquishment in perpetuity of all present and future rights to this * software under copyright law. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. * * For more information, please refer to <http://unlicense.org/> */ package java.util; import java.lang.reflect.Array; import java.util.function.BiFunctionEx; import java.util.function.ConsumerEx; import java.util.function.Function; import java.util.function.FunctionEx; import java.util.function.Predicate; import java.util.function.PredicateEx; import java.util.function.ToDoubleFunctionEx; import java.util.function.ToIntFunctionEx; import java.util.function.ToLongFunctionEx; import jxtn.core.axi.collections.AfterConditionIterator; import jxtn.core.axi.collections.BeforeConditionIterator; import jxtn.core.axi.collections.ConcatedIterator; import jxtn.core.axi.collections.ExpandedIterator; import jxtn.core.axi.collections.FilteredIterator; import jxtn.core.axi.collections.IndexedItem; import jxtn.core.axi.collections.IndexedIterator; import jxtn.core.axi.collections.LinkLineIterator; import jxtn.core.axi.collections.LinkTreeIterator; import jxtn.core.axi.collections.MappedIterator; import jxtn.core.axi.collections.SkippedIterator; import jxtn.core.axi.comparators.MemberComparators; /** * {@link Iterator}的延伸功能。 * <p> * 添加延伸時應同步更新{@link java.lang.IterableExt}。 * </p> * * @author AqD * @param <E> 列舉項目型態 */ public interface IteratorExt<E> { /** * 結合多個列舉器。 * * @param <T> 列舉項目型態 * @param iterators 要結合的列舉器集合 * @return 結合的列舉器 */ @SafeVarargs public static <T> Iterator<T> concatAll(Iterator<? extends T>... iterators) { return new ConcatedIterator<>(Arrays.asList(iterators).iterator()); } /** * 結合多個列舉器。 * * @param <T> 列舉項目型態 * @param iteratorIterable 要結合的列舉器的列舉 * @return 結合的列舉器 */ public static <T> Iterator<T> concatAll(Iterable<Iterator<? extends T>> iteratorIterable) { return new ConcatedIterator<>(iteratorIterable.iterator()); } /** * 結合多個列舉器。 * * @param <T> 列舉項目型態 * @param iteratorIterator 要結合的列舉器的列舉器 * @return 結合的列舉器 */ public static <T> Iterator<T> concatAll(Iterator<Iterator<? extends T>> iteratorIterator) { return new ConcatedIterator<>(iteratorIterator); } /** * 建立線性結構的串接列舉器。 * * @param <T> 列舉項目型態 * @param item 初始項目 * @param getNext 取得每個項目的下一個項目的函數,傳回null表示結尾 * @return 串接列舉器 */ public static <T> Iterator<T> linkLine(T item, Function<? super T, ? extends T> getNext) { return new LinkLineIterator<>(item, getNext); } /** * 建立樹狀結構的串接列舉器。 * * @param <T> 列舉項目型態 * @param item 初始項目;根結點 * @param getChildren 取得每個項目的子項目集合,傳回null表示結尾 * @return 串接列舉器 */ public static <T> Iterator<T> linkTree(T item, Function<? super T, ? extends Iterator<? extends T>> getChildren) { return new LinkTreeIterator<>(item, getChildren); } /** * 針對每個項目執行指定動作 * * @param <TException> 動作可拋出的例外型態 * @param action 要執行的動作 * @throws TException 表示{@code action}丟出例外 */ default <TException extends Exception> void forEachEx(ConsumerEx<? super E, ? extends TException> action) throws TException { Objects.requireNonNull(action); Iterator<E> thiz = (Iterator<E>) this; while (thiz.hasNext()) { action.acceptEx(thiz.next()); } } ////////////////////////////////////////////////////////////////////////// // 條件測試 // /** * 檢查是否所有剩餘項目皆符合指定條件。 * <p> * 結束後列舉器會停在結尾。 * </p> * * @param <TException> 測試條件可拋出的例外型態 * @param condition 條件測試的函數 * @return true表示符合,或沒有項目可測試false表示任一項目不符合 * @throws TException 表示{@code condition}丟出例外 */ default <TException extends Exception> boolean all(PredicateEx<? super E, ? extends TException> condition) throws TException { Iterator<E> thiz = (Iterator<E>) this; while (thiz.hasNext()) { E item = thiz.next(); if (!condition.testEx(item)) { return false; } } return true; } /** * 檢查是否有任一項目符合指定條件。 * <p> * 結束後列舉器會停在第一筆符合項目之後或是結尾。 * </p> * * @param <TException> 測試條件可拋出的例外型態 * @param condition 條件測試的函數 * @return true表示符合false表示所有項目皆不符合,或沒有項目可測試 * @throws TException 表示{@code condition}丟出例外 */ default <TException extends Exception> boolean any(PredicateEx<? super E, ? extends TException> condition) throws TException { Iterator<E> thiz = (Iterator<E>) this; while (thiz.hasNext()) { E item = thiz.next(); if (condition.testEx(item)) { return true; } } return false; } ////////////////////////////////////////////////////////////////////////// // 列舉轉換 // /** * 將目前列舉器作為指定項目型態的列舉器傳回。 * * @param <V> 傳回項目型態 * @return 指定項目型態的列舉器(物件仍為目前列舉器) */ @SuppressWarnings("unchecked") default <V> Iterator<V> as() { return (Iterator<V>) this; } /** * 結合多個項目到結尾。 * * @param tailItems 要結合在結尾的其他項目 * @return 目前列舉及{@code tailItems}的結合 */ @SuppressWarnings("unchecked") default Iterator<E> append(E... tailItems) { List<Iterator<? extends E>> list = Arrays.asList( (Iterator<E>) this, Arrays.asList(tailItems).iterator()); return new ConcatedIterator<>(list.iterator()); } /** * 結合多個項目到開頭。 * * @param headItems 要結合在開頭的其他項目 * @return 目前列舉及{@code tailItems}的結合 */ @SuppressWarnings("unchecked") default Iterator<E> prepend(E... headItems) { List<Iterator<? extends E>> list = Arrays.asList( Arrays.asList(headItems).iterator(), (Iterator<E>) this); return new ConcatedIterator<>(list.iterator()); } /** * 結合多個列舉器。 * * @param iterators 要結合在後面的其他列舉器 * @return 目前列舉器及{@code iterators}的結合 */ @SuppressWarnings("unchecked") default Iterator<E> concat(Iterator<? extends E>... iterators) { List<Iterator<? extends E>> list = new ArrayList<>(iterators.length + 1); list.add((Iterator<E>) this); for (Iterator<? extends E> other : iterators) list.add(other); return new ConcatedIterator<>(list.iterator()); } /** * 依照展開函數建立展開列舉器。 * * @param <R> 展開項目型態 * @param expander 展開項目的函數 * @return 展開列舉器,依賴原有的列舉器 */ default <R> Iterator<R> expand(Function<? super E, Iterator<R>> expander) { Iterator<E> thiz = (Iterator<E>) this; return new ExpandedIterator<>(thiz, expander); } /** * 依照條件建立過濾列舉器。 * * @param condition 過濾條件 * @return 過濾列舉器,依賴原有的列舉器 */ default Iterator<E> filter(Predicate<? super E> condition) { Iterator<E> thiz = (Iterator<E>) this; return new FilteredIterator<>(thiz, condition); } /** * 依照條件建立剔除開頭的列舉器。 * <p> * 列舉內容只保留第一個符合條件後的所有項目(包含該項目)。 * </p> * * @param condition 過濾條件 * @return 過濾列舉器,依賴原有的列舉器 */ default Iterator<E> after(Predicate<? super E> condition) { Iterator<E> thiz = (Iterator<E>) this; return new AfterConditionIterator<>(thiz, condition); } /** * 依照條件建立剔除結尾的列舉器。 * <p> * 列舉內容只保留第一個符合條件前的所有項目(不含該項目)。 * </p> * * @param condition 過濾條件 * @return 過濾列舉器,依賴原有的列舉器 */ default Iterator<E> before(Predicate<? super E> condition) { Iterator<E> thiz = (Iterator<E>) this; return new BeforeConditionIterator<>(thiz, condition); } /** * 建立加上索引的列舉器。 * * @return 加上索引的列舉器,依賴原有的列舉器 */ default Iterator<IndexedItem<E>> indexed() { Iterator<E> thiz = (Iterator<E>) this; return new IndexedIterator<>(thiz); } /** * 依照對照函數建立對照列舉器。 * * @param <R> 對照項目型態 * @param mapper 對照項目的函數 * @return 對照列舉器,依賴原有的列舉器 */ default <R> Iterator<R> map(Function<? super E, ? extends R> mapper) { Iterator<E> thiz = (Iterator<E>) this; return new MappedIterator<>(thiz, mapper); } /** * 建立只包含指定型態項目的列舉器。 * * @param <R> 要取得項目的型態 * @param type 要取得項目的型態 * @return 只包含{@code type}型態項目的列舉 */ @SuppressWarnings("unchecked") default <R> Iterator<R> ofType(Class<? extends R> type) { Iterator<E> thiz = (Iterator<E>) this; return thiz.filter(type::isInstance).map(e -> (R) e); } /** * 建立跳過指定項目數量的列舉器。 * * @param count 要跳過的項目數量 * @return 跳過指定數量的列舉器,依賴原有的列舉器 */ default Iterator<E> skip(int count) { Iterator<E> thiz = (Iterator<E>) this; return new SkippedIterator<>(thiz, count); } ////////////////////////////////////////////////////////////////////////// // 項目挑選 // /** * 取得符合條件的下一筆項目。 * <p> * 結束後列舉器會停在第一筆符合項目之後或是結尾。 * </p> * * @param <TException> 測試條件可拋出的例外型態 * @param condition 取得項目的條件測試函數 * @return 下一筆項目 * @throws NoSuchElementException 沒有下一筆或符合條件的項目 * @throws TException 表示{@code condition}丟出例外 */ default <TException extends Exception> E next(PredicateEx<? super E, ? extends TException> condition) throws TException { Iterator<E> thiz = (Iterator<E>) this; while (thiz.hasNext()) { E item = thiz.next(); if (condition.testEx(item)) { return item; } } throw new NoSuchElementException(); } /** * 取得符合條件的下一筆項目。 * <p> * 結束後列舉器會停在第一筆符合項目之後或是結尾。 * </p> * * @return 下一筆項目,或null表示沒有下一筆或符合條件的項目 */ default E nextOrNull() { Iterator<E> thiz = (Iterator<E>) this; if (thiz.hasNext()) { return thiz.next(); } return null; } /** * 取得符合條件的下一筆項目。 * <p> * 結束後列舉器會停在第一筆符合項目之後或是結尾。 * </p> * * @param <TException> 測試條件可拋出的例外型態 * @param condition 取得項目的條件測試函數 * @return 下一筆項目,或null表示沒有下一筆或符合條件的項目 * @throws TException 表示{@code condition}丟出例外 */ default <TException extends Exception> E nextOrNull(PredicateEx<? super E, ? extends TException> condition) throws TException { Iterator<E> thiz = (Iterator<E>) this; while (thiz.hasNext()) { E item = thiz.next(); if (condition.testEx(item)) { return item; } } return null; } /** * 取得第N筆項目。 * * @param position 位置(相對於目前位置) * @return 第N筆項目 * @throws NoSuchElementException 沒有第N筆項目 */ default E nextNth(int position) { Iterator<E> thiz = (Iterator<E>) this; for (int i = 0; i < position; i++) { thiz.next(); } return thiz.next(); } /** * 取得第N筆項目。 * * @param position 位置(相對於目前位置) * @return 第N筆項目,或null表示沒有第N筆項目 */ default E nextNthOrNull(int position) { Iterator<E> thiz = (Iterator<E>) this; for (int i = 0; i < position; i++) { if (!thiz.hasNext()) return null; thiz.next(); } if (!thiz.hasNext()) return null; return thiz.next(); } /** * 取得下一個可計算出最大數值的項目。 * * @param <TException> 計算數值函數可拋出的例外型態 * @param <V> 數值型態 * @param getValue 計算項目數值的函數 * @return 下一個計算出最大數值的項目(跳過NULL數值) * @throws NoSuchElementException 沒有下一筆項目 * @throws TException 表示{@code getValue}丟出例外 */ default <V extends Comparable<? super V>, TException extends Exception> E nextOfMax(FunctionEx<? super E, ? extends V, ? extends TException> getValue) throws TException { Iterator<E> thiz = (Iterator<E>) this; if (!thiz.hasNext()) throw new NoSuchElementException(); E maxE = thiz.next(); V maxV = getValue.applyEx(maxE); while (thiz.hasNext()) { E curE = thiz.next(); V curV = getValue.applyEx(curE); if (maxV == null || maxV.compareTo(curV) < 0) { maxV = curV; maxE = curE; } } return maxE; } /** * 取得下一個可計算出最大數值的項目。 * * @param <TException> 計算數值函數可拋出的例外型態 * @param getValue 計算項目數值的函數 * @return 下一個計算出最大數值的項目 * @throws NoSuchElementException 沒有下一筆項目 * @throws TException 表示{@code getValue}丟出例外 */ default <TException extends Exception> E nextOfMaxDouble(ToDoubleFunctionEx<? super E, ? extends TException> getValue) throws TException { Iterator<E> thiz = (Iterator<E>) this; if (!thiz.hasNext()) throw new NoSuchElementException(); E maxE = thiz.next(); double maxV = getValue.applyAsDoubleEx(maxE); while (thiz.hasNext()) { E curE = thiz.next(); double curV = getValue.applyAsDoubleEx(curE); if (maxV < curV) { maxV = curV; maxE = curE; } } return maxE; } /** * 取得下一個可計算出最大數值的項目。 * * @param <TException> 計算數值函數可拋出的例外型態 * @param getValue 計算項目數值的函數 * @return 下一個計算出最大數值的項目 * @throws NoSuchElementException 沒有下一筆項目 * @throws TException 表示{@code getValue}丟出例外 */ default <TException extends Exception> E nextOfMaxInt(ToIntFunctionEx<? super E, ? extends TException> getValue) throws TException { Iterator<E> thiz = (Iterator<E>) this; if (!thiz.hasNext()) throw new NoSuchElementException(); E maxE = thiz.next(); int maxV = getValue.applyAsIntEx(maxE); while (thiz.hasNext()) { E curE = thiz.next(); int curV = getValue.applyAsIntEx(curE); if (maxV < curV) { maxV = curV; maxE = curE; } } return maxE; } /** * 取得下一個可計算出最大數值的項目。 * * @param <TException> 計算數值函數可拋出的例外型態 * @param getValue 計算項目數值的函數 * @return 下一個計算出最大數值的項目 * @throws NoSuchElementException 沒有下一筆項目 * @throws TException 表示{@code getValue}丟出例外 */ default <TException extends Exception> E nextOfMaxLong(ToLongFunctionEx<? super E, ? extends TException> getValue) throws TException { Iterator<E> thiz = (Iterator<E>) this; if (!thiz.hasNext()) throw new NoSuchElementException(); E maxE = thiz.next(); long maxV = getValue.applyAsLongEx(maxE); while (thiz.hasNext()) { E curE = thiz.next(); long curV = getValue.applyAsLongEx(curE); if (maxV < curV) { maxV = curV; maxE = curE; } } return maxE; } /** * 取得下一個可計算出最小數值的項目。 * * @param <TException> 計算數值函數可拋出的例外型態 * @param <V> 數值型態 * @param getValue 計算項目數值的函數 * @return 下一個計算出最小數值的項目(跳過NULL數值) * @throws NoSuchElementException 沒有下一筆項目 * @throws TException 表示{@code getValue}丟出例外 */ default <V extends Comparable<? super V>, TException extends Exception> E nextOfMin(FunctionEx<? super E, ? extends V, ? extends TException> getValue) throws TException { Iterator<E> thiz = (Iterator<E>) this; if (!thiz.hasNext()) throw new NoSuchElementException(); E minE = thiz.next(); V minV = getValue.applyEx(minE); while (thiz.hasNext()) { E curE = thiz.next(); V curV = getValue.applyEx(curE); if (minV == null || minV.compareTo(curV) > 0) { minV = curV; minE = curE; } } return minE; } /** * 取得下一個可計算出最小數值的項目。 * * @param <TException> 計算數值函數可拋出的例外型態 * @param getValue 計算項目數值的函數 * @return 下一個計算出最小數值的項目 * @throws NoSuchElementException 沒有下一筆項目 * @throws TException 表示{@code getValue}丟出例外 */ default <TException extends Exception> E nextOfMinDouble(ToDoubleFunctionEx<? super E, ? extends TException> getValue) throws TException { Iterator<E> thiz = (Iterator<E>) this; if (!thiz.hasNext()) throw new NoSuchElementException(); E minE = thiz.next(); double minV = getValue.applyAsDoubleEx(minE); while (thiz.hasNext()) { E curE = thiz.next(); double curV = getValue.applyAsDoubleEx(curE); if (minV > curV) { minV = curV; minE = curE; } } return minE; } /** * 取得下一個可計算出最小數值的項目。 * * @param <TException> 計算數值函數可拋出的例外型態 * @param getValue 計算項目數值的函數 * @return 下一個計算出最小數值的項目 * @throws NoSuchElementException 沒有下一筆項目 * @throws TException 表示{@code getValue}丟出例外 */ default <TException extends Exception> E nextOfMinInt(ToIntFunctionEx<? super E, ? extends TException> getValue) throws TException { Iterator<E> thiz = (Iterator<E>) this; if (!thiz.hasNext()) throw new NoSuchElementException(); E minE = thiz.next(); int minV = getValue.applyAsIntEx(minE); while (thiz.hasNext()) { E curE = thiz.next(); int curV = getValue.applyAsIntEx(curE); if (minV > curV) { minV = curV; minE = curE; } } return minE; } /** * 取得下一個可計算出最小數值的項目。 * * @param <TException> 計算數值函數可拋出的例外型態 * @param getValue 計算項目數值的函數 * @return 下一個計算出最小數值的項目 * @throws NoSuchElementException 沒有下一筆項目 * @throws TException 表示{@code getValue}丟出例外 */ default <TException extends Exception> E nextOfMinLong(ToLongFunctionEx<? super E, ? extends TException> getValue) throws TException { Iterator<E> thiz = (Iterator<E>) this; if (!thiz.hasNext()) throw new NoSuchElementException(); E minE = thiz.next(); long minV = getValue.applyAsLongEx(minE); while (thiz.hasNext()) { E curE = thiz.next(); long curV = getValue.applyAsLongEx(curE); if (minV > curV) { minV = curV; minE = curE; } } return minE; } ////////////////////////////////////////////////////////////////////////// // 項目統整 // /** * 用目前項目值建立陣列。 * * @param type 陣列項目型態 * @return 包含目前項目的陣列 */ @SuppressWarnings("unchecked") default E[] toArray(Class<E> type) { Iterator<E> thiz = (Iterator<E>) this; ArrayList<E> list = thiz.toArrayList(); E[] array = (E[]) Array.newInstance(type, list.size()); return list.toArray(array); } /** * 用目前項目值建立{@link ArrayList}。 * * @return 包含目前項目的{@link ArrayList} */ default ArrayList<E> toArrayList() { Iterator<E> thiz = (Iterator<E>) this; ArrayList<E> coll = new ArrayList<>(); while (thiz.hasNext()) { coll.add(thiz.next()); } return coll; } /** * 用目前項目值建立{@link ArrayList},依照條件做過濾。 * * @param <TException> 測試條件可拋出的例外型態 * @param condition 取得項目的條件測試函數 * @return 包含符合條件項目的{@link ArrayList} * @throws TException 表示{@code mapper}丟出例外 */ default <TException extends Exception> ArrayList<E> toArrayListFiltered(PredicateEx<? super E, ? extends TException> condition) throws TException { Iterator<E> thiz = (Iterator<E>) this; ArrayList<E> coll = new ArrayList<>(); while (thiz.hasNext()) { E e = thiz.next(); if (condition.testEx(e)) coll.add(e); } return coll; } /** * 用目前項目值建立{@link ArrayList},依照函數做對照。 * * @param <R> 對照項目型態 * @param <TException> 對照函數可拋出的例外型態 * @param mapper 對照項目的函數 * @return 包含目前項目對照結果的{@link ArrayList} * @throws TException 表示{@code mapper}丟出例外 */ default <R, TException extends Exception> ArrayList<R> toArrayListMapped(FunctionEx<? super E, ? extends R, ? extends TException> mapper) throws TException { Iterator<E> thiz = (Iterator<E>) this; ArrayList<R> coll = new ArrayList<>(); while (thiz.hasNext()) { coll.add(mapper.applyEx(thiz.next())); } return coll; } /** * 用目前項目值建立{@link ArrayList},依照鍵值做排序。 * * @param <V> 鍵值型態 * @param getKey 計算每個項目的鍵值 * @return 包含目前項目的{@link ArrayList},已排序 */ default <V extends Comparable<?>> ArrayList<E> toArrayListSorted(Function<? super E, ? extends V> getKey) { Iterator<E> thiz = (Iterator<E>) this; ArrayList<E> sorted = thiz.toArrayList(); sorted.sort(MemberComparators.byComparable(getKey)); return sorted; } /** * 用目前項目值建立{@link ArrayList},依照比較器做排序。 * * @param comparator 項目的比較器 * @return 包含目前項目的{@link ArrayList},已排序 */ default ArrayList<E> toArrayListSorted(Comparator<? super E> comparator) { Iterator<E> thiz = (Iterator<E>) this; ArrayList<E> sorted = thiz.toArrayList(); sorted.sort(comparator); return sorted; } /** * 用目前項目值建立{@link HashMap}。 * * @param <K> {@link HashMap}鍵值型態 * @param <KException> 計算鍵值函數可拋出的例外型態 * @param getKey 計算項目於新{@link HashMap}內的鍵值 * @return 包含目前項目對照結果的{@link HashMap} * @throws KException 表示{@code getKey}丟出例外 */ default <K, KException extends Exception> HashMap<K, E> toHashMap(FunctionEx<? super E, ? extends K, ? extends KException> getKey) throws KException { Iterator<E> thiz = (Iterator<E>) this; HashMap<K, E> coll = new HashMap<>(); while (thiz.hasNext()) { E item = thiz.next(); K k = getKey.applyEx(item); coll.put(k, item); } return coll; } /** * 用目前項目值建立{@link HashMap}。 * * @param <K> {@link HashMap}鍵值型態 * @param <V> {@link HashMap}項目值型態 * @param <KException> 計算鍵值函數可拋出的例外型態 * @param <VException> 計算項目值函數可拋出的例外型態 * @param getKey 計算項目於新{@link HashMap}內的鍵值 * @param getValue 計算項目於新{@link HashMap}內的項目值 * @return 包含目前項目對照結果的{@link HashMap} * @throws KException 表示{@code getKey}丟出例外 * @throws VException 表示{@code getValue}丟出例外 */ default <K, V, KException extends Exception, VException extends Exception> HashMap<K, V> toHashMap( FunctionEx<? super E, ? extends K, ? extends KException> getKey, FunctionEx<? super E, ? extends V, ? extends VException> getValue) throws KException, VException { Iterator<E> thiz = (Iterator<E>) this; HashMap<K, V> coll = new HashMap<>(); while (thiz.hasNext()) { E item = thiz.next(); K k = getKey.applyEx(item); V v = getValue.applyEx(item); coll.put(k, v); } return coll; } /** * 用目前項目值建立{@link HashMap},依照鍵值做分群。 * * @param <K> 分群鍵值型態 * @param <KException> 計算鍵值函數可拋出的例外型態 * @param getKey 計算每個項目的鍵值 * @return 包含目前項目分群組的{@link HashMap} * @throws KException 表示{@code getKey}丟出例外 */ default <K, KException extends Exception> HashMap<K, ArrayList<E>> toHashMapGrouped(FunctionEx<? super E, ? extends K, ? extends KException> getKey) throws KException { Iterator<E> thiz = (Iterator<E>) this; HashMap<K, ArrayList<E>> result = new HashMap<>(); while (thiz.hasNext()) { E item = thiz.next(); K key = getKey.applyEx(item); ArrayList<E> list = result.get(key); if (list == null) { list = new ArrayList<>(); result.put(key, list); } list.add(item); } return result; } /** * 用目前項目值建立{@link HashMap},依照鍵值做分群。 * * @param <K> 群組鍵值型態 * @param <V> 項目值型態 * @param <KException> 計算鍵值函數可拋出的例外型態 * @param <VException> 計算項目值函數可拋出的例外型態 * @param getKey 計算每個項目做分組的鍵值 * @param getValue 計算項目於新{@link HashMap}內的項目值 * @return 包含目前項目分群組的{@link HashMap} * @throws KException 表示{@code getKey}丟出例外 * @throws VException 表示{@code getValue}丟出例外 */ default <K, V, KException extends Exception, VException extends Exception> HashMap<K, ArrayList<V>> toHashMapGrouped( FunctionEx<? super E, ? extends K, ? extends KException> getKey, FunctionEx<? super E, ? extends V, ? extends VException> getValue) throws KException, VException { Iterator<E> thiz = (Iterator<E>) this; HashMap<K, ArrayList<V>> result = new HashMap<>(); while (thiz.hasNext()) { E item = thiz.next(); K key = getKey.applyEx(item); ArrayList<V> list = result.get(key); if (list == null) { list = new ArrayList<>(); result.put(key, list); } V value = getValue.applyEx(item); list.add(value); } return result; } /** * 用目前項目值建立{@link HashSet}。 * <p> * 重複值會被重疊覆蓋,後面的優先。 * </p> * * @return 包含目前項目的{@link HashSet} */ default HashSet<E> toHashSet() { Iterator<E> thiz = (Iterator<E>) this; HashSet<E> coll = new HashSet<>(); while (thiz.hasNext()) { coll.add(thiz.next()); } return coll; } /** * 用目前項目值建立{@link TreeMap}。 * * @param <K> {@link TreeMap}鍵值型態 * @param <KException> 計算鍵值函數可拋出的例外型態 * @param getKey 計算項目於新{@link TreeMap}內的鍵值 * @return 包含目前項目對照結果的{@link TreeMap} * @throws KException 表示{@code getKey}丟出例外 */ default <K, KException extends Exception> TreeMap<K, E> toTreeMap(FunctionEx<? super E, ? extends K, ? extends KException> getKey) throws KException { Iterator<E> thiz = (Iterator<E>) this; TreeMap<K, E> coll = new TreeMap<>(); while (thiz.hasNext()) { E item = thiz.next(); K k = getKey.applyEx(item); coll.put(k, item); } return coll; } /** * 用目前項目值建立{@link TreeMap}。 * * @param <K> {@link TreeMap}鍵值型態 * @param <V> {@link TreeMap}項目值型態 * @param <KException> 計算鍵值函數可拋出的例外型態 * @param <VException> 計算項目值函數可拋出的例外型態 * @param getKey 計算項目於新{@link TreeMap}內的鍵值 * @param getValue 計算項目於新{@link TreeMap}內的項目值 * @return 包含目前項目對照結果的{@link TreeMap} * @throws KException 表示{@code getKey}丟出例外 * @throws VException 表示{@code getValue}丟出例外 */ default <K, V, KException extends Exception, VException extends Exception> TreeMap<K, V> toTreeMap( FunctionEx<? super E, ? extends K, ? extends KException> getKey, FunctionEx<? super E, ? extends V, ? extends VException> getValue) throws KException, VException { Iterator<E> thiz = (Iterator<E>) this; TreeMap<K, V> coll = new TreeMap<>(); while (thiz.hasNext()) { E item = thiz.next(); K k = getKey.applyEx(item); V v = getValue.applyEx(item); coll.put(k, v); } return coll; } /** * 用目前項目值建立{@link TreeMap},依照鍵值做分群。 * * @param <K> 分群鍵值型態 * @param <KException> 計算鍵值函數可拋出的例外型態 * @param getKey 計算每個項目的鍵值 * @return 包含目前項目分群組的{@link TreeMap} * @throws KException 表示{@code getKey}丟出例外 */ default <K, KException extends Exception> TreeMap<K, ArrayList<E>> toTreeMapGrouped(FunctionEx<? super E, ? extends K, ? extends KException> getKey) throws KException { Iterator<E> thiz = (Iterator<E>) this; TreeMap<K, ArrayList<E>> result = new TreeMap<>(); while (thiz.hasNext()) { E item = thiz.next(); K key = getKey.applyEx(item); ArrayList<E> list = result.get(key); if (list == null) { list = new ArrayList<>(); result.put(key, list); } list.add(item); } return result; } /** * 用目前項目值建立{@link TreeMap},依照鍵值做分群。 * * @param <K> 群組鍵值型態 * @param <V> 項目值型態 * @param <KException> 計算鍵值函數可拋出的例外型態 * @param <VException> 計算項目值函數可拋出的例外型態 * @param getKey 計算每個項目做分組的鍵值 * @param getValue 計算項目於新{@link TreeMap}內的項目值 * @return 包含目前項目分群組的{@link TreeMap} * @throws KException 表示{@code getKey}丟出例外 * @throws VException 表示{@code getValue}丟出例外 */ default <K, V, KException extends Exception, VException extends Exception> TreeMap<K, ArrayList<V>> toTreeMapGrouped( FunctionEx<? super E, ? extends K, ? extends KException> getKey, FunctionEx<? super E, ? extends V, ? extends VException> getValue) throws KException, VException { Iterator<E> thiz = (Iterator<E>) this; TreeMap<K, ArrayList<V>> result = new TreeMap<>(); while (thiz.hasNext()) { E item = thiz.next(); K key = getKey.applyEx(item); ArrayList<V> list = result.get(key); if (list == null) { list = new ArrayList<>(); result.put(key, list); } V value = getValue.applyEx(item); list.add(value); } return result; } ////////////////////////////////////////////////////////////////////////// // 數學統計 // /** * 進行歸約動作 * * @param <U> 歸約結果型態 * @param <TException> 累加函數可拋出的例外型態 * @param identity 初始值 * @param accumulator 累加函數 * @return 歸約結果 * @throws TException 表示{@code accumulator}丟出例外 */ default <U, TException extends Exception> U reduce( U identity, BiFunctionEx<U, ? super E, U, TException> accumulator) throws TException { Iterator<E> thiz = (Iterator<E>) this; U result = identity; while (thiz.hasNext()) { E e = thiz.next(); result = accumulator.applyEx(result, e); } return result; } /** * 統計符合條件的項目數量。 * * @param <TException> 過濾條件函數可拋出的例外型態 * @param condition 過濾條件的函數 * @return 符合條件的項目數量 * @throws TException 表示{@code condition}丟出例外 */ default <TException extends Exception> int count(PredicateEx<? super E, ? extends TException> condition) throws TException { Iterator<E> thiz = (Iterator<E>) this; int count = 0; while (thiz.hasNext()) { E e = thiz.next(); if (condition.testEx(e)) count += 1; } return count; } /** * 計算項目代表數值的平均。 * * @param <TException> 計算數值函數可拋出的例外型態 * @param getValue 計算項目數值的函數 * @return 項目代表數值的平均,或null表示沒有項目 * @throws TException 表示{@code getValue}丟出例外 */ default <TException extends Exception> Double avgDouble(ToDoubleFunctionEx<? super E, ? extends TException> getValue) throws TException { Iterator<E> thiz = (Iterator<E>) this; double total = 0; double count = 0; while (thiz.hasNext()) { E e = thiz.next(); double v = getValue.applyAsDoubleEx(e); total += v; count += 1; } if (count > 0) { return total / count; } else { return null; } } /** * 計算項目代表數值的平均。 * * @param <TException> 計算數值函數可拋出的例外型態 * @param getValue 計算項目數值的函數 * @return 項目代表數值的平均,或null表示沒有項目 * @throws TException 表示{@code getValue}丟出例外 */ default <TException extends Exception> Integer avgInt(ToIntFunctionEx<? super E, ? extends TException> getValue) throws TException { Iterator<E> thiz = (Iterator<E>) this; double total = 0; double count = 0; while (thiz.hasNext()) { E e = thiz.next(); int v = getValue.applyAsIntEx(e); total += v; count += 1; } if (count > 0) { return Math.round((float) (total / count)); } else { return null; } } /** * 計算項目代表數值的平均。 * * @param <TException> 計算數值函數可拋出的例外型態 * @param getValue 計算項目數值的函數 * @return 項目代表數值的平均,或null表示沒有項目 * @throws TException 表示{@code getValue}丟出例外 */ default <TException extends Exception> Long avgLong(ToLongFunctionEx<? super E, ? extends TException> getValue) throws TException { Iterator<E> thiz = (Iterator<E>) this; double total = 0; double count = 0; while (thiz.hasNext()) { E e = thiz.next(); long v = getValue.applyAsLongEx(e); total += v; count += 1; } if (count > 0) { return Math.round(total / count); } else { return null; } } /** * 計算項目代表數值的最大值。 * * @param <TException> 計算數值函數可拋出的例外型態 * @param getValue 計算項目數值的函數 * @return 項目代表數值的最大值,或null表示沒有項目 * @throws TException 表示{@code getValue}丟出例外 */ default <TException extends Exception> Double maxDouble(ToDoubleFunctionEx<? super E, ? extends TException> getValue) throws TException { Iterator<E> thiz = (Iterator<E>) this; Double maxValue = null; while (thiz.hasNext()) { E e = thiz.next(); double v = getValue.applyAsDoubleEx(e); if (maxValue == null || maxValue < v) { maxValue = v; } } return maxValue; } /** * 計算項目代表數值的最大值。 * * @param <TException> 計算數值函數可拋出的例外型態 * @param getValue 計算項目數值的函數 * @return 項目代表數值的最大值,或null表示沒有項目 * @throws TException 表示{@code getValue}丟出例外 */ default <TException extends Exception> Integer maxInt(ToIntFunctionEx<? super E, ? extends TException> getValue) throws TException { Iterator<E> thiz = (Iterator<E>) this; Integer maxValue = null; while (thiz.hasNext()) { E e = thiz.next(); int v = getValue.applyAsIntEx(e); if (maxValue == null || maxValue < v) { maxValue = v; } } return maxValue; } /** * 計算項目代表數值的最大值。 * * @param <TException> 計算數值函數可拋出的例外型態 * @param getValue 計算項目數值的函數 * @return 項目代表數值的最大值,或null表示沒有項目 * @throws TException 表示{@code getValue}丟出例外 */ default <TException extends Exception> Long maxLong(ToLongFunctionEx<? super E, ? extends TException> getValue) throws TException { Iterator<E> thiz = (Iterator<E>) this; Long maxValue = null; while (thiz.hasNext()) { E e = thiz.next(); long v = getValue.applyAsLongEx(e); if (maxValue == null || maxValue < v) { maxValue = v; } } return maxValue; } /** * 計算項目代表數值的最小值。 * * @param <TException> 計算數值函數可拋出的例外型態 * @param getValue 計算項目數值的函數 * @return 項目代表數值的最小值,或null表示沒有項目 * @throws TException 表示{@code getValue}丟出例外 */ default <TException extends Exception> Double minDouble(ToDoubleFunctionEx<? super E, ? extends TException> getValue) throws TException { Iterator<E> thiz = (Iterator<E>) this; Double minValue = null; while (thiz.hasNext()) { E e = thiz.next(); double v = getValue.applyAsDoubleEx(e); if (minValue == null || minValue > v) { minValue = v; } } return minValue; } /** * 計算項目代表數值的最小值。 * * @param <TException> 計算數值函數可拋出的例外型態 * @param getValue 計算項目數值的函數 * @return 項目代表數值的最小值,或null表示沒有項目 * @throws TException 表示{@code getValue}丟出例外 */ default <TException extends Exception> Integer minInt(ToIntFunctionEx<? super E, ? extends TException> getValue) throws TException { Iterator<E> thiz = (Iterator<E>) this; Integer minValue = null; while (thiz.hasNext()) { E e = thiz.next(); int v = getValue.applyAsIntEx(e); if (minValue == null || minValue > v) { minValue = v; } } return minValue; } /** * 計算項目代表數值的最小值。 * * @param <TException> 計算數值函數可拋出的例外型態 * @param getValue 計算項目數值的函數 * @return 項目代表數值的最小值,或null表示沒有項目 * @throws TException 表示{@code getValue}丟出例外 */ default <TException extends Exception> Long minLong(ToLongFunctionEx<? super E, ? extends TException> getValue) throws TException { Iterator<E> thiz = (Iterator<E>) this; Long minValue = null; while (thiz.hasNext()) { E e = thiz.next(); long v = getValue.applyAsLongEx(e); if (minValue == null || minValue > v) { minValue = v; } } return minValue; } /** * 計算項目代表數值的總和。 * * @param <TException> 計算數值函數可拋出的例外型態 * @param getValue 計算項目數值的函數 * @return 項目代表數值的總和,或null表示沒有項目 * @throws TException 表示{@code getValue}丟出例外 */ default <TException extends Exception> double sumDouble(ToDoubleFunctionEx<? super E, ? extends TException> getValue) throws TException { Iterator<E> thiz = (Iterator<E>) this; double sumValue = 0; while (thiz.hasNext()) { E e = thiz.next(); sumValue += getValue.applyAsDoubleEx(e); } return sumValue; } /** * 計算項目代表數值的總和。 * * @param <TException> 計算數值函數可拋出的例外型態 * @param getValue 計算項目數值的函數 * @return 項目代表數值的總和 * @throws TException 表示{@code getValue}丟出例外 */ default <TException extends Exception> int sumInt(ToIntFunctionEx<? super E, ? extends TException> getValue) throws TException { Iterator<E> thiz = (Iterator<E>) this; int sumValue = 0; while (thiz.hasNext()) { E e = thiz.next(); sumValue += getValue.applyAsIntEx(e); } return sumValue; } /** * 計算項目代表數值的總和。 * * @param <TException> 計算數值函數可拋出的例外型態 * @param getValue 計算項目數值的函數 * @return 項目代表數值的總和 * @throws TException 表示{@code getValue}丟出例外 */ default <TException extends Exception> long sumLong(ToIntFunctionEx<? super E, ? extends TException> getValue) throws TException { Iterator<E> thiz = (Iterator<E>) this; long sumValue = 0; while (thiz.hasNext()) { E e = thiz.next(); sumValue += getValue.applyAsIntEx(e); } return sumValue; } /** * 計算項目代表數值的總和。 * * @param <TException> 計算數值函數可拋出的例外型態 * @param getValue 計算項目數值的函數 * @return 項目代表數值的總和 * @throws TException 表示{@code getValue}丟出例外 */ default <TException extends Exception> long sumLong(ToLongFunctionEx<? super E, ? extends TException> getValue) throws TException { Iterator<E> thiz = (Iterator<E>) this; long sumValue = 0; while (thiz.hasNext()) { E e = thiz.next(); sumValue += getValue.applyAsLongEx(e); } return sumValue; } }
jxtn.core.axi/src/java/util/IteratorExt.java: reformat
jxtn.core.axi/src/java/util/IteratorExt.java
jxtn.core.axi/src/java/util/IteratorExt.java: reformat
<ide><path>xtn.core.axi/src/java/util/IteratorExt.java <ide> result = accumulator.applyEx(result, e); <ide> } <ide> return result; <del> <ide> } <ide> <ide> /**
Java
apache-2.0
349db2fadebf8a2408c5af60a5fe688c3279266f
0
heshamMassoud/RouteMe-API
package com.routeme.model; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import com.google.maps.model.DirectionsRoute; import com.google.maps.model.DirectionsStep; import com.google.maps.model.StopDetails; import com.google.maps.model.TransitDetails; import com.google.maps.model.TransitLine; import com.google.maps.model.TravelMode; import com.google.maps.model.Vehicle; import com.routeme.utility.directions.GoogleDirectionsUtility; import com.routeme.utility.directions.RouteParseException; public class TransitRoute extends Route { public TransitRoute(DirectionsRoute googleDirectionsRoute) throws RouteParseException { super(googleDirectionsRoute); if (departureTime == null || arrivalTime == null) { throw new RouteParseException(); } transportationModes = new ArrayList<String>(); this.setPredictionIoId(); } private void setPredictionIoId() { this.predictionIoId = ""; StopDetails departureStop = null; StopDetails arrivalStop = null; for (int i = 0; i < steps.length; i++) { DirectionsStep currentStep = steps[i]; if (currentStep.travelMode == TravelMode.TRANSIT) { TransitDetails transitDetails = currentStep.transitDetails; if (departureStop == null) { departureStop = transitDetails.departureStop; } arrivalStop = transitDetails.arrivalStop; this.predictionIoId += getTransitStepSummary(transitDetails); if (i != steps.length - 1) { this.predictionIoId += "_"; } } } this.predictionIoId = "[" + departureStop.name + "]" + this.predictionIoId; this.predictionIoId += "[" + arrivalStop.name + "]"; this.predictionIoId = GoogleDirectionsUtility.replaceUmlaut(this.predictionIoId); } private void addTransportationMode(String transportationMode) { transportationModes.add(transportationMode); } private String getTransitStepSummary(TransitDetails transitDetails) { TransitLine transitLine = transitDetails.line; Vehicle transitVehicle = transitLine.vehicle; String headSign = transitDetails.headsign; String lineShortName = transitLine.shortName; String munichVehicleName = GoogleDirectionsUtility.getMunichTransitVehicleName(transitVehicle); addTransportationMode(munichVehicleName); setStepData(munichVehicleName, lineShortName, transitLine.color, headSign); return munichVehicleName + lineShortName + "(" + headSign + ")"; } private void setStepData(String vehicleName, String lineShortName, String lineHexColor, String headSign) { Map<String, String> stepData = new HashMap<String, String>(); stepData.put(TRANSPORTATION_MODE_KEY, vehicleName); stepData.put(TRANSIT_VEHICLE_SHORT_NAME_KEY, lineShortName); stepData.put(TRANSIT_LINE_HEX_COLOR, lineHexColor); stepData.put(TRANSIT_LINE_HEADSIGN, headSign); this.stepsData.add(stepData); } }
src/main/java/com/routeme/model/TransitRoute.java
package com.routeme.model; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import com.google.maps.model.DirectionsRoute; import com.google.maps.model.DirectionsStep; import com.google.maps.model.StopDetails; import com.google.maps.model.TransitDetails; import com.google.maps.model.TransitLine; import com.google.maps.model.TravelMode; import com.google.maps.model.Vehicle; import com.routeme.utility.directions.GoogleDirectionsUtility; import com.routeme.utility.directions.RouteParseException; public class TransitRoute extends Route { boolean firstVehicleInformationSet = false; public TransitRoute(DirectionsRoute googleDirectionsRoute) throws RouteParseException { super(googleDirectionsRoute); if (departureTime == null || arrivalTime == null) { throw new RouteParseException(); } transportationModes = new ArrayList<String>(); this.setPredictionIoId(); } private void setPredictionIoId() { this.predictionIoId = ""; StopDetails departureStop = null; StopDetails arrivalStop = null; for (int i = 0; i < steps.length; i++) { DirectionsStep currentStep = steps[i]; if (currentStep.travelMode == TravelMode.TRANSIT) { TransitDetails transitDetails = currentStep.transitDetails; if (departureStop == null) { departureStop = transitDetails.departureStop; } arrivalStop = transitDetails.arrivalStop; this.predictionIoId += getTransitStepSummary(transitDetails); if (i != steps.length - 1) { this.predictionIoId += "_"; } } } this.predictionIoId = "[" + departureStop.name + "]" + this.predictionIoId; this.predictionIoId += "[" + arrivalStop.name + "]"; this.predictionIoId = GoogleDirectionsUtility.replaceUmlaut(this.predictionIoId); } private void addTransportationMode(String transportationMode) { transportationModes.add(transportationMode); } private String getTransitStepSummary(TransitDetails transitDetails) { TransitLine transitLine = transitDetails.line; Vehicle transitVehicle = transitLine.vehicle; String headSign = transitDetails.headsign; String lineShortName = transitLine.shortName; String munichVehicleName = GoogleDirectionsUtility.getMunichTransitVehicleName(transitVehicle); addTransportationMode(munichVehicleName); setStepData(munichVehicleName, lineShortName, transitLine.color, headSign); return munichVehicleName + lineShortName + "(" + headSign + ")"; } private void setStepData(String vehicleName, String lineShortName, String lineHexColor, String headSign) { Map<String, String> stepData = new HashMap<String, String>(); stepData.put(TRANSPORTATION_MODE_KEY, vehicleName); stepData.put(TRANSIT_VEHICLE_SHORT_NAME_KEY, lineShortName); stepData.put(TRANSIT_LINE_HEX_COLOR, lineHexColor); stepData.put(TRANSIT_LINE_HEADSIGN, headSign); this.stepsData.add(stepData); } }
Remove unneeded variable
src/main/java/com/routeme/model/TransitRoute.java
Remove unneeded variable
<ide><path>rc/main/java/com/routeme/model/TransitRoute.java <ide> import com.routeme.utility.directions.RouteParseException; <ide> <ide> public class TransitRoute extends Route { <del> boolean firstVehicleInformationSet = false; <ide> <ide> public TransitRoute(DirectionsRoute googleDirectionsRoute) throws RouteParseException { <ide> super(googleDirectionsRoute);
Java
apache-2.0
b25454632258fda8367947d0e5640585406d3b62
0
javamelody/javamelody,javamelody/javamelody,javamelody/javamelody
/* * Copyright 2008-2010 by Emeric Vernat * * This file is part of Java Melody. * * Java Melody is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Java Melody is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with Java Melody. If not, see <http://www.gnu.org/licenses/>. */ package net.bull.javamelody; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectOutputStream; import java.io.Serializable; import java.util.ArrayList; import java.util.Collections; import java.util.Date; import java.util.List; import java.util.Locale; import javax.servlet.http.HttpSession; /** * Informations sur une session http. * L'état d'une instance est initialisé à son instanciation et non mutable; * il est donc de fait thread-safe. * Cet état est celui d'une session http à un instant t. * Les instances sont sérialisables pour pouvoir être transmises au serveur de collecte. * @author Emeric Vernat */ class SessionInformations implements Serializable { static final String SESSION_COUNTRY_KEY = "javamelody.country"; static final String SESSION_REMOTE_ADDR = "javamelody.remoteAddr"; static final String SESSION_REMOTE_USER = "javamelody.remoteUser"; private static final long serialVersionUID = -2689338895804445093L; // on utilise ce ByteArrayOutputStream pour calculer les tailles sérialisées, // on n'a qu'une instance pour éviter d'instancier un gros tableau d'octets à chaque session @SuppressWarnings("all") private static final ByteArrayOutputStream TEMP_OUTPUT = new ByteArrayOutputStream(8 * 1024); private final String id; private final Date lastAccess; private final Date age; private final Date expirationDate; private final int attributeCount; private final boolean serializable; private final String country; private final String remoteAddr; private final String remoteUser; private final int serializedSize; @SuppressWarnings("all") private final List<SessionAttribute> attributes; static class SessionAttribute implements Serializable { private static final long serialVersionUID = 4786854834871331127L; private final String name; private final String type; private final String content; private final boolean serializable; private final int serializedSize; SessionAttribute(HttpSession session, String attributeName) { super(); assert session != null; assert attributeName != null; name = attributeName; final Object value = session.getAttribute(attributeName); serializable = value == null || value instanceof Serializable; serializedSize = getObjectSize(value); if (value == null) { content = null; type = null; } else { String tmp; try { tmp = String.valueOf(value); } catch (final Exception e) { tmp = e.toString(); } content = tmp; type = value.getClass().getName(); } } String getName() { return name; } String getType() { return type; } String getContent() { return content; } boolean isSerializable() { return serializable; } int getSerializedSize() { return serializedSize; } } @SuppressWarnings("unchecked") SessionInformations(HttpSession session, boolean includeAttributes) { super(); assert session != null; id = session.getId(); final long now = System.currentTimeMillis(); lastAccess = new Date(now - session.getLastAccessedTime()); age = new Date(now - session.getCreationTime()); expirationDate = new Date(session.getLastAccessedTime() + session.getMaxInactiveInterval() * 1000L); final List<String> attributeNames = Collections.list(session.getAttributeNames()); attributeCount = attributeNames.size(); serializable = computeSerializable(session, attributeNames); final Object countryCode = session.getAttribute(SESSION_COUNTRY_KEY); if (countryCode == null) { country = null; } else { country = countryCode.toString().toLowerCase(Locale.getDefault()); } final Object addr = session.getAttribute(SESSION_REMOTE_ADDR); if (addr == null) { remoteAddr = null; } else { remoteAddr = addr.toString(); } Object user = session.getAttribute(SESSION_REMOTE_USER); if (user == null) { // si getRemoteUser() n'était pas renseigné, on essaye ACEGI_SECURITY_LAST_USERNAME // (notamment pour Hudson/Jenkins) user = session.getAttribute("ACEGI_SECURITY_LAST_USERNAME"); if (user == null) { // et sinon SPRING_SECURITY_LAST_USERNAME user = session.getAttribute("SPRING_SECURITY_LAST_USERNAME"); } } if (user == null) { remoteUser = null; } else { remoteUser = user.toString(); } serializedSize = computeSerializedSize(session, attributeNames); if (includeAttributes) { attributes = new ArrayList<SessionAttribute>(attributeCount); for (final String attributeName : attributeNames) { attributes.add(new SessionAttribute(session, attributeName)); } } else { attributes = null; } } private boolean computeSerializable(HttpSession session, List<String> attributeNames) { for (final String attributeName : attributeNames) { final Object attributeValue = session.getAttribute(attributeName); if (!(attributeValue == null || attributeValue instanceof Serializable)) { return false; } } return true; } private int computeSerializedSize(HttpSession session, List<String> attributeNames) { if (!serializable) { // la taille pour la session est inconnue si un de ses attributs n'est pas sérialisable return -1; } // On calcule la taille sérialisée de tous les attributs en sérialisant une liste les contenant // Rq : la taille sérialisée des attributs ensembles peut être très inférieure à la somme // des tailles sérialisées, car des attributs peuvent référencer des objets communs, // mais la liste contenant introduit un overhead fixe sur le résultat par rapport à la somme des tailles // (de même que l'introduirait la sérialisation de l'objet HttpSession avec ses propriétés standards) // Rq : on ne peut calculer la taille sérialisée exacte de l'objet HttpSession // car cette interface JavaEE n'est pas déclarée Serializable et l'implémentation au moins dans tomcat // n'est pas Serializable non plus // Rq : la taille occupée en mémoire par une session http est un peu différente de la taille sérialisée // car la sérialisation d'un objet est différente des octets occupés en mémoire // et car les objets retenus par une session sont éventuellement référencés par ailleurs // (la fin de la session ne réduirait alors pas l'occupation mémoire autant que la taille de la session) final List<Serializable> serializableAttributes = new ArrayList<Serializable>( attributeNames.size()); for (final String attributeName : attributeNames) { final Object attributeValue = session.getAttribute(attributeName); serializableAttributes.add((Serializable) attributeValue); } return getObjectSize(serializableAttributes); } String getId() { return id; } Date getLastAccess() { return lastAccess; } Date getAge() { return age; } Date getExpirationDate() { return expirationDate; } int getAttributeCount() { return attributeCount; } boolean isSerializable() { return serializable; } String getCountry() { return country; } String getCountryDisplay() { final String myCountry = getCountry(); if (myCountry == null) { return null; } // "fr" est sans conséquence return new Locale("fr", myCountry).getDisplayCountry(I18N.getCurrentLocale()); } String getRemoteAddr() { return remoteAddr; } String getRemoteUser() { return remoteUser; } int getSerializedSize() { return serializedSize; } List<SessionAttribute> getAttributes() { return Collections.unmodifiableList(attributes); } /** {@inheritDoc} */ @Override public String toString() { return getClass().getSimpleName() + "[id=" + getId() + ", remoteAddr=" + getRemoteAddr() + ", serializedSize=" + getSerializedSize() + ']'; } static int getObjectSize(Object object) { if (!(object instanceof Serializable)) { return -1; } final Serializable serializable = (Serializable) object; // synchronized pour protéger l'accès à TEMP_OUTPUT static synchronized (TEMP_OUTPUT) { TEMP_OUTPUT.reset(); try { final ObjectOutputStream out = new ObjectOutputStream(TEMP_OUTPUT); try { out.writeObject(serializable); } finally { out.close(); } return TEMP_OUTPUT.size(); } catch (final IOException e) { return -1; } } } }
javamelody-core/src/main/java/net/bull/javamelody/SessionInformations.java
/* * Copyright 2008-2010 by Emeric Vernat * * This file is part of Java Melody. * * Java Melody is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Java Melody is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with Java Melody. If not, see <http://www.gnu.org/licenses/>. */ package net.bull.javamelody; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectOutputStream; import java.io.Serializable; import java.util.ArrayList; import java.util.Collections; import java.util.Date; import java.util.List; import java.util.Locale; import javax.servlet.http.HttpSession; /** * Informations sur une session http. * L'état d'une instance est initialisé à son instanciation et non mutable; * il est donc de fait thread-safe. * Cet état est celui d'une session http à un instant t. * Les instances sont sérialisables pour pouvoir être transmises au serveur de collecte. * @author Emeric Vernat */ class SessionInformations implements Serializable { static final String SESSION_COUNTRY_KEY = "javamelody.country"; static final String SESSION_REMOTE_ADDR = "javamelody.remoteAddr"; static final String SESSION_REMOTE_USER = "javamelody.remoteUser"; private static final long serialVersionUID = -2689338895804445093L; // on utilise ce ByteArrayOutputStream pour calculer les tailles sérialisées, // on n'a qu'une instance pour éviter d'instancier un gros tableau d'octets à chaque session @SuppressWarnings("all") private static final ByteArrayOutputStream TEMP_OUTPUT = new ByteArrayOutputStream(8 * 1024); private final String id; private final Date lastAccess; private final Date age; private final Date expirationDate; private final int attributeCount; private final boolean serializable; private final String country; private final String remoteAddr; private final String remoteUser; private final int serializedSize; @SuppressWarnings("all") private final List<SessionAttribute> attributes; static class SessionAttribute implements Serializable { private static final long serialVersionUID = 4786854834871331127L; private final String name; private final String type; private final String content; private final boolean serializable; private final int serializedSize; SessionAttribute(HttpSession session, String attributeName) { super(); assert session != null; assert attributeName != null; name = attributeName; final Object value = session.getAttribute(attributeName); serializable = value == null || value instanceof Serializable; serializedSize = getObjectSize(value); if (value == null) { content = null; type = null; } else { String tmp; try { tmp = String.valueOf(value); } catch (final Exception e) { tmp = e.toString(); } content = tmp; type = value.getClass().getName(); } } String getName() { return name; } String getType() { return type; } String getContent() { return content; } boolean isSerializable() { return serializable; } int getSerializedSize() { return serializedSize; } } @SuppressWarnings("unchecked") SessionInformations(HttpSession session, boolean includeAttributes) { super(); assert session != null; id = session.getId(); final long now = System.currentTimeMillis(); lastAccess = new Date(now - session.getLastAccessedTime()); age = new Date(now - session.getCreationTime()); expirationDate = new Date(session.getLastAccessedTime() + session.getMaxInactiveInterval() * 1000L); final List<String> attributeNames = Collections.list(session.getAttributeNames()); attributeCount = attributeNames.size(); serializable = computeSerializable(session, attributeNames); final Object countryCode = session.getAttribute(SESSION_COUNTRY_KEY); if (countryCode == null) { country = null; } else { country = countryCode.toString().toLowerCase(Locale.getDefault()); } final Object addr = session.getAttribute(SESSION_REMOTE_ADDR); if (addr == null) { remoteAddr = null; } else { remoteAddr = addr.toString(); } final Object user = session.getAttribute(SESSION_REMOTE_USER); if (user == null) { remoteUser = null; } else { remoteUser = user.toString(); } serializedSize = computeSerializedSize(session, attributeNames); if (includeAttributes) { attributes = new ArrayList<SessionAttribute>(attributeCount); for (final String attributeName : attributeNames) { attributes.add(new SessionAttribute(session, attributeName)); } } else { attributes = null; } } private boolean computeSerializable(HttpSession session, List<String> attributeNames) { for (final String attributeName : attributeNames) { final Object attributeValue = session.getAttribute(attributeName); if (!(attributeValue == null || attributeValue instanceof Serializable)) { return false; } } return true; } private int computeSerializedSize(HttpSession session, List<String> attributeNames) { if (!serializable) { // la taille pour la session est inconnue si un de ses attributs n'est pas sérialisable return -1; } // On calcule la taille sérialisée de tous les attributs en sérialisant une liste les contenant // Rq : la taille sérialisée des attributs ensembles peut être très inférieure à la somme // des tailles sérialisées, car des attributs peuvent référencer des objets communs, // mais la liste contenant introduit un overhead fixe sur le résultat par rapport à la somme des tailles // (de même que l'introduirait la sérialisation de l'objet HttpSession avec ses propriétés standards) // Rq : on ne peut calculer la taille sérialisée exacte de l'objet HttpSession // car cette interface JavaEE n'est pas déclarée Serializable et l'implémentation au moins dans tomcat // n'est pas Serializable non plus // Rq : la taille occupée en mémoire par une session http est un peu différente de la taille sérialisée // car la sérialisation d'un objet est différente des octets occupés en mémoire // et car les objets retenus par une session sont éventuellement référencés par ailleurs // (la fin de la session ne réduirait alors pas l'occupation mémoire autant que la taille de la session) final List<Serializable> serializableAttributes = new ArrayList<Serializable>( attributeNames.size()); for (final String attributeName : attributeNames) { final Object attributeValue = session.getAttribute(attributeName); serializableAttributes.add((Serializable) attributeValue); } return getObjectSize(serializableAttributes); } String getId() { return id; } Date getLastAccess() { return lastAccess; } Date getAge() { return age; } Date getExpirationDate() { return expirationDate; } int getAttributeCount() { return attributeCount; } boolean isSerializable() { return serializable; } String getCountry() { return country; } String getCountryDisplay() { final String myCountry = getCountry(); if (myCountry == null) { return null; } // "fr" est sans conséquence return new Locale("fr", myCountry).getDisplayCountry(I18N.getCurrentLocale()); } String getRemoteAddr() { return remoteAddr; } String getRemoteUser() { return remoteUser; } int getSerializedSize() { return serializedSize; } List<SessionAttribute> getAttributes() { return Collections.unmodifiableList(attributes); } /** {@inheritDoc} */ @Override public String toString() { return getClass().getSimpleName() + "[id=" + getId() + ", remoteAddr=" + getRemoteAddr() + ", serializedSize=" + getSerializedSize() + ']'; } static int getObjectSize(Object object) { if (!(object instanceof Serializable)) { return -1; } final Serializable serializable = (Serializable) object; // synchronized pour protéger l'accès à TEMP_OUTPUT static synchronized (TEMP_OUTPUT) { TEMP_OUTPUT.reset(); try { final ObjectOutputStream out = new ObjectOutputStream(TEMP_OUTPUT); try { out.writeObject(serializable); } finally { out.close(); } return TEMP_OUTPUT.size(); } catch (final IOException e) { return -1; } } } }
To display the username in the list of http sessions, look at ACEGI_SECURITY_LAST_USERNAME and SPRING_SECURITY_LAST_USERNAME if getRemoteUser() was null (In particular, for Jenkins/Hudson)
javamelody-core/src/main/java/net/bull/javamelody/SessionInformations.java
To display the username in the list of http sessions, look at ACEGI_SECURITY_LAST_USERNAME and SPRING_SECURITY_LAST_USERNAME if getRemoteUser() was null (In particular, for Jenkins/Hudson)
<ide><path>avamelody-core/src/main/java/net/bull/javamelody/SessionInformations.java <ide> remoteAddr = addr.toString(); <ide> } <ide> <del> final Object user = session.getAttribute(SESSION_REMOTE_USER); <add> Object user = session.getAttribute(SESSION_REMOTE_USER); <add> if (user == null) { <add> // si getRemoteUser() n'était pas renseigné, on essaye ACEGI_SECURITY_LAST_USERNAME <add> // (notamment pour Hudson/Jenkins) <add> user = session.getAttribute("ACEGI_SECURITY_LAST_USERNAME"); <add> if (user == null) { <add> // et sinon SPRING_SECURITY_LAST_USERNAME <add> user = session.getAttribute("SPRING_SECURITY_LAST_USERNAME"); <add> } <add> } <ide> if (user == null) { <ide> remoteUser = null; <ide> } else {
JavaScript
mit
610b05c31a322227c325e3d5f613ed3073a3b9ae
0
dumconstantin/generator-x,dumconstantin/generator-x,dumconstantin/generator-x
// ---------------------------------- // GeneratorX // @author Constantin Dumitrescu // @author Bogdan Matei // @company Brandup // @version 0.1.0 // ---------------------------------- (function () { "use strict"; var fs = require('fs'), path = require('path'), PNG = require('pngjs').PNG, events = new require('events'); // GLOBAL TODOs // // TODO: If the designer has his Types and Rulers in anything else // than pixels, all values must be converted before using. // Defaults: types (points) rulers (in?) // // /** * Has method * Will provide a response for a chain of Object properties * e.g: x.has('one.of.these.properties'); */ Object.defineProperty(Object.prototype, '_has', { enumerable : false, value : function(params) { var tester; if ('function' !== typeof params && 'string' === typeof params) { try { eval('tester = this.' + params); // This eval is not evil , as long is completely secured if (undefined === tester) { throw new Error('The property ' + params + ' is not available'); } } catch (e) { return false; } } else { return false; } return true; } }); /** * getValueOf * Retrieves the value of a chained Object properties */ Object.defineProperty(Object.prototype, '_get', { enumerable : false, value : function(params, fallback) { var value; if ('function' !== typeof params && 'string' === typeof params) { try { eval('value = this.' + params.toString()); if (undefined === value) { throw new Error('not available'); } } catch (e) { if (undefined !== fallback) { return fallback; } return undefined; } } else { return false; } return value; } }); // TODO: Create a test suite generator to get the GenX File and generate also images // Which will be shown on the same page as a left and right comparison. function init(generator) { generator.getDocumentInfo().then( function (document) { runGenerator(document, generator); }, function (err) { console.error(" Error in getDocumentInfo:", err); } ).done(); } function stringify(obj, circularProperties) { var stringified, circularProperties = circularProperties ? circularProperties : []; function removeCircular(name, value) { if (-1 === circularProperties.indexOf(name)) { return value; } else { //Undefined properties will be removed from JSON. return undefined; } } try { if (0 === circularProperties.length) { stringified = JSON.stringify(obj, null, 4); } else { stringified = JSON.stringify(obj, removeCircular, 4); } } catch (e) { console.error('Stringify error:', e); stringified = String(obj); } return stringified; } // TODO: Spawn a worker to handle the saving of the pixmap. function savePixmap(pixmap, filePath, emitter){ var pixels = pixmap.pixels, len = pixels.length, pixel, location, png, channelNo = pixmap.channelCount; // Convert from ARGB to RGBA, we do this every 4 pixel values (channelCount) for(location = 0; location < len; location += channelNo){ pixel = pixels[location]; pixels[location] = pixels[location + 1]; pixels[location + 1] = pixels[location + 2]; pixels[location + 2] = pixels[location + 3]; pixels[location + 3] = pixel; } var png = new PNG({ width: pixmap.width, height: pixmap.height }); png.data = pixels; png.on('end', function () { emitter.emit('finishedImage'); }); png .pack() .pipe(fs.createWriteStream(filePath)) } function getCSSFontFamily(fontName) { var font = ""; switch (fontName) { case 'Oswald': font += "\n @font-face {" + " font-family: 'oswaldbook'; " + " src: url('fonts/oswald-regular.eot');" + " src: url('fonts/oswald-regular.eot?#iefix') format('embedded-opentype')," + " url('fonts/oswald-regular.woff') format('woff')," + " url('fonts/oswald-regular.ttf') format('truetype')," + " url('fonts/oswald-regular.svg#oswaldbook') format('svg');" + " font-weight: normal;" + " font-style: normal; " + " } \n"; break; case 'IcoMoon': font += "@font-face { " + " font-family: 'icomoonregular';" + " src: url('fonts/icomoon.eot');" + " src: url('fonts/icomoon.eot?#iefix') format('embedded-opentype')," + " url('fonts/icomoon.woff') format('woff')," + " url('fonts/icomoon.ttf') format('truetype')," + " url('fonts/icomoon.svg#icomoonregular') format('svg');" + " font-weight: normal;" + " font-style: normal;" + " } \n"; break; case 'Futura': break; case 'Helvetica': break; case 'Helvetica Neue': break; case 'Arial': break; case 'Myriad': break; case 'Tipogram': break; case 'Roboto': var roboto = { black: 'robotoblack', blackitalic: 'robotoblack_italic', bold: 'robotobold', bolditalic: 'robotobold_italic', italic: 'robotoitalic', light: 'robotolight', medium: 'robotomedium', mediumitalic: 'robotomedium_italic', regular: 'robotoregular', thin: 'robotothin', thinitalic: 'robotothin_italic' }; Object.keys(roboto).forEach(function (variant) { font += "@font-face {" + "font-family: '" + roboto[variant]+ "'; " + " src: url('fonts/roboto-" + variant + ".eot'); " + " src: url('fonts/roboto-" + variant + ".eot?#iefix') format('embedded-opentype')," + " url('fonts/roboto-" + variant + ".woff') format('woff')," + " url('fonts/roboto-" + variant + ".ttf') format('truetype')," + " url('fonts/roboto-" + variant + ".svg#roboto" + variant + "') format('svg');" + "font-weight: normal;" + "font-style: normal;" + "}"; }); break; default: // console.log('The font name "' + fontName + '" is not supported.'); break; } return font; } function createBoxShadow(shadowStyles, shadowType, elementType) { var property = "", shadow = shadowStyles[shadowType], angle = 0 < shadow.angle ? shadow.angle : 360 + shadow.angle, // 91 is so that the substraction does not result in 0; normalisedAngle = angle - 90 * Math.floor(angle / 91), x, y, percent; if (-1 === ['outerGlow', 'innerGlow'].indexOf(shadowType)) { // TODO: Accomodate for the chokeMatte property percent = normalisedAngle / 90; if (angle <= 90) { x = - (shadow.distance - shadow.distance * percent); y = shadow.distance * percent; } else if (angle <= 180) { x = shadow.distance * percent; y = shadow.distance - shadow.distance * percent; } else if (angle <= 270) { x = shadow.distance - shadow.distance * percent; y = - shadow.distance * percent; } else if (angle <= 360) { x = - (shadow.distance * percent); y = - (shadow.distance - shadow.distance * percent); } } else { x = 0; y = 0; } if (true === shadowStyles.outer.active && 'inset' === shadowType) { property += ', '; } if (true === shadowStyles.outerGlow.active && 'innerGlow' === shadowType) { property += ', '; } // TODO: For outer glows, create the use case for gradient usage instead // of solid color. property += Math.round(x) + 'px ' + Math.round(y) + 'px '; // TOOD: Establish the relation between innerGlow parameters (chokeMatte and size) and // omolog values in CSS. // It seems that a Choke: 90%, Size: 10px is the same as box-shadow: 0 0 0 10px if ('innerGlow' === shadowType) { if (0 !== shadow.spread) { property += (shadow.blur - (shadow.blur * shadow.spread / 100)) + 'px '; } // If this is a text layer then a pseudo element will be generated for the glow. // The text-shadow does not have an additional parameter. if ('textLayer' !== elementType) { property += shadow.blur + 'px '; } } else if ('outerGlow' === shadowType) { property += shadow.blur + 'px '; // Same as above. if ('textLayer' !== elementType) { property += shadow.spread + 'px '; } } else { property += shadow.blur + 'px '; } property += ' rgba(' + Math.round(shadow.color.red) + ', ' + Math.round(shadow.color.green) + ', ' + Math.round(shadow.color.blue) + ', ' + (shadow.opacity / 100) + ')'; if (('inset' === shadowType || 'innerGlow' === shadowType) && 'textLayer' !== elementType) { property += ' inset'; } return property; } // All sections are still layers. // The semantic is given by the way the interaction with the dom will occur // A layer must have: // - tag: div, p, span, etc // - class // - id // - text // - parent/nextSibling/prevSibling for traversing // - css all the css properties that will eventually end in the stylesheet // Parsing will be made in 3 stages: // 1. The parsing of the PSD document with absolute styles - Done // 2. From the absolute styles connections between elements will emerge (e.g. floats, overlay, etc) // 3. Establish the logical order of dom elements (based on float, etc) // 4. Find patterns in styles through css duplication, hierachy and inheritance to optimise the css creation // 5. Create the HTML version of the structure // 6. Create the CSS version of the layers // 7. Create a file with the HTML and CSS code // TODO: For layers that have the same name regardless of their position // in the structure tree, allocate different cssNames to avoid id collision function parseCSS(style, globalStyles, overWrites) { // TODO: Add default styles for all the bellow properties. var css = { top: style._get('bounds.top', 0), right: style._get('bounds.right', 0), bottom: style._get('bounds.bottom', 0), left: style._get('bounds.left', 0), position: 'static', background: { masterActive: style._get('layerEffects.masterFXSwitch', true), active: style._has('fill'), color: { red: style._get('fill.color.red', 255), green: style._get('fill.color.green', 255), blue: style._get('fill.color.blue', 255) }, gradient: { colors: [], locations: [], reverse: style._get('layerEffects.gradientFill.reverse', false), type: 'linear', opacity: style._get('layerEffects.gradientFill.opacity.value', 100), angle: style._get('layerEffects.gradientFill.angle.value', -90) }, // Background type (linear, radial, angle) type: style._get('layerEffects.gradientFill.type', 'linear') }, opacity: style._get('blendOptions.opacity.value', 100) / 100, border: { masterActive: style._get('layerEffects.masterFXSwitch', true), active: style._has('layerEffects.frameFX'), color: { red: style._get('layerEffects.frameFX.color.red', 255), green: style._get('layerEffects.frameFX.color.green', 255), blue: style._get('layerEffects.frameFX.color.blue', 255) }, opacity: style._get('layerEffects.frameFX.opacity.value', 100), size: style._get('layerEffects.frameFX.size', 3) }, boxSizing: style._get('layerEffects.frameFX.style', 'outsetFrame'), boxShadow: { masterActive: style._get('layerEffects.masterFXSwitch', true), active: style._has('layerEffects.dropShadow') || style._has('layerEffects.innerShadow') || style._has('layerEffects.outerGlow') || style._has('layerEffects.innerGlow'), outer: { active: style._has('layerEffects.dropShadow'), color: { red: style._get('layerEffects.dropShadow.color.red', 0), green: style._get('layerEffects.dropShadow.color.green', 0), blue: style._get('layerEffects.dropShadow.color.blue', 0) }, opacity: style._get('layerEffects.dropShadow.opacity.value', 75), distance: style._get('layerEffects.dropShadow.distance', 5), blur: style._get('layerEffects.dropShadow.blur', 5), angle: style._get('layerEffects.dropShadow.localLightingAngle.value', 120), spread: style._get('layerEffects.dropShadow.chokeMatte', 0) }, inset: { active: style._has('layerEffects.innerShadow'), color: { red: style._get('layerEffects.innerShadow.color.red', 0), green: style._get('layerEffects.innerShadow.color.green', 0), blue: style._get('layerEffects.innerShadow.color.blue', 0) }, opacity: style._get('layerEffects.innerShadow.opacity.value', 75), distance: style._get('layerEffects.innerShadow.distance', 5), blur: style._get('layerEffects.innerShadow.blur', 5), // TODO: Add global lighting angle angle: style._get('layerEffects.innerShadow.localLightingAngle.value', 120), spread: style._get('layerEffects.innerShadow.chokeMatte', 0) }, outerGlow: { active: style._has('layerEffects.outerGlow'), color: { red: style._get('layerEffects.outerGlow.color.red', 255), green: style._get('layerEffects.outerGlow.color.green', 255), blue: style._get('layerEffects.outerGlow.color.blue', 190), }, blur: style._get('layerEffects.outerGlow.blur', 5), opacity: style._get('layerEffects.outerGlow.opacity.value', 75), spread: style._get('layerEffects.outerGlow.chokeMatte', 0) }, innerGlow: { active: style._has('layerEffects.innerGlow'), color: { red: style._get('layerEffects.innerGlow.color.red', 255), green: style._get('layerEffects.innerGlow.color.green', 255), blue: style._get('layerEffects.innerGlow.color.blue', 190), }, blur: style._get('layerEffects.innerGlow.blur', 5), opacity: style._get('layerEffects.innerGlow.opacity.value', 75), spread: style._get('layerEffects.innerGlow.chokeMatte', 0) } }, borderRadius: [], zIndex: style.index, color: { red: style._get('text.textStyleRange[0].textStyle.color.red', 0), green: style._get('text.textStyleRange[0].textStyle.color.green', 0), blue: style._get('text.textStyleRange[0].textStyle.color.blue', 0) }, fontSize: style._get('text.textStyleRange[0].textStyle.size', 16), textAlign: style._get('text.paragraphStyleRange[0].paragraphStyle.align', 'inherit'), fontFamily: { family: style._get('text.textStyleRange[0].textStyle.fontName', 'Arial'), variant: style._get('text.textStyleRange[0].textStyle.fontStyleName', 'Regular') } }, textColor; Object.keys(overWrites).forEach(function (property) { css[property] = overWrites[property]; }); // ----------------- // Background styles // Fill color overwritted by the blend options css.background.color = { red: style._get('layerEffects.solidFill.color.red', css.background.color.red), green: style._get('layerEffects.solidFill.color.green', css.background.color.green), blue: style._get('layerEffects.solidFill.color.blue', css.background.color.blue) }; // Inner and outer shadows can opt to not use globalAngles and have // the default angle. if (true === style._get('layerEffects.innerShadow.useGlobalAngle', true)) { css.boxShadow.inset.angle = globalStyles.globalLight.angle; } if (true === style._get('layerEffects.dropShadow.useGlobalAngle', true)) { css.boxShadow.outer.angle = globalStyles.globalLight.angle; } // TODO: It seems that for shadows the 100% opacity is not 100% CSS opacity // but somewhere around 80%. Experiment with this and try to find a // good approximation. // TODO: Account for different blend modes for each style. This would be an // advanced feature and would require a canvas to plot individual features // and an implementation of blend mode algorithms to obtain accurate CSS // values. // TODO: Depending on the degree of accuracy the user requires, the layer can be // exported as an image to ensure that all FX styles are 100% accurate. // TODO: Implement Radial Gradient // TODO: Implement Angle Gradient // TODO: Implement Drop shadow countour settings on layersEffects.dropShadow.transferSpec // Gradient Colors style._get('layerEffects.gradientFill.gradient.colors', []).forEach(function (color) { css.background.gradient.colors.push({ red: color.color.red, green: color.color.green, blue: color.color.blue, location: color.location, type: color.type, midpoint: color.midpoint }); css.background.gradient.locations.push(color.location); }); // The color array is in reverse order due to the way is added css.background.gradient.colors.reverse(); // TODO: Implement border // Border Radius switch (style._get('path.pathComponents[0].origin.type', '')) { case 'roundedRect': css.borderRadius = style._get('path.pathComponents[0].origin.radii', []); break; case 'ellipse': // this actually requires to be transffered to an SVG // ellipse implementation (function () { var bounds = style._get('path.pathComponents[0].origin.bounds', {}), width = bounds.bottom - bounds.top, height = bounds.right - bounds.left; css.borderRadius[0] = height / 2; }()); break; default: // There is no border radius. break; } if (true === style._has('strokeStyle', false)) { // TODO: Implement strokeStyles for shape layers. // This can either be a new ::before / ::after element with // a transparent background and a border. // OR in some cases it might be an SVG. } if (false === style._get('strokeStyle.fillEnabled', true)) { css.background.active = false; } // [TEMP] Default dimensions. css.width = css.right - css.left; css.height = css.bottom - css.top; if ('textLayer' === style.type) { // TODO: Revisit lineHeight / leading styles. There might be // a better way to parse lineHeight. // 30 seems to be the default leading/line height. // In CSS the line height is set on the line on which the text sits // while leading seems to be the distance between lines. // 7. However, if leading is set to "auto", the actual leading number is 120% of the font size. css.lineHeight = (css.fontSize + style._get('text.textStyleRange[0].textStyle.leading', 30) / 2) - 1; /* (function () { var baseLineShift = Math.abs(style._get('text.textStyleRange[0].textStyle.baselineShift', 1)); // 1px baseLineShift = 2.40566 if (2.40566 > baseLineShift) { css.fontSize = Math.floor(css.fontSize / 2); css.lineHeight = Math.floor(css.lineHeight / 2); } }()); */ (function () { var textStyleRanges = style._get('text.textStyleRange', []); if (1 === textStyleRanges.length) { css.fontWeight = style._get('text.textStyleRange[0].textStyle.syntheticBold', false), css.fontStyle = style._get('text.textStyleRange[0].textStyle.syntheticItalic', false) } else { css.fontWeight = false; css.fontStyle = false; } }()); // TODO: Implement the WebKit algorithm to detect the real width of the // text with all the styles attached. // This should do the following: // 1. Parse the .ttf file // 2. Create the sequence of text vectors dictated by the .ttf rules // of binding characters // 3. Add the text transformation on the created sequence of vectors // 4. Extract the width pixel value from the vector implementation in // bitmap environment. // TODO: Adjust the estimated px value bellow that seems to accomodate // the difference between PSD and Browser text rendering. css.width = css.width + 10; css.height = 'auto'; // Definitions: // boundingBox: the coordinates that wrap the text // bounds: the coordinates that wrap the user defined area for the text or // if the area wasn't defined by the user, the total area occupied // by the text which might be different than the boundingBox coordinates (function () { var bounds = style._get('text.bounds'), boxBounds = style._get('text.boundingBox'), boundsWidth = bounds.right - bounds.left, boundsHeight = bounds.bottom - bounds.top, boxBoundsWidth = boxBounds.right - boxBounds.left, boxWidthDifference = boxBoundsWidth - boundsWidth; // From inital experimentation the difference between the bounds // when not having a user defined area is within a 10 px range. // Of course, this is empiric evidence and needs further research. // Also, an area that is less than 10 px from the area occupied // by the text leaves little room for alignment (which is in fact // the goal of this). If the desiner did create a less than 10 px // container for the text then this might be a bad practice to do // so. if (6 > Math.abs(boxWidthDifference)) { // The text does not have a defined area and an be left // to be arranged through the alignment styles of the parent // element. css.textAlign = 'left'; // TODO: This is a sub optimal solution to compensate for the difference between // line height and leading. css.top -= 7; } else { // The text has a defined area and needs to be further // wrapped in a parent container element. css.width = boundsWidth; css.height = boundsHeight; css.left -= Math.ceil(boxBounds.left); } }()); } // [TEMP] Overwrite positioning for now css.position = 'absolute'; // TODO: Implement outer glow // TODO: Implement inner shadow/inner glow // --------- // Text styles // For some reason font size comes in a different format that is // TODO: Line height // leading / font size // css.lineHeight = ((style._get('text.textStyleRange[0].textStyle.leading', 16) / css.fontSize) * 1000 ) / 1000; // // Overwrites // // Border requires adjustments to top, left and widht, height if (true === css.border.active) { // TODO: Figure out how to keep the box-sizing: border-box. Currently // inside photoshop you set the content css.backgroundClip = 'content-box'; if ('insetFrame' === css.boxSizing) { css.borderRadius.forEach(function (bound, index) { css.borderRadius[index] = bound + css.border.size; }); } else if ('outsetFrame' === css.boxSizing) { css.top -= css.border.size; css.left -= css.border.size; css.borderRadius.forEach(function (bound, index) { css.borderRadius[index] = bound + css.border.size; }); } else if ('centeredFrame' === css.boxSizing) { css.top -= css.border.size / 2; css.left -= css.border.size / 2; css.width -= css.border.size; css.height -= css.border.size; css.borderRadius.forEach(function (bound, index) { css.borderRadius[index] = bound + css.border.size; }); } else { console.log('The box sizing "' + css.boxSizing + '" is not recognised.'); } } return css; } function parseText(layer) { var text = layer._get('text.textKey', ''), transformedText = '', textRanges = layer._get('text.textStyleRange', []), lastParsedIndex = 0; if (1 === textRanges.length) { // If there is just one text range that means the text // is uniform. } else { textRanges.forEach(function (range) { var extractedText = text.substr(range.from, range.to - range.from), styles = "", fontFamily = range.textStyle.fontName, fontVariant = range.textStyle.fontStyleName; // For some reason Photoshop sometimes returns a duplicated // text range. if (lastParsedIndex !== range.to) { return; } lastParsedIndex = range.to; styles += 'font-family: ' + fontFamily.toLowerCase() + fontVariant.replace(' ', '_').toLowerCase(); // TODO: Add the ability to combine bold, italic or // other styles on a single text. This might require // 1. a single wrapper with clases: // <span class="bold italic fontSize20px">Text</span> // 2. or a custom id // <span id="custom-styling-113">Text</span> // I think I would prefer option No. 1 if (true === range.textStyle.syntheticBold) { extractedText = '<strong style="' + styles + '">' + extractedText + '</strong>'; } else if (true === range.textStyle.syntheticItalic) { extractedText = '<em style="' + styles + '">' + extractedText + '</em>'; } else { extractedText = '<span style="' + styles + '">' + extractedText + '</span>'; } transformedText += extractedText; }); } if ('' !== transformedText) { text = transformedText; } return text; } var getUnique = (function () { var id = 0; return function () { id += 1; return id; }; }()); function Layer(structure, layer, overWrites) { var _this = this, parsedCSS; this.id = layer.id; this.siblings = []; this.visible = layer.visible; this.name = layer.name; this.index = layer.index; this.type = layer.type; this.text = ''; this.structure = structure; // Raw css styles. // This are similar to a "computed" style. Will include // all element styles which then can be further optimised. this.css = parseCSS(layer, structure.styles, overWrites); // Layer type specific configuration switch (layer.type) { case 'layerSection': this.tag = 'div'; break; case 'shapeLayer': this.tag = 'div'; // TODO: This means the path might require to be produced in SVG somehow if ('unknown' === layer._get('path.pathComponents[0].origin.type', 'shapeLayer')) { this.tag = 'img'; } break; case 'textLayer': this.tag = 'span'; this.text = parseText(layer); break; case 'layer': this.tag = 'img'; break; default: console.log('The layer type "' + layer.type + '" is no recognised.'); break; } // Image layers should be exported also with layer FX. // Layer FX can be disabled. if ('img' === this.tag) { this.css.boxShadow.active = false; this.css.background.active = false; this.css.border.active = false; if (undefined !== layer.boundsWithFX) { this.css.top = layer.boundsWithFX.top; this.css.left = layer.boundsWithFX.left; this.css.bottom = layer.boundsWithFX.bottom; this.css.right = layer.boundsWithFX.right; this.css.width = this.css.right - this.css.left; this.css.height = this.css.bottom - this.css.top; } } // Parse children layers. if (undefined !== layer.layers) { layer.layers.forEach(function (siblingLayer, index) { structure.addLayer(_this.siblings, layer.layers, siblingLayer, index); }); } } Layer.prototype.getCSSName = function (name) { return name.replace(/([a-z])([A-Z])/g, '$1-$2').toLowerCase(); }; Layer.prototype.getCSSProperty = function (name) { var property = this.getCSSName(name) + ': ', after = "", value = this.css[name], _this = this; // TODO: Add if statement for dealing with Master Active switch switch (name) { case 'top': property += Math.round(value) - Math.round(this.parent.css.top) + 'px'; break; case 'right': property += 'auto'; // Math.round(value) + 'px'; break; case 'bottom': property += 'auto'; // Math.round(value) + 'px'; break; case 'left': property += Math.round(value) - Math.round(this.parent.css.left) + 'px'; break; case 'position': property += value; break; case 'width': property += value; if ('auto' !== value) { property += 'px'; } break; case 'height': property += value; if ('auto' !== value) { property += 'px'; } break; case 'background': if (true === value.active && true === value.masterActive) { // In photohop there is the case where bitmap layers have background styles applied // but still keep a large portion transparent. This leads to images that cover everything // behind them. if ('img' !== this.tag) { if (0 < value.gradient.colors.length) { property += 'linear-gradient('; if (true === value.gradient.reverse) { value.gradient.colors.reverse(); } property += Math.abs(value.gradient.angle + 90) + 'deg, '; value.gradient.colors.forEach(function (color, index, colors) { property += 'rgba(' + Math.round(color.red) + ',' + Math.round(color.green) + ',' + Math.round(color.blue) + ', ' + (value.gradient.opacity / 100).toFixed(2) + ') ' + Math.round((value.gradient.locations[index] * 100) / 4096) + '%'; if (index < colors.length - 1) { property += ', '; } }); property += ')'; } else if (null !== value.color.red) { property += 'rgb(' + Math.round(value.color.red) + ', ' + Math.round(value.color.green) + ', ' + Math.round(value.color.blue) + ')'; } else { property += 'transparent'; } } else { property += 'transparent'; } } else { // The background is not active. } break; case 'zIndex': property += value; break; case 'border': if (true === value.active) { property += Math.round(value.size) + 'px solid rgba(' + Math.round(value.color.red) + ', ' + Math.round(value.color.green) + ', ' + Math.round(value.color.blue) + ', ' + (value.opacity / 100).toFixed(2) + ')'; } break; case 'boxSizing': if ('outsetFrame' === value) { property += 'content-box;' } else if ('insetFrame' === value) { property += 'border-box;' } else if ('centeredFrame' === value) { property += 'padding-box'; } else { console.log('Border sizing property ' + value + ' was not found.'); } break; case 'borderRadius': if (0 < value.length) { value.forEach(function (bound) { property += Math.ceil(bound) + 'px '; after += Math.ceil(bound) + 'px '; }); } // Type: roundedRect, ellipse break; case 'opacity': property += value; break; case 'color': if (0 !== Object.keys(value).length) { property += 'rgb(' + Math.round(value.red) + ', ' + Math.round(value.green) + ', ' + Math.round(value.blue) + ')'; } else { property += 'inherit'; } break; case 'fontSize': property += Math.round(value) + 'px'; break; case 'textAlign': property += value; break; case 'fontWeight': if (true === value) { property += 'bold'; } else { property += 'normal'; } break; case 'fontStyle': if (true === value) { property += 'italic'; } else { property += 'normal'; } break; case 'boxShadow': if (true === value.active) { if ('textLayer' === _this.type) { property = 'text-shadow: '; } ['outerGlow', 'innerGlow'].forEach(function (glowType) { if (true === value[glowType].active) { after += createBoxShadow(value, glowType, _this.type); } }); ['outer', 'inset'].forEach(function (shadowType) { if (true === value[shadowType].active) { property += createBoxShadow(value, shadowType, _this.type); } }); } else { // Not active } break; case 'backgroundClip': property += value; break; case 'lineHeight': property += Math.round(value) + 'px'; break; case 'fontFamily': property += value.family.toLowerCase(); if ('Regular' !== value.variant) { property += value.variant.replace(' ', '_').toLowerCase() } break; default: console.log('CSS property "' + name + '" is not regonized.'); break; } return { property: property, after: after }; }; Layer.prototype.getCSS = function () { var _this = this, css = '', addFont = '', before = ''; if (false === this.visible) { return ''; } css += '\n#' + this.cssId + ' {\n'; Object.keys(this.css).forEach(function (property) { var parsedCSS = _this.getCSSProperty(property); // TODO: Add outer glow as an after element. // TODO: Add _this.css[property].active testing before trying to create a method. css += '\t' + parsedCSS.property + ';\n'; if ('' !== parsedCSS.after) { if ('boxShadow' === property && 'textLayer' === _this.type) { before += '\ttext-shadow: ' + parsedCSS.after + ';\n'; } else { before += '\t' + _this.getCSSName(property) + ': ' + parsedCSS.after + ';\n'; } } // Implementing certain styles require additional rules based // on the type of the element and the property being styled if ('textLayer' === _this.type && 'background' === property) { // TODO: Fix gradient opacity on for text layers. css += '\t' + '-webkit-background-clip: text;\n'; // css += '\t' + '-webkit-text-fill-color: transparent;\n'; } if ('textLayer' === _this.type && 'fontFamily' === property) { addFont = _this.css[property].family; } // console.log(getCSSFontFamily(_this[property])); }); css += '}'; // TODO: If the font was already added do not add it again. css += getCSSFontFamily(addFont); if ("" !== before) { css += '\n#' + this.cssId + '::before {\n'; if ('' !== this.text) { css += '\tcontent: "' + this.text .replace('\r', ' \\A ') .replace(/[\s]+/g, ' ') + '";\n'; } else { css += '\tcontent: "";\n'; } css += '\tdisplay: block;\n'; css += '\twidth: 100%;\n'; css += '\theight: 100%;\n'; css += '\tposition: absolute;\n'; css += '\ttop: 0;\n'; css += '\tleft: 0;\n'; css += 'white-space: pre;'; css += 'color: transparent;'; css += before; css += '}\n'; } this.siblings.forEach(function (sibling) { css += sibling.getCSS(); }); return css; }; Layer.prototype.getHTML = function () { var html = '', content = '', attributes = ''; if (false === this.visible) { return ''; } content += this.text .replace("\r", "<br />"); this.siblings.forEach(function (sibling) { content += sibling.getHTML(); }); switch (this.tag) { case 'img': html += '\n<' + this.tag + ' id="' + this.cssId + '" src="' + this.structure.folders.images + this.fileName + '" />'; break; case 'div': html += '\n<' + this.tag + ' id="' + this.cssId + '">' + content + '</' + this.tag + '>'; break; case 'span': html += '\n<' + this.tag + ' id="' + this.cssId + '">' + content + '</' + this.tag + '>'; break; } return html; }; // Config should contain: // folder Obj // files Obj // document Obj - reference to the document // generator Obj - reference to the generator function Structure(config) { var _this = this; Object.keys(config).forEach(function (configKey) { _this[configKey] = config[configKey]; }) this.layers = []; this.html = ''; this.css = ''; this.psdPath = this.document.file; this.psdName = this.psdPath.substr(this.psdPath.lastIndexOf('/') + 1, this.psdPath.length); // Store IDs to ensure there is no collision between styles. this.cssIds = []; this.imagesQueue = []; this.styles = { globalLight: { angle: this.document._get('globalLight.angle', 118), altitude: 0 } }; // This is the top most parent of the document. // Catch all traversal that arrive here. this.parent = { css: parseCSS({}, this.styles, {}), cssId: 'global', }; this.header = '<!DOCTYPE html>' + '<head>' + '<link rel="stylesheet" href="style.css">' + '</head>' + '<body>'; this.footer = '</body></html>'; // Set listeners. this.events = new events.EventEmitter(); this.events.on('finishedImage', function (event) { _this.finishedImage(); }); } Structure.prototype.finishedImage = function () { console.log('Finished an image'); this.nextImage(); }; Structure.prototype.createLayers = function () { var _this = this; this.document.layers.forEach(function (layer, index) { _this.addLayer(_this.layers, _this.document.layers, layer, index); }); }; Structure.prototype.addLayer = function (storage, layers, layer, index) { var overWrites = {}, overWriteLayer; // Ignore masks for now! // TODO: Do not ignore masks. if (true !== layer.mask.removed) { return; } if (true === layer.clipped) { overWriteLayer = layers[index + 1]; overWrites = { top: overWriteLayer._get('bounds.top', 0), right: overWriteLayer._get('bounds.right', 0), bottom: overWriteLayer._get('bounds.bottom', 0), left: overWriteLayer._get('bounds.left', 0) } } storage.push(new Layer(this, layer, overWrites)); }; Structure.prototype.linkLayers = function () { function linkLayers(layers, parent) { layers.forEach(function (layer, index) { layer.parent = parent; if (0 < index) { layer.prev = layers[index - 1]; } if (layers.length > index + 1) { layer.next = layers[index + 1]; } linkLayers(layer.siblings, layer); }); } linkLayers(this.layers, this.parent); }; Structure.prototype.refreshCode = function () { var _this = this; // Reset html and css this.html = ""; this.css = ""; this.layers.forEach(function (layer) { _this.html += layer.getHTML(); _this.css += layer.getCSS(); }); this.html = this.header + this.html + this.footer; }; Structure.prototype.saveToJSON = function () { fs.writeFileSync(this.files.document, stringify(this.document)); fs.writeFileSync( this.files.structure, stringify(this, ['parent', 'prev', 'next', 'document', 'generator', 'structure']) ); console.log('Saved raw document to "' + this.files.document + '"'); console.log('Saved parsed structure to "' + this.files.structure + '"'); }; Structure.prototype.output = function () { fs.writeFileSync(this.files.html, this.html); fs.writeFileSync(this.files.css, this.css); console.log('Index.html and style.css were created.'); }; Structure.prototype.generateImages = function () { var _this = this; function generateImages(layers) { layers.forEach(function (layer) { if ('img' === layer.tag) { // TODO: Add a layer hashsum at the end of the layer to ensure that // if the layer has changed then the image should be regenerated as well. layer.fileName = _this.psdName + '_' + layer.parent.cssId + '_' + layer.cssId + '.png'; layer.filePath = _this.folders.images + layer.fileName; if (true === fs.existsSync(layer.filePath)) { // The image already exists. No need to regenerate it. } else { _this.imagesQueue.push({ id: layer.id, filePath: layer.filePath }); } } if (0 !== layer.siblings.length) { generateImages(layer.siblings); } else { // The no further siblings must be checked for images. } }); } generateImages(this.layers); // Being exporting images. this.nextImage(); }; Structure.prototype.nextImage = function () { var _this = this, imageData; console.log('Triggering next image.'); if (0 === this.imagesQueue.length) { console.log('All images have been generated.'); } else { // FIFO imageData = this.imagesQueue.shift(); this.generator.getPixmap(this.document.id, imageData.id, {}).then( function(pixmap){ savePixmap(pixmap, imageData.filePath, _this.events); }, function(err){ console.error("Pixmap error:", err); } ).done(); } }; Structure.prototype.generateCssIds = function () { var _this = this; function generateCssIds(layers) { layers.forEach(function (layer, index) { layer.cssId = layer.parent.cssId + '-' + layer.name .replace(/&/, '') .replace(/^\//, 'a') .replace(/^[0-9]/g, 'a') .replace(/\s/g, '-'); if (-1 === _this.cssIds.indexOf(layer.cssId)) { // The ID is unique and can be used. } else { layer.cssId += index; } _this.cssIds.push(layer.cssId); if (0 < layer.siblings.length) { generateCssIds(layer.siblings); } }); } generateCssIds(this.layers); }; function runGenerator(document, generator) { var structure = new Structure({ folders: { images: path.resolve(__dirname, 'images/') + '/' }, files: { html: path.resolve(__dirname, 'index.html'), css: path.resolve(__dirname, 'style.css'), document: path.resolve(__dirname, 'document.json'), structure: path.resolve(__dirname, 'structure.json') }, document: document, generator: generator }); structure.createLayers(); structure.linkLayers(); structure.generateCssIds(); structure.generateImages(); structure.saveToJSON(); structure.refreshCode(); structure.output(); } // Verificarea de float este simpla: // - Daca un element incepe de la marginea unui container // - Daca un element nu incepe de la marginea unui container dar are acceasi distanta // de sus ca unul care incepe de la marginea unui container // - Daca un element este intre alte elemente care au aceeasi distanta intre ele // si unul dintre elemente incepe de la marginea unui container // - /* function findFloatables(layers, type) { var flotables = [], firstElementsInRow = [], disposeFloatables = false, marginColumn, marginRow; if (1 < layers.length) { // Order layers by left alignment layers.sort(function (left, right) { return left.properties.parsedCSS.left > right.properties.parsedCSS.left; }); // Order layers by top down alignment layers.sort(function (left, right) { return left.properties.parsedCSS.top > right.properties.parsedCSS.top; }); // Clone array layers.forEach(function (layer) { flotables.push(layer); }); /* // Find the layers that have the same top flotables = flotables.filter(function (layer) { if (flotables[0].properties.parsedCSS.top === layer.properties.parsedCSS.top) { return true; } }); // Calculate the necessary margin for all floated layers marginColumn = flotables[1].properties.parsedCSS.left - (flotables[0].properties.parsedCSS.left + parseInt(flotables[0].properties.parsedCSS.width)); console.log("MarginColumn: " + marginColumn); // The first element of each row must not have margins firstElementsInRow.push(flotables[0].id); console.log(firstElementsInRow); // Find the margin between other layers flotables = flotables.filter(function (layer, index) { var prev = flotables[index - 1], value; // If a flotable candidate did not conform with the margin // then all following canditates are also not floated. if (true === disposeFloatables) { return false; } if (undefined !== prev) { // If floated cantidate is on a different row. if (prev.properties.parsedCSS.top !== layer.properties.parsedCSS.top) { firstElementsInRow.push(layer.id); // Calculate the bottom margin of the above row marginRow = layer.properties.parsedCSS.top - (parseInt(flotables[0].properties.parsedCSS.height) + flotables[0].properties.parsedCSS.top); return true; } value = layer.properties.parsedCSS.left - (prev.properties.parsedCSS.left + parseInt(prev.properties.parsedCSS.width)); console.log(layer.properties.parsedCSS.left + " vs " + prev.properties.parsedCSS.left + " vs " + prev.properties.parsedCSS.width); console.log("Value: " + value); if (value === marginColumn) { return true; } else { disposeFloatables = true; return false; } } else { return true; // The first floated element which is also reference. } }); console.log('Found ' + flotables.length + ' ' + type + ' floatable elements.'); } return { elements: flotables, marginColumn: marginColumn, marginRow: marginRow, firstElementsInRow: firstElementsInRow }; }*/ exports.init = init; }());
main.js
// ---------------------------------- // GeneratorX // @author Constantin Dumitrescu // @author Bogdan Matei // @company Brandup // @version 0.1.0 // ---------------------------------- (function () { "use strict"; var fs = require('fs'), path = require('path'), PNG = require('pngjs').PNG, events = new require('events'); // GLOBAL TODOs // // TODO: If the designer has his Types and Rulers in anything else // than pixels, all values must be converted before using. // Defaults: types (points) rulers (in?) // // /** * Has method * Will provide a response for a chain of Object properties * e.g: x.has('one.of.these.properties'); */ Object.defineProperty(Object.prototype, '_has', { enumerable : false, value : function(params) { var tester; if ('function' !== typeof params && 'string' === typeof params) { try { eval('tester = this.' + params); // This eval is not evil , as long is completely secured if (undefined === tester) { throw new Error('The property ' + params + ' is not available'); } } catch (e) { return false; } } else { return false; } return true; } }); /** * getValueOf * Retrieves the value of a chained Object properties */ Object.defineProperty(Object.prototype, '_get', { enumerable : false, value : function(params, fallback) { var value; if ('function' !== typeof params && 'string' === typeof params) { try { eval('value = this.' + params.toString()); if (undefined === value) { throw new Error('not available'); } } catch (e) { if (undefined !== fallback) { return fallback; } return undefined; } } else { return false; } return value; } }); // TODO: Create a test suite generator to get the GenX File and generate also images // Which will be shown on the same page as a left and right comparison. function init(generator) { generator.getDocumentInfo().then( function (document) { runGenerator(document, generator); }, function (err) { console.error(" Error in getDocumentInfo:", err); } ).done(); } function stringify(obj, circularProperties) { var stringified, circularProperties = circularProperties ? circularProperties : []; function removeCircular(name, value) { if (-1 === circularProperties.indexOf(name)) { return value; } else { //Undefined properties will be removed from JSON. return undefined; } } try { if (0 === circularProperties.length) { stringified = JSON.stringify(obj, null, 4); } else { stringified = JSON.stringify(obj, removeCircular, 4); } } catch (e) { console.error('Stringify error:', e); stringified = String(obj); } return stringified; } // TODO: Spawn a worker to handle the saving of the pixmap. function savePixmap(pixmap, filePath, emitter){ var pixels = pixmap.pixels, len = pixels.length, pixel, location, png, channelNo = pixmap.channelCount; // Convert from ARGB to RGBA, we do this every 4 pixel values (channelCount) for(location = 0; location < len; location += channelNo){ pixel = pixels[location]; pixels[location] = pixels[location + 1]; pixels[location + 1] = pixels[location + 2]; pixels[location + 2] = pixels[location + 3]; pixels[location + 3] = pixel; } var png = new PNG({ width: pixmap.width, height: pixmap.height }); png.data = pixels; png.on('end', function () { emitter.emit('finishedImage'); }); png .pack() .pipe(fs.createWriteStream(filePath)) } function getCSSFontFamily(fontName) { var font = ""; switch (fontName) { case 'Oswald': font += "\n @font-face {" + " font-family: 'oswaldbook'; " + " src: url('fonts/oswald-regular.eot');" + " src: url('fonts/oswald-regular.eot?#iefix') format('embedded-opentype')," + " url('fonts/oswald-regular.woff') format('woff')," + " url('fonts/oswald-regular.ttf') format('truetype')," + " url('fonts/oswald-regular.svg#oswaldbook') format('svg');" + " font-weight: normal;" + " font-style: normal; " + " } \n"; break; case 'IcoMoon': font += "@font-face { " + " font-family: 'icomoonregular';" + " src: url('fonts/icomoon.eot');" + " src: url('fonts/icomoon.eot?#iefix') format('embedded-opentype')," + " url('fonts/icomoon.woff') format('woff')," + " url('fonts/icomoon.ttf') format('truetype')," + " url('fonts/icomoon.svg#icomoonregular') format('svg');" + " font-weight: normal;" + " font-style: normal;" + " } \n"; break; case 'Futura': break; case 'Helvetica': break; case 'Helvetica Neue': break; case 'Arial': break; case 'Myriad': break; case 'Tipogram': break; case 'Roboto': var roboto = { black: 'robotoblack', blackitalic: 'robotoblack_italic', bold: 'robotobold', bolditalic: 'robotobold_italic', italic: 'robotoitalic', light: 'robotolight', medium: 'robotomedium', mediumitalic: 'robotomedium_italic', regular: 'robotoregular', thin: 'robotothin', thinitalic: 'robotothin_italic' }; Object.keys(roboto).forEach(function (variant) { font += "@font-face {" + "font-family: '" + roboto[variant]+ "'; " + " src: url('fonts/roboto-" + variant + ".eot'); " + " src: url('fonts/roboto-" + variant + ".eot?#iefix') format('embedded-opentype')," + " url('fonts/roboto-" + variant + ".woff') format('woff')," + " url('fonts/roboto-" + variant + ".ttf') format('truetype')," + " url('fonts/roboto-" + variant + ".svg#roboto" + variant + "') format('svg');" + "font-weight: normal;" + "font-style: normal;" + "}"; }); break; default: // console.log('The font name "' + fontName + '" is not supported.'); break; } return font; } function createBoxShadow(shadowStyles, shadowType, elementType) { var property = "", shadow = shadowStyles[shadowType], angle = 0 < shadow.angle ? shadow.angle : 360 + shadow.angle, // 91 is so that the substraction does not result in 0; normalisedAngle = angle - 90 * Math.floor(angle / 91), x, y, percent; if (-1 === ['outerGlow', 'innerGlow'].indexOf(shadowType)) { // TODO: Accomodate for the chokeMatte property percent = normalisedAngle / 90; if (angle <= 90) { x = - (shadow.distance - shadow.distance * percent); y = shadow.distance * percent; } else if (angle <= 180) { x = shadow.distance * percent; y = shadow.distance - shadow.distance * percent; } else if (angle <= 270) { x = shadow.distance - shadow.distance * percent; y = - shadow.distance * percent; } else if (angle <= 360) { x = - (shadow.distance * percent); y = - (shadow.distance - shadow.distance * percent); } } else { x = 0; y = 0; } if (true === shadowStyles.outer.active && 'inset' === shadowType) { property += ', '; } if (true === shadowStyles.outerGlow.active && 'innerGlow' === shadowType) { property += ', '; } // TODO: For outer glows, create the use case for gradient usage instead // of solid color. property += Math.round(x) + 'px ' + Math.round(y) + 'px '; // TOOD: Establish the relation between innerGlow parameters (chokeMatte and size) and // omolog values in CSS. // It seems that a Choke: 90%, Size: 10px is the same as box-shadow: 0 0 0 10px if ('innerGlow' === shadowType) { if (0 !== shadow.spread) { property += (shadow.blur - (shadow.blur * shadow.spread / 100)) + 'px '; } // If this is a text layer then a pseudo element will be generated for the glow. // The text-shadow does not have an additional parameter. if ('textLayer' !== elementType) { property += shadow.blur + 'px '; } } else if ('outerGlow' === shadowType) { property += shadow.blur + 'px '; // Same as above. if ('textLayer' !== elementType) { property += shadow.spread + 'px '; } } else { property += shadow.blur + 'px '; } property += ' rgba(' + Math.round(shadow.color.red) + ', ' + Math.round(shadow.color.green) + ', ' + Math.round(shadow.color.blue) + ', ' + (shadow.opacity / 100) + ')'; if (('inset' === shadowType || 'innerGlow' === shadowType) && 'textLayer' !== elementType) { property += ' inset'; } return property; } // All sections are still layers. // The semantic is given by the way the interaction with the dom will occur // A layer must have: // - tag: div, p, span, etc // - class // - id // - text // - parent/nextSibling/prevSibling for traversing // - css all the css properties that will eventually end in the stylesheet // Parsing will be made in 3 stages: // 1. The parsing of the PSD document with absolute styles - Done // 2. From the absolute styles connections between elements will emerge (e.g. floats, overlay, etc) // 3. Establish the logical order of dom elements (based on float, etc) // 4. Find patterns in styles through css duplication, hierachy and inheritance to optimise the css creation // 5. Create the HTML version of the structure // 6. Create the CSS version of the layers // 7. Create a file with the HTML and CSS code // TODO: For layers that have the same name regardless of their position // in the structure tree, allocate different cssNames to avoid id collision function parseCSS(style, globalStyles, overWrites) { // TODO: Add default styles for all the bellow properties. var css = { top: style._get('bounds.top', 0), right: style._get('bounds.right', 0), bottom: style._get('bounds.bottom', 0), left: style._get('bounds.left', 0), position: 'static', background: { masterActive: style._get('layerEffects.masterFXSwitch', true), active: style._has('fill'), color: { red: style._get('fill.color.red', 255), green: style._get('fill.color.green', 255), blue: style._get('fill.color.blue', 255) }, gradient: { colors: [], locations: [], reverse: style._get('layerEffects.gradientFill.reverse', false), type: 'linear', opacity: style._get('layerEffects.gradientFill.opacity.value', 100), angle: style._get('layerEffects.gradientFill.angle.value', -90) }, // Background type (linear, radial, angle) type: style._get('layerEffects.gradientFill.type', 'linear') }, opacity: style._get('blendOptions.opacity.value', 100) / 100, border: { masterActive: style._get('layerEffects.masterFXSwitch', true), active: style._has('layerEffects.frameFX'), color: { red: style._get('layerEffects.frameFX.color.red', 255), green: style._get('layerEffects.frameFX.color.green', 255), blue: style._get('layerEffects.frameFX.color.blue', 255) }, opacity: style._get('layerEffects.frameFX.opacity.value', 100), size: style._get('layerEffects.frameFX.size', 3) }, boxSizing: style._get('layerEffects.frameFX.style', 'outsetFrame'), boxShadow: { masterActive: style._get('layerEffects.masterFXSwitch', true), active: style._has('layerEffects.dropShadow') || style._has('layerEffects.innerShadow') || style._has('layerEffects.outerGlow') || style._has('layerEffects.innerGlow'), outer: { active: style._has('layerEffects.dropShadow'), color: { red: style._get('layerEffects.dropShadow.color.red', 0), green: style._get('layerEffects.dropShadow.color.green', 0), blue: style._get('layerEffects.dropShadow.color.blue', 0) }, opacity: style._get('layerEffects.dropShadow.opacity.value', 75), distance: style._get('layerEffects.dropShadow.distance', 5), blur: style._get('layerEffects.dropShadow.blur', 5), angle: style._get('layerEffects.dropShadow.localLightingAngle.value', 120), spread: style._get('layerEffects.dropShadow.chokeMatte', 0) }, inset: { active: style._has('layerEffects.innerShadow'), color: { red: style._get('layerEffects.innerShadow.color.red', 0), green: style._get('layerEffects.innerShadow.color.green', 0), blue: style._get('layerEffects.innerShadow.color.blue', 0) }, opacity: style._get('layerEffects.innerShadow.opacity.value', 75), distance: style._get('layerEffects.innerShadow.distance', 5), blur: style._get('layerEffects.innerShadow.blur', 5), // TODO: Add global lighting angle angle: style._get('layerEffects.innerShadow.localLightingAngle.value', 120), spread: style._get('layerEffects.innerShadow.chokeMatte', 0) }, outerGlow: { active: style._has('layerEffects.outerGlow'), color: { red: style._get('layerEffects.outerGlow.color.red', 255), green: style._get('layerEffects.outerGlow.color.green', 255), blue: style._get('layerEffects.outerGlow.color.blue', 190), }, blur: style._get('layerEffects.outerGlow.blur', 5), opacity: style._get('layerEffects.outerGlow.opacity.value', 75), spread: style._get('layerEffects.outerGlow.chokeMatte', 0) }, innerGlow: { active: style._has('layerEffects.innerGlow'), color: { red: style._get('layerEffects.innerGlow.color.red', 255), green: style._get('layerEffects.innerGlow.color.green', 255), blue: style._get('layerEffects.innerGlow.color.blue', 190), }, blur: style._get('layerEffects.innerGlow.blur', 5), opacity: style._get('layerEffects.innerGlow.opacity.value', 75), spread: style._get('layerEffects.innerGlow.chokeMatte', 0) } }, borderRadius: [], zIndex: style.index, color: { red: style._get('text.textStyleRange[0].textStyle.color.red', 0), green: style._get('text.textStyleRange[0].textStyle.color.green', 0), blue: style._get('text.textStyleRange[0].textStyle.color.blue', 0) }, fontSize: style._get('text.textStyleRange[0].textStyle.size', 16), textAlign: style._get('text.paragraphStyleRange[0].paragraphStyle.align', 'inherit'), fontFamily: { family: style._get('text.textStyleRange[0].textStyle.fontName', 'Arial'), variant: style._get('text.textStyleRange[0].textStyle.fontStyleName', 'Regular') } }, textColor; Object.keys(overWrites).forEach(function (property) { css[property] = overWrites[property]; }); // ----------------- // Background styles // Fill color overwritted by the blend options css.background.color = { red: style._get('layerEffects.solidFill.color.red', css.background.color.red), green: style._get('layerEffects.solidFill.color.green', css.background.color.green), blue: style._get('layerEffects.solidFill.color.blue', css.background.color.blue) }; // Inner and outer shadows can opt to not use globalAngles and have // the default angle. if (true === style._get('layerEffects.innerShadow.useGlobalAngle', true)) { css.boxShadow.inset.angle = globalStyles.globalLight.angle; } if (true === style._get('layerEffects.dropShadow.useGlobalAngle', true)) { css.boxShadow.outer.angle = globalStyles.globalLight.angle; } // TODO: It seems that for shadows the 100% opacity is not 100% CSS opacity // but somewhere around 80%. Experiment with this and try to find a // good approximation. // TODO: Account for different blend modes for each style. This would be an // advanced feature and would require a canvas to plot individual features // and an implementation of blend mode algorithms to obtain accurate CSS // values. // TODO: Depending on the degree of accuracy the user requires, the layer can be // exported as an image to ensure that all FX styles are 100% accurate. // TODO: Implement Radial Gradient // TODO: Implement Angle Gradient // TODO: Implement Drop shadow countour settings on layersEffects.dropShadow.transferSpec // Gradient Colors style._get('layerEffects.gradientFill.gradient.colors', []).forEach(function (color) { css.background.gradient.colors.push({ red: color.color.red, green: color.color.green, blue: color.color.blue, location: color.location, type: color.type, midpoint: color.midpoint }); css.background.gradient.locations.push(color.location); }); // The color array is in reverse order due to the way is added css.background.gradient.colors.reverse(); // TODO: Implement border // Border Radius switch (style._get('path.pathComponents[0].origin.type', '')) { case 'roundedRect': css.borderRadius = style._get('path.pathComponents[0].origin.radii', []); break; case 'ellipse': // this actually requires to be transffered to an SVG // ellipse implementation (function () { var bounds = style._get('path.pathComponents[0].origin.bounds', {}), width = bounds.bottom - bounds.top, height = bounds.right - bounds.left; css.borderRadius[0] = height / 2; }()); break; default: // There is no border radius. break; } if (true === style._has('strokeStyle', false)) { // TODO: Implement strokeStyles for shape layers. // This can either be a new ::before / ::after element with // a transparent background and a border. // OR in some cases it might be an SVG. } if (false === style._get('strokeStyle.fillEnabled', true)) { css.background.active = false; } // [TEMP] Default dimensions. css.width = css.right - css.left; css.height = css.bottom - css.top; if ('textLayer' === style.type) { // TODO: Revisit lineHeight / leading styles. There might be // a better way to parse lineHeight. // 30 seems to be the default leading/line height. // In CSS the line height is set on the line on which the text sits // while leading seems to be the distance between lines. // 7. However, if leading is set to "auto", the actual leading number is 120% of the font size. css.lineHeight = (css.fontSize + style._get('text.textStyleRange[0].textStyle.leading', 30) / 2) - 1; /* (function () { var baseLineShift = Math.abs(style._get('text.textStyleRange[0].textStyle.baselineShift', 1)); // 1px baseLineShift = 2.40566 if (2.40566 > baseLineShift) { css.fontSize = Math.floor(css.fontSize / 2); css.lineHeight = Math.floor(css.lineHeight / 2); } }()); */ // TODO: This is a sub optimal solution to compensate for the difference between // line height and leading. css.top -= 7; (function () { var textStyleRanges = style._get('text.textStyleRange', []); if (1 === textStyleRanges.length) { css.fontWeight = style._get('text.textStyleRange[0].textStyle.syntheticBold', false), css.fontStyle = style._get('text.textStyleRange[0].textStyle.syntheticItalic', false) } else { css.fontWeight = false; css.fontStyle = false; } }()); // TODO: Implement the WebKit algorithm to detect the real width of the // text with all the styles attached. // This should do the following: // 1. Parse the .ttf file // 2. Create the sequence of text vectors dictated by the .ttf rules // of binding characters // 3. Add the text transformation on the created sequence of vectors // 4. Extract the width pixel value from the vector implementation in // bitmap environment. // TODO: Adjust the estimated px value bellow that seems to accomodate // the difference between PSD and Browser text rendering. css.width = css.width + 10; css.height = 'auto'; // Definitions: // boundingBox: the coordinates that wrap the text // bounds: the coordinates that wrap the user defined area for the text or // if the area wasn't defined by the user, the total area occupied // by the text which might be different than the boundingBox coordinates (function () { var bounds = style._get('text.bounds'), boxBounds = style._get('text.boundingBox'), boundsWidth = bounds.right - bounds.left, boundsHeight = bounds.bottom - bounds.top, boxBoundsWidth = boxBounds.right - boxBounds.left, boxWidthDifference = boxBoundsWidth - boundsWidth; // From inital experimentation the difference between the bounds // when not having a user defined area is within a 10 px range. // Of course, this is empiric evidence and needs further research. // Also, an area that is less than 10 px from the area occupied // by the text leaves little room for alignment (which is in fact // the goal of this). If the desiner did create a less than 10 px // container for the text then this might be a bad practice to do // so. if (6 > Math.abs(boxWidthDifference)) { // The text does not have a defined area and an be left // to be arranged through the alignment styles of the parent // element. css.textAlign = 'left'; } else { // The text has a defined area and needs to be further // wrapped in a parent container element. css.width = boundsWidth; css.height = boundsHeight; css.left -= Math.ceil(boxBounds.left); } }()); } // [TEMP] Overwrite positioning for now css.position = 'absolute'; // TODO: Implement outer glow // TODO: Implement inner shadow/inner glow // --------- // Text styles // For some reason font size comes in a different format that is // TODO: Line height // leading / font size // css.lineHeight = ((style._get('text.textStyleRange[0].textStyle.leading', 16) / css.fontSize) * 1000 ) / 1000; // // Overwrites // // Border requires adjustments to top, left and widht, height if (true === css.border.active) { // TODO: Figure out how to keep the box-sizing: border-box. Currently // inside photoshop you set the content css.backgroundClip = 'content-box'; if ('insetFrame' === css.boxSizing) { css.borderRadius.forEach(function (bound, index) { css.borderRadius[index] = bound + css.border.size; }); } else if ('outsetFrame' === css.boxSizing) { css.top -= css.border.size; css.left -= css.border.size; css.borderRadius.forEach(function (bound, index) { css.borderRadius[index] = bound + css.border.size; }); } else if ('centeredFrame' === css.boxSizing) { css.top -= css.border.size / 2; css.left -= css.border.size / 2; css.width -= css.border.size; css.height -= css.border.size; css.borderRadius.forEach(function (bound, index) { css.borderRadius[index] = bound + css.border.size; }); } else { console.log('The box sizing "' + css.boxSizing + '" is not recognised.'); } } return css; } function parseText(layer) { var text = layer._get('text.textKey', ''), transformedText = '', textRanges = layer._get('text.textStyleRange', []), lastParsedIndex = 0; if (1 === textRanges.length) { // If there is just one text range that means the text // is uniform. } else { textRanges.forEach(function (range) { var extractedText = text.substr(range.from, range.to - range.from), styles = "", fontFamily = range.textStyle.fontName, fontVariant = range.textStyle.fontStyleName; // For some reason Photoshop sometimes returns a duplicated // text range. if (lastParsedIndex !== range.to) { return; } lastParsedIndex = range.to; styles += 'font-family: ' + fontFamily.toLowerCase() + fontVariant.replace(' ', '_').toLowerCase(); // TODO: Add the ability to combine bold, italic or // other styles on a single text. This might require // 1. a single wrapper with clases: // <span class="bold italic fontSize20px">Text</span> // 2. or a custom id // <span id="custom-styling-113">Text</span> // I think I would prefer option No. 1 if (true === range.textStyle.syntheticBold) { extractedText = '<strong style="' + styles + '">' + extractedText + '</strong>'; } else if (true === range.textStyle.syntheticItalic) { extractedText = '<em style="' + styles + '">' + extractedText + '</em>'; } else { extractedText = '<span style="' + styles + '">' + extractedText + '</span>'; } transformedText += extractedText; }); } if ('' !== transformedText) { text = transformedText; } return text; } var getUnique = (function () { var id = 0; return function () { id += 1; return id; }; }()); function Layer(structure, layer, overWrites) { var _this = this, parsedCSS; this.id = layer.id; this.siblings = []; this.visible = layer.visible; this.name = layer.name; this.index = layer.index; this.type = layer.type; this.text = ''; this.structure = structure; // Raw css styles. // This are similar to a "computed" style. Will include // all element styles which then can be further optimised. this.css = parseCSS(layer, structure.styles, overWrites); // Layer type specific configuration switch (layer.type) { case 'layerSection': this.tag = 'div'; break; case 'shapeLayer': this.tag = 'div'; // TODO: This means the path might require to be produced in SVG somehow if ('unknown' === layer._get('path.pathComponents[0].origin.type', 'shapeLayer')) { this.tag = 'img'; } break; case 'textLayer': this.tag = 'span'; this.text = parseText(layer); break; case 'layer': this.tag = 'img'; break; default: console.log('The layer type "' + layer.type + '" is no recognised.'); break; } // Image layers should be exported also with layer FX. // Layer FX can be disabled. if ('img' === this.tag) { this.css.boxShadow.active = false; this.css.background.active = false; this.css.border.active = false; if (undefined !== layer.boundsWithFX) { this.css.top = layer.boundsWithFX.top; this.css.left = layer.boundsWithFX.left; this.css.bottom = layer.boundsWithFX.bottom; this.css.right = layer.boundsWithFX.right; this.css.width = this.css.right - this.css.left; this.css.height = this.css.bottom - this.css.top; } } // Parse children layers. if (undefined !== layer.layers) { layer.layers.forEach(function (siblingLayer, index) { structure.addLayer(_this.siblings, layer.layers, siblingLayer, index); }); } } Layer.prototype.getCSSName = function (name) { return name.replace(/([a-z])([A-Z])/g, '$1-$2').toLowerCase(); }; Layer.prototype.getCSSProperty = function (name) { var property = this.getCSSName(name) + ': ', after = "", value = this.css[name], _this = this; // TODO: Add if statement for dealing with Master Active switch switch (name) { case 'top': property += Math.round(value) - Math.round(this.parent.css.top) + 'px'; break; case 'right': property += 'auto'; // Math.round(value) + 'px'; break; case 'bottom': property += 'auto'; // Math.round(value) + 'px'; break; case 'left': property += Math.round(value) - Math.round(this.parent.css.left) + 'px'; break; case 'position': property += value; break; case 'width': property += value; if ('auto' !== value) { property += 'px'; } break; case 'height': property += value; if ('auto' !== value) { property += 'px'; } break; case 'background': if (true === value.active && true === value.masterActive) { // In photohop there is the case where bitmap layers have background styles applied // but still keep a large portion transparent. This leads to images that cover everything // behind them. if ('img' !== this.tag) { if (0 < value.gradient.colors.length) { property += 'linear-gradient('; if (true === value.gradient.reverse) { value.gradient.colors.reverse(); } property += Math.abs(value.gradient.angle + 90) + 'deg, '; value.gradient.colors.forEach(function (color, index, colors) { property += 'rgba(' + Math.round(color.red) + ',' + Math.round(color.green) + ',' + Math.round(color.blue) + ', ' + (value.gradient.opacity / 100).toFixed(2) + ') ' + Math.round((value.gradient.locations[index] * 100) / 4096) + '%'; if (index < colors.length - 1) { property += ', '; } }); property += ')'; } else if (null !== value.color.red) { property += 'rgb(' + Math.round(value.color.red) + ', ' + Math.round(value.color.green) + ', ' + Math.round(value.color.blue) + ')'; } else { property += 'transparent'; } } else { property += 'transparent'; } } else { // The background is not active. } break; case 'zIndex': property += value; break; case 'border': if (true === value.active) { property += Math.round(value.size) + 'px solid rgba(' + Math.round(value.color.red) + ', ' + Math.round(value.color.green) + ', ' + Math.round(value.color.blue) + ', ' + (value.opacity / 100).toFixed(2) + ')'; } break; case 'boxSizing': if ('outsetFrame' === value) { property += 'content-box;' } else if ('insetFrame' === value) { property += 'border-box;' } else if ('centeredFrame' === value) { property += 'padding-box'; } else { console.log('Border sizing property ' + value + ' was not found.'); } break; case 'borderRadius': if (0 < value.length) { value.forEach(function (bound) { property += Math.ceil(bound) + 'px '; after += Math.ceil(bound) + 'px '; }); } // Type: roundedRect, ellipse break; case 'opacity': property += value; break; case 'color': if (0 !== Object.keys(value).length) { property += 'rgb(' + Math.round(value.red) + ', ' + Math.round(value.green) + ', ' + Math.round(value.blue) + ')'; } else { property += 'inherit'; } break; case 'fontSize': property += Math.round(value) + 'px'; break; case 'textAlign': property += value; break; case 'fontWeight': if (true === value) { property += 'bold'; } else { property += 'normal'; } break; case 'fontStyle': if (true === value) { property += 'italic'; } else { property += 'normal'; } break; case 'boxShadow': if (true === value.active) { if ('textLayer' === _this.type) { property = 'text-shadow: '; } ['outerGlow', 'innerGlow'].forEach(function (glowType) { if (true === value[glowType].active) { after += createBoxShadow(value, glowType, _this.type); } }); ['outer', 'inset'].forEach(function (shadowType) { if (true === value[shadowType].active) { property += createBoxShadow(value, shadowType, _this.type); } }); } else { // Not active } break; case 'backgroundClip': property += value; break; case 'lineHeight': property += Math.round(value) + 'px'; break; case 'fontFamily': property += value.family.toLowerCase(); if ('Regular' !== value.variant) { property += value.variant.replace(' ', '_').toLowerCase() } break; default: console.log('CSS property "' + name + '" is not regonized.'); break; } return { property: property, after: after }; }; Layer.prototype.getCSS = function () { var _this = this, css = '', addFont = '', before = ''; if (false === this.visible) { return ''; } css += '\n#' + this.cssId + ' {\n'; Object.keys(this.css).forEach(function (property) { var parsedCSS = _this.getCSSProperty(property); // TODO: Add outer glow as an after element. // TODO: Add _this.css[property].active testing before trying to create a method. css += '\t' + parsedCSS.property + ';\n'; if ('' !== parsedCSS.after) { if ('boxShadow' === property && 'textLayer' === _this.type) { before += '\ttext-shadow: ' + parsedCSS.after + ';\n'; } else { before += '\t' + _this.getCSSName(property) + ': ' + parsedCSS.after + ';\n'; } } // Implementing certain styles require additional rules based // on the type of the element and the property being styled if ('textLayer' === _this.type && 'background' === property) { // TODO: Fix gradient opacity on for text layers. css += '\t' + '-webkit-background-clip: text;\n'; // css += '\t' + '-webkit-text-fill-color: transparent;\n'; } if ('textLayer' === _this.type && 'fontFamily' === property) { addFont = _this.css[property].family; } // console.log(getCSSFontFamily(_this[property])); }); css += '}'; // TODO: If the font was already added do not add it again. css += getCSSFontFamily(addFont); if ("" !== before) { css += '\n#' + this.cssId + '::before {\n'; if ('' !== this.text) { css += '\tcontent: "' + this.text .replace('\r', ' \\A ') .replace(/[\s]+/g, ' ') + '";\n'; } else { css += '\tcontent: "";\n'; } css += '\tdisplay: block;\n'; css += '\twidth: 100%;\n'; css += '\theight: 100%;\n'; css += '\tposition: absolute;\n'; css += '\ttop: 0;\n'; css += '\tleft: 0;\n'; css += 'white-space: pre;'; css += 'color: transparent;'; css += before; css += '}\n'; } this.siblings.forEach(function (sibling) { css += sibling.getCSS(); }); return css; }; Layer.prototype.getHTML = function () { var html = '', content = '', attributes = ''; if (false === this.visible) { return ''; } content += this.text .replace("\r", "<br />"); this.siblings.forEach(function (sibling) { content += sibling.getHTML(); }); switch (this.tag) { case 'img': html += '\n<' + this.tag + ' id="' + this.cssId + '" src="' + this.structure.folders.images + this.fileName + '" />'; break; case 'div': html += '\n<' + this.tag + ' id="' + this.cssId + '">' + content + '</' + this.tag + '>'; break; case 'span': html += '\n<' + this.tag + ' id="' + this.cssId + '">' + content + '</' + this.tag + '>'; break; } return html; }; // Config should contain: // folder Obj // files Obj // document Obj - reference to the document // generator Obj - reference to the generator function Structure(config) { var _this = this; Object.keys(config).forEach(function (configKey) { _this[configKey] = config[configKey]; }) this.layers = []; this.html = ''; this.css = ''; this.psdPath = this.document.file; this.psdName = this.psdPath.substr(this.psdPath.lastIndexOf('/') + 1, this.psdPath.length); // Store IDs to ensure there is no collision between styles. this.cssIds = []; this.imagesQueue = []; this.styles = { globalLight: { angle: this.document._get('globalLight.angle', 118), altitude: 0 } }; // This is the top most parent of the document. // Catch all traversal that arrive here. this.parent = { css: parseCSS({}, this.styles, {}), cssId: 'global', }; this.header = '<!DOCTYPE html>' + '<head>' + '<link rel="stylesheet" href="style.css">' + '</head>' + '<body>'; this.footer = '</body></html>'; // Set listeners. this.events = new events.EventEmitter(); this.events.on('finishedImage', function (event) { _this.finishedImage(); }); } Structure.prototype.finishedImage = function () { console.log('Finished an image'); this.nextImage(); }; Structure.prototype.createLayers = function () { var _this = this; this.document.layers.forEach(function (layer, index) { _this.addLayer(_this.layers, _this.document.layers, layer, index); }); }; Structure.prototype.addLayer = function (storage, layers, layer, index) { var overWrites = {}, overWriteLayer; // Ignore masks for now! // TODO: Do not ignore masks. if (true !== layer.mask.removed) { return; } if (true === layer.clipped) { overWriteLayer = layers[index + 1]; overWrites = { top: overWriteLayer._get('bounds.top', 0), right: overWriteLayer._get('bounds.right', 0), bottom: overWriteLayer._get('bounds.bottom', 0), left: overWriteLayer._get('bounds.left', 0) } } storage.push(new Layer(this, layer, overWrites)); }; Structure.prototype.linkLayers = function () { function linkLayers(layers, parent) { layers.forEach(function (layer, index) { layer.parent = parent; if (0 < index) { layer.prev = layers[index - 1]; } if (layers.length > index + 1) { layer.next = layers[index + 1]; } linkLayers(layer.siblings, layer); }); } linkLayers(this.layers, this.parent); }; Structure.prototype.refreshCode = function () { var _this = this; // Reset html and css this.html = ""; this.css = ""; this.layers.forEach(function (layer) { _this.html += layer.getHTML(); _this.css += layer.getCSS(); }); this.html = this.header + this.html + this.footer; }; Structure.prototype.saveToJSON = function () { fs.writeFileSync(this.files.document, stringify(this.document)); fs.writeFileSync( this.files.structure, stringify(this, ['parent', 'prev', 'next', 'document', 'generator', 'structure']) ); console.log('Saved raw document to "' + this.files.document + '"'); console.log('Saved parsed structure to "' + this.files.structure + '"'); }; Structure.prototype.output = function () { fs.writeFileSync(this.files.html, this.html); fs.writeFileSync(this.files.css, this.css); console.log('Index.html and style.css were created.'); }; Structure.prototype.generateImages = function () { var _this = this; function generateImages(layers) { layers.forEach(function (layer) { if ('img' === layer.tag) { // TODO: Add a layer hashsum at the end of the layer to ensure that // if the layer has changed then the image should be regenerated as well. layer.fileName = _this.psdName + '_' + layer.parent.cssId + '_' + layer.cssId + '.png'; layer.filePath = _this.folders.images + layer.fileName; if (true === fs.existsSync(layer.filePath)) { // The image already exists. No need to regenerate it. } else { _this.imagesQueue.push({ id: layer.id, filePath: layer.filePath }); } } if (0 !== layer.siblings.length) { generateImages(layer.siblings); } else { // The no further siblings must be checked for images. } }); } generateImages(this.layers); // Being exporting images. this.nextImage(); }; Structure.prototype.nextImage = function () { var _this = this, imageData; console.log('Triggering next image.'); if (0 === this.imagesQueue.length) { console.log('All images have been generated.'); } else { // FIFO imageData = this.imagesQueue.shift(); this.generator.getPixmap(this.document.id, imageData.id, {}).then( function(pixmap){ savePixmap(pixmap, imageData.filePath, _this.events); }, function(err){ console.error("Pixmap error:", err); } ).done(); } }; Structure.prototype.generateCssIds = function () { var _this = this; function generateCssIds(layers) { layers.forEach(function (layer, index) { layer.cssId = layer.parent.cssId + '-' + layer.name .replace(/&/, '') .replace(/^\//, 'a') .replace(/^[0-9]/g, 'a') .replace(/\s/g, '-'); if (-1 === _this.cssIds.indexOf(layer.cssId)) { // The ID is unique and can be used. } else { layer.cssId += index; } _this.cssIds.push(layer.cssId); if (0 < layer.siblings.length) { generateCssIds(layer.siblings); } }); } generateCssIds(this.layers); }; function runGenerator(document, generator) { var structure = new Structure({ folders: { images: path.resolve(__dirname, 'images/') + '/' }, files: { html: path.resolve(__dirname, 'index.html'), css: path.resolve(__dirname, 'style.css'), document: path.resolve(__dirname, 'document.json'), structure: path.resolve(__dirname, 'structure.json') }, document: document, generator: generator }); structure.createLayers(); structure.linkLayers(); structure.generateCssIds(); structure.generateImages(); structure.saveToJSON(); structure.refreshCode(); structure.output(); } // Verificarea de float este simpla: // - Daca un element incepe de la marginea unui container // - Daca un element nu incepe de la marginea unui container dar are acceasi distanta // de sus ca unul care incepe de la marginea unui container // - Daca un element este intre alte elemente care au aceeasi distanta intre ele // si unul dintre elemente incepe de la marginea unui container // - /* function findFloatables(layers, type) { var flotables = [], firstElementsInRow = [], disposeFloatables = false, marginColumn, marginRow; if (1 < layers.length) { // Order layers by left alignment layers.sort(function (left, right) { return left.properties.parsedCSS.left > right.properties.parsedCSS.left; }); // Order layers by top down alignment layers.sort(function (left, right) { return left.properties.parsedCSS.top > right.properties.parsedCSS.top; }); // Clone array layers.forEach(function (layer) { flotables.push(layer); }); /* // Find the layers that have the same top flotables = flotables.filter(function (layer) { if (flotables[0].properties.parsedCSS.top === layer.properties.parsedCSS.top) { return true; } }); // Calculate the necessary margin for all floated layers marginColumn = flotables[1].properties.parsedCSS.left - (flotables[0].properties.parsedCSS.left + parseInt(flotables[0].properties.parsedCSS.width)); console.log("MarginColumn: " + marginColumn); // The first element of each row must not have margins firstElementsInRow.push(flotables[0].id); console.log(firstElementsInRow); // Find the margin between other layers flotables = flotables.filter(function (layer, index) { var prev = flotables[index - 1], value; // If a flotable candidate did not conform with the margin // then all following canditates are also not floated. if (true === disposeFloatables) { return false; } if (undefined !== prev) { // If floated cantidate is on a different row. if (prev.properties.parsedCSS.top !== layer.properties.parsedCSS.top) { firstElementsInRow.push(layer.id); // Calculate the bottom margin of the above row marginRow = layer.properties.parsedCSS.top - (parseInt(flotables[0].properties.parsedCSS.height) + flotables[0].properties.parsedCSS.top); return true; } value = layer.properties.parsedCSS.left - (prev.properties.parsedCSS.left + parseInt(prev.properties.parsedCSS.width)); console.log(layer.properties.parsedCSS.left + " vs " + prev.properties.parsedCSS.left + " vs " + prev.properties.parsedCSS.width); console.log("Value: " + value); if (value === marginColumn) { return true; } else { disposeFloatables = true; return false; } } else { return true; // The first floated element which is also reference. } }); console.log('Found ' + flotables.length + ' ' + type + ' floatable elements.'); } return { elements: flotables, marginColumn: marginColumn, marginRow: marginRow, firstElementsInRow: firstElementsInRow }; }*/ exports.init = init; }());
Moved the css.top -= 7 for text layers to where the box/plain text verification is made
main.js
Moved the css.top -= 7 for text layers to where the box/plain text verification is made
<ide><path>ain.js <ide> }()); <ide> */ <ide> <del> // TODO: This is a sub optimal solution to compensate for the difference between <del> // line height and leading. <del> css.top -= 7; <del> <ide> (function () { <ide> var textStyleRanges = style._get('text.textStyleRange', []); <ide> <ide> // to be arranged through the alignment styles of the parent <ide> // element. <ide> css.textAlign = 'left'; <add> <add> // TODO: This is a sub optimal solution to compensate for the difference between <add> // line height and leading. <add> css.top -= 7; <ide> } else { <ide> // The text has a defined area and needs to be further <ide> // wrapped in a parent container element.
JavaScript
mit
fb6a8a87f93a3702eff61e3fa564a25763a65d87
0
ZetaRet/protoss
/** * Author: Zeta Ret, Ivo Yankulovski * Zeta Ret XeltoSS ASTConstructor * Generates ASTConstructorInstance of type function * Version: 1.00 * Date: 2018 **/ function ASTConstructor(key,data,datahandler){ var ASTConstructorInstance=function ASTConstructorInstance(){}; ASTConstructorInstance.constructor=arguments.callee; ASTConstructorInstance.key=key; ASTConstructorInstance.data=data; ASTConstructorInstance.datahandler=datahandler; ASTConstructorInstance.toString=function toString(){return this.datahandler?this.datahandler(this.key,this.data):this.data.toString()}; return ASTConstructorInstance; }
xeltoss/ASTConstructor.js
/** * Author: Zeta Ret, Ivo Yankulovski * Zeta Ret XeltoSS ASTConstructor * Generates ASTConstructorInstance of type function * Version: 1.00 * Date: 2019 **/ function ASTConstructor(key,data,datahandler){ var ASTConstructorInstance=function ASTConstructorInstance(){}; ASTConstructorInstance.constructor=arguments.callee; ASTConstructorInstance.key=key; ASTConstructorInstance.data=data; ASTConstructorInstance.datahandler=datahandler; ASTConstructorInstance.toString=function toString(){return this.datahandler?this.datahandler(this.key,this.data):this.data.toString()}; return ASTConstructorInstance; }
Update ASTConstructor.js
xeltoss/ASTConstructor.js
Update ASTConstructor.js
<ide><path>eltoss/ASTConstructor.js <ide> * Zeta Ret XeltoSS ASTConstructor <ide> * Generates ASTConstructorInstance of type function <ide> * Version: 1.00 <del> * Date: 2019 <add> * Date: 2018 <ide> **/ <ide> function ASTConstructor(key,data,datahandler){ <ide> var ASTConstructorInstance=function ASTConstructorInstance(){};
Java
apache-2.0
e5cde55fc55fb0b23dffb8dd648194d969c32b3f
0
stevespringett/dependency-track,stevespringett/dependency-track,stevespringett/dependency-track
/* * This file is part of Dependency-Track. * * Dependency-Track is free software: you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free * Software Foundation, either version 3 of the License, or (at your option) any * later version. * * Dependency-Track is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License along with * Dependency-Track. If not, see http://www.gnu.org/licenses/. */ package org.owasp.dependencytrack.parser.dependencycheck; import alpine.Config; import org.junit.Assert; import org.junit.Test; import org.owasp.dependencytrack.BaseTest; import org.owasp.dependencytrack.model.Component; import org.owasp.dependencytrack.model.Project; import org.owasp.dependencytrack.model.Scan; import org.owasp.dependencytrack.parser.dependencycheck.model.Analysis; import org.owasp.dependencytrack.parser.dependencycheck.model.Dependency; import org.owasp.dependencytrack.parser.dependencycheck.model.Evidence; import org.owasp.dependencytrack.persistence.QueryManager; import java.io.File; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.TimeZone; public class DependencyCheckParserTest extends BaseTest { public DependencyCheckParserTest() { Config.enableUnitTests(); } @Test public void parseTest() throws Exception { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ"); sdf.setTimeZone(TimeZone.getTimeZone("GMT-7:00")); File file = new File("src/test/resources/dependency-check-report.xml"); Analysis analysis = new DependencyCheckParser().parse(file); Assert.assertEquals("1.4.4", analysis.getScanInfo().getEngineVersion()); Assert.assertEquals(17, analysis.getScanInfo().getDataSources().size()); Assert.assertEquals("My Example Application", analysis.getProjectInfo().getName()); Assert.assertEquals("2016-12-06T20:08:02.748-0700", sdf.format(analysis.getProjectInfo().getReportDate())); Assert.assertEquals("This report contains data retrieved from the National Vulnerability Database: http://nvd.nist.gov", analysis.getProjectInfo().getCredits()); Assert.assertEquals(1034, analysis.getDependencies().size()); int foundCount = 0; for (Dependency dependency: analysis.getDependencies()) { if (dependency.getFileName().equals("bootstrap.jar")) { foundCount++; Assert.assertEquals("/workspace/apache-tomcat-7.0.52/bin/bootstrap.jar", dependency.getFilePath()); Assert.assertEquals("ed56f95fdb8ee2903d821253f09f49f4", dependency.getMd5()); Assert.assertEquals("d841369b0cf38390d451015786b6a8ff803d22cd", dependency.getSha1()); Assert.assertEquals(12, dependency.getEvidenceCollected().size()); Assert.assertEquals("vendor", dependency.getEvidenceCollected().get(0).getType()); Assert.assertEquals("HIGH", dependency.getEvidenceCollected().get(0).getConfidence()); Assert.assertEquals("file", dependency.getEvidenceCollected().get(0).getSource()); Assert.assertEquals("name", dependency.getEvidenceCollected().get(0).getName()); Assert.assertEquals("bootstrap", dependency.getEvidenceCollected().get(0).getValue()); Assert.assertEquals(2, dependency.getIdentifiers().getIdentifiers().size()); Assert.assertEquals("cpe", dependency.getIdentifiers().getIdentifiers().get(0).getType()); Assert.assertEquals("HIGH", dependency.getIdentifiers().getIdentifiers().get(0).getConfidence()); Assert.assertEquals("(cpe:/a:apache:tomcat:7.0.52)", dependency.getIdentifiers().getIdentifiers().get(0).getName()); Assert.assertEquals("https://web.nvd.nist.gov/view/vuln/search-results?adv_search=true&cves=on&cpe_version=cpe%3A%2Fa%3Aapache%3Atomcat%3A7.0.52", dependency.getIdentifiers().getIdentifiers().get(0).getUrl()); Assert.assertEquals(18, dependency.getVulnerabilities().getVulnerabilities().size()); Assert.assertEquals("CVE-2016-6325", dependency.getVulnerabilities().getVulnerabilities().get(0).getName()); Assert.assertEquals("7.2", dependency.getVulnerabilities().getVulnerabilities().get(0).getCvssScore()); Assert.assertEquals("LOCAL", dependency.getVulnerabilities().getVulnerabilities().get(0).getCvssAccessVector()); Assert.assertEquals("LOW", dependency.getVulnerabilities().getVulnerabilities().get(0).getCvssAccessComplexity()); Assert.assertEquals("NONE", dependency.getVulnerabilities().getVulnerabilities().get(0).getCvssAuthenticationr()); Assert.assertEquals("COMPLETE", dependency.getVulnerabilities().getVulnerabilities().get(0).getCvssConfidentialImpact()); Assert.assertEquals("COMPLETE", dependency.getVulnerabilities().getVulnerabilities().get(0).getCvssIntegrityImpact()); Assert.assertEquals("COMPLETE", dependency.getVulnerabilities().getVulnerabilities().get(0).getCvssAvailabilityImpact()); Assert.assertEquals("High", dependency.getVulnerabilities().getVulnerabilities().get(0).getSeverity()); Assert.assertEquals("CWE-264 Permissions, Privileges, and Access Controls", dependency.getVulnerabilities().getVulnerabilities().get(0).getCwe()); Assert.assertEquals("The Tomcat package on Red Hat Enterprise Linux (RHEL) 5 through 7, JBoss Web Server 3.0, and JBoss EWS 2 uses weak permissions for (1) /etc/sysconfig/tomcat and (2) /etc/tomcat/tomcat.conf, which allows local users to gain privileges by leveraging membership in the tomcat group.", dependency.getVulnerabilities().getVulnerabilities().get(0).getDescription()); Assert.assertEquals(4, dependency.getVulnerabilities().getVulnerabilities().get(0).getReferences().size()); Assert.assertEquals("REDHAT", dependency.getVulnerabilities().getVulnerabilities().get(0).getReferences().get(3).getSource()); Assert.assertEquals("RHSA-2016:2046", dependency.getVulnerabilities().getVulnerabilities().get(0).getReferences().get(3).getName()); Assert.assertEquals("http://www.securityfocus.com/bid/91453", dependency.getVulnerabilities().getVulnerabilities().get(3).getReferences().get(0).getUrl()); Assert.assertEquals(1, dependency.getVulnerabilities().getVulnerabilities().get(0).getVulnerableSoftware().size()); Assert.assertEquals("cpe:/a:apache:tomcat:-", dependency.getVulnerabilities().getVulnerabilities().get(0).getVulnerableSoftware().get(0)); } else if (dependency.getFileName().equals("ant-testutil.jar")) { foundCount++; Assert.assertNull(dependency.getVulnerabilities().getVulnerabilities()); Assert.assertEquals(1, dependency.getVulnerabilities().getSuppressedVulnerabilities().size()); } } Assert.assertEquals(2, foundCount); } @Test public void objectModelingTest() throws Exception { File file = new File("src/test/resources/dependency-check-report.xml"); Analysis analysis = new DependencyCheckParser().parse(file); QueryManager qm = new QueryManager(); Project project = qm.createProject(analysis.getProjectInfo().getName(), "My Description", "1.0.0", null, null); Scan scan = qm.createScan(project, new Date(), new Date()); Assert.assertEquals(analysis.getProjectInfo().getName(), project.getName()); Assert.assertEquals(project, scan.getProject()); List<Component> components = new ArrayList<>(); for (Dependency dependency: analysis.getDependencies()) { Component component = qm.createComponent( dependency.getFileName(), // name null, // version null, // group dependency.getFileName(), dependency.getMd5(), dependency.getSha1(), dependency.getDescription(), null, // resolved license //todo: try to match it dependency.getLicense(), null ); Assert.assertNotNull(component); Assert.assertEquals(dependency.getFileName(), component.getFilename()); components.add(component); qm.bind(scan, component); for (Evidence evidence: dependency.getEvidenceCollected()) { qm.createEvidence(component, evidence.getType(), evidence.getConfidenceScore(evidence.getConfidenceType()), evidence.getSource(), evidence.getName(), evidence.getValue()); } } Assert.assertEquals(1034, components.size()); qm.close(); } }
src/test/java/org/owasp/dependencytrack/parser/dependencycheck/DependencyCheckParserTest.java
/* * This file is part of Dependency-Track. * * Dependency-Track is free software: you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free * Software Foundation, either version 3 of the License, or (at your option) any * later version. * * Dependency-Track is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License along with * Dependency-Track. If not, see http://www.gnu.org/licenses/. */ package org.owasp.dependencytrack.parser.dependencycheck; import alpine.Config; import org.junit.Assert; import org.junit.Test; import org.owasp.dependencytrack.BaseTest; import org.owasp.dependencytrack.model.Component; import org.owasp.dependencytrack.model.Project; import org.owasp.dependencytrack.model.Scan; import org.owasp.dependencytrack.parser.dependencycheck.model.Analysis; import org.owasp.dependencytrack.parser.dependencycheck.model.Dependency; import org.owasp.dependencytrack.parser.dependencycheck.model.Evidence; import org.owasp.dependencytrack.persistence.QueryManager; import java.io.File; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.TimeZone; public class DependencyCheckParserTest extends BaseTest { public DependencyCheckParserTest() { Config.enableUnitTests(); } @Test public void parseTest() throws Exception { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ"); sdf.setTimeZone(TimeZone.getTimeZone("GMT-7:00")); File file = new File("src/test/resources/dependency-check-report.xml"); Analysis analysis = new DependencyCheckParser().parse(file); Assert.assertEquals("1.4.4", analysis.getScanInfo().getEngineVersion()); Assert.assertEquals(17, analysis.getScanInfo().getDataSources().size()); Assert.assertEquals("My Example Application", analysis.getProjectInfo().getName()); Assert.assertEquals("2016-12-06T20:08:02.748-0700", sdf.format(analysis.getProjectInfo().getReportDate())); Assert.assertEquals("This report contains data retrieved from the National Vulnerability Database: http://nvd.nist.gov", analysis.getProjectInfo().getCredits()); Assert.assertEquals(1034, analysis.getDependencies().size()); int foundCount = 0; for (Dependency dependency: analysis.getDependencies()) { if (dependency.getFileName().equals("bootstrap.jar")) { foundCount++; Assert.assertEquals("/workspace/apache-tomcat-7.0.52/bin/bootstrap.jar", dependency.getFilePath()); Assert.assertEquals("ed56f95fdb8ee2903d821253f09f49f4", dependency.getMd5()); Assert.assertEquals("d841369b0cf38390d451015786b6a8ff803d22cd", dependency.getSha1()); Assert.assertEquals(12, dependency.getEvidenceCollected().size()); Assert.assertEquals("vendor", dependency.getEvidenceCollected().get(0).getType()); Assert.assertEquals("HIGH", dependency.getEvidenceCollected().get(0).getConfidence()); Assert.assertEquals("file", dependency.getEvidenceCollected().get(0).getSource()); Assert.assertEquals("name", dependency.getEvidenceCollected().get(0).getName()); Assert.assertEquals("bootstrap", dependency.getEvidenceCollected().get(0).getValue()); Assert.assertEquals(2, dependency.getIdentifiers().getIdentifiers().size()); Assert.assertEquals("cpe", dependency.getIdentifiers().getIdentifiers().get(0).getType()); Assert.assertEquals("HIGH", dependency.getIdentifiers().getIdentifiers().get(0).getConfidence()); Assert.assertEquals("(cpe:/a:apache:tomcat:7.0.52)", dependency.getIdentifiers().getIdentifiers().get(0).getName()); Assert.assertEquals("https://web.nvd.nist.gov/view/vuln/search-results?adv_search=true&cves=on&cpe_version=cpe%3A%2Fa%3Aapache%3Atomcat%3A7.0.52", dependency.getIdentifiers().getIdentifiers().get(0).getUrl()); Assert.assertEquals(18, dependency.getVulnerabilities().getVulnerabilities().size()); Assert.assertEquals("CVE-2016-6325", dependency.getVulnerabilities().getVulnerabilities().get(0).getName()); Assert.assertEquals("7.2", dependency.getVulnerabilities().getVulnerabilities().get(0).getCvssScore()); Assert.assertEquals("LOCAL", dependency.getVulnerabilities().getVulnerabilities().get(0).getCvssAccessVector()); Assert.assertEquals("LOW", dependency.getVulnerabilities().getVulnerabilities().get(0).getCvssAccessComplexity()); Assert.assertEquals("NONE", dependency.getVulnerabilities().getVulnerabilities().get(0).getCvssAuthenticationr()); Assert.assertEquals("COMPLETE", dependency.getVulnerabilities().getVulnerabilities().get(0).getCvssConfidentialImpact()); Assert.assertEquals("COMPLETE", dependency.getVulnerabilities().getVulnerabilities().get(0).getCvssIntegrityImpact()); Assert.assertEquals("COMPLETE", dependency.getVulnerabilities().getVulnerabilities().get(0).getCvssAvailabilityImpact()); Assert.assertEquals("High", dependency.getVulnerabilities().getVulnerabilities().get(0).getSeverity()); Assert.assertEquals("CWE-264 Permissions, Privileges, and Access Controls", dependency.getVulnerabilities().getVulnerabilities().get(0).getCwe()); Assert.assertEquals("The Tomcat package on Red Hat Enterprise Linux (RHEL) 5 through 7, JBoss Web Server 3.0, and JBoss EWS 2 uses weak permissions for (1) /etc/sysconfig/tomcat and (2) /etc/tomcat/tomcat.conf, which allows local users to gain privileges by leveraging membership in the tomcat group.", dependency.getVulnerabilities().getVulnerabilities().get(0).getDescription()); Assert.assertEquals(4, dependency.getVulnerabilities().getVulnerabilities().get(0).getReferences().size()); Assert.assertEquals("REDHAT", dependency.getVulnerabilities().getVulnerabilities().get(0).getReferences().get(3).getSource()); Assert.assertEquals("RHSA-2016:2046", dependency.getVulnerabilities().getVulnerabilities().get(0).getReferences().get(3).getName()); Assert.assertEquals("http://www.securityfocus.com/bid/91453", dependency.getVulnerabilities().getVulnerabilities().get(3).getReferences().get(0).getUrl()); Assert.assertEquals(1, dependency.getVulnerabilities().getVulnerabilities().get(0).getVulnerableSoftware().size()); Assert.assertEquals("cpe:/a:apache:tomcat:-", dependency.getVulnerabilities().getVulnerabilities().get(0).getVulnerableSoftware().get(0)); } else if (dependency.getFileName().equals("ant-testutil.jar")) { foundCount++; Assert.assertNull(dependency.getVulnerabilities().getVulnerabilities()); Assert.assertEquals(1, dependency.getVulnerabilities().getSuppressedVulnerabilities().size()); } } Assert.assertEquals(2, foundCount); } @Test public void objectModelingTest() throws Exception { File file = new File("src/test/resources/dependency-check-report.xml"); Analysis analysis = new DependencyCheckParser().parse(file); QueryManager qm = new QueryManager(); Project project = qm.createProject(analysis.getProjectInfo().getName(), "My Description", "1.0.0", null, null); Scan scan = qm.createScan(project, new Date(), new Date()); Assert.assertEquals(analysis.getProjectInfo().getName(), project.getName()); Assert.assertEquals(project, scan.getProject()); List<Component> components = new ArrayList<>(); for (Dependency dependency: analysis.getDependencies()) { Component component = qm.createComponent( dependency.getFileName(), dependency.getFileName(), dependency.getMd5(), dependency.getSha1(), dependency.getDescription(), dependency.getLicense(), null ); Assert.assertNotNull(component); Assert.assertEquals(dependency.getFileName(), component.getFilename()); components.add(component); qm.bind(scan, component); for (Evidence evidence: dependency.getEvidenceCollected()) { qm.createEvidence(component, evidence.getType(), evidence.getConfidenceScore(evidence.getConfidenceType()), evidence.getSource(), evidence.getName(), evidence.getValue()); } } Assert.assertEquals(1034, components.size()); qm.close(); } }
Updating test for new method sig
src/test/java/org/owasp/dependencytrack/parser/dependencycheck/DependencyCheckParserTest.java
Updating test for new method sig
<ide><path>rc/test/java/org/owasp/dependencytrack/parser/dependencycheck/DependencyCheckParserTest.java <ide> List<Component> components = new ArrayList<>(); <ide> for (Dependency dependency: analysis.getDependencies()) { <ide> Component component = qm.createComponent( <del> dependency.getFileName(), <add> dependency.getFileName(), // name <add> null, // version <add> null, // group <ide> dependency.getFileName(), <ide> dependency.getMd5(), <ide> dependency.getSha1(), <ide> dependency.getDescription(), <add> null, // resolved license //todo: try to match it <ide> dependency.getLicense(), <ide> null <ide> ); <add> <ide> Assert.assertNotNull(component); <ide> Assert.assertEquals(dependency.getFileName(), component.getFilename()); <ide> components.add(component);
JavaScript
mit
3b4db4d3aa2d56216ce660bbb1f795bdce5992ac
0
Pix---/ioBroker.tankerkoenig,Pix---/ioBroker.tankerkoenig
/* jshint -W097 */// jshint strict:false /*jslint node: true */ 'use strict'; const utils = require(__dirname + '/lib/utils'); // Get common adapter utils const request = require('request'); const adapterName = require('./package.json').name.split('.').pop(); let result; let err; let url = ""; let timer = null; let stopTimer = null; let isStopping = false; let systemLang = 'de'; let adapter; function startAdapter(options) { options = options || {}; Object.assign(options, { name: adapterName, systemConfig: true, useFormatDate: true/*, ready: function () { main(); }, objectChange: function (id, obj) { adapter.log.info('objectChange ' + id + ' ' + JSON.stringify(obj)); }, stateChange: function (id, state) {}, unload: function () { if (timer) { clearInterval(timer); timer = 0; } isStopping = true; } */ }); adapter = new utils.Adapter(options); adapter.on('ready', function() { main(); }); adapter.on('objectChange', function (id, obj) { adapter.log.info('objectChange ' + id + ' ' + JSON.stringify(obj)); }); adapter.on('stateChange', function (id, state) { }); adapter.on('unload', function () { if (timer) { clearInterval(timer); timer = 0; } isStopping = true; }); return adapter; }); let optinNoLog = false; function stop() { if (stopTimer) clearTimeout(stopTimer); // Stop only if schedule mode if (adapter.common && adapter.common.mode == 'schedule') { stopTimer = setTimeout(function () { stopTimer = null; if (timer) clearInterval(timer); isStopping = true; adapter.stop(); }, 30000); } } process.on('SIGINT', function () { if (timer) clearTimeout(timer); }); function writeLog(logtext,logtype) { // wenn optinNoLog TRUE keine Ausgabe bei info, warn und debug, nur bei error if (!optinNoLog) { // Ausgabe bei info, debug und error if (logtype === 'silly') adapter.log.silly(logtext); if (logtype === 'info') adapter.log.info(logtext); if (logtype === 'debug') adapter.log.debug(logtext); if (logtype === 'warn') adapter.log.warn(logtext); if (logtype === 'error') adapter.log.error(logtext); } else { // Ausgabe nur bei error if (logtype === 'error') adapter.log.error(logtext); } } // Dezimalstellen des Preises ermitteln function cutPrice(preis) { preis = parseFloat(preis); let temp = preis * 100; // 100facher Preis jetzt mit einer Nachkommastelle const temp2 = preis * 1000; // 1000facher Preis ohne Nachkommastelle temp = Math.floor(temp); // Nachkommastelle (.x) wird abgeschnitten temp = temp / 100; // es bleiben zwei Nachkommastellen let price_short = temp.toFixed(2); // Preis mit 2 Nachkommastellen ausgeben (abgeschnitten) let price_3rd_digit = Math.ceil(temp2 - (temp * 1000)); // Dritte Nachommastelle einzeln ermitteln return { priceshort: price_short, // als String wg. Nullen zB 1.10 statt 1.1 price3rd: parseInt(price_3rd_digit, 10), price: preis }; } function readData(url) { request(url, function (error, response, body) { if (!error && response.statusCode === 200) { let result; writeLog('Typ Body: ' + typeof body + ' >>> Body Inhalt: ' + body, 'debug'); // fertiges JSON als String try{ result = JSON.parse(body); // String zu Objekt //var data = JSON.stringify(result, null, 2); // Objekt zu String für ausgabe // JSON check if (result.ok) { writeLog('JSON ok', 'debug'); adapter.setState('json', {ack: true, val: body}); // nur String (also body) speichern //VARIABLEN NIEDRIGSTER PREIS definieren let cheapest_e5; // wird mal 0 bis 9 let cheapest_e5_stationid; // passende ID der Tankstelle let cheapest_e10; let cheapest_e10_stationid; let cheapest_diesel; let cheapest_diesel_stationid; // Ermitteln, wo der erste Eintrag in der Liste / Einstellungen steht (durch Runterzählen) for (let j = 9; j >= 0; j--) { const stationID = adapter.config.stationsarray[j][0]; // sowas 'a7cdd9cf-b467-4aac-8eab-d662f082511e' if (!adapter.config.stationsarray[j][0]) { adapter.log.debug('Einstellung/Eintrag Nr. ' + j + ' ist leer'); } else { if (result.prices[stationID].e5 > 0) { cheapest_e5 = j; cheapest_e5_stationid = adapter.config.stationsarray[j][0]; } if (result.prices[stationID].e10 > 0) { cheapest_e10 = j; cheapest_e10_stationid = adapter.config.stationsarray[j][0]; } if (result.prices[stationID].diesel > 0) { cheapest_diesel = j; cheapest_diesel_stationid = adapter.config.stationsarray[j][0]; } } // die letzten gefundenen Einträge beim Runterzählen, // also die ersten in der Liste sind jetzt der Maßstab für den Vergleich, ob billiger oder nicht } // Reset if (adapter.config.resetValues) { // billigstes E5 adapter.setState('stations.cheapest.e5.feed', 0); adapter.setState('stations.cheapest.e5.price', 0); adapter.setState('stations.cheapest.e5.short', ''); adapter.setState('stations.cheapest.e5.3rd', 0);// dritte stelle adapter.setState('stations.cheapest.e5.combined', 'keine Daten'); adapter.setState('stations.cheapest.e5.name', ''); adapter.setState('stations.cheapest.e5.status', ''); adapter.setState('stations.cheapest.e5.station_id', ''); // billigstes E10 adapter.setState('stations.cheapest.e10.feed', 0); adapter.setState('stations.cheapest.e10.price', 0); adapter.setState('stations.cheapest.e10.short', '0'); adapter.setState('stations.cheapest.e10.3rd', 0); adapter.setState('stations.cheapest.e10.combined', 'keine Daten'); adapter.setState('stations.cheapest.e10.name', ''); adapter.setState('stations.cheapest.e10.status', ''); adapter.setState('stations.cheapest.e10.station_id', ''); // billigster Diesel adapter.setState('stations.cheapest.diesel.feed', 0); adapter.setState('stations.cheapest.diesel.price', 0); adapter.setState('stations.cheapest.diesel.short', '0');// zweistellig adapter.setState('stations.cheapest.diesel.3rd', 0);// dritte stelle adapter.setState('stations.cheapest.diesel.combined', 'keine Daten'); adapter.setState('stations.cheapest.diesel.name', ''); adapter.setState('stations.cheapest.diesel.status', ''); adapter.setState('stations.cheapest.diesel.station_id', ''); } // alle Stationen durchgehen for (let i = 0; i < 10; i++) { const stationID = adapter.config.stationsarray[i][0]; // sowas 'a7cdd9cf-b467-4aac-8eab-d662f082511e' const stationName = adapter.config.stationsarray[i][1]; // sowas 'Esso Hamburg Flughafenstraße' // hier alle States für Status und Preise leeren (0.00 oder 0), falls nicht alle 10 Felder ausgefüllt sind (ohne ack true) if (adapter.config.resetValues) { // Zeile testweise eingefügt adapter.setState('stations.' + i + '.status', ''); adapter.setState('stations.' + i + '.e5.feed', 0); if (i < 2) adapter.setState('stations.' + i + '.e5.feed', 0); adapter.setState('stations.' + i + '.e5.short', 0); adapter.setState('stations.' + i + '.e5.3rd', 0); adapter.setState('stations.' + i + '.e5.combined', ''); adapter.setState('stations.' + i + '.e10.feed', 0); if (i < 2) adapter.setState('stations.' + i + '.e10.feed', 0); adapter.setState('stations.' + i + '.e10.short', 0); adapter.setState('stations.' + i + '.e10.3rd', 0); adapter.setState('stations.' + i + '.e10.combined', ''); adapter.setState('stations.' + i + '.diesel.feed', 0); if (i < 2) adapter.setState('stations.' + i + '.diesel.feed', 0); adapter.setState('stations.' + i + '.diesel.short', 0); adapter.setState('stations.' + i + '.diesel.3rd', 0); adapter.setState('stations.' + i + '.diesel.combined', ''); } // Zeile testweise eingefügt if (stationID.length === 36) { // wenn StationID bekannt, also Settings-Feld gefüllt writeLog('Station ' + stationID + ' ' + stationName + ' wird bearbeitet ...','debug'); const status = result.prices[stationID].status; // Namen und Status in jedem Fall schreiben adapter.setState('stations.' + i + '.name', {ack: true, val: stationName}); adapter.setState('stations.' + i + '.status', {ack: true, val: status}); adapter.setState('stations.' + i + '.station_id', {ack: true, val: stationID}); // status checken if (status.indexOf('not found') !== -1) { writeLog('Station ' + stationID + ' nicht gefunden', 'warn'); adapter.setState('stations.' + i + '.e5.combined', '<span class="station_notfound">nicht gefunden</span>'); adapter.setState('stations.' + i + '.e10.combined', '<span class="station_notfound">nicht gefunden</span>'); adapter.setState('stations.' + i + '.diesel.combined', '<span class="station_notfound">nicht gefunden</span>'); } else if (status.indexOf('closed') !== -1) { writeLog('Station ' + stationID + ' ' + stationName + ' geschlossen', 'debug'); adapter.setState('stations.' + i + '.e5.combined', '<span class="station_closed">geschlossen</span>'); adapter.setState('stations.' + i + '.e10.combined', '<span class="station_closed">geschlossen</span>'); adapter.setState('stations.' + i + '.diesel.combined', '<span class="station_closed">geschlossen</span>'); } else if (status.indexOf('open') !== -1) { // wenn false im Preis für e5 steht, ... 0 bleibt stehen if (!result.prices[stationID].e5) { writeLog('In Station ' + stationID + ' ' + stationName + ' kein E5 vefügbar', 'debug'); } else { const prices = cutPrice(result.prices[stationID].e5); //adapter.log.debug('In Station ' + stationID + ' ' + stationName + ' kostet E5: ' + result.prices[stationID].e5 + '€'); adapter.setState('stations.' + i + '.e5.feed', {ack: true, val: parseFloat(result.prices[stationID].e5)}); if (i < 2) adapter.setState('stations.' + i + '.e5.price', {ack: true, val: prices.price}); // normal float adapter.setState('stations.' + i + '.e5.short', {ack: true, val: prices.priceshort});// zweistellig adapter.setState('stations.' + i + '.e5.3rd', {ack: true, val: prices.price3rd});// dritte stelle adapter.setState('stations.' + i + '.e5.combined', '<span class="station_open">' + prices.priceshort + '<sup style="font-size: 50%">' + prices.price3rd + '</sup> <span class="station_combined_euro">€</span></span>'); // Niedrigsten Preis E5 ermitteln writeLog('E5-Preis-Feld ' + i + ' gefüllt', 'debug'); if ( parseFloat(result.prices[stationID].e5) < parseFloat(result.prices[cheapest_e5_stationid].e5) ) { cheapest_e5 = i; cheapest_e5_stationid = adapter.config.stationsarray[i][0]; writeLog('Billigster E5 bisher: ' + cheapest_e5 + '. Tankstelle', 'debug'); } else { writeLog('E5: Station ' + i + ' teurer als bisher billigste Station ' + cheapest_e5, 'debug'); } } if (!result.prices[stationID].e10) { writeLog('In Station ' + stationID + ' ' + stationName + ' kein E10 vefügbar', 'debug'); } else { const prices = cutPrice(result.prices[stationID].e10); //adapter.log.debug('In Station ' + stationID + ' ' + stationName + ' kostet E10: ' + result.prices[stationID].e10 + '€'); adapter.setState('stations.' + i + '.e10.feed', {ack: true, val: parseFloat(result.prices[stationID].e10)}); if (i < 2) adapter.setState('stations.' + i + '.e10.price', {ack: true, val: prices.price}); // normal float adapter.setState('stations.' + i + '.e10.short', {ack: true, val: prices.priceshort}); adapter.setState('stations.' + i + '.e10.3rd', {ack: true, val: prices.price3rd}); adapter.setState('stations.' + i + '.e10.combined', '<span class="station_open">' + prices.priceshort + '<sup style="font-size: 50%">' + prices.price3rd + '</sup> <span class="station_combined_euro">€</span></span>'); /// Niedrigsten Preis E10 ermitteln writeLog('E10-Preis-Feld ' + i + ' gefüllt', 'debug'); if ( parseFloat(result.prices[stationID].e10) < parseFloat(result.prices[cheapest_e10_stationid].e10) ) { cheapest_e10 = i; cheapest_e10_stationid = adapter.config.stationsarray[i][0]; writeLog('Billigster E10 bisher: ' + cheapest_e10 + '. Tankstelle', 'debug'); } else { writeLog('E10: Station ' + i + ' teurer als bisher billigste Station ' + cheapest_e10, 'debug'); } } if (!result.prices[stationID].diesel) { writeLog('In Station ' + stationID + ' ' + stationName + ' kein Diesel vefügbar', 'debug'); } else { const prices = cutPrice(result.prices[stationID].diesel); //adapter.log.debug('In Station ' + stationID + ' ' + stationName + ' kostet Diesel: ' + result.prices[stationID].diesel + '€'); adapter.setState('stations.' + i + '.diesel.feed', {ack: true, val: parseFloat(result.prices[stationID].diesel)}); if (i < 2) adapter.setState('stations.' + i + '.diesel.price', {ack: true, val: prices.price}); // normal float adapter.setState('stations.' + i + '.diesel.short', {ack: true, val: prices.priceshort}); adapter.setState('stations.' + i + '.diesel.3rd', {ack: true, val: prices.price3rd}); adapter.setState('stations.' + i + '.diesel.combined', '<span class="station_open">' + prices.priceshort + '<sup style="font-size: 50%">' + prices.price3rd + '</sup> <span class="station_combined_euro">€</span></span>'); // Niedrigsten Preis Diesel ermitteln writeLog('Diesel-Preis-Feld ' + i + ' gefüllt', 'debug'); if ( parseFloat(result.prices[stationID].diesel) < parseFloat(result.prices[cheapest_diesel_stationid].diesel) ) { cheapest_diesel = i; cheapest_diesel_stationid = adapter.config.stationsarray[i][0]; writeLog('Billigster Diesel bisher: ' + cheapest_diesel + '. Tankstelle', 'debug' ); } else { writeLog('Diesel: Station ' + i + ' teurer als bisher billigste Station ' + cheapest_diesel, 'debug'); } } } // Ende Status 'open' } // Ende Station } // Ende Schleife // AUSGABE NIEDRIGSTER PREIS // billigstes E5 let prices = cutPrice(result.prices[cheapest_e5_stationid].e5); writeLog('Billigster E5: ' + cheapest_e5 + '. Tankstelle ' + adapter.config.stationsarray[cheapest_e5][1] + ', Preis: ' + parseFloat(result.prices[cheapest_e5_stationid].e5), 'debug'); adapter.setState('stations.cheapest.e5.feed', {ack: true, val: parseFloat(result.prices[cheapest_e5_stationid].e5)}); adapter.setState('stations.cheapest.e5.price', {ack: true, val: prices.price});// float adapter.setState('stations.cheapest.e5.short', {ack: true, val: prices.priceshort});// zweistellig adapter.setState('stations.cheapest.e5.3rd', {ack: true, val: prices.price3rd});// dritte stelle adapter.setState('stations.cheapest.e5.combined', '<span class="station_open">' + prices.priceshort + '<sup style="font-size: 50%">' + prices.price3rd + '</sup> <span class="station_combined_euro">€</span></span>'); adapter.setState('stations.cheapest.e5.name', {ack: true, val: adapter.config.stationsarray[cheapest_e5][1]}); adapter.setState('stations.cheapest.e5.status', {ack: true, val: result.prices[cheapest_e5_stationid].status}); adapter.setState('stations.cheapest.e5.station_id', {ack: true, val: cheapest_e5_stationid}); // billigstes E10 prices = cutPrice(result.prices[cheapest_e5_stationid].e10); writeLog('Billigster E10: ' + cheapest_e10 + '. Tankstelle ' + adapter.config.stationsarray[cheapest_e10][1] + ', Preis: ' + parseFloat(result.prices[cheapest_e10_stationid].e10), 'debug'); adapter.setState('stations.cheapest.e10.feed', {ack: true, val: parseFloat(result.prices[cheapest_e10_stationid].e10)}); adapter.setState('stations.cheapest.e10.price', {ack: true, val: prices.price});// float adapter.setState('stations.cheapest.e10.short', {ack: true, val: prices.priceshort});// zweistellig adapter.setState('stations.cheapest.e10.3rd', {ack: true, val: prices.price3rd});// dritte stelle adapter.setState('stations.cheapest.e10.combined', '<span class="station_open">' + prices.priceshort + '<sup style="font-size: 50%">' + prices.price3rd + '</sup> <span class="station_combined_euro">€</span></span>'); adapter.setState('stations.cheapest.e10.name', {ack: true, val: adapter.config.stationsarray[cheapest_e10][1]}); adapter.setState('stations.cheapest.e10.status', {ack: true, val: result.prices[cheapest_e10_stationid].status}); adapter.setState('stations.cheapest.e10.station_id', {ack: true, val: cheapest_e10_stationid}); // billigster Diesel prices = cutPrice(result.prices[cheapest_e5_stationid].diesel); writeLog('Billigster Diesel: ' + cheapest_diesel + '. Tankstelle ' + adapter.config.stationsarray[cheapest_diesel][1] + ', Preis: ' + parseFloat(result.prices[cheapest_diesel_stationid].diesel), 'debug'); adapter.setState('stations.cheapest.diesel.feed', {ack: true, val: parseFloat(result.prices[cheapest_diesel_stationid].diesel)}); adapter.setState('stations.cheapest.diesel.price', {ack: true, val: prices.price});// float adapter.setState('stations.cheapest.diesel.short', {ack: true, val: prices.priceshort});// zweistellig adapter.setState('stations.cheapest.diesel.3rd', {ack: true, val: prices.price3rd});// dritte stelle adapter.setState('stations.cheapest.diesel.combined', '<span class="station_open">' + prices.priceshort + '<sup style="font-size: 50%">' + prices.price3rd + '</sup> <span class="station_combined_euro">€</span></span>'); adapter.setState('stations.cheapest.diesel.name', {ack: true, val: adapter.config.stationsarray[cheapest_diesel][1]}); adapter.setState('stations.cheapest.diesel.status', {ack: true, val: result.prices[cheapest_diesel_stationid].status}); adapter.setState('stations.cheapest.diesel.station_id', {ack: true, val: cheapest_diesel_stationid}); // ENDE AUSGABE NIEDRIGSTER PREIS writeLog('objects written', 'debug'); } else { writeLog('JSON returns error - Station ID or API-Key probably not correct', 'error'); } } catch (e) { writeLog('Spritpreise einlesen (gezielte Stationen via ID) - Parse Fehler: ' + e, 'error'); } } else writeLog('Spritpreise einlesen (gezielte Stationen via ID) - Fehler: ' + error, 'error'); }); // Ende request } function buildQuery() { // Abfrage erstellen (max 10 Tankstellen ID) /* String muss so aussehenen: 'ididididididid','idididididid' dabei werden Häkchen und Komma URLencoded dargestellt, also %2C für Komma und %22 für Häkchen die folgenden Zeilen fügen die Felder mit den ID der Stationen zusammen, unabhänggig, ob Felder freigeblieben sind. Vor dem ersten und nach dem letzten Feld kommt natürlich kein Komma. */ var stations = (adapter.config.station0.length > 0) ? '%22' + adapter.config.station0 + '%22' : ''; //adapter.log.debug('Stations 1: ' + stations); if (stations.length > 0) stations = (adapter.config.station1.length > 0) ? stations + '%2C%22' + adapter.config.station1 + '%22' : stations; else stations = (adapter.config.station1.length > 0) ? stations + '%22' + adapter.config.station1 + '%22' : stations; //adapter.log.debug('Stations 2: ' + stations); if (stations.length > 0) stations = (adapter.config.station2.length > 0) ? stations + '%2C%22' + adapter.config.station2 + '%22' : stations; else stations = (adapter.config.station2.length > 0) ? stations + '%22' + adapter.config.station2 + '%22' : stations; //adapter.log.debug('Stations 3: ' + stations); if (stations.length > 0) stations = (adapter.config.station3.length > 0) ? stations + '%2C%22' + adapter.config.station3 + '%22' : stations; else stations = (adapter.config.station3.length > 0) ? stations + '%22' + adapter.config.station3 + '%22' : stations; //adapter.log.debug('Stations 4: ' + stations); if (stations.length > 0) stations = (adapter.config.station4.length > 0) ? stations + '%2C%22' + adapter.config.station4 + '%22' : stations; else stations = (adapter.config.station4.length > 0) ? stations + '%22' + adapter.config.station4 + '%22' : stations; //adapter.log.debug('Stations 5: ' + stations); if (stations.length > 0) stations = (adapter.config.station5.length > 0) ? stations + '%2C%22' + adapter.config.station5 + '%22' : stations; else stations = (adapter.config.station5.length > 0) ? stations + '%22' + adapter.config.station5 + '%22' : stations; //adapter.log.debug('Stations 6: ' + stations); if (stations.length > 0) stations = (adapter.config.station6.length > 0) ? stations + '%2C%22' + adapter.config.station6 + '%22' : stations; else stations = (adapter.config.station6.length > 0) ? stations + '%22' + adapter.config.station6 + '%22' : stations; //adapter.log.debug('Stations 7: ' + stations); if (stations.length > 0) stations = (adapter.config.station7.length > 0) ? stations + '%2C%22' + adapter.config.station7 + '%22' : stations; else stations = (adapter.config.station7.length > 0) ? stations + '%22' + adapter.config.station7 + '%22' : stations; //adapter.log.debug('Stations 8: ' + stations); if (stations.length > 0) stations = (adapter.config.station8.length > 0) ? stations + '%2C%22' + adapter.config.station8 + '%22' : stations; else stations = (adapter.config.station8.length > 0) ? stations + '%22' + adapter.config.station8 + '%22' : stations; //adapter.log.debug('Stations 9: ' + stations); if (stations.length > 0) stations = (adapter.config.station9.length > 0) ? stations + '%2C%22' + adapter.config.station9 + '%22' : stations; else stations = (adapter.config.station9.length > 0) ? stations + '%22' + adapter.config.station9 + '%22' : stations; //adapter.log.debug('Stations 10: ' + stations); // String in URL einbetten (in eckigen Klammern) und mit APIKey var url = 'https://creativecommons.tankerkoenig.de/json/prices.php?ids=%5B' + stations + '%5D&apikey=' + adapter.config.apikey; return url; } function syncConfig(callback) { //APIKEY let tasks = []; writeLog('Option <reset values> is ' + adapter.config.resetValues, 'debug'); writeLog('API Key Länge: ' + (adapter.config.apikey?adapter.config.apikey.length:0) + ' Zeichen', 'debug'); if (adapter.config.apikey === undefined) { writeLog('No API-Key found.', 'error'); return; // abbruch } else if (adapter.config.apikey.length < 36) { writeLog('API-Key too short, should be 36 digits.', 'error'); return; // abbruch } else if (adapter.config.apikey.length > 36) { writeLog('API-Key too long, should be 36 digits.', 'error'); return; // abbruch } tasks.push({ type: 'extendObject', id: 'tank', data: { common: { name: 'tank', read: true, write: false } } }); processTasks(tasks, function () { var count = 0; url = buildQuery(); if (!count && callback) callback(); }); // noLog optinNoLog = adapter.config.noLogs; // wichtig für function writeLog() } function processTasks(tasks, callback) { if (!tasks || !tasks.length) { callback && callback(); } else { let task = tasks.shift(); let timeout = setTimeout(function () { adapter.log.warn('Please update js-controller to at least 1.2.0'); timeout = null; processTasks(tasks, callback); }, 1000); if (task.type === 'extendObject') { adapter.extendObject(task.id, task.data, function (/* err */) { if (timeout) { clearTimeout(timeout); timeout = null; setImmediate(processTasks, tasks, callback); } }); } else if (task.type === 'deleteState') { adapter.deleteState('', host, task.id, function (/* err */) { if (timeout) { clearTimeout(timeout); timeout = null; setImmediate(processTasks, tasks, callback); } }); } else { adapter.log.error('Unknown task name: ' + JSON.stringify(task)); if (timeout) { clearTimeout(timeout); timeout = null; setImmediate(processTasks, tasks, callback); } } } } function getTanke(tanke) { if (stopTimer) clearTimeout(stopTimer); if (!tanke) { timer = setTimeout(function () { getTanke('go'); }, adapter.config.interval); return; } readData(url); if (!isStopping) { setTimeout(function () { getTanke(''); }, 0); }; } function main() { // adapter.config.interval = parseInt(adapter.config.interval, 10); adapter.config.interval = 0; // polling min 5min if (adapter.config.interval < 5000) { adapter.config.interval = 60 * 1000 * 5; } syncConfig(function () { getTanke('go'); }); adapter.subscribeStates('*'); } // If started as allInOne/compact mode => return function to create instance if (module && module.parent) { module.exports = startAdapter; } else { // or start the instance directly startAdapter(); }
main.js
/* jshint -W097 */// jshint strict:false /*jslint node: true */ 'use strict'; const utils = require(__dirname + '/lib/utils'); // Get common adapter utils const request = require('request'); const adapterName = require('./package.json').name.split('.').pop(); let result; let err; let url = ""; let timer = null; let stopTimer = null; let isStopping = false; let systemLang = 'de'; let adapter; function startAdapter(options) { options = options || {}; Object.assign(options, { name: adapterName, systemConfig: true, useFormatDate: true/*, ready: function () { main(); }, objectChange: function (id, obj) { adapter.log.info('objectChange ' + id + ' ' + JSON.stringify(obj)); }, stateChange: function (id, state) {}, unload: function () { if (timer) { clearInterval(timer); timer = 0; } isStopping = true; } */ }); adapter = new utils.Adapter(options); adapter.on('ready', function() { main(); }); adapter.on('objectChange', function (id, obj) { adapter.log.info('objectChange ' + id + ' ' + JSON.stringify(obj)); }); adapter.on('stateChange', function (id, state) { }); adapter.on('unload', function () { if (timer) { clearInterval(timer); timer = 0; } isStopping = true; }); return adapter; }); let optinNoLog = false; function stop() { if (stopTimer) clearTimeout(stopTimer); // Stop only if schedule mode if (adapter.common && adapter.common.mode == 'schedule') { stopTimer = setTimeout(function () { stopTimer = null; if (timer) clearInterval(timer); isStopping = true; adapter.stop(); }, 30000); } } process.on('SIGINT', function () { if (timer) clearTimeout(timer); }); function writeLog(logtext,logtype) { // wenn optinNoLog TRUE keine Ausgabe bei info, warn und debug, nur bei error if (!optinNoLog) { // Ausgabe bei info, debug und error if (logtype === 'silly') adapter.log.silly(logtext); if (logtype === 'info') adapter.log.info(logtext); if (logtype === 'debug') adapter.log.debug(logtext); if (logtype === 'warn') adapter.log.warn(logtext); if (logtype === 'error') adapter.log.error(logtext); } else { // Ausgabe nur bei error if (logtype === 'error') adapter.log.error(logtext); } } // Dezimalstellen des Preises ermitteln function cutPrice(preis) { preis = parseFloat(preis); let temp = preis * 100; // 100facher Preis jetzt mit einer Nachkommastelle const temp2 = preis * 1000; // 1000facher Preis ohne Nachkommastelle temp = Math.floor(temp); // Nachkommastelle (.x) wird abgeschnitten temp = temp / 100; // es bleiben zwei Nachkommastellen let price_short = temp.toFixed(2); // Preis mit 2 Nachkommastellen ausgeben (abgeschnitten) let price_3rd_digit = Math.ceil(temp2 - (temp * 1000)); // Dritte Nachommastelle einzeln ermitteln return { priceshort: price_short, // als String wg. Nullen zB 1.10 statt 1.1 price3rd: parseInt(price_3rd_digit, 10), price: preis }; } function readData(url) { request(url, function (error, response, body) { if (!error && response.statusCode === 200) { let result; writeLog('Typ Body: ' + typeof body + ' >>> Body Inhalt: ' + body, 'debug'); // fertiges JSON als String try{ result = JSON.parse(body); // String zu Objekt //var data = JSON.stringify(result, null, 2); // Objekt zu String für ausgabe // JSON check if (result.ok) { writeLog('JSON ok', 'debug'); adapter.setState('json', {ack: true, val: body}); // nur String (also body) speichern //VARIABLEN NIEDRIGSTER PREIS definieren let cheapest_e5; // wird mal 0 bis 9 let cheapest_e5_stationid; // passende ID der Tankstelle let cheapest_e10; let cheapest_e10_stationid; let cheapest_diesel; let cheapest_diesel_stationid; // Ermitteln, wo der erste Eintrag in der Liste / Einstellungen steht (durch Runterzählen) for (let j = 9; j >= 0; j--) { const stationID = adapter.config.stationsarray[j][0]; // sowas 'a7cdd9cf-b467-4aac-8eab-d662f082511e' if (!adapter.config.stationsarray[j][0]) { adapter.log.debug('Einstellung/Eintrag Nr. ' + j + ' ist leer'); } else { if (result.prices[stationID].e5 > 0) { cheapest_e5 = j; cheapest_e5_stationid = adapter.config.stationsarray[j][0]; } if (result.prices[stationID].e10 > 0) { cheapest_e10 = j; cheapest_e10_stationid = adapter.config.stationsarray[j][0]; } if (result.prices[stationID].diesel > 0) { cheapest_diesel = j; cheapest_diesel_stationid = adapter.config.stationsarray[j][0]; } } // die letzten gefundenen Einträge beim Runterzählen, // also die ersten in der Liste sind jetzt der Maßstab für den Vergleich, ob billiger oder nicht } // Reset if (adapter.config.resetValues) { // billigstes E5 adapter.setState('stations.cheapest.e5.feed', 0); adapter.setState('stations.cheapest.e5.price', 0); adapter.setState('stations.cheapest.e5.short', ''); adapter.setState('stations.cheapest.e5.3rd', 0);// dritte stelle adapter.setState('stations.cheapest.e5.combined', 'keine Daten'); adapter.setState('stations.cheapest.e5.name', ''); adapter.setState('stations.cheapest.e5.status', ''); adapter.setState('stations.cheapest.e5.station_id', ''); // billigstes E10 adapter.setState('stations.cheapest.e10.feed', 0); adapter.setState('stations.cheapest.e10.price', 0); adapter.setState('stations.cheapest.e10.short', '0'); adapter.setState('stations.cheapest.e10.3rd', 0); adapter.setState('stations.cheapest.e10.combined', 'keine Daten'); adapter.setState('stations.cheapest.e10.name', ''); adapter.setState('stations.cheapest.e10.status', ''); adapter.setState('stations.cheapest.e10.station_id', ''); // billigster Diesel adapter.setState('stations.cheapest.diesel.feed', 0); adapter.setState('stations.cheapest.diesel.price', 0); adapter.setState('stations.cheapest.diesel.short', '0');// zweistellig adapter.setState('stations.cheapest.diesel.3rd', 0);// dritte stelle adapter.setState('stations.cheapest.diesel.combined', 'keine Daten'); adapter.setState('stations.cheapest.diesel.name', ''); adapter.setState('stations.cheapest.diesel.status', ''); adapter.setState('stations.cheapest.diesel.station_id', ''); } // alle Stationen durchgehen for (let i = 0; i < 10; i++) { const stationID = adapter.config.stationsarray[i][0]; // sowas 'a7cdd9cf-b467-4aac-8eab-d662f082511e' const stationName = adapter.config.stationsarray[i][1]; // sowas 'Esso Hamburg Flughafenstraße' // hier alle States für Status und Preise leeren (0.00 oder 0), falls nicht alle 10 Felder ausgefüllt sind (ohne ack true) if (adapter.config.resetValues) { // Zeile testweise eingefügt adapter.setState('stations.' + i + '.status', ''); adapter.setState('stations.' + i + '.e5.feed', 0); if (i < 2) adapter.setState('stations.' + i + '.e5.feed', 0); adapter.setState('stations.' + i + '.e5.short', 0); adapter.setState('stations.' + i + '.e5.3rd', 0); adapter.setState('stations.' + i + '.e5.combined', ''); adapter.setState('stations.' + i + '.e10.feed', 0); if (i < 2) adapter.setState('stations.' + i + '.e10.feed', 0); adapter.setState('stations.' + i + '.e10.short', 0); adapter.setState('stations.' + i + '.e10.3rd', 0); adapter.setState('stations.' + i + '.e10.combined', ''); adapter.setState('stations.' + i + '.diesel.feed', 0); if (i < 2) adapter.setState('stations.' + i + '.diesel.feed', 0); adapter.setState('stations.' + i + '.diesel.short', 0); adapter.setState('stations.' + i + '.diesel.3rd', 0); adapter.setState('stations.' + i + '.diesel.combined', ''); } // Zeile testweise eingefügt if (stationID.length === 36) { // wenn StationID bekannt, also Settings-Feld gefüllt writeLog('Station ' + stationID + ' ' + stationName + ' wird bearbeitet ...','debug'); const status = result.prices[stationID].status; // Namen und Status in jedem Fall schreiben adapter.setState('stations.' + i + '.name', {ack: true, val: stationName}); adapter.setState('stations.' + i + '.status', {ack: true, val: status}); adapter.setState('stations.' + i + '.station_id', {ack: true, val: stationID}); // status checken if (status.indexOf('not found') !== -1) { writeLog('Station ' + stationID + ' nicht gefunden', 'warn'); adapter.setState('stations.' + i + '.e5.combined', '<span class="station_notfound">nicht gefunden</span>'); adapter.setState('stations.' + i + '.e10.combined', '<span class="station_notfound">nicht gefunden</span>'); adapter.setState('stations.' + i + '.diesel.combined', '<span class="station_notfound">nicht gefunden</span>'); } else if (status.indexOf('closed') !== -1) { writeLog('Station ' + stationID + ' ' + stationName + ' geschlossen', 'debug'); adapter.setState('stations.' + i + '.e5.combined', '<span class="station_closed">geschlossen</span>'); adapter.setState('stations.' + i + '.e10.combined', '<span class="station_closed">geschlossen</span>'); adapter.setState('stations.' + i + '.diesel.combined', '<span class="station_closed">geschlossen</span>'); } else if (status.indexOf('open') !== -1) { // wenn false im Preis für e5 steht, ... 0 bleibt stehen if (!result.prices[stationID].e5) { writeLog('In Station ' + stationID + ' ' + stationName + ' kein E5 vefügbar', 'debug'); } else { const prices = cutPrice(result.prices[stationID].e5); //adapter.log.debug('In Station ' + stationID + ' ' + stationName + ' kostet E5: ' + result.prices[stationID].e5 + '€'); adapter.setState('stations.' + i + '.e5.feed', {ack: true, val: parseFloat(result.prices[stationID].e5)}); if (i < 2) adapter.setState('stations.' + i + '.e5.price', {ack: true, val: prices.price}); // normal float adapter.setState('stations.' + i + '.e5.short', {ack: true, val: prices.priceshort});// zweistellig adapter.setState('stations.' + i + '.e5.3rd', {ack: true, val: prices.price3rd});// dritte stelle adapter.setState('stations.' + i + '.e5.combined', '<span class="station_open">' + prices.priceshort + '<sup style="font-size: 50%">' + prices.price3rd + '</sup> <span class="station_combined_euro">€</span></span>'); // Niedrigsten Preis E5 ermitteln writeLog('E5-Preis-Feld ' + i + ' gefüllt', 'debug'); if ( parseFloat(result.prices[stationID].e5) < parseFloat(result.prices[cheapest_e5_stationid].e5) ) { cheapest_e5 = i; cheapest_e5_stationid = adapter.config.stationsarray[i][0]; writeLog('Billigster E5 bisher: ' + cheapest_e5 + '. Tankstelle', 'debug'); } else { writeLog('E5: Station ' + i + ' teurer als bisher billigste Station ' + cheapest_e5, 'debug'); } } if (!result.prices[stationID].e10) { writeLog('In Station ' + stationID + ' ' + stationName + ' kein E10 vefügbar', 'debug'); } else { const prices = cutPrice(result.prices[stationID].e10); //adapter.log.debug('In Station ' + stationID + ' ' + stationName + ' kostet E10: ' + result.prices[stationID].e10 + '€'); adapter.setState('stations.' + i + '.e10.feed', {ack: true, val: parseFloat(result.prices[stationID].e10)}); if (i < 2) adapter.setState('stations.' + i + '.e10.price', {ack: true, val: prices.price}); // normal float adapter.setState('stations.' + i + '.e10.short', {ack: true, val: prices.priceshort}); adapter.setState('stations.' + i + '.e10.3rd', {ack: true, val: prices.price3rd}); adapter.setState('stations.' + i + '.e10.combined', '<span class="station_open">' + prices.priceshort + '<sup style="font-size: 50%">' + prices.price3rd + '</sup> <span class="station_combined_euro">€</span></span>'); /// Niedrigsten Preis E10 ermitteln writeLog('E10-Preis-Feld ' + i + ' gefüllt', 'debug'); if ( parseFloat(result.prices[stationID].e10) < parseFloat(result.prices[cheapest_e10_stationid].e10) ) { cheapest_e10 = i; cheapest_e10_stationid = adapter.config.stationsarray[i][0]; writeLog('Billigster E10 bisher: ' + cheapest_e10 + '. Tankstelle', 'debug'); } else { writeLog('E10: Station ' + i + ' teurer als bisher billigste Station ' + cheapest_e10, 'debug'); } } if (!result.prices[stationID].diesel) { writeLog('In Station ' + stationID + ' ' + stationName + ' kein Diesel vefügbar', 'debug'); } else { const prices = cutPrice(result.prices[stationID].diesel); //adapter.log.debug('In Station ' + stationID + ' ' + stationName + ' kostet Diesel: ' + result.prices[stationID].diesel + '€'); adapter.setState('stations.' + i + '.diesel.feed', {ack: true, val: parseFloat(result.prices[stationID].diesel)}); if (i < 2) adapter.setState('stations.' + i + '.diesel.price', {ack: true, val: prices.price}); // normal float adapter.setState('stations.' + i + '.diesel.short', {ack: true, val: prices.priceshort}); adapter.setState('stations.' + i + '.diesel.3rd', {ack: true, val: prices.price3rd}); adapter.setState('stations.' + i + '.diesel.combined', '<span class="station_open">' + prices.priceshort + '<sup style="font-size: 50%">' + prices.price3rd + '</sup> <span class="station_combined_euro">€</span></span>'); // Niedrigsten Preis Diesel ermitteln writeLog('Diesel-Preis-Feld ' + i + ' gefüllt', 'debug'); if ( parseFloat(result.prices[stationID].diesel) < parseFloat(result.prices[cheapest_diesel_stationid].diesel) ) { cheapest_diesel = i; cheapest_diesel_stationid = adapter.config.stationsarray[i][0]; writeLog('Billigster Diesel bisher: ' + cheapest_diesel + '. Tankstelle', 'debug' ); } else { writeLog('Diesel: Station ' + i + ' teurer als bisher billigste Station ' + cheapest_diesel, 'debug'); } } } // Ende Status 'open' } // Ende Station } // Ende Schleife // AUSGABE NIEDRIGSTER PREIS // billigstes E5 let prices = cutPrice(result.prices[cheapest_e5_stationid].e5); writeLog('Billigster E5: ' + cheapest_e5 + '. Tankstelle ' + adapter.config.stationsarray[cheapest_e5][1] + ', Preis: ' + parseFloat(result.prices[cheapest_e5_stationid].e5), 'debug'); adapter.setState('stations.cheapest.e5.feed', {ack: true, val: parseFloat(result.prices[cheapest_e5_stationid].e5)}); adapter.setState('stations.cheapest.e5.price', {ack: true, val: prices.price});// float adapter.setState('stations.cheapest.e5.short', {ack: true, val: prices.priceshort});// zweistellig adapter.setState('stations.cheapest.e5.3rd', {ack: true, val: prices.price3rd});// dritte stelle adapter.setState('stations.cheapest.e5.combined', '<span class="station_open">' + prices.priceshort + '<sup style="font-size: 50%">' + prices.price3rd + '</sup> <span class="station_combined_euro">€</span></span>'); adapter.setState('stations.cheapest.e5.name', {ack: true, val: adapter.config.stationsarray[cheapest_e5][1]}); adapter.setState('stations.cheapest.e5.status', {ack: true, val: result.prices[cheapest_e5_stationid].status}); adapter.setState('stations.cheapest.e5.station_id', {ack: true, val: cheapest_e5_stationid}); // billigstes E10 prices = cutPrice(result.prices[cheapest_e5_stationid].e10); writeLog('Billigster E10: ' + cheapest_e10 + '. Tankstelle ' + adapter.config.stationsarray[cheapest_e10][1] + ', Preis: ' + parseFloat(result.prices[cheapest_e10_stationid].e10), 'debug'); adapter.setState('stations.cheapest.e10.feed', {ack: true, val: parseFloat(result.prices[cheapest_e10_stationid].e10)}); adapter.setState('stations.cheapest.e10.price', {ack: true, val: prices.price});// float adapter.setState('stations.cheapest.e10.short', {ack: true, val: prices.priceshort});// zweistellig adapter.setState('stations.cheapest.e10.3rd', {ack: true, val: prices.price3rd});// dritte stelle adapter.setState('stations.cheapest.e10.combined', '<span class="station_open">' + prices.priceshort + '<sup style="font-size: 50%">' + prices.price3rd + '</sup> <span class="station_combined_euro">€</span></span>'); adapter.setState('stations.cheapest.e10.name', {ack: true, val: adapter.config.stationsarray[cheapest_e10][1]}); adapter.setState('stations.cheapest.e10.status', {ack: true, val: result.prices[cheapest_e10_stationid].status}); adapter.setState('stations.cheapest.e10.station_id', {ack: true, val: cheapest_e10_stationid}); // billigster Diesel prices = cutPrice(result.prices[cheapest_e5_stationid].diesel); writeLog('Billigster Diesel: ' + cheapest_diesel + '. Tankstelle ' + adapter.config.stationsarray[cheapest_diesel][1] + ', Preis: ' + parseFloat(result.prices[cheapest_diesel_stationid].diesel), 'debug'); adapter.setState('stations.cheapest.diesel.feed', {ack: true, val: parseFloat(result.prices[cheapest_diesel_stationid].diesel)}); adapter.setState('stations.cheapest.diesel.price', {ack: true, val: prices.price});// float adapter.setState('stations.cheapest.diesel.short', {ack: true, val: prices.priceshort});// zweistellig adapter.setState('stations.cheapest.diesel.3rd', {ack: true, val: prices.price3rd});// dritte stelle adapter.setState('stations.cheapest.diesel.combined', '<span class="station_open">' + prices.priceshort + '<sup style="font-size: 50%">' + prices.price3rd + '</sup> <span class="station_combined_euro">€</span></span>'); adapter.setState('stations.cheapest.diesel.name', {ack: true, val: adapter.config.stationsarray[cheapest_diesel][1]}); adapter.setState('stations.cheapest.diesel.status', {ack: true, val: result.prices[cheapest_diesel_stationid].status}); adapter.setState('stations.cheapest.diesel.station_id', {ack: true, val: cheapest_diesel_stationid}); // ENDE AUSGABE NIEDRIGSTER PREIS writeLog('objects written', 'debug'); } else { writeLog('JSON returns error - Station ID or API-Key probably not correct', 'error'); } } catch (e) { writeLog('Spritpreise einlesen (gezielte Stationen via ID) - Parse Fehler: ' + e, 'error'); } } else writeLog('Spritpreise einlesen (gezielte Stationen via ID) - Fehler: ' + error, 'error'); }); // Ende request } function buildQuery() { // Abfrage erstellen (max 10 Tankstellen ID) /* String muss so aussehenen: 'ididididididid','idididididid' dabei werden Häkchen und Komma URLencoded dargestellt, also %2C für Komma und %22 für Häkchen die folgenden Zeilen fügen die Felder mit den ID der Stationen zusammen, unabhänggig, ob Felder freigeblieben sind. Vor dem ersten und nach dem letzten Feld kommt natürlich kein Komma. */ var stations = (adapter.config.station0.length > 0) ? '%22' + adapter.config.station0 + '%22' : ''; //adapter.log.debug('Stations 1: ' + stations); if (stations.length > 0) stations = (adapter.config.station1.length > 0) ? stations + '%2C%22' + adapter.config.station1 + '%22' : stations; else stations = (adapter.config.station1.length > 0) ? stations + '%22' + adapter.config.station1 + '%22' : stations; //adapter.log.debug('Stations 2: ' + stations); if (stations.length > 0) stations = (adapter.config.station2.length > 0) ? stations + '%2C%22' + adapter.config.station2 + '%22' : stations; else stations = (adapter.config.station2.length > 0) ? stations + '%22' + adapter.config.station2 + '%22' : stations; //adapter.log.debug('Stations 3: ' + stations); if (stations.length > 0) stations = (adapter.config.station3.length > 0) ? stations + '%2C%22' + adapter.config.station3 + '%22' : stations; else stations = (adapter.config.station3.length > 0) ? stations + '%22' + adapter.config.station3 + '%22' : stations; //adapter.log.debug('Stations 4: ' + stations); if (stations.length > 0) stations = (adapter.config.station4.length > 0) ? stations + '%2C%22' + adapter.config.station4 + '%22' : stations; else stations = (adapter.config.station4.length > 0) ? stations + '%22' + adapter.config.station4 + '%22' : stations; //adapter.log.debug('Stations 5: ' + stations); if (stations.length > 0) stations = (adapter.config.station5.length > 0) ? stations + '%2C%22' + adapter.config.station5 + '%22' : stations; else stations = (adapter.config.station5.length > 0) ? stations + '%22' + adapter.config.station5 + '%22' : stations; //adapter.log.debug('Stations 6: ' + stations); if (stations.length > 0) stations = (adapter.config.station6.length > 0) ? stations + '%2C%22' + adapter.config.station6 + '%22' : stations; else stations = (adapter.config.station6.length > 0) ? stations + '%22' + adapter.config.station6 + '%22' : stations; //adapter.log.debug('Stations 7: ' + stations); if (stations.length > 0) stations = (adapter.config.station7.length > 0) ? stations + '%2C%22' + adapter.config.station7 + '%22' : stations; else stations = (adapter.config.station7.length > 0) ? stations + '%22' + adapter.config.station7 + '%22' : stations; //adapter.log.debug('Stations 8: ' + stations); if (stations.length > 0) stations = (adapter.config.station8.length > 0) ? stations + '%2C%22' + adapter.config.station8 + '%22' : stations; else stations = (adapter.config.station8.length > 0) ? stations + '%22' + adapter.config.station8 + '%22' : stations; //adapter.log.debug('Stations 9: ' + stations); if (stations.length > 0) stations = (adapter.config.station9.length > 0) ? stations + '%2C%22' + adapter.config.station9 + '%22' : stations; else stations = (adapter.config.station9.length > 0) ? stations + '%22' + adapter.config.station9 + '%22' : stations; //adapter.log.debug('Stations 10: ' + stations); // String in URL einbetten (in eckigen Klammern) und mit APIKey var url = 'https://creativecommons.tankerkoenig.de/json/prices.php?ids=%5B' + stations + '%5D&apikey=' + adapter.config.apikey; return url; } function syncConfig(callback) { //APIKEY let tasks = []; writeLog('Option <reset values> is ' + adapter.config.resetValues, 'debug'); writeLog('API Key Länge: ' + (adapter.config.apikey?adapter.config.apikey.length:0) + ' Zeichen', 'debug'); if (adapter.config.apikey === undefined) { writeLog('No API-Key found.', 'error'); return; // abbruch } else if (adapter.config.apikey.length < 36) { writeLog('API-Key too short, should be 36 digits.', 'error'); return; // abbruch } else if (adapter.config.apikey.length > 36) { writeLog('API-Key too long, should be 36 digits.', 'error'); return; // abbruch } tasks.push({ type: 'extendObject', id: 'tank', data: { common: { name: 'tank', read: true, write: false } } }); processTasks(tasks, function () { var count = 0; url = buildQuery(); if (!count && callback) callback(); }); // noLog optinNoLog = adapter.config.noLogs; // wichtig für function writeLog() } function processTasks(tasks, callback) { if (!tasks || !tasks.length) { callback && callback(); } else { let task = tasks.shift(); let timeout = setTimeout(function () { adapter.log.warn('Please update js-controller to at least 1.2.0'); timeout = null; processTasks(tasks, callback); }, 1000); if (task.type === 'extendObject') { adapter.extendObject(task.id, task.data, function (/* err */) { if (timeout) { clearTimeout(timeout); timeout = null; setImmediate(processTasks, tasks, callback); } }); } else if (task.type === 'deleteState') { adapter.deleteState('', host, task.id, function (/* err */) { if (timeout) { clearTimeout(timeout); timeout = null; setImmediate(processTasks, tasks, callback); } }); } else { adapter.log.error('Unknown task name: ' + JSON.stringify(task)); if (timeout) { clearTimeout(timeout); timeout = null; setImmediate(processTasks, tasks, callback); } } } } function getTanke(tanke) { if (stopTimer) clearTimeout(stopTimer); if (!tanke) { timer = setTimeout(function () { getTanke('go'); }, adapter.config.interval); return; } readData(url); if (!isStopping) { setTimeout(function () { getTanke(''); }, 0); }; } function main() { // adapter.config.interval = parseInt(adapter.config.interval, 10); adapter.config.interval = 0; // polling min 15 min. if (adapter.config.interval < 5000) { adapter.config.interval = 60 * 1000 * 15; } syncConfig(function () { getTanke('go'); }); adapter.subscribeStates('*'); } // If started as allInOne/compact mode => return function to create instance if (module && module.parent) { module.exports = startAdapter; } else { // or start the instance directly startAdapter(); }
1.3.1 request issue fixed
main.js
1.3.1 request issue fixed
<ide><path>ain.js <ide> // adapter.config.interval = parseInt(adapter.config.interval, 10); <ide> adapter.config.interval = 0; <ide> <del>// polling min 15 min. <add>// polling min 5min <ide> if (adapter.config.interval < 5000) { <del> adapter.config.interval = 60 * 1000 * 15; <add> adapter.config.interval = 60 * 1000 * 5; <ide> } <ide> syncConfig(function () { <ide> getTanke('go');
Java
bsd-3-clause
dcd18e37afb1f9794b39de387aba8ceef82ce748
0
fmapfmapfmap/onionoo-dev,fmapfmapfmap/onionoo-dev,fmapfmapfmap/onionoo-dev
/* Copyright 2011, 2012 The Tor Project * See LICENSE for licensing information */ package org.torproject.onionoo; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.regex.Pattern; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.codec.DecoderException; import org.apache.commons.codec.binary.Hex; import org.apache.commons.codec.digest.DigestUtils; public class ResourceServlet extends HttpServlet { private static final long serialVersionUID = 7236658979947465319L; private String outDirString; public void init(ServletConfig config) throws ServletException { super.init(config); this.outDirString = config.getInitParameter("outDir"); this.readSummaryFile(); } long summaryFileLastModified = -1L; boolean readSummaryFile = false; private String relaysPublishedLine = null, bridgesPublishedLine = null; private List<String> relayLines = new ArrayList<String>(), bridgeLines = new ArrayList<String>(); private Map<String, String> relayFingerprintSummaryLines = new HashMap<String, String>(), bridgeFingerprintSummaryLines = new HashMap<String, String>(); private void readSummaryFile() { File summaryFile = new File(this.outDirString + "summary.json"); if (!summaryFile.exists()) { readSummaryFile = false; return; } if (summaryFile.lastModified() > this.summaryFileLastModified) { this.relayLines.clear(); this.bridgeLines.clear(); this.relayFingerprintSummaryLines.clear(); this.bridgeFingerprintSummaryLines.clear(); try { BufferedReader br = new BufferedReader(new FileReader( summaryFile)); String line; while ((line = br.readLine()) != null) { if (line.contains("\"relays_published\":")) { this.relaysPublishedLine = line.startsWith("{") ? line : "{" + line; } else if (line.startsWith("\"bridges_published\":")) { this.bridgesPublishedLine = line; } else if (line.startsWith("\"relays\":")) { while ((line = br.readLine()) != null && !line.equals("],")) { this.relayLines.add(line); int fingerprintStart = line.indexOf("\"f\":\""); if (fingerprintStart > 0) { fingerprintStart += "\"f\":\"".length(); String fingerprint = line.substring(fingerprintStart, fingerprintStart + 40); String hashedFingerprint = DigestUtils.shaHex( Hex.decodeHex(fingerprint.toCharArray())). toUpperCase(); this.relayFingerprintSummaryLines.put(fingerprint, line); this.relayFingerprintSummaryLines.put(hashedFingerprint, line); } } } else if (line.startsWith("\"bridges\":")) { while ((line = br.readLine()) != null && !line.equals("]}")) { this.bridgeLines.add(line); int hashedFingerprintStart = line.indexOf("\"h\":\""); if (hashedFingerprintStart > 0) { hashedFingerprintStart += "\"h\":\"".length(); String hashedFingerprint = line.substring( hashedFingerprintStart, hashedFingerprintStart + 40); String hashedHashedFingerprint = DigestUtils.shaHex( Hex.decodeHex(hashedFingerprint.toCharArray())). toUpperCase(); this.bridgeFingerprintSummaryLines.put(hashedFingerprint, line); this.bridgeFingerprintSummaryLines.put( hashedHashedFingerprint, line); } } } } br.close(); } catch (IOException e) { return; } catch (DecoderException e) { return; } } this.summaryFileLastModified = summaryFile.lastModified(); this.readSummaryFile = true; } public long getLastModified(HttpServletRequest request) { this.readSummaryFile(); return this.summaryFileLastModified; } public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { this.readSummaryFile(); if (!this.readSummaryFile) { response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); return; } String uri = request.getRequestURI(); if (uri.startsWith("/onionoo/")) { uri = uri.substring("/onionoo".length()); } String resourceType = null; if (uri.startsWith("/summary/")) { resourceType = "summary"; } else if (uri.startsWith("/details/")) { resourceType = "details"; } else if (uri.startsWith("/bandwidth/")) { resourceType = "bandwidth"; } else { response.sendError(HttpServletResponse.SC_BAD_REQUEST); return; } /* Handle any errors resulting from invalid requests. */ if (uri.equals("/" + resourceType + "/all")) { } else if (uri.equals("/" + resourceType + "/running")) { } else if (uri.equals("/" + resourceType + "/relays")) { } else if (uri.equals("/" + resourceType + "/bridges")) { } else if (uri.startsWith("/" + resourceType + "/search/")) { String searchParameter = this.parseSearchParameter(uri.substring( ("/" + resourceType + "/search/").length())); if (searchParameter == null) { response.sendError(HttpServletResponse.SC_BAD_REQUEST); return; } } else if (uri.startsWith("/" + resourceType + "/lookup/")) { Set<String> fingerprintParameters = this.parseFingerprintParameters( uri.substring(("/" + resourceType + "/lookup/").length())); if (fingerprintParameters == null) { response.sendError(HttpServletResponse.SC_BAD_REQUEST); return; } } else { response.sendError(HttpServletResponse.SC_BAD_REQUEST); return; } /* Set response headers and start writing the response. */ response.setHeader("Access-Control-Allow-Origin", "*"); response.setContentType("application/json"); response.setCharacterEncoding("utf-8"); PrintWriter pw = response.getWriter(); if (uri.equals("/" + resourceType + "/all")) { pw.print(this.relaysPublishedLine + "\n"); this.writeAllRelays(pw, resourceType); pw.print(this.bridgesPublishedLine + "\n"); this.writeAllBridges(pw, resourceType); } else if (uri.equals("/" + resourceType + "/running")) { pw.print(this.relaysPublishedLine + "\n"); this.writeRunningRelays(pw, resourceType); pw.print(this.bridgesPublishedLine + "\n"); this.writeRunningBridges(pw, resourceType); } else if (uri.equals("/" + resourceType + "/relays")) { pw.print(this.relaysPublishedLine + "\n"); this.writeAllRelays(pw, resourceType); pw.print(this.bridgesPublishedLine + "\n"); this.writeNoBridges(pw); } else if (uri.equals("/" + resourceType + "/bridges")) { pw.print(this.relaysPublishedLine + "\n"); this.writeNoRelays(pw); pw.print(this.bridgesPublishedLine + "\n"); this.writeAllBridges(pw, resourceType); } else if (uri.startsWith("/" + resourceType + "/search/")) { String searchParameter = this.parseSearchParameter(uri.substring( ("/" + resourceType + "/search/").length())); pw.print(this.relaysPublishedLine + "\n"); this.writeMatchingRelays(pw, searchParameter, resourceType); pw.print(this.bridgesPublishedLine + "\n"); this.writeMatchingBridges(pw, searchParameter, resourceType); } else if (uri.startsWith("/" + resourceType + "/lookup/")) { Set<String> fingerprintParameters = this.parseFingerprintParameters( uri.substring(("/" + resourceType + "/lookup/").length())); pw.print(this.relaysPublishedLine + "\n"); this.writeRelaysWithFingerprints(pw, fingerprintParameters, resourceType); pw.print(this.bridgesPublishedLine + "\n"); this.writeBridgesWithFingerprints(pw, fingerprintParameters, resourceType); } pw.flush(); pw.close(); } private static Pattern searchParameterPattern = Pattern.compile("^\\$?[0-9a-fA-F]{1,40}$|^[0-9a-zA-Z\\.]{1,19}$"); private String parseSearchParameter(String parameter) { if (!searchParameterPattern.matcher(parameter).matches()) { return null; } return parameter; } private static Pattern fingerprintParameterPattern = Pattern.compile("^[0-9a-zA-Z]{1,40}$"); private Set<String> parseFingerprintParameters(String parameter) { if (!fingerprintParameterPattern.matcher(parameter).matches()) { return null; } Set<String> parsedFingerprints = new HashSet<String>(); if (parameter.length() != 40) { return null; } parsedFingerprints.add(parameter); return parsedFingerprints; } private void writeAllRelays(PrintWriter pw, String resourceType) { pw.print("\"relays\":["); int written = 0; for (String line : this.relayLines) { String lines = this.getFromSummaryLine(line, resourceType); if (lines.length() > 0) { pw.print((written++ > 0 ? ",\n" : "\n") + lines); } } pw.print("],\n"); } private void writeRunningRelays(PrintWriter pw, String resourceType) { pw.print("\"relays\":["); int written = 0; for (String line : this.relayLines) { if (line.contains("\"r\":true")) { String lines = this.getFromSummaryLine(line, resourceType); if (lines.length() > 0) { pw.print((written++ > 0 ? ",\n" : "\n") + lines); } } } pw.print("\n],\n"); } private void writeNoRelays(PrintWriter pw) { pw.print("\"relays\":[\n"); pw.print("],\n"); } private void writeMatchingRelays(PrintWriter pw, String searchTerm, String resourceType) { if (searchTerm.length() == 40) { Set<String> fingerprints = new HashSet<String>(); fingerprints.add(searchTerm); this.writeRelaysWithFingerprints(pw, fingerprints, resourceType); } else { pw.print("\"relays\":["); int written = 0; for (String line : this.relayLines) { boolean lineMatches = false; if (searchTerm.startsWith("$")) { /* Search is for $-prefixed fingerprint. */ if (line.contains("\"f\":\"" + searchTerm.substring(1).toUpperCase())) { /* $-prefixed fingerprint matches. */ lineMatches = true; } } else if (line.toLowerCase().contains("\"n\":\"" + searchTerm.toLowerCase())) { /* Nickname matches. */ lineMatches = true; } else if ("unnamed".startsWith(searchTerm.toLowerCase()) && line.startsWith("{\"f\":")) { /* Nickname "Unnamed" matches. */ lineMatches = true; } else if (line.contains("\"f\":\"" + searchTerm.toUpperCase())) { /* Non-$-prefixed fingerprint matches. */ lineMatches = true; } else if (line.substring(line.indexOf("\"a\":[")).contains("\"" + searchTerm.toLowerCase())) { /* Address matches. */ lineMatches = true; } if (lineMatches) { String lines = this.getFromSummaryLine(line, resourceType); if (lines.length() > 0) { pw.print((written++ > 0 ? ",\n" : "\n") + lines); } } } pw.print("\n],\n"); } } private void writeRelaysWithFingerprints(PrintWriter pw, Set<String> fingerprints, String resourceType) { pw.print("\"relays\":["); int written = 0; for (String fingerprint : fingerprints) { if (this.relayFingerprintSummaryLines.containsKey( fingerprint.toUpperCase())) { String summaryLine = this.relayFingerprintSummaryLines.get( fingerprint.toUpperCase()); String lines = this.getFromSummaryLine(summaryLine, resourceType); if (lines.length() > 0) { pw.print((written++ > 0 ? ",\n" : "\n") + lines); } } } pw.print("\n],\n"); } private void writeAllBridges(PrintWriter pw, String resourceType) { pw.print("\"bridges\":["); int written = 0; for (String line : this.bridgeLines) { String lines = this.getFromSummaryLine(line, resourceType); if (lines.length() > 0) { pw.print((written++ > 0 ? ",\n" : "\n") + lines); } } pw.print("\n]}\n"); } private void writeRunningBridges(PrintWriter pw, String resourceType) { pw.print("\"bridges\":["); int written = 0; for (String line : this.bridgeLines) { if (line.contains("\"r\":true")) { String lines = this.getFromSummaryLine(line, resourceType); if (lines.length() > 0) { pw.print((written++ > 0 ? ",\n" : "\n") + lines); } } } pw.print("\n]}\n"); } private void writeNoBridges(PrintWriter pw) { pw.print("\"bridges\":[\n"); pw.print("]}\n"); } private void writeMatchingBridges(PrintWriter pw, String searchTerm, String resourceType) { if (searchTerm.startsWith("$")) { searchTerm = searchTerm.substring(1); } if (searchTerm.length() == 40) { Set<String> fingerprints = new HashSet<String>(); fingerprints.add(searchTerm); this.writeBridgesWithFingerprints(pw, fingerprints, resourceType); } else { pw.print("\"bridges\":["); int written = 0; for (String line : this.bridgeLines) { if (line.contains("\"h\":\"" + searchTerm.toUpperCase())) { String lines = this.getFromSummaryLine(line, resourceType); if (lines.length() > 0) { pw.print((written++ > 0 ? ",\n" : "\n") + lines); } } } pw.print("\n]}\n"); } } private void writeBridgesWithFingerprints(PrintWriter pw, Set<String> fingerprints, String resourceType) { pw.print("\"bridges\":["); int written = 0; for (String fingerprint : fingerprints) { if (this.bridgeFingerprintSummaryLines.containsKey( fingerprint.toUpperCase())) { String summaryLine = this.bridgeFingerprintSummaryLines.get( fingerprint.toUpperCase()); String lines = this.getFromSummaryLine(summaryLine, resourceType); if (lines.length() > 0) { pw.print((written++ > 0 ? ",\n" : "\n") + lines); } } } pw.print("\n]}\n"); } private String getFromSummaryLine(String summaryLine, String resourceType) { if (resourceType.equals("summary")) { return this.writeSummaryLine(summaryLine); } else if (resourceType.equals("details")) { return this.writeDetailsLines(summaryLine); } else if (resourceType.equals("bandwidth")) { return this.writeBandwidthLines(summaryLine); } else { return ""; } } private String writeSummaryLine(String summaryLine) { return (summaryLine.endsWith(",") ? summaryLine.substring(0, summaryLine.length() - 1) : summaryLine); } private String writeDetailsLines(String summaryLine) { String fingerprint = null; if (summaryLine.contains("\"f\":\"")) { fingerprint = summaryLine.substring(summaryLine.indexOf( "\"f\":\"") + "\"f\":\"".length()); } else if (summaryLine.contains("\"h\":\"")) { fingerprint = summaryLine.substring(summaryLine.indexOf( "\"h\":\"") + "\"h\":\"".length()); } else { return ""; } fingerprint = fingerprint.substring(0, 40); File detailsFile = new File(this.outDirString + "details/" + fingerprint); StringBuilder sb = new StringBuilder(); String detailsLines = null; if (detailsFile.exists()) { try { BufferedReader br = new BufferedReader(new FileReader( detailsFile)); String line = br.readLine(); if (line != null) { sb.append("{"); while ((line = br.readLine()) != null) { if (!line.startsWith("\"desc_published\":")) { sb.append(line + "\n"); } } } br.close(); detailsLines = sb.toString(); if (detailsLines.length() > 1) { detailsLines = detailsLines.substring(0, detailsLines.length() - 1); } } catch (IOException e) { } } if (detailsLines != null) { return detailsLines; } else { return ""; } } private String writeBandwidthLines(String summaryLine) { String fingerprint = null; if (summaryLine.contains("\"f\":\"")) { fingerprint = summaryLine.substring(summaryLine.indexOf( "\"f\":\"") + "\"f\":\"".length()); } else if (summaryLine.contains("\"h\":\"")) { fingerprint = summaryLine.substring(summaryLine.indexOf( "\"h\":\"") + "\"h\":\"".length()); } else { return ""; } fingerprint = fingerprint.substring(0, 40); File bandwidthFile = new File(this.outDirString + "bandwidth/" + fingerprint); StringBuilder sb = new StringBuilder(); String bandwidthLines = null; if (bandwidthFile.exists()) { try { BufferedReader br = new BufferedReader(new FileReader( bandwidthFile)); String line; while ((line = br.readLine()) != null) { sb.append(line + "\n"); } br.close(); bandwidthLines = sb.toString(); } catch (IOException e) { } } if (bandwidthLines != null) { bandwidthLines = bandwidthLines.substring(0, bandwidthLines.length() - 1); return bandwidthLines; } else { return ""; } } }
src/org/torproject/onionoo/ResourceServlet.java
/* Copyright 2011, 2012 The Tor Project * See LICENSE for licensing information */ package org.torproject.onionoo; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.regex.Pattern; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.codec.DecoderException; import org.apache.commons.codec.binary.Hex; import org.apache.commons.codec.digest.DigestUtils; public class ResourceServlet extends HttpServlet { private static final long serialVersionUID = 7236658979947465319L; private String outDirString; public void init(ServletConfig config) throws ServletException { super.init(config); this.outDirString = config.getInitParameter("outDir"); this.readSummaryFile(); } long summaryFileLastModified = -1L; boolean readSummaryFile = false; private String relaysPublishedLine = null, bridgesPublishedLine = null; private List<String> relayLines = new ArrayList<String>(), bridgeLines = new ArrayList<String>(); private Map<String, String> relayFingerprintSummaryLines = new HashMap<String, String>(), bridgeFingerprintSummaryLines = new HashMap<String, String>(); private void readSummaryFile() { File summaryFile = new File(this.outDirString + "summary.json"); if (!summaryFile.exists()) { readSummaryFile = false; return; } if (summaryFile.lastModified() > this.summaryFileLastModified) { this.relayLines.clear(); this.bridgeLines.clear(); this.relayFingerprintSummaryLines.clear(); this.bridgeFingerprintSummaryLines.clear(); try { BufferedReader br = new BufferedReader(new FileReader( summaryFile)); String line; while ((line = br.readLine()) != null) { if (line.contains("\"relays_published\":")) { this.relaysPublishedLine = line.startsWith("{") ? line : "{" + line; } else if (line.startsWith("\"bridges_published\":")) { this.bridgesPublishedLine = line; } else if (line.startsWith("\"relays\":")) { while ((line = br.readLine()) != null && !line.equals("],")) { this.relayLines.add(line); int fingerprintStart = line.indexOf("\"f\":\""); if (fingerprintStart > 0) { fingerprintStart += "\"f\":\"".length(); String fingerprint = line.substring(fingerprintStart, fingerprintStart + 40); String hashedFingerprint = DigestUtils.shaHex( Hex.decodeHex(fingerprint.toCharArray())). toUpperCase(); this.relayFingerprintSummaryLines.put(fingerprint, line); this.relayFingerprintSummaryLines.put(hashedFingerprint, line); } } } else if (line.startsWith("\"bridges\":")) { while ((line = br.readLine()) != null && !line.equals("]}")) { this.bridgeLines.add(line); int hashedFingerprintStart = line.indexOf("\"h\":\""); if (hashedFingerprintStart > 0) { hashedFingerprintStart += "\"h\":\"".length(); String hashedFingerprint = line.substring( hashedFingerprintStart, hashedFingerprintStart + 40); String hashedHashedFingerprint = DigestUtils.shaHex( Hex.decodeHex(hashedFingerprint.toCharArray())). toUpperCase(); this.bridgeFingerprintSummaryLines.put(hashedFingerprint, line); this.bridgeFingerprintSummaryLines.put( hashedHashedFingerprint, line); } } } } br.close(); } catch (IOException e) { return; } catch (DecoderException e) { return; } } this.summaryFileLastModified = summaryFile.lastModified(); this.readSummaryFile = true; } public long getLastModified(HttpServletRequest request) { this.readSummaryFile(); return this.summaryFileLastModified; } public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { this.readSummaryFile(); if (!this.readSummaryFile) { response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); return; } String uri = request.getRequestURI(); if (uri.startsWith("/onionoo/")) { uri = uri.substring("/onionoo".length()); } String resourceType = null; if (uri.startsWith("/summary/")) { resourceType = "summary"; } else if (uri.startsWith("/details/")) { resourceType = "details"; } else if (uri.startsWith("/bandwidth/")) { resourceType = "bandwidth"; } else { response.sendError(HttpServletResponse.SC_BAD_REQUEST); return; } /* Handle any errors resulting from invalid requests. */ if (uri.equals("/" + resourceType + "/all")) { } else if (uri.equals("/" + resourceType + "/running")) { } else if (uri.equals("/" + resourceType + "/relays")) { } else if (uri.equals("/" + resourceType + "/bridges")) { } else if (uri.startsWith("/" + resourceType + "/search/")) { String searchParameter = this.parseSearchParameter(uri.substring( ("/" + resourceType + "/search/").length())); if (searchParameter == null) { response.sendError(HttpServletResponse.SC_BAD_REQUEST); return; } } else if (uri.startsWith("/" + resourceType + "/lookup/")) { Set<String> fingerprintParameters = this.parseFingerprintParameters( uri.substring(("/" + resourceType + "/lookup/").length())); if (fingerprintParameters == null) { response.sendError(HttpServletResponse.SC_BAD_REQUEST); return; } } else { response.sendError(HttpServletResponse.SC_BAD_REQUEST); return; } /* Set response headers and start writing the response. */ response.setHeader("Access-Control-Allow-Origin", "*"); response.setContentType("application/json"); response.setCharacterEncoding("utf-8"); PrintWriter pw = response.getWriter(); if (uri.equals("/" + resourceType + "/all")) { pw.print(this.relaysPublishedLine + "\n"); this.writeAllRelays(pw, resourceType); pw.print(this.bridgesPublishedLine + "\n"); this.writeAllBridges(pw, resourceType); } else if (uri.equals("/" + resourceType + "/running")) { pw.print(this.relaysPublishedLine + "\n"); this.writeRunningRelays(pw, resourceType); pw.print(this.bridgesPublishedLine + "\n"); this.writeRunningBridges(pw, resourceType); } else if (uri.equals("/" + resourceType + "/relays")) { pw.print(this.relaysPublishedLine + "\n"); this.writeAllRelays(pw, resourceType); pw.print(this.bridgesPublishedLine + "\n"); this.writeNoBridges(pw); } else if (uri.equals("/" + resourceType + "/bridges")) { pw.print(this.relaysPublishedLine + "\n"); this.writeNoRelays(pw); pw.print(this.bridgesPublishedLine + "\n"); this.writeAllBridges(pw, resourceType); } else if (uri.startsWith("/" + resourceType + "/search/")) { String searchParameter = this.parseSearchParameter(uri.substring( ("/" + resourceType + "/search/").length())); pw.print(this.relaysPublishedLine + "\n"); this.writeMatchingRelays(pw, searchParameter, resourceType); pw.print(this.bridgesPublishedLine + "\n"); this.writeMatchingBridges(pw, searchParameter, resourceType); } else if (uri.startsWith("/" + resourceType + "/lookup/")) { Set<String> fingerprintParameters = this.parseFingerprintParameters( uri.substring(("/" + resourceType + "/lookup/").length())); pw.print(this.relaysPublishedLine + "\n"); this.writeRelaysWithFingerprints(pw, fingerprintParameters, resourceType); pw.print(this.bridgesPublishedLine + "\n"); this.writeBridgesWithFingerprints(pw, fingerprintParameters, resourceType); } pw.flush(); pw.close(); } private static Pattern searchParameterPattern = Pattern.compile("^\\$?[0-9a-fA-F]{1,40}$|^[0-9a-zA-Z\\.]{1,19}$"); private String parseSearchParameter(String parameter) { if (!searchParameterPattern.matcher(parameter).matches()) { return null; } return parameter; } private static Pattern fingerprintParameterPattern = Pattern.compile("^[0-9a-zA-Z]{1,40}$"); private Set<String> parseFingerprintParameters(String parameter) { if (!fingerprintParameterPattern.matcher(parameter).matches()) { return null; } Set<String> parsedFingerprints = new HashSet<String>(); if (parameter.length() != 40) { return null; } parsedFingerprints.add(parameter); return parsedFingerprints; } private void writeAllRelays(PrintWriter pw, String resourceType) { pw.print("\"relays\":["); int written = 0; for (String line : this.relayLines) { String lines = this.getFromSummaryLine(line, resourceType); if (lines.length() > 0) { pw.print((written++ > 0 ? ",\n" : "\n") + lines); } } pw.print("],\n"); } private void writeRunningRelays(PrintWriter pw, String resourceType) { pw.print("\"relays\":["); int written = 0; for (String line : this.relayLines) { if (line.contains("\"r\":true")) { String lines = this.getFromSummaryLine(line, resourceType); if (lines.length() > 0) { pw.print((written++ > 0 ? ",\n" : "\n") + lines); } } } pw.print("\n],\n"); } private void writeNoRelays(PrintWriter pw) { pw.print("\"relays\":[\n"); pw.print("],\n"); } private void writeMatchingRelays(PrintWriter pw, String searchTerm, String resourceType) { if (searchTerm.length() == 40) { Set<String> fingerprints = new HashSet<String>(); fingerprints.add(searchTerm); this.writeRelaysWithFingerprints(pw, fingerprints, resourceType); } else { pw.print("\"relays\":["); int written = 0; for (String line : this.relayLines) { boolean lineMatches = false; if (searchTerm.startsWith("$")) { /* Search is for $-prefixed fingerprint. */ if (line.contains("\"f\":\"" + searchTerm.substring(1).toUpperCase())) { /* $-prefixed fingerprint matches. */ lineMatches = true; } } else if (line.toLowerCase().contains("\"n\":\"" + searchTerm.toLowerCase())) { /* Nickname matches. */ lineMatches = true; } else if ("unnamed".startsWith(searchTerm.toLowerCase()) && line.startsWith("{\"f\":")) { /* Nickname "Unnamed" matches. */ lineMatches = true; } else if (line.contains("\"f\":\"" + searchTerm.toUpperCase())) { /* Non-$-prefixed fingerprint matches. */ lineMatches = true; } else if (line.substring(line.indexOf("\"a\":[")).contains("\"" + searchTerm.toLowerCase())) { /* Address matches. */ lineMatches = true; } if (lineMatches) { String lines = this.getFromSummaryLine(line, resourceType); if (lines.length() > 0) { pw.print((written++ > 0 ? ",\n" : "\n") + lines); } } } pw.print("\n],\n"); } } private void writeRelaysWithFingerprints(PrintWriter pw, Set<String> fingerprints, String resourceType) { pw.print("\"relays\":["); int written = 0; for (String fingerprint : fingerprints) { if (this.relayFingerprintSummaryLines.containsKey( fingerprint.toUpperCase())) { String summaryLine = this.relayFingerprintSummaryLines.get( fingerprint.toUpperCase()); String lines = this.getFromSummaryLine(summaryLine, resourceType); if (lines.length() > 0) { pw.print((written++ > 0 ? ",\n" : "\n") + lines); } } } pw.print("\n],\n"); } private void writeAllBridges(PrintWriter pw, String resourceType) { pw.print("\"bridges\":["); int written = 0; for (String line : this.bridgeLines) { String lines = this.getFromSummaryLine(line, resourceType); if (lines.length() > 0) { pw.print((written++ > 0 ? ",\n" : "\n") + lines); } } pw.print("\n]}\n"); } private void writeRunningBridges(PrintWriter pw, String resourceType) { pw.print("\"bridges\":["); int written = 0; for (String line : this.bridgeLines) { if (line.contains("\"r\":true")) { String lines = this.getFromSummaryLine(line, resourceType); if (lines.length() > 0) { pw.print((written++ > 0 ? ",\n" : "\n") + lines); } } } pw.print("\n]}\n"); } private void writeNoBridges(PrintWriter pw) { pw.print("\"bridges\":[\n"); pw.print("]}\n"); } private void writeMatchingBridges(PrintWriter pw, String searchTerm, String resourceType) { if (searchTerm.startsWith("$")) { searchTerm = searchTerm.substring(1); } if (searchTerm.length() == 40) { Set<String> fingerprints = new HashSet<String>(); fingerprints.add(searchTerm); this.writeBridgesWithFingerprints(pw, fingerprints, resourceType); } else { pw.print("\"bridges\":["); int written = 0; for (String line : this.bridgeLines) { if (line.contains("\"h\":\"" + searchTerm.toUpperCase())) { String lines = this.getFromSummaryLine(line, resourceType); if (lines.length() > 0) { pw.print((written++ > 0 ? ",\n" : "\n") + lines); } } } pw.print("\n]}\n"); } } private void writeBridgesWithFingerprints(PrintWriter pw, Set<String> fingerprints, String resourceType) { pw.print("\"bridges\":["); int written = 0; for (String fingerprint : fingerprints) { if (this.bridgeFingerprintSummaryLines.containsKey( fingerprint.toUpperCase())) { String summaryLine = this.bridgeFingerprintSummaryLines.get( fingerprint.toUpperCase()); String lines = this.getFromSummaryLine(summaryLine, resourceType); if (lines.length() > 0) { pw.print((written++ > 0 ? ",\n" : "\n") + lines); } } } pw.print("\n]}\n"); } private String getFromSummaryLine(String summaryLine, String resourceType) { if (resourceType.equals("summary")) { return this.writeSummaryLine(summaryLine); } else if (resourceType.equals("details")) { return this.writeDetailsLines(summaryLine); } else if (resourceType.equals("bandwidth")) { return this.writeBandwidthLines(summaryLine); } else { return ""; } } private String writeSummaryLine(String summaryLine) { return (summaryLine.endsWith(",") ? summaryLine.substring(0, summaryLine.length() - 1) : summaryLine); } private String writeDetailsLines(String summaryLine) { String fingerprint = null; if (summaryLine.contains("\"f\":\"")) { fingerprint = summaryLine.substring(summaryLine.indexOf( "\"f\":\"") + "\"f\":\"".length()); } else if (summaryLine.contains("\"h\":\"")) { fingerprint = summaryLine.substring(summaryLine.indexOf( "\"h\":\"") + "\"h\":\"".length()); } else { return ""; } fingerprint = fingerprint.substring(0, 40); File detailsFile = new File(this.outDirString + "details/" + fingerprint); StringBuilder sb = new StringBuilder(); String detailsLines = null; if (detailsFile.exists()) { try { BufferedReader br = new BufferedReader(new FileReader( detailsFile)); String line = br.readLine(); if (line != null) { sb.append("{"); while ((line = br.readLine()) != null) { if (!line.startsWith("\"desc_published\":")) { sb.append(line + "\n"); } } } br.close(); detailsLines = sb.toString(); if (detailsLines.length() > 1) { detailsLines = detailsLines.substring(0, detailsLines.length() - 1); } } catch (IOException e) { } } if (detailsLines != null) { return detailsLines; } else { return ""; } } private String writeBandwidthLines(String summaryLine) { String fingerprint = null; if (summaryLine.contains("\"f\":\"")) { fingerprint = summaryLine.substring(summaryLine.indexOf( "\"f\":\"") + "\"f\":\"".length()); } else if (summaryLine.contains("\"h\":\"")) { fingerprint = summaryLine.substring(summaryLine.indexOf( "\"h\":\"") + "\"h\":\"".length()); } else { return ""; } fingerprint = fingerprint.substring(0, 40); File detailsFile = new File(this.outDirString + "bandwidth/" + fingerprint); StringBuilder sb = new StringBuilder(); String bandwidthLines = null; if (detailsFile.exists()) { try { BufferedReader br = new BufferedReader(new FileReader( detailsFile)); String line; while ((line = br.readLine()) != null) { sb.append(line + "\n"); } br.close(); bandwidthLines = sb.toString(); } catch (IOException e) { } } if (bandwidthLines != null) { bandwidthLines = bandwidthLines.substring(0, bandwidthLines.length() - 1); return bandwidthLines; } else { return ""; } } }
Rename a variable.
src/org/torproject/onionoo/ResourceServlet.java
Rename a variable.
<ide><path>rc/org/torproject/onionoo/ResourceServlet.java <ide> return ""; <ide> } <ide> fingerprint = fingerprint.substring(0, 40); <del> File detailsFile = new File(this.outDirString + "bandwidth/" <add> File bandwidthFile = new File(this.outDirString + "bandwidth/" <ide> + fingerprint); <ide> StringBuilder sb = new StringBuilder(); <ide> String bandwidthLines = null; <del> if (detailsFile.exists()) { <add> if (bandwidthFile.exists()) { <ide> try { <ide> BufferedReader br = new BufferedReader(new FileReader( <del> detailsFile)); <add> bandwidthFile)); <ide> String line; <ide> while ((line = br.readLine()) != null) { <ide> sb.append(line + "\n");
Java
apache-2.0
7ab5dc7cf4ba4bf786d750e455bcdde022974e66
0
EmmyLua/IntelliJ-EmmyLua,EmmyLua/IntelliJ-EmmyLua,tangzx/IntelliJ-EmmyLua,tangzx/IntelliJ-EmmyLua,EmmyLua/IntelliJ-EmmyLua,tangzx/IntelliJ-EmmyLua,EmmyLua/IntelliJ-EmmyLua,tangzx/IntelliJ-EmmyLua
/* * Copyright (c) 2017. tangzx([email protected]) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.tang.intellij.lua.codeInsight.intention; import com.intellij.codeInsight.intention.impl.BaseIntentionAction; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.project.Project; import com.intellij.psi.PsiFile; import com.intellij.psi.util.PsiTreeUtil; import com.intellij.util.IncorrectOperationException; import com.tang.intellij.lua.psi.LuaClassMethodDef; import com.tang.intellij.lua.psi.LuaClassMethodName; import org.jetbrains.annotations.Nls; import org.jetbrains.annotations.NotNull; /** * * Created by TangZX on 2016/12/16. */ public abstract class ClassMethodBasedIntention extends BaseIntentionAction { @Nls @NotNull @Override public String getFamilyName() { return "ClassMethodBasedIntention"; } @Override public boolean isAvailable(@NotNull Project project, Editor editor, PsiFile psiFile) { LuaClassMethodName methodName = PsiTreeUtil.findElementOfClassAtOffset(psiFile, editor.getCaretModel().getOffset(), LuaClassMethodName.class, false); if (methodName == null) return false; LuaClassMethodDef classMethodDef = PsiTreeUtil.getParentOfType(methodName, LuaClassMethodDef.class); return isAvailable(classMethodDef, editor); } protected boolean isAvailable(LuaClassMethodDef methodDef, Editor editor) { return false; } @Override public void invoke(@NotNull Project project, Editor editor, PsiFile psiFile) throws IncorrectOperationException { LuaClassMethodDef classMethodDef = PsiTreeUtil.findElementOfClassAtOffset(psiFile, editor.getCaretModel().getOffset(), LuaClassMethodDef.class, false); invoke(classMethodDef, editor); } protected void invoke(LuaClassMethodDef methodDef, Editor editor) { } }
src/main/java/com/tang/intellij/lua/codeInsight/intention/ClassMethodBasedIntention.java
/* * Copyright (c) 2017. tangzx([email protected]) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.tang.intellij.lua.codeInsight.intention; import com.intellij.codeInsight.intention.impl.BaseIntentionAction; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.project.Project; import com.intellij.psi.PsiFile; import com.intellij.psi.util.PsiTreeUtil; import com.intellij.util.IncorrectOperationException; import com.tang.intellij.lua.psi.LuaClassMethodDef; import org.jetbrains.annotations.Nls; import org.jetbrains.annotations.NotNull; /** * * Created by TangZX on 2016/12/16. */ public abstract class ClassMethodBasedIntention extends BaseIntentionAction { @Nls @NotNull @Override public String getFamilyName() { return "ClassMethodBasedIntention"; } @Override public boolean isAvailable(@NotNull Project project, Editor editor, PsiFile psiFile) { LuaClassMethodDef classMethodDef = PsiTreeUtil.findElementOfClassAtOffset(psiFile, editor.getCaretModel().getOffset(), LuaClassMethodDef.class, false); return classMethodDef != null && isAvailable(classMethodDef, editor); } protected boolean isAvailable(LuaClassMethodDef methodDef, Editor editor) { return false; } @Override public void invoke(@NotNull Project project, Editor editor, PsiFile psiFile) throws IncorrectOperationException { LuaClassMethodDef classMethodDef = PsiTreeUtil.findElementOfClassAtOffset(psiFile, editor.getCaretModel().getOffset(), LuaClassMethodDef.class, false); invoke(classMethodDef, editor); } protected void invoke(LuaClassMethodDef methodDef, Editor editor) { } }
method intention
src/main/java/com/tang/intellij/lua/codeInsight/intention/ClassMethodBasedIntention.java
method intention
<ide><path>rc/main/java/com/tang/intellij/lua/codeInsight/intention/ClassMethodBasedIntention.java <ide> import com.intellij.psi.util.PsiTreeUtil; <ide> import com.intellij.util.IncorrectOperationException; <ide> import com.tang.intellij.lua.psi.LuaClassMethodDef; <add>import com.tang.intellij.lua.psi.LuaClassMethodName; <ide> import org.jetbrains.annotations.Nls; <ide> import org.jetbrains.annotations.NotNull; <ide> <ide> <ide> @Override <ide> public boolean isAvailable(@NotNull Project project, Editor editor, PsiFile psiFile) { <del> LuaClassMethodDef classMethodDef = PsiTreeUtil.findElementOfClassAtOffset(psiFile, editor.getCaretModel().getOffset(), LuaClassMethodDef.class, false); <del> return classMethodDef != null && isAvailable(classMethodDef, editor); <add> LuaClassMethodName methodName = PsiTreeUtil.findElementOfClassAtOffset(psiFile, editor.getCaretModel().getOffset(), LuaClassMethodName.class, false); <add> if (methodName == null) <add> return false; <add> LuaClassMethodDef classMethodDef = PsiTreeUtil.getParentOfType(methodName, LuaClassMethodDef.class); <add> return isAvailable(classMethodDef, editor); <ide> } <ide> <ide> protected boolean isAvailable(LuaClassMethodDef methodDef, Editor editor) {
JavaScript
mit
cdffe8fa40aec4fb9f533668257bf6e3d71a78aa
0
HenrikJoreteg/Happy.js,HenrikJoreteg/Happy.js
/*global $*/ (function happyJS($) { function trim(el) { return (''.trim) ? el.val().trim() : $.trim(el.val()); } $.fn.isHappy = function isHappy(config) { var fields = [], item; var pauseMessages = false; function isFunction(obj) { return !!(obj && obj.constructor && obj.call && obj.apply); } function defaultError(error) { //Default error template var msgErrorClass = config.classes && config.classes.message || 'unhappyMessage'; return $('<span id="' + error.id + '" class="' + msgErrorClass + '" role="alert">' + error.message + '</span>'); } function getError(error) { //Generate error html from either config or default if (isFunction(config.errorTemplate)) { return config.errorTemplate(error); } return defaultError(error); } function handleSubmit(e) { var i, l; var errors = false; for (i = 0, l = fields.length; i < l; i += 1) { if (!fields[i].testValid(true)) { errors = true; } } if (errors) { if (isFunction(config.unHappy)) config.unHappy(e); return false; } else if (config.testMode) { e.preventDefault(); if (window.console) console.warn('would have submitted'); if (isFunction(config.happy)) return config.happy(e); } if (isFunction(config.happy)) return config.happy(e); } function handleMouseUp() { pauseMessages = false; } function handleMouseDown() { pauseMessages = true; $(window).bind('mouseup', handleMouseUp); } function processField(opts, selector) { var field = $(selector); selector = field.prop('id') || field.prop('name').replace(['[',']'], ''); var error = { message: opts.message || '', id: selector + '_unhappy' }; var errorEl = $(error.id).length > 0 ? $(error.id) : getError(error); var handleBlur = function handleBlur() { if (!pauseMessages) { field.testValid(); } else { $(window).bind('mouseup', field.testValid.bind(this)); } }; fields.push(field); field.testValid = function testValid(submit) { var val, gotFunc, temp; var el = $(this); var errorTarget = (opts.errorTarget && $(opts.errorTarget)) || el; var error = false; var required = !!el.get(0).attributes.getNamedItem('required') || opts.required; var password = (field.attr('type') === 'password'); var arg = isFunction(opts.arg) ? opts.arg() : opts.arg; var fieldErrorClass = config.classes && config.classes.field || 'unhappy'; // handle control groups (checkboxes, radio) if (el.length > 1) { val = []; el.each(function(i,obj) { val.push($(obj).val()); }); val = val.join(','); } else { // clean it or trim it if (isFunction(opts.clean)) { val = opts.clean(el.val()); } else if (!password && typeof opts.trim === 'undefined' || opts.trim) { val = trim(el); } else { val = el.val(); } // write it back to the field el.val(val); } // get the value gotFunc = ((val.length > 0 || required === 'sometimes') && isFunction(opts.test)); // check if we've got an error on our hands if (submit === true && required === true && val.length === 0) { error = true; } else if (gotFunc) { error = !opts.test(val, arg); } if (error) { errorTarget.addClass(fieldErrorClass).after(errorEl); return false; } else { temp = errorEl.get(0); // this is for zepto if (temp.parentNode) { temp.parentNode.removeChild(temp); } errorTarget.removeClass(fieldErrorClass); return true; } }; field.bind(opts.when || config.when || 'blur', handleBlur); } for (item in config.fields) { processField(config.fields[item], item); } $(config.submitButton || this).bind('mousedown', handleMouseDown); if (config.submitButton) { $(config.submitButton).click(handleSubmit); } else { this.bind('submit', handleSubmit); } return this; }; })(this.jQuery || this.Zepto);
happy.js
/*global $*/ (function happyJS($) { function trim(el) { return (''.trim) ? el.val().trim() : $.trim(el.val()); } $.fn.isHappy = function isHappy(config) { var fields = [], item; var pauseMessages = false; function isFunction(obj) { return !!(obj && obj.constructor && obj.call && obj.apply); } function defaultError(error) { //Default error template var msgErrorClass = config.classes && config.classes.message || 'unhappyMessage'; return $('<span id="' + error.id + '" class="' + msgErrorClass + '" role="alert">' + error.message + '</span>'); } function getError(error) { //Generate error html from either config or default if (isFunction(config.errorTemplate)) { return config.errorTemplate(error); } return defaultError(error); } function handleSubmit(e) { var i, l; var errors = false; for (i = 0, l = fields.length; i < l; i += 1) { if (!fields[i].testValid(true)) { errors = true; } } if (errors) { if (isFunction(config.unHappy)) config.unHappy(); return false; } else if (config.testMode) { e.preventDefault(); if (window.console) console.warn('would have submitted'); if (isFunction(config.happy)) return config.happy(); } if (isFunction(config.happy)) return config.happy(); } function handleMouseUp() { pauseMessages = false; } function handleMouseDown() { pauseMessages = true; $(window).bind('mouseup', handleMouseUp); } function processField(opts, selector) { var field = $(selector); selector = field.prop('id') || field.prop('name').replace(['[',']'], ''); var error = { message: opts.message || '', id: selector + '_unhappy' }; var errorEl = $(error.id).length > 0 ? $(error.id) : getError(error); var handleBlur = function handleBlur() { if (!pauseMessages) { field.testValid(); } else { $(window).bind('mouseup', field.testValid.bind(this)); } }; fields.push(field); field.testValid = function testValid(submit) { var val, gotFunc, temp; var el = $(this); var errorTarget = (opts.errorTarget && $(opts.errorTarget)) || el; var error = false; var required = !!el.get(0).attributes.getNamedItem('required') || opts.required; var password = (field.attr('type') === 'password'); var arg = isFunction(opts.arg) ? opts.arg() : opts.arg; var fieldErrorClass = config.classes && config.classes.field || 'unhappy'; // handle control groups (checkboxes, radio) if (el.length > 1) { val = []; el.each(function(i,obj) { val.push($(obj).val()); }); val = val.join(','); } else { // clean it or trim it if (isFunction(opts.clean)) { val = opts.clean(el.val()); } else if (!password && typeof opts.trim === 'undefined' || opts.trim) { val = trim(el); } else { val = el.val(); } // write it back to the field el.val(val); } // get the value gotFunc = ((val.length > 0 || required === 'sometimes') && isFunction(opts.test)); // check if we've got an error on our hands if (submit === true && required === true && val.length === 0) { error = true; } else if (gotFunc) { error = !opts.test(val, arg); } if (error) { errorTarget.addClass(fieldErrorClass).after(errorEl); return false; } else { temp = errorEl.get(0); // this is for zepto if (temp.parentNode) { temp.parentNode.removeChild(temp); } errorTarget.removeClass(fieldErrorClass); return true; } }; field.bind(opts.when || config.when || 'blur', handleBlur); } for (item in config.fields) { processField(config.fields[item], item); } $(config.submitButton || this).bind('mousedown', handleMouseDown); if (config.submitButton) { $(config.submitButton).click(handleSubmit); } else { this.bind('submit', handleSubmit); } return this; }; })(this.jQuery || this.Zepto);
Forwarding events to happy / unHappy
happy.js
Forwarding events to happy / unHappy
<ide><path>appy.js <ide> } <ide> } <ide> if (errors) { <del> if (isFunction(config.unHappy)) config.unHappy(); <add> if (isFunction(config.unHappy)) config.unHappy(e); <ide> return false; <ide> } else if (config.testMode) { <ide> e.preventDefault(); <ide> if (window.console) console.warn('would have submitted'); <del> if (isFunction(config.happy)) return config.happy(); <add> if (isFunction(config.happy)) return config.happy(e); <ide> } <del> if (isFunction(config.happy)) return config.happy(); <add> if (isFunction(config.happy)) return config.happy(e); <ide> } <ide> function handleMouseUp() { <ide> pauseMessages = false;
Java
mit
2320ba236a5942ce85e9924876dc0bdc91858bfd
0
matabii/scale-imageview-android,ihollysee/scale-imageview-android
package com.matabii.dev.scaleimageview; import android.content.Context; import android.graphics.Bitmap; import android.graphics.Matrix; import android.graphics.drawable.Drawable; import android.util.AttributeSet; import android.util.FloatMath; import android.view.GestureDetector; import android.view.MotionEvent; import android.view.View; import android.view.View.OnTouchListener; import android.widget.ImageView; public class ScaleImageView extends ImageView implements OnTouchListener { private Context mContext; private float MAX_SCALE = 2f; private Matrix mMatrix; private final float[] mMatrixValues = new float[9]; // display width height. private int mWidth; private int mHeight; private int mIntrinsicWidth; private int mIntrinsicHeight; private float mScale; private float mMinScale; private float mPrevDistance; private boolean isScaling; private int mPrevMoveX; private int mPrevMoveY; private GestureDetector mDetector; String TAG = "ScaleImageView"; public ScaleImageView(Context context, AttributeSet attr) { super(context, attr); this.mContext = context; initialize(); } public ScaleImageView(Context context) { super(context); this.mContext = context; initialize(); } @Override public void setImageBitmap(Bitmap bm) { super.setImageBitmap(bm); this.initialize(); } private void initialize() { this.setScaleType(ScaleType.MATRIX); this.mMatrix = new Matrix(); Drawable d = getDrawable(); if (d != null) { mIntrinsicWidth = d.getIntrinsicWidth(); mIntrinsicHeight = d.getIntrinsicHeight(); setOnTouchListener(this); } mDetector = new GestureDetector(mContext, new GestureDetector.SimpleOnGestureListener() { @Override public boolean onDoubleTap(MotionEvent e) { maxZoomTo((int) e.getX(), (int) e.getY()); cutting(); return super.onDoubleTap(e); } }); } @Override protected boolean setFrame(int l, int t, int r, int b) { mWidth = r - l; mHeight = b - t; mMatrix.reset(); mScale = (float) r / (float) mIntrinsicWidth; int paddingHeight = 0; int paddingWidth = 0; // scaling vertical if (mScale * mIntrinsicHeight > mHeight) { mScale = (float) mHeight / (float) mIntrinsicHeight; mMatrix.postScale(mScale, mScale); paddingWidth = (r - mWidth) / 2; paddingHeight = 0; // scaling horizontal } else { mMatrix.postScale(mScale, mScale); paddingHeight = (b - mHeight) / 2; paddingWidth = 0; } mMatrix.postTranslate(paddingWidth, paddingHeight); setImageMatrix(mMatrix); mMinScale = mScale; zoomTo(mScale, mWidth / 2, mHeight / 2); cutting(); return super.setFrame(l, t, r, b); } protected float getValue(Matrix matrix, int whichValue) { matrix.getValues(mMatrixValues); return mMatrixValues[whichValue]; } protected float getScale() { return getValue(mMatrix, Matrix.MSCALE_X); } public float getTranslateX() { return getValue(mMatrix, Matrix.MTRANS_X); } protected float getTranslateY() { return getValue(mMatrix, Matrix.MTRANS_Y); } protected void maxZoomTo(int x, int y) { if (mMinScale != getScale() && (getScale() - mMinScale) > 0.1f) { // threshold 0.1f float scale = mMinScale / getScale(); zoomTo(scale, x, y); } else { float scale = MAX_SCALE / getScale(); zoomTo(scale, x, y); } } public void zoomTo(float scale, int x, int y) { if (getScale() * scale < mMinScale) { return; } if (scale >= 1 && getScale() * scale > MAX_SCALE) { return; } mMatrix.postScale(scale, scale); // move to center mMatrix.postTranslate(-(mWidth * scale - mWidth) / 2, -(mHeight * scale - mHeight) / 2); // move x and y distance mMatrix.postTranslate(-(x - (mWidth / 2)) * scale, 0); mMatrix.postTranslate(0, -(y - (mHeight / 2)) * scale); setImageMatrix(mMatrix); } public void cutting() { int width = (int) (mIntrinsicWidth * getScale()); int height = (int) (mIntrinsicHeight * getScale()); if (getTranslateX() < -(width - mWidth)) { mMatrix.postTranslate(-(getTranslateX() + width - mWidth), 0); } if (getTranslateX() > 0) { mMatrix.postTranslate(-getTranslateX(), 0); } if (getTranslateY() < -(height - mHeight)) { mMatrix.postTranslate(0, -(getTranslateY() + height - mHeight)); } if (getTranslateY() > 0) { mMatrix.postTranslate(0, -getTranslateY()); } if (width < mWidth) { mMatrix.postTranslate((mWidth - width) / 2, 0); } if (height < mHeight) { mMatrix.postTranslate(0, (mHeight - height) / 2); } setImageMatrix(mMatrix); } private float distance(float x0, float x1, float y0, float y1) { float x = x0 - x1; float y = y0 - y1; return FloatMath.sqrt(x * x + y * y); } private float dispDistance() { return FloatMath.sqrt(mWidth * mWidth + mHeight * mHeight); } @Override public boolean onTouchEvent(MotionEvent event) { if (mDetector.onTouchEvent(event)) { return true; } int touchCount = event.getPointerCount(); switch (event.getAction()) { case MotionEvent.ACTION_DOWN: case MotionEvent.ACTION_POINTER_1_DOWN: case MotionEvent.ACTION_POINTER_2_DOWN: if (touchCount >= 2) { float distance = distance(event.getX(0), event.getX(1), event.getY(0), event.getY(1)); mPrevDistance = distance; isScaling = true; } else { mPrevMoveX = (int) event.getX(); mPrevMoveY = (int) event.getY(); } case MotionEvent.ACTION_MOVE: if (touchCount >= 2 && isScaling) { float dist = distance(event.getX(0), event.getX(1), event.getY(0), event.getY(1)); float scale = (dist - mPrevDistance) / dispDistance(); mPrevDistance = dist; scale += 1; scale = scale * scale; zoomTo(scale, mWidth / 2, mHeight / 2); cutting(); } else if (!isScaling) { int distanceX = mPrevMoveX - (int) event.getX(); int distanceY = mPrevMoveY - (int) event.getY(); mPrevMoveX = (int) event.getX(); mPrevMoveY = (int) event.getY(); mMatrix.postTranslate(-distanceX, -distanceY); cutting(); } break; case MotionEvent.ACTION_UP: case MotionEvent.ACTION_POINTER_UP: case MotionEvent.ACTION_POINTER_2_UP: if (event.getPointerCount() <= 1) { isScaling = false; } break; } return true; } @Override public boolean onTouch(View v, MotionEvent event) { return super.onTouchEvent(event); } }
src/com/matabii/dev/scaleimageview/ScaleImageView.java
package com.matabii.dev.scaleimageview; import android.content.Context; import android.graphics.Bitmap; import android.graphics.Matrix; import android.graphics.drawable.Drawable; import android.util.AttributeSet; import android.util.FloatMath; import android.view.GestureDetector; import android.view.MotionEvent; import android.view.View; import android.view.View.OnTouchListener; import android.widget.ImageView; public class ScaleImageView extends ImageView implements OnTouchListener { private float MAX_SCALE = 2f; private Matrix mMatrix; private final float[] mMatrixValues = new float[9]; // display width height. private int mWidth; private int mHeight; private int mIntrinsicWidth; private int mIntrinsicHeight; private float mScale; private float mMinScale; private float mPrevDistance; private boolean isScaling; private int mPrevMoveX; private int mPrevMoveY; private GestureDetector mDetector; String TAG = "ScaleImageView"; public ScaleImageView(Context context, AttributeSet attr) { super(context, attr); initialize(); } public ScaleImageView(Context context) { super(context); initialize(); } @Override public void setImageBitmap(Bitmap bm) { super.setImageBitmap(bm); this.initialize(); } private void initialize() { this.setScaleType(ScaleType.MATRIX); this.mMatrix = new Matrix(); Drawable d = getDrawable(); if (d != null) { mIntrinsicWidth = d.getIntrinsicWidth(); mIntrinsicHeight = d.getIntrinsicHeight(); setOnTouchListener(this); } mDetector = new GestureDetector(new GestureDetector.SimpleOnGestureListener() { @Override public boolean onDoubleTap(MotionEvent e) { maxZoomTo((int) e.getX(), (int) e.getY()); cutting(); return super.onDoubleTap(e); } }); } @Override protected boolean setFrame(int l, int t, int r, int b) { mWidth = r - l; mHeight = b - t; mMatrix.reset(); mScale = (float) r / (float) mIntrinsicWidth; int paddingHeight = 0; int paddingWidth = 0; // scaling vertical if (mScale * mIntrinsicHeight > mHeight) { mScale = (float) mHeight / (float) mIntrinsicHeight; mMatrix.postScale(mScale, mScale); paddingWidth = (r - mWidth) / 2; paddingHeight = 0; // scaling horizontal } else { mMatrix.postScale(mScale, mScale); paddingHeight = (b - mHeight) / 2; paddingWidth = 0; } mMatrix.postTranslate(paddingWidth, paddingHeight); setImageMatrix(mMatrix); mMinScale = mScale; zoomTo(mScale, mWidth / 2, mHeight / 2); cutting(); return super.setFrame(l, t, r, b); } protected float getValue(Matrix matrix, int whichValue) { matrix.getValues(mMatrixValues); return mMatrixValues[whichValue]; } protected float getScale() { return getValue(mMatrix, Matrix.MSCALE_X); } public float getTranslateX() { return getValue(mMatrix, Matrix.MTRANS_X); } protected float getTranslateY() { return getValue(mMatrix, Matrix.MTRANS_Y); } protected void maxZoomTo(int x, int y) { if (mMinScale != getScale() && (getScale() - mMinScale) > 0.1f) { // threshold 0.1f float scale = mMinScale / getScale(); zoomTo(scale, x, y); } else { float scale = MAX_SCALE / getScale(); zoomTo(scale, x, y); } } public void zoomTo(float scale, int x, int y) { if (getScale() * scale < mMinScale) { return; } if (scale >= 1 && getScale() * scale > MAX_SCALE) { return; } mMatrix.postScale(scale, scale); // move to center mMatrix.postTranslate(-(mWidth * scale - mWidth) / 2, -(mHeight * scale - mHeight) / 2); // move x and y distance mMatrix.postTranslate(-(x - (mWidth / 2)) * scale, 0); mMatrix.postTranslate(0, -(y - (mHeight / 2)) * scale); setImageMatrix(mMatrix); } public void cutting() { int width = (int) (mIntrinsicWidth * getScale()); int height = (int) (mIntrinsicHeight * getScale()); if (getTranslateX() < -(width - mWidth)) { mMatrix.postTranslate(-(getTranslateX() + width - mWidth), 0); } if (getTranslateX() > 0) { mMatrix.postTranslate(-getTranslateX(), 0); } if (getTranslateY() < -(height - mHeight)) { mMatrix.postTranslate(0, -(getTranslateY() + height - mHeight)); } if (getTranslateY() > 0) { mMatrix.postTranslate(0, -getTranslateY()); } if (width < mWidth) { mMatrix.postTranslate((mWidth - width) / 2, 0); } if (height < mHeight) { mMatrix.postTranslate(0, (mHeight - height) / 2); } setImageMatrix(mMatrix); } private float distance(float x0, float x1, float y0, float y1) { float x = x0 - x1; float y = y0 - y1; return FloatMath.sqrt(x * x + y * y); } private float dispDistance() { return FloatMath.sqrt(mWidth * mWidth + mHeight * mHeight); } @Override public boolean onTouchEvent(MotionEvent event) { if (mDetector.onTouchEvent(event)) { return true; } int touchCount = event.getPointerCount(); switch (event.getAction()) { case MotionEvent.ACTION_DOWN: case MotionEvent.ACTION_POINTER_1_DOWN: case MotionEvent.ACTION_POINTER_2_DOWN: if (touchCount >= 2) { float distance = distance(event.getX(0), event.getX(1), event.getY(0), event.getY(1)); mPrevDistance = distance; isScaling = true; } else { mPrevMoveX = (int) event.getX(); mPrevMoveY = (int) event.getY(); } case MotionEvent.ACTION_MOVE: if (touchCount >= 2 && isScaling) { float dist = distance(event.getX(0), event.getX(1), event.getY(0), event.getY(1)); float scale = (dist - mPrevDistance) / dispDistance(); mPrevDistance = dist; scale += 1; scale = scale * scale; zoomTo(scale, mWidth / 2, mHeight / 2); cutting(); } else if (!isScaling) { int distanceX = mPrevMoveX - (int) event.getX(); int distanceY = mPrevMoveY - (int) event.getY(); mPrevMoveX = (int) event.getX(); mPrevMoveY = (int) event.getY(); mMatrix.postTranslate(-distanceX, -distanceY); cutting(); } break; case MotionEvent.ACTION_UP: case MotionEvent.ACTION_POINTER_UP: case MotionEvent.ACTION_POINTER_2_UP: if (event.getPointerCount() <= 1) { isScaling = false; } break; } return true; } @Override public boolean onTouch(View v, MotionEvent event) { return super.onTouchEvent(event); } }
fix deprecated method of GestureDetector class.
src/com/matabii/dev/scaleimageview/ScaleImageView.java
fix deprecated method of GestureDetector class.
<ide><path>rc/com/matabii/dev/scaleimageview/ScaleImageView.java <ide> import android.widget.ImageView; <ide> <ide> public class ScaleImageView extends ImageView implements OnTouchListener { <add> private Context mContext; <ide> private float MAX_SCALE = 2f; <ide> <ide> private Matrix mMatrix; <ide> <ide> public ScaleImageView(Context context, AttributeSet attr) { <ide> super(context, attr); <add> this.mContext = context; <ide> initialize(); <ide> } <ide> <ide> public ScaleImageView(Context context) { <ide> super(context); <add> this.mContext = context; <ide> initialize(); <ide> } <ide> <ide> mIntrinsicHeight = d.getIntrinsicHeight(); <ide> setOnTouchListener(this); <ide> } <del> mDetector = new GestureDetector(new GestureDetector.SimpleOnGestureListener() { <add> mDetector = new GestureDetector(mContext, new GestureDetector.SimpleOnGestureListener() { <ide> @Override <ide> public boolean onDoubleTap(MotionEvent e) { <ide> maxZoomTo((int) e.getX(), (int) e.getY());
Java
apache-2.0
ade9e99a5a3252522eb00eb768fecfc02e7200b1
0
ceylon/ceylon-js,ceylon/ceylon-js,ceylon/ceylon-js
package com.redhat.ceylon.compiler.js; import static com.redhat.ceylon.compiler.typechecker.analyzer.Util.eliminateParensAndWidening; import java.io.File; import java.io.IOException; import java.io.StringWriter; import java.io.Writer; import java.util.ArrayList; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.Stack; import org.antlr.runtime.CommonToken; import com.redhat.ceylon.compiler.Options; import com.redhat.ceylon.compiler.js.TypeUtils.RuntimeMetamodelAnnotationGenerator; import com.redhat.ceylon.compiler.typechecker.model.Class; import com.redhat.ceylon.compiler.typechecker.model.ClassAlias; import com.redhat.ceylon.compiler.typechecker.model.ClassOrInterface; import com.redhat.ceylon.compiler.typechecker.model.Declaration; import com.redhat.ceylon.compiler.typechecker.model.Functional; import com.redhat.ceylon.compiler.typechecker.model.Interface; import com.redhat.ceylon.compiler.typechecker.model.Method; import com.redhat.ceylon.compiler.typechecker.model.MethodOrValue; import com.redhat.ceylon.compiler.typechecker.model.Module; import com.redhat.ceylon.compiler.typechecker.model.Package; import com.redhat.ceylon.compiler.typechecker.model.ProducedType; import com.redhat.ceylon.compiler.typechecker.model.Scope; import com.redhat.ceylon.compiler.typechecker.model.Setter; import com.redhat.ceylon.compiler.typechecker.model.TypeAlias; import com.redhat.ceylon.compiler.typechecker.model.TypeDeclaration; import com.redhat.ceylon.compiler.typechecker.model.TypeParameter; import com.redhat.ceylon.compiler.typechecker.model.Util; import com.redhat.ceylon.compiler.typechecker.model.Value; import com.redhat.ceylon.compiler.typechecker.tree.*; import com.redhat.ceylon.compiler.typechecker.tree.Tree.*; public class GenerateJsVisitor extends Visitor implements NaturalVisitor { private final Stack<Continuation> continues = new Stack<>(); private final JsIdentifierNames names; private final Set<Declaration> directAccess = new HashSet<>(); private final Set<Declaration> generatedAttributes = new HashSet<>(); private final RetainedVars retainedVars = new RetainedVars(); final ConditionGenerator conds; private final InvocationGenerator invoker; private final List<CommonToken> tokens; private final ErrorVisitor errVisitor = new ErrorVisitor(); private int dynblock; private int exitCode = 0; static final class SuperVisitor extends Visitor { private final List<Declaration> decs; SuperVisitor(List<Declaration> decs) { this.decs = decs; } @Override public void visit(QualifiedMemberOrTypeExpression qe) { Term primary = eliminateParensAndWidening(qe.getPrimary()); if (primary instanceof Super) { decs.add(qe.getDeclaration()); } super.visit(qe); } @Override public void visit(QualifiedType that) { if (that.getOuterType() instanceof SuperType) { decs.add(that.getDeclarationModel()); } super.visit(that); } public void visit(Tree.ClassOrInterface qe) { //don't recurse if (qe instanceof ClassDefinition) { ExtendedType extType = ((ClassDefinition) qe).getExtendedType(); if (extType != null) { super.visit(extType); } } } } private final class OuterVisitor extends Visitor { boolean found = false; private Declaration dec; private OuterVisitor(Declaration dec) { this.dec = dec; } @Override public void visit(QualifiedMemberOrTypeExpression qe) { if (qe.getPrimary() instanceof Outer || qe.getPrimary() instanceof This) { if ( qe.getDeclaration().equals(dec) ) { found = true; } } super.visit(qe); } } private List<? extends Statement> currentStatements = null; private Writer out; private final Writer originalOut; final Options opts; private CompilationUnit root; static final String function="function "; private boolean needIndent = true; private int indentLevel = 0; Package getCurrentPackage() { return root.getUnit().getPackage(); } /** Returns the module name for the language module. */ String getClAlias() { return jsout.getLanguageModuleAlias(); } @Override public void handleException(Exception e, Node that) { that.addUnexpectedError(that.getMessage(e, this)); } private final JsOutput jsout; public GenerateJsVisitor(JsOutput out, Options options, JsIdentifierNames names, List<CommonToken> tokens) throws IOException { this.jsout = out; this.opts = options; this.out = out.getWriter(); originalOut = out.getWriter(); this.names = names; conds = new ConditionGenerator(this, names, directAccess); this.tokens = tokens; invoker = new InvocationGenerator(this, names, retainedVars); } InvocationGenerator getInvoker() { return invoker; } /** Returns the helper component to handle naming. */ JsIdentifierNames getNames() { return names; } static interface GenerateCallback { public void generateValue(); } /** Print generated code to the Writer specified at creation time. * Automatically prints indentation first if necessary. * @param code The main code * @param codez Optional additional strings to print after the main code. */ void out(String code, String... codez) { try { if (!opts.isMinify() && opts.isIndent() && needIndent) { for (int i=0;i<indentLevel;i++) { out.write(" "); } } needIndent = false; out.write(code); for (String s : codez) { out.write(s); } if (opts.isVerbose() && out == originalOut) { //Print code to console (when printing to REAL output) System.out.print(code); for (String s : codez) { System.out.print(s); } } } catch (IOException ioe) { throw new RuntimeException("Generating JS code", ioe); } } /** Prints a newline. Indentation will automatically be printed by {@link #out(String, String...)} * when the next line is started. */ void endLine() { endLine(false); } /** Prints a newline. Indentation will automatically be printed by {@link #out(String, String...)} * when the next line is started. * @param semicolon if <code>true</code> then a semicolon is printed at the end * of the previous line*/ void endLine(boolean semicolon) { if (semicolon) { out(";"); if (opts.isMinify())return; } out("\n"); needIndent = opts.isIndent() && !opts.isMinify(); } /** Calls {@link #endLine()} if the current position is not already the beginning * of a line. */ void beginNewLine() { if (!needIndent) { endLine(false); } } /** Increases indentation level, prints opening brace and newline. Indentation will * automatically be printed by {@link #out(String, String...)} when the next line is started. */ void beginBlock() { indentLevel++; out("{"); if (!opts.isMinify())endLine(false); } /** Decreases indentation level, prints a closing brace in new line (using * {@link #beginNewLine()}) and calls {@link #endLine()}. */ void endBlockNewLine() { endBlock(false, true); } /** Decreases indentation level, prints a closing brace in new line (using * {@link #beginNewLine()}) and calls {@link #endLine()}. * @param semicolon if <code>true</code> then prints a semicolon after the brace*/ void endBlockNewLine(boolean semicolon) { endBlock(semicolon, true); } /** Decreases indentation level and prints a closing brace in new line (using * {@link #beginNewLine()}). */ void endBlock() { endBlock(false, false); } /** Decreases indentation level and prints a closing brace in new line (using * {@link #beginNewLine()}). * @param semicolon if <code>true</code> then prints a semicolon after the brace * @param newline if <code>true</code> then additionally calls {@link #endLine()} */ void endBlock(boolean semicolon, boolean newline) { indentLevel--; if (!opts.isMinify())beginNewLine(); out(semicolon ? "};" : "}"); if (semicolon&&opts.isMinify())return; if (newline) { endLine(false); } } /** Prints source code location in the form "at [filename] ([location])" */ void location(Node node) { out(" at ", node.getUnit().getFilename(), " (", node.getLocation(), ")"); } private String generateToString(final GenerateCallback callback) { final Writer oldWriter = out; out = new StringWriter(); callback.generateValue(); final String str = out.toString(); out = oldWriter; return str; } @Override public void visit(final Tree.CompilationUnit that) { root = that; if (!that.getModuleDescriptors().isEmpty()) { ModuleDescriptor md = that.getModuleDescriptors().get(0); out("ex$.$mod$ans$="); TypeUtils.outputAnnotationsFunction(md.getAnnotationList(), null, this); endLine(true); if (md.getImportModuleList() != null && !md.getImportModuleList().getImportModules().isEmpty()) { out("ex$.$mod$imps=function(){return{"); if (!opts.isMinify())endLine(); boolean first=true; for (ImportModule im : md.getImportModuleList().getImportModules()) { final StringBuilder path=new StringBuilder("'"); if (im.getImportPath()==null) { if (im.getQuotedLiteral()==null) { throw new CompilerErrorException("Invalid imported module"); } else { final String ql = im.getQuotedLiteral().getText(); path.append(ql.substring(1, ql.length()-1)); } } else { for (Identifier id : im.getImportPath().getIdentifiers()) { if (path.length()>1)path.append('.'); path.append(id.getText()); } } final String qv = im.getVersion().getText(); path.append('/').append(qv.substring(1, qv.length()-1)).append("'"); if (first)first=false;else{out(",");endLine();} out(path.toString(), ":"); TypeUtils.outputAnnotationsFunction(im.getAnnotationList(), null, this); } if (!opts.isMinify())endLine(); out("};};"); if (!opts.isMinify())endLine(); } } if (!that.getPackageDescriptors().isEmpty()) { final String pknm = that.getUnit().getPackage().getNameAsString().replaceAll("\\.", "\\$"); out("ex$.$pkg$ans$", pknm, "="); TypeUtils.outputAnnotationsFunction(that.getPackageDescriptors().get(0).getAnnotationList(), null, this); endLine(true); } for (CompilerAnnotation ca: that.getCompilerAnnotations()) { ca.visit(this); } if (that.getImportList() != null) { that.getImportList().visit(this); } visitStatements(that.getDeclarations()); } public void visit(final Tree.Import that) { } @Override public void visit(final Tree.Parameter that) { out(names.name(that.getParameterModel())); } @Override public void visit(final Tree.ParameterList that) { out("("); boolean first=true; boolean ptypes = false; //Check if this is the first parameter list if (that.getScope() instanceof Method && that.getModel().isFirst()) { ptypes = ((Method)that.getScope()).getTypeParameters() != null && !((Method)that.getScope()).getTypeParameters().isEmpty(); } for (Parameter param: that.getParameters()) { if (!first) out(","); out(names.name(param.getParameterModel())); first = false; } if (ptypes) { if (!first) out(","); out("$$$mptypes"); } out(")"); } void visitStatements(List<? extends Statement> statements) { List<String> oldRetainedVars = retainedVars.reset(null); final List<? extends Statement> prevStatements = currentStatements; currentStatements = statements; for (int i=0; i<statements.size(); i++) { Statement s = statements.get(i); s.visit(this); if (!opts.isMinify())beginNewLine(); retainedVars.emitRetainedVars(this); } retainedVars.reset(oldRetainedVars); currentStatements = prevStatements; } @Override public void visit(final Tree.Body that) { visitStatements(that.getStatements()); } @Override public void visit(final Tree.Block that) { List<Statement> stmnts = that.getStatements(); if (stmnts.isEmpty()) { out("{}"); } else { beginBlock(); visitStatements(stmnts); endBlock(); } } void initSelf(Node node) { final NeedsThisVisitor ntv = new NeedsThisVisitor(node); if (ntv.needsThisReference()) { final String me=names.self(prototypeOwner); out("var ", me, "=this"); //Code inside anonymous inner types sometimes gens direct refs to the outer instance //We can detect if that's going to happen and declare the ref right here if (ntv.needsOuterReference()) { final Declaration od = Util.getContainingDeclaration(prototypeOwner); if (od instanceof TypeDeclaration) { out(",", names.self((TypeDeclaration)od), "=", me, ".outer$"); } } endLine(true); } } /** Visitor that determines if a method definition will need the "this" reference. */ class NeedsThisVisitor extends Visitor { private boolean refs=false; private boolean outerRefs=false; NeedsThisVisitor(Node n) { if (prototypeOwner != null) { n.visit(this); } } @Override public void visit(Tree.This that) { refs = true; } @Override public void visit(Tree.Outer that) { refs = true; } @Override public void visit(Tree.Super that) { refs = true; } private boolean check(final Scope origScope) { Scope s = origScope; while (s != null) { if (s == prototypeOwner || (s instanceof TypeDeclaration && prototypeOwner.inherits((TypeDeclaration)s))) { refs = true; if (prototypeOwner.isAnonymous() && prototypeOwner.isMember()) { outerRefs=true; } return true; } s = s.getContainer(); } //Check the other way around as well s = prototypeOwner; while (s != null) { if (s == origScope || (s instanceof TypeDeclaration && origScope instanceof TypeDeclaration && ((TypeDeclaration)s).inherits((TypeDeclaration)origScope))) { refs = true; return true; } s = s.getContainer(); } return false; } public void visit(Tree.MemberOrTypeExpression that) { if (refs)return; if (that.getDeclaration() == null) { //Some expressions in dynamic blocks can have null declarations super.visit(that); return; } if (!check(that.getDeclaration().getContainer())) { super.visit(that); } } public void visit(Tree.Type that) { if (!check(that.getTypeModel().getDeclaration())) { super.visit(that); } } boolean needsThisReference() { return refs; } boolean needsOuterReference() { return outerRefs; } } void comment(Tree.Declaration that) { if (!opts.isComment() || opts.isMinify()) return; endLine(); String dname = that.getNodeType(); if (dname.endsWith("Declaration") || dname.endsWith("Definition")) { dname = dname.substring(0, dname.length()-7); } out("//", dname, " ", that.getDeclarationModel().getName()); location(that); endLine(); } boolean share(Declaration d) { return share(d, true); } private boolean share(Declaration d, boolean excludeProtoMembers) { boolean shared = false; if (!(excludeProtoMembers && opts.isOptimize() && d.isClassOrInterfaceMember()) && isCaptured(d)) { beginNewLine(); outerSelf(d); String dname=names.name(d); if (dname.endsWith("()")){ dname = dname.substring(0, dname.length()-2); } out(".", dname, "=", dname); endLine(true); shared = true; } return shared; } @Override public void visit(final Tree.ClassDeclaration that) { if (opts.isOptimize() && that.getDeclarationModel().isClassOrInterfaceMember()) return; classDeclaration(that); } private void addClassDeclarationToPrototype(TypeDeclaration outer, final Tree.ClassDeclaration that) { classDeclaration(that); final String tname = names.name(that.getDeclarationModel()); out(names.self(outer), ".", tname, "=", tname); endLine(true); } private void addAliasDeclarationToPrototype(TypeDeclaration outer, Tree.TypeAliasDeclaration that) { comment(that); final TypeAlias d = that.getDeclarationModel(); String path = qualifiedPath(that, d, true); if (path.length() > 0) { path += '.'; } String tname = names.name(d); tname = tname.substring(0, tname.length()-2); String _tmp=names.createTempVariable(); out(names.self(outer), ".", tname, "=function(){var ", _tmp, "="); TypeUtils.typeNameOrList(that, that.getTypeSpecifier().getType().getTypeModel(), this, true); out(";", _tmp, ".$crtmm$="); TypeUtils.encodeForRuntime(that,d,this); out(";return ", _tmp, ";}"); endLine(true); } @Override public void visit(final Tree.InterfaceDeclaration that) { if (!(opts.isOptimize() && that.getDeclarationModel().isClassOrInterfaceMember())) { interfaceDeclaration(that); } } private void addInterfaceDeclarationToPrototype(TypeDeclaration outer, final Tree.InterfaceDeclaration that) { interfaceDeclaration(that); final String tname = names.name(that.getDeclarationModel()); out(names.self(outer), ".", tname, "=", tname); endLine(true); } private void addInterfaceToPrototype(ClassOrInterface type, final Tree.InterfaceDefinition interfaceDef) { TypeGenerator.interfaceDefinition(interfaceDef, this); Interface d = interfaceDef.getDeclarationModel(); out(names.self(type), ".", names.name(d), "=", names.name(d)); endLine(true); } @Override public void visit(final Tree.InterfaceDefinition that) { if (!(opts.isOptimize() && that.getDeclarationModel().isClassOrInterfaceMember())) { TypeGenerator.interfaceDefinition(that, this); } } private void addClassToPrototype(ClassOrInterface type, final Tree.ClassDefinition classDef) { TypeGenerator.classDefinition(classDef, this); final String tname = names.name(classDef.getDeclarationModel()); out(names.self(type), ".", tname, "=", tname); endLine(true); } @Override public void visit(final Tree.ClassDefinition that) { if (!(opts.isOptimize() && that.getDeclarationModel().isClassOrInterfaceMember())) { TypeGenerator.classDefinition(that, this); } } private void interfaceDeclaration(final Tree.InterfaceDeclaration that) { //Don't even bother with nodes that have errors if (errVisitor.hasErrors(that))return; comment(that); final Interface d = that.getDeclarationModel(); final String aname = names.name(d); Tree.StaticType ext = that.getTypeSpecifier().getType(); out(function, aname, "("); if (d.getTypeParameters() != null && !d.getTypeParameters().isEmpty()) { out("$$targs$$,"); } out(names.self(d), "){"); final ProducedType pt = ext.getTypeModel(); final TypeDeclaration aliased = pt.getDeclaration(); qualify(that,aliased); out(names.name(aliased), "("); if (!pt.getTypeArguments().isEmpty()) { TypeUtils.printTypeArguments(that, pt.getTypeArguments(), this, true, pt.getVarianceOverrides()); out(","); } out(names.self(d), ");}"); endLine(); out(aname,".$crtmm$="); TypeUtils.encodeForRuntime(that, d, this); endLine(true); share(d); } private void classDeclaration(final Tree.ClassDeclaration that) { //Don't even bother with nodes that have errors if (errVisitor.hasErrors(that))return; comment(that); final Class d = that.getDeclarationModel(); final String aname = names.name(d); final Tree.ClassSpecifier ext = that.getClassSpecifier(); out(function, aname, "("); //Generate each parameter because we need to append one at the end for (Parameter p: that.getParameterList().getParameters()) { p.visit(this); out(", "); } if (d.getTypeParameters() != null && !d.getTypeParameters().isEmpty()) { out("$$targs$$,"); } out(names.self(d), "){return "); TypeDeclaration aliased = ext.getType().getDeclarationModel(); qualify(that, aliased); out(names.name(aliased), "("); if (ext.getInvocationExpression().getPositionalArgumentList() != null) { ext.getInvocationExpression().getPositionalArgumentList().visit(this); if (!ext.getInvocationExpression().getPositionalArgumentList().getPositionalArguments().isEmpty()) { out(","); } } else { out("/*PENDIENTE NAMED ARG CLASS DECL */"); } Map<TypeParameter, ProducedType> invargs = ext.getType().getTypeModel().getTypeArguments(); if (invargs != null && !invargs.isEmpty()) { TypeUtils.printTypeArguments(that, invargs, this, true, ext.getType().getTypeModel().getVarianceOverrides()); out(","); } out(names.self(d), ");}"); endLine(); out(aname, ".$$="); qualify(that, aliased); out(names.name(aliased), ".$$"); endLine(true); out(aname,".$crtmm$="); TypeUtils.encodeForRuntime(that, d, this); endLine(true); share(d); } @Override public void visit(final Tree.TypeAliasDeclaration that) { //Don't even bother with nodes that have errors if (errVisitor.hasErrors(that))return; final TypeAlias d = that.getDeclarationModel(); if (opts.isOptimize() && d.isClassOrInterfaceMember()) return; comment(that); final String tname=names.createTempVariable(); out(function, names.name(d), "{var ", tname, "="); TypeUtils.typeNameOrList(that, that.getTypeSpecifier().getType().getTypeModel(), this, false); out(";", tname, ".$crtmm$="); TypeUtils.encodeForRuntime(that, d, this, new RuntimeMetamodelAnnotationGenerator() { @Override public void generateAnnotations() { TypeUtils.outputAnnotationsFunction(that.getAnnotationList(), d, GenerateJsVisitor.this); } }); out(";return ", tname, ";}"); endLine(); share(d); } void referenceOuter(TypeDeclaration d) { if (!d.isToplevel()) { final ClassOrInterface coi = Util.getContainingClassOrInterface(d.getContainer()); if (coi != null) { out(names.self(d), ".outer$"); if (d.isClassOrInterfaceMember()) { out("=this"); } else { out("=", names.self(coi)); } endLine(true); } } } /** Returns the name of the type or its $init$ function if it's local. */ String typeFunctionName(final Tree.StaticType type, boolean removeAlias) { TypeDeclaration d = type.getTypeModel().getDeclaration(); if ((removeAlias && d.isAlias()) || d instanceof com.redhat.ceylon.compiler.typechecker.model.Constructor) { d = d.getExtendedTypeDeclaration(); } boolean inProto = opts.isOptimize() && (type.getScope().getContainer() instanceof TypeDeclaration); String tfn = memberAccessBase(type, d, false, qualifiedPath(type, d, inProto)); if (removeAlias && !isImported(type.getUnit().getPackage(), d)) { int idx = tfn.lastIndexOf('.'); if (idx > 0) { tfn = tfn.substring(0, idx+1) + "$init$" + tfn.substring(idx+1) + "()"; } else { tfn = "$init$" + tfn + "()"; } } return tfn; } void addToPrototype(Node node, ClassOrInterface d, List<Tree.Statement> statements) { final boolean isSerial = d instanceof com.redhat.ceylon.compiler.typechecker.model.Class && ((com.redhat.ceylon.compiler.typechecker.model.Class)d).isSerializable(); boolean enter = opts.isOptimize(); ArrayList<com.redhat.ceylon.compiler.typechecker.model.Parameter> plist = null; if (enter) { enter = !statements.isEmpty(); if (d instanceof com.redhat.ceylon.compiler.typechecker.model.Class) { com.redhat.ceylon.compiler.typechecker.model.ParameterList _pl = ((com.redhat.ceylon.compiler.typechecker.model.Class)d).getParameterList(); if (_pl != null) { plist = new ArrayList<>(_pl.getParameters().size()); plist.addAll(_pl.getParameters()); enter |= !plist.isEmpty(); } } } if (enter || isSerial) { final List<? extends Statement> prevStatements = currentStatements; currentStatements = statements; out("(function(", names.self(d), ")"); beginBlock(); if (enter) { for (Statement s: statements) { addToPrototype(d, s, plist); } //Generated attributes with corresponding parameters will remove them from the list if (plist != null) { for (com.redhat.ceylon.compiler.typechecker.model.Parameter p : plist) { generateAttributeForParameter(node, (com.redhat.ceylon.compiler.typechecker.model.Class)d, p); } } if (d.isMember()) { ClassOrInterface coi = Util.getContainingClassOrInterface(d.getContainer()); if (coi != null && d.inherits(coi)) { out(names.self(d), ".", names.name(d),"=", names.name(d), ";"); } } } if (isSerial) { SerializationHelper.addSerializer(node, (com.redhat.ceylon.compiler.typechecker.model.Class)d, this); } endBlock(); out(")(", names.name(d), ".$$.prototype)"); endLine(true); currentStatements = prevStatements; } } void generateAttributeForParameter(Node node, com.redhat.ceylon.compiler.typechecker.model.Class d, com.redhat.ceylon.compiler.typechecker.model.Parameter p) { final String privname = names.name(p) + "_"; defineAttribute(names.self(d), names.name(p.getModel())); out("{"); if (p.getModel().isLate()) { generateUnitializedAttributeReadCheck("this."+privname, names.name(p)); } out("return this.", privname, ";}"); if (p.getModel().isVariable() || p.getModel().isLate()) { final String param = names.createTempVariable(); out(",function(", param, "){"); if (p.getModel().isLate() && !p.getModel().isVariable()) { generateImmutableAttributeReassignmentCheck("this."+privname, names.name(p)); } out("return this.", privname, "=", param, ";}"); } else { out(",undefined"); } out(","); TypeUtils.encodeForRuntime(node, p.getModel(), this); out(")"); endLine(true); } private ClassOrInterface prototypeOwner; private void addToPrototype(ClassOrInterface d, final Tree.Statement s, List<com.redhat.ceylon.compiler.typechecker.model.Parameter> params) { ClassOrInterface oldPrototypeOwner = prototypeOwner; prototypeOwner = d; if (s instanceof MethodDefinition) { addMethodToPrototype(d, (MethodDefinition)s); } else if (s instanceof MethodDeclaration) { //Don't even bother with nodes that have errors if (errVisitor.hasErrors(s))return; FunctionHelper.methodDeclaration(d, (MethodDeclaration) s, this); } else if (s instanceof AttributeGetterDefinition) { addGetterToPrototype(d, (AttributeGetterDefinition)s); } else if (s instanceof AttributeDeclaration) { AttributeGenerator.addGetterAndSetterToPrototype(d, (AttributeDeclaration) s, this); } else if (s instanceof ClassDefinition) { addClassToPrototype(d, (ClassDefinition) s); } else if (s instanceof InterfaceDefinition) { addInterfaceToPrototype(d, (InterfaceDefinition) s); } else if (s instanceof ObjectDefinition) { addObjectToPrototype(d, (ObjectDefinition) s); } else if (s instanceof ClassDeclaration) { addClassDeclarationToPrototype(d, (ClassDeclaration) s); } else if (s instanceof InterfaceDeclaration) { addInterfaceDeclarationToPrototype(d, (InterfaceDeclaration) s); } else if (s instanceof SpecifierStatement) { addSpecifierToPrototype(d, (SpecifierStatement) s); } else if (s instanceof TypeAliasDeclaration) { addAliasDeclarationToPrototype(d, (TypeAliasDeclaration)s); } //This fixes #231 for prototype style if (params != null && s instanceof Tree.Declaration) { Declaration m = ((Tree.Declaration)s).getDeclarationModel(); for (Iterator<com.redhat.ceylon.compiler.typechecker.model.Parameter> iter = params.iterator(); iter.hasNext();) { com.redhat.ceylon.compiler.typechecker.model.Parameter _p = iter.next(); if (m.getName() != null && m.getName().equals(_p.getName())) { iter.remove(); break; } } } prototypeOwner = oldPrototypeOwner; } void declareSelf(ClassOrInterface d) { out("if(", names.self(d), "===undefined)"); if (d instanceof com.redhat.ceylon.compiler.typechecker.model.Class && d.isAbstract()) { out(getClAlias(), "throwexc(", getClAlias(), "InvocationException$meta$model("); out("\"Cannot instantiate abstract class ", d.getQualifiedNameString(), "\"),'?','?')"); } else { out(names.self(d), "=new "); if (opts.isOptimize() && d.isClassOrInterfaceMember()) { out("this."); } out(names.name(d), ".$$;"); } endLine(); } void instantiateSelf(ClassOrInterface d) { out("var ", names.self(d), "=new "); if (opts.isOptimize() && d.isClassOrInterfaceMember()) { out("this."); } out(names.name(d), ".$$;"); } private void addObjectToPrototype(ClassOrInterface type, final Tree.ObjectDefinition objDef) { TypeGenerator.objectDefinition(objDef, this); Value d = objDef.getDeclarationModel(); Class c = (Class) d.getTypeDeclaration(); out(names.self(type), ".", names.name(c), "=", names.name(c), ";", names.self(type), ".", names.name(c), ".$crtmm$="); TypeUtils.encodeForRuntime(objDef, d, this); endLine(true); } @Override public void visit(final Tree.ObjectDefinition that) { Value d = that.getDeclarationModel(); if (!(opts.isOptimize() && d.isClassOrInterfaceMember())) { TypeGenerator.objectDefinition(that, this); } else { //Don't even bother with nodes that have errors if (errVisitor.hasErrors(that))return; Class c = (Class) d.getTypeDeclaration(); comment(that); outerSelf(d); out(".", names.privateName(d), "="); outerSelf(d); out(".", names.name(c), "()"); endLine(true); } } @Override public void visit(final Tree.ObjectExpression that) { out("function(){"); try { TypeGenerator.defineObject(that, null, that.getSatisfiedTypes(), that.getExtendedType(), that.getClassBody(), null, this); } catch (Exception e) { e.printStackTrace(); } out("}()"); } @Override public void visit(final Tree.MethodDeclaration that) { //Don't even bother with nodes that have errors if (errVisitor.hasErrors(that))return; FunctionHelper.methodDeclaration(null, that, this); } boolean shouldStitch(Declaration d) { return JsCompiler.isCompilingLanguageModule() && d.isNative(); } private File getStitchedFilename(final Declaration d, final String suffix) { String fqn = d.getQualifiedNameString(); if (fqn.startsWith("ceylon.language"))fqn = fqn.substring(15); if (fqn.startsWith("::"))fqn=fqn.substring(2); fqn = fqn.replace('.', '/').replace("::", "/"); return new File(Stitcher.LANGMOD_JS_SRC, fqn + suffix); } /** Reads a file with hand-written snippet and outputs it to the current writer. */ boolean stitchNative(final Declaration d, final Tree.Declaration n) { final File f = getStitchedFilename(d, ".js"); if (f.exists() && f.canRead()) { jsout.outputFile(f); if (d.isClassOrInterfaceMember()) { if (d instanceof Value)return true;//Native values are defined as attributes out(names.self((TypeDeclaration)d.getContainer()), "."); } out(names.name(d), ".$crtmm$="); TypeUtils.encodeForRuntime(d, n.getAnnotationList(), this); endLine(true); return true; } else { if (d instanceof ClassOrInterface==false) { final String err = "REQUIRED NATIVE FILE MISSING FOR " + d.getQualifiedNameString() + " => " + f + ", containing " + names.name(d); System.out.println(err); out("/*", err, "*/"); } return false; } } /** Stitch a snippet of code to initialize type (usually a call to initTypeProto). */ boolean stitchInitializer(TypeDeclaration d) { final File f = getStitchedFilename(d, "$init.js"); if (f.exists() && f.canRead()) { jsout.outputFile(f); return true; } return false; } boolean stitchConstructorHelper(final Tree.ClassOrInterface coi, final String partName) { final File f; if (JsCompiler.isCompilingLanguageModule()) { f = getStitchedFilename(coi.getDeclarationModel(), partName + ".js"); } else { f = new File(new File(coi.getUnit().getFullPath()).getParentFile(), String.format("%s%s.js", names.name(coi.getDeclarationModel()), partName)); } if (f.exists() && f.isFile() && f.canRead()) { if (opts.isVerbose() || JsCompiler.isCompilingLanguageModule()) { System.out.println("Stitching in " + f + ". It must contain an anonymous function " + "which will be invoked with the same arguments as the " + names.name(coi.getDeclarationModel()) + " constructor."); } out("("); jsout.outputFile(f); out(")"); TypeGenerator.generateParameters(coi.getTypeParameterList(), coi instanceof Tree.ClassDefinition ? ((Tree.ClassDefinition)coi).getParameterList() : null, coi.getDeclarationModel(), this); endLine(true); } return false; } @Override public void visit(final Tree.MethodDefinition that) { //Don't even bother with nodes that have errors if (errVisitor.hasErrors(that))return; final Method d = that.getDeclarationModel(); if (!((opts.isOptimize() && d.isClassOrInterfaceMember()) || isNative(d))) { comment(that); initDefaultedParameters(that.getParameterLists().get(0), d); FunctionHelper.methodDefinition(that, this, true); //Add reference to metamodel out(names.name(d), ".$crtmm$="); TypeUtils.encodeForRuntime(d, that.getAnnotationList(), this); endLine(true); } } /** Get the specifier expression for a Parameter, if one is available. */ private SpecifierOrInitializerExpression getDefaultExpression(final Tree.Parameter param) { final SpecifierOrInitializerExpression expr; if (param instanceof ParameterDeclaration || param instanceof InitializerParameter) { MethodDeclaration md = null; if (param instanceof ParameterDeclaration) { TypedDeclaration td = ((ParameterDeclaration) param).getTypedDeclaration(); if (td instanceof AttributeDeclaration) { expr = ((AttributeDeclaration) td).getSpecifierOrInitializerExpression(); } else if (td instanceof MethodDeclaration) { md = (MethodDeclaration)td; expr = md.getSpecifierExpression(); } else { param.addUnexpectedError("Don't know what to do with TypedDeclaration " + td.getClass().getName()); expr = null; } } else { expr = ((InitializerParameter) param).getSpecifierExpression(); } } else { param.addUnexpectedError("Don't know what to do with defaulted/sequenced param " + param); expr = null; } return expr; } /** Create special functions with the expressions for defaulted parameters in a parameter list. */ void initDefaultedParameters(final Tree.ParameterList params, Method container) { if (!container.isMember())return; for (final Parameter param : params.getParameters()) { com.redhat.ceylon.compiler.typechecker.model.Parameter pd = param.getParameterModel(); if (pd.isDefaulted()) { final SpecifierOrInitializerExpression expr = getDefaultExpression(param); if (expr == null) { continue; } qualify(params, container); out(names.name(container), "$defs$", pd.getName(), "=function"); params.visit(this); out("{"); initSelf(expr); out("return "); if (param instanceof ParameterDeclaration && ((ParameterDeclaration)param).getTypedDeclaration() instanceof MethodDeclaration) { // function parameter defaulted using "=>" FunctionHelper.singleExprFunction( ((MethodDeclaration)((ParameterDeclaration)param).getTypedDeclaration()).getParameterLists(), expr.getExpression(), null, true, true, this); } else if (!isNaturalLiteral(expr.getExpression().getTerm())) { expr.visit(this); } out(";}"); endLine(true); } } } /** Initialize the sequenced, defaulted and captured parameters in a type declaration. */ void initParameters(final Tree.ParameterList params, TypeDeclaration typeDecl, Method m) { for (final Parameter param : params.getParameters()) { com.redhat.ceylon.compiler.typechecker.model.Parameter pd = param.getParameterModel(); final String paramName = names.name(pd); if (pd.isDefaulted() || pd.isSequenced()) { out("if(", paramName, "===undefined){", paramName, "="); if (pd.isDefaulted()) { if (m !=null && m.isMember()) { qualify(params, m); out(names.name(m), "$defs$", pd.getName(), "("); boolean firstParam=true; for (com.redhat.ceylon.compiler.typechecker.model.Parameter p : m.getParameterLists().get(0).getParameters()) { if (firstParam){firstParam=false;}else out(","); out(names.name(p)); } out(")"); } else { final SpecifierOrInitializerExpression expr = getDefaultExpression(param); if (expr == null) { param.addUnexpectedError("Default expression missing for " + pd.getName()); out("null"); } else if (param instanceof ParameterDeclaration && ((ParameterDeclaration)param).getTypedDeclaration() instanceof MethodDeclaration) { // function parameter defaulted using "=>" FunctionHelper.singleExprFunction( ((MethodDeclaration)((ParameterDeclaration)param).getTypedDeclaration()).getParameterLists(), expr.getExpression(), m, true, true, this); } else { expr.visit(this); } } } else { out(getClAlias(), "getEmpty()"); } out(";}"); endLine(); } if ((typeDecl != null) && pd.getModel().isCaptured()) { out(names.self(typeDecl), ".", paramName, "_=", paramName); if (!opts.isOptimize() && pd.isHidden()) { //belt and suspenders... out(";", names.self(typeDecl), ".", paramName, "=", paramName); } endLine(true); } } } private void addMethodToPrototype(TypeDeclaration outer, final Tree.MethodDefinition that) { //Don't even bother with nodes that have errors if (errVisitor.hasErrors(that))return; Method d = that.getDeclarationModel(); if (!opts.isOptimize()||!d.isClassOrInterfaceMember()) return; comment(that); initDefaultedParameters(that.getParameterLists().get(0), d); out(names.self(outer), ".", names.name(d), "="); FunctionHelper.methodDefinition(that, this, false); //Add reference to metamodel out(names.self(outer), ".", names.name(d), ".$crtmm$="); TypeUtils.encodeForRuntime(d, that.getAnnotationList(), this); endLine(true); } @Override public void visit(final Tree.AttributeGetterDefinition that) { Value d = that.getDeclarationModel(); if (opts.isOptimize()&&d.isClassOrInterfaceMember()) return; comment(that); if (defineAsProperty(d)) { defineAttribute(names.self((TypeDeclaration)d.getContainer()), names.name(d)); AttributeGenerator.getter(that, this); final AttributeSetterDefinition setterDef = associatedSetterDefinition(d); if (setterDef == null) { out(",undefined"); } else { out(",function(", names.name(setterDef.getDeclarationModel().getParameter()), ")"); AttributeGenerator.setter(setterDef, this); } out(","); TypeUtils.encodeForRuntime(d, that.getAnnotationList(), this); if (setterDef != null) { out(","); TypeUtils.encodeForRuntime(setterDef.getDeclarationModel(), setterDef.getAnnotationList(), this); } out(");"); } else { out(function, names.getter(d), "()"); AttributeGenerator.getter(that, this); endLine(); out(names.getter(d), ".$crtmm$="); TypeUtils.encodeForRuntime(that, d, this); if (!shareGetter(d)) { out(";"); } generateAttributeMetamodel(that, true, false); } } private void addGetterToPrototype(TypeDeclaration outer, final Tree.AttributeGetterDefinition that) { Value d = that.getDeclarationModel(); if (!opts.isOptimize()||!d.isClassOrInterfaceMember()) return; comment(that); defineAttribute(names.self(outer), names.name(d)); AttributeGenerator.getter(that, this); final AttributeSetterDefinition setterDef = associatedSetterDefinition(d); if (setterDef == null) { out(",undefined"); } else { out(",function(", names.name(setterDef.getDeclarationModel().getParameter()), ")"); AttributeGenerator.setter(setterDef, this); } out(","); TypeUtils.encodeForRuntime(d, that.getAnnotationList(), this); if (setterDef != null) { out(","); TypeUtils.encodeForRuntime(setterDef.getDeclarationModel(), setterDef.getAnnotationList(), this); } out(");"); } Tree.AttributeSetterDefinition associatedSetterDefinition( final Value valueDecl) { final Setter setter = valueDecl.getSetter(); if ((setter != null) && (currentStatements != null)) { for (Statement stmt : currentStatements) { if (stmt instanceof AttributeSetterDefinition) { final AttributeSetterDefinition setterDef = (AttributeSetterDefinition) stmt; if (setterDef.getDeclarationModel() == setter) { return setterDef; } } } } return null; } /** Exports a getter function; useful in non-prototype style. */ boolean shareGetter(final MethodOrValue d) { boolean shared = false; if (isCaptured(d)) { beginNewLine(); outerSelf(d); out(".", names.getter(d), "=", names.getter(d)); endLine(true); shared = true; } return shared; } @Override public void visit(final Tree.AttributeSetterDefinition that) { Setter d = that.getDeclarationModel(); if ((opts.isOptimize()&&d.isClassOrInterfaceMember()) || defineAsProperty(d)) return; comment(that); out("function ", names.setter(d.getGetter()), "(", names.name(d.getParameter()), ")"); AttributeGenerator.setter(that, this); if (!shareSetter(d)) { out(";"); } if (!d.isToplevel())outerSelf(d); out(names.setter(d.getGetter()), ".$crtmm$="); TypeUtils.encodeForRuntime(d, that.getAnnotationList(), this); endLine(true); generateAttributeMetamodel(that, false, true); } boolean isCaptured(Declaration d) { if (d.isToplevel()||d.isClassOrInterfaceMember()) { //TODO: what about things nested inside control structures if (d.isShared() || d.isCaptured() ) { return true; } else { OuterVisitor ov = new OuterVisitor(d); ov.visit(root); return ov.found; } } else { return false; } } boolean shareSetter(final MethodOrValue d) { boolean shared = false; if (isCaptured(d)) { beginNewLine(); outerSelf(d); out(".", names.setter(d), "=", names.setter(d)); endLine(true); shared = true; } return shared; } @Override public void visit(final Tree.AttributeDeclaration that) { final Value d = that.getDeclarationModel(); //Check if the attribute corresponds to a class parameter //This is because of the new initializer syntax final com.redhat.ceylon.compiler.typechecker.model.Parameter param = d.isParameter() ? ((Functional)d.getContainer()).getParameter(d.getName()) : null; final boolean asprop = defineAsProperty(d); if (d.isFormal()) { if (!opts.isOptimize()) { generateAttributeMetamodel(that, false, false); } } else { comment(that); SpecifierOrInitializerExpression specInitExpr = that.getSpecifierOrInitializerExpression(); final boolean addGetter = (specInitExpr != null) || (param != null) || !d.isMember() || d.isVariable() || d.isLate(); final boolean addSetter = (d.isVariable() || d.isLate()) && !asprop; if (opts.isOptimize() && d.isClassOrInterfaceMember()) { if ((specInitExpr != null && !(specInitExpr instanceof LazySpecifierExpression)) || d.isLate()) { outerSelf(d); out(".", names.privateName(d), "="); if (d.isLate()) { out("undefined"); } else { super.visit(that); } endLine(true); } } else if (specInitExpr instanceof LazySpecifierExpression) { if (asprop) { defineAttribute(names.self((TypeDeclaration)d.getContainer()), names.name(d)); out("{"); } else { out(function, names.getter(d), "(){"); } initSelf(that); out("return "); if (!isNaturalLiteral(specInitExpr.getExpression().getTerm())) { int boxType = boxStart(specInitExpr.getExpression().getTerm()); specInitExpr.getExpression().visit(this); if (boxType == 4) out("/*TODO: callable targs 1*/"); boxUnboxEnd(boxType); } out(";}"); if (asprop) { Tree.AttributeSetterDefinition setterDef = null; if (d.isVariable()) { setterDef = associatedSetterDefinition(d); if (setterDef != null) { out(",function(", names.name(setterDef.getDeclarationModel().getParameter()), ")"); AttributeGenerator.setter(setterDef, this); } } if (setterDef == null) { out(",undefined"); } out(","); TypeUtils.encodeForRuntime(d, that.getAnnotationList(), this); if (setterDef != null) { out(","); TypeUtils.encodeForRuntime(setterDef.getDeclarationModel(), setterDef.getAnnotationList(), this); } out(")"); endLine(true); } else { endLine(true); shareGetter(d); } } else { if (addGetter) { AttributeGenerator.generateAttributeGetter(that, d, specInitExpr, names.name(param), this, directAccess); } if (addSetter) { AttributeGenerator.generateAttributeSetter(that, d, this); } } boolean addMeta=!opts.isOptimize() || d.isToplevel(); if (!d.isToplevel()) { addMeta |= Util.getContainingDeclaration(d).isAnonymous(); } if (addMeta) { generateAttributeMetamodel(that, addGetter, addSetter); } } } /** Generate runtime metamodel info for an attribute declaration or definition. */ void generateAttributeMetamodel(final Tree.TypedDeclaration that, final boolean addGetter, final boolean addSetter) { //No need to define all this for local values Scope _scope = that.getScope(); while (_scope != null) { //TODO this is bound to change for local decl metamodel if (_scope instanceof Declaration) { if (_scope instanceof Method)return; else break; } _scope = _scope.getContainer(); } Declaration d = that.getDeclarationModel(); if (d instanceof Setter) d = ((Setter)d).getGetter(); final String pname = names.getter(d); if (!generatedAttributes.contains(d)) { if (d.isToplevel()) { out("var "); } else if (outerSelf(d)) { out("."); } //issue 297 this is only needed in some cases out("$prop$", pname, "={$crtmm$:"); TypeUtils.encodeForRuntime(d, that.getAnnotationList(), this); out("}"); endLine(true); if (d.isToplevel()) { out("ex$.$prop$", pname, "=$prop$", pname); endLine(true); } generatedAttributes.add(d); } if (addGetter) { if (!d.isToplevel()) { if (outerSelf(d))out("."); } out("$prop$", pname, ".get="); if (isCaptured(d) && !defineAsProperty(d)) { out(pname); endLine(true); out(pname, ".$crtmm$=$prop$", pname, ".$crtmm$"); } else { out("function(){return ", names.name(d), "}"); } endLine(true); } if (addSetter) { final String pset = names.setter(d instanceof Setter ? ((Setter)d).getGetter() : d); if (!d.isToplevel()) { if (outerSelf(d))out("."); } out("$prop$", pname, ".set=", pset); endLine(true); out("if(", pset, ".$crtmm$===undefined)", pset, ".$crtmm$=$prop$", pname, ".$crtmm$"); endLine(true); } } void generateUnitializedAttributeReadCheck(String privname, String pubname) { //TODO we can later optimize this, to replace this getter with the plain one //once the value has been defined out("if(", privname, "===undefined)throw ", getClAlias(), "InitializationError('Attempt to read unitialized attribute «", pubname, "»');"); } void generateImmutableAttributeReassignmentCheck(String privname, String pubname) { out("if(", privname, "!==undefined)throw ", getClAlias(), "InitializationError('Attempt to reassign immutable attribute «", pubname, "»');"); } @Override public void visit(final Tree.CharLiteral that) { out(getClAlias(), "Character("); out(String.valueOf(that.getText().codePointAt(1))); out(",true)"); } /** Escapes a StringLiteral (needs to be quoted). */ String escapeStringLiteral(String s) { StringBuilder text = new StringBuilder(s); //Escape special chars for (int i=0; i < text.length();i++) { switch(text.charAt(i)) { case 8:text.replace(i, i+1, "\\b"); i++; break; case 9:text.replace(i, i+1, "\\t"); i++; break; case 10:text.replace(i, i+1, "\\n"); i++; break; case 12:text.replace(i, i+1, "\\f"); i++; break; case 13:text.replace(i, i+1, "\\r"); i++; break; case 34:text.replace(i, i+1, "\\\""); i++; break; case 39:text.replace(i, i+1, "\\'"); i++; break; case 92:text.replace(i, i+1, "\\\\"); i++; break; case 0x2028:text.replace(i, i+1, "\\u2028"); i++; break; case 0x2029:text.replace(i, i+1, "\\u2029"); i++; break; } } return text.toString(); } @Override public void visit(final Tree.StringLiteral that) { out("\"", escapeStringLiteral(that.getText()), "\""); } @Override public void visit(final Tree.StringTemplate that) { //TODO optimize to avoid generating initial "" and final .plus("") List<StringLiteral> literals = that.getStringLiterals(); List<Expression> exprs = that.getExpressions(); for (int i = 0; i < literals.size(); i++) { StringLiteral literal = literals.get(i); literal.visit(this); if (i>0)out(")"); if (i < exprs.size()) { out(".plus("); final Expression expr = exprs.get(i); expr.visit(this); if (expr.getTypeModel() == null || !"ceylon.language::String".equals(expr.getTypeModel().getProducedTypeQualifiedName())) { out(".string"); } out(").plus("); } } } @Override public void visit(final Tree.FloatLiteral that) { out(getClAlias(), "Float(", that.getText(), ")"); } public long parseNaturalLiteral(Tree.NaturalLiteral that) throws NumberFormatException { char prefix = that.getText().charAt(0); int radix = 10; String nt = that.getText(); if (prefix == '$' || prefix == '#') { radix = prefix == '$' ? 2 : 16; nt = nt.substring(1); } return new java.math.BigInteger(nt, radix).longValue(); } @Override public void visit(final Tree.NaturalLiteral that) { try { out("(", Long.toString(parseNaturalLiteral(that)), ")"); } catch (NumberFormatException ex) { that.addError("Invalid numeric literal " + that.getText()); } } @Override public void visit(final Tree.This that) { out(names.self(Util.getContainingClassOrInterface(that.getScope()))); } @Override public void visit(final Tree.Super that) { out(names.self(Util.getContainingClassOrInterface(that.getScope()))); } @Override public void visit(final Tree.Outer that) { boolean outer = false; if (opts.isOptimize()) { Scope scope = that.getScope(); while ((scope != null) && !(scope instanceof TypeDeclaration)) { scope = scope.getContainer(); } if (scope != null && ((TypeDeclaration)scope).isClassOrInterfaceMember()) { out(names.self((TypeDeclaration) scope), "."); outer = true; } } if (outer) { out("outer$"); } else { out(names.self(that.getTypeModel().getDeclaration())); } } @Override public void visit(final Tree.BaseMemberExpression that) { BmeGenerator.generateBme(that, this, false); } /** Tells whether a declaration can be accessed directly (using its name) or * through its getter. */ boolean accessDirectly(Declaration d) { return !accessThroughGetter(d) || directAccess.contains(d) || d.isParameter(); } private boolean accessThroughGetter(Declaration d) { return (d instanceof MethodOrValue) && !(d instanceof Method) && !defineAsProperty(d); } boolean defineAsProperty(Declaration d) { // for now, only define member attributes as properties, not toplevel attributes return d.isMember() && d instanceof MethodOrValue && !(d instanceof Method); } /** Returns true if the top-level declaration for the term is annotated "nativejs" */ static boolean isNative(final Tree.Term t) { if (t instanceof MemberOrTypeExpression) { return isNative(((MemberOrTypeExpression)t).getDeclaration()); } return false; } /** Returns true if the declaration is annotated "nativejs" */ static boolean isNative(Declaration d) { return hasAnnotationByName(getToplevel(d), "nativejs") || TypeUtils.isUnknown(d); } private static Declaration getToplevel(Declaration d) { while (d != null && !d.isToplevel()) { Scope s = d.getContainer(); // Skip any non-declaration elements while (s != null && !(s instanceof Declaration)) { s = s.getContainer(); } d = (Declaration) s; } return d; } private static boolean hasAnnotationByName(Declaration d, String name){ if (d != null) { for(com.redhat.ceylon.compiler.typechecker.model.Annotation annotation : d.getAnnotations()){ if(annotation.getName().equals(name)) return true; } } return false; } private void generateSafeOp(final Tree.QualifiedMemberOrTypeExpression that) { boolean isMethod = that.getDeclaration() instanceof Method; String lhsVar = createRetainedTempVar(); out("(", lhsVar, "="); super.visit(that); out(","); if (isMethod) { out(getClAlias(), "JsCallable(", lhsVar, ","); } out(getClAlias(),"nn$(", lhsVar, ")?"); if (isMethod && !((Method)that.getDeclaration()).getTypeParameters().isEmpty()) { //Method ref with type parameters BmeGenerator.printGenericMethodReference(this, that, lhsVar, memberAccess(that, lhsVar)); } else { out(memberAccess(that, lhsVar)); } out(":null)"); if (isMethod) { out(")"); } } void supervisit(final Tree.QualifiedMemberOrTypeExpression that) { super.visit(that); } @Override public void visit(final Tree.QualifiedMemberExpression that) { //Big TODO: make sure the member is actually // refined by the current class! if (that.getMemberOperator() instanceof SafeMemberOp) { generateSafeOp(that); } else if (that.getMemberOperator() instanceof SpreadOp) { SequenceGenerator.generateSpread(that, this); } else if (that.getDeclaration() instanceof Method && that.getSignature() == null) { //TODO right now this causes that all method invocations are done this way //we need to filter somehow to only use this pattern when the result is supposed to be a callable //looks like checking for signature is a good way (not THE way though; named arg calls don't have signature) generateCallable(that, null); } else if (that.getStaticMethodReference() && that.getDeclaration()!=null) { out("function($O$) {return "); if (that.getDeclaration() instanceof Method) { if (BmeGenerator.hasTypeParameters(that)) { BmeGenerator.printGenericMethodReference(this, that, "$O$", "$O$."+names.name(that.getDeclaration())); } else { out(getClAlias(), "JsCallable($O$,$O$.", names.name(that.getDeclaration()), ")"); } out(";}"); } else { out("$O$.", names.name(that.getDeclaration()), ";}"); } } else { final String lhs = generateToString(new GenerateCallback() { @Override public void generateValue() { GenerateJsVisitor.super.visit(that); } }); out(memberAccess(that, lhs)); } } private void generateCallable(final Tree.QualifiedMemberOrTypeExpression that, String name) { if (that.getPrimary() instanceof Tree.BaseTypeExpression) { //it's a static method ref if (name == null) { name = memberAccess(that, ""); } out("function(x){return "); if (BmeGenerator.hasTypeParameters(that)) { BmeGenerator.printGenericMethodReference(this, that, "x", "x."+name); } else { out(getClAlias(), "JsCallable(x,x.", name, ")"); } out(";}"); return; } final Declaration d = that.getDeclaration(); if (d.isToplevel() && d instanceof Method) { //Just output the name out(names.name(d)); return; } String primaryVar = createRetainedTempVar(); out("(", primaryVar, "="); that.getPrimary().visit(this); out(","); final String member = (name == null) ? memberAccess(that, primaryVar) : (primaryVar+"."+name); if (that.getDeclaration() instanceof Method && !((Method)that.getDeclaration()).getTypeParameters().isEmpty()) { //Method ref with type parameters BmeGenerator.printGenericMethodReference(this, that, primaryVar, member); } else { out(getClAlias(), "JsCallable(", primaryVar, ",", getClAlias(), "nn$(", primaryVar, ")?", member, ":null)"); } out(")"); } /** * Checks if the given node is a MemberOrTypeExpression or QualifiedType which * represents an access to a supertype member and returns the scope of that * member or null. */ Scope getSuperMemberScope(Node node) { Scope scope = null; if (node instanceof QualifiedMemberOrTypeExpression) { // Check for "super.member" QualifiedMemberOrTypeExpression qmte = (QualifiedMemberOrTypeExpression) node; final Term primary = eliminateParensAndWidening(qmte.getPrimary()); if (primary instanceof Super) { scope = qmte.getDeclaration().getContainer(); } } else if (node instanceof QualifiedType) { // Check for super.Membertype QualifiedType qtype = (QualifiedType) node; if (qtype.getOuterType() instanceof SuperType) { scope = qtype.getDeclarationModel().getContainer(); } } return scope; } String getMember(Node node, Declaration decl, String lhs) { final StringBuilder sb = new StringBuilder(); if (lhs != null) { if (lhs.length() > 0) { sb.append(lhs); } } else if (node instanceof BaseMemberOrTypeExpression) { BaseMemberOrTypeExpression bmte = (BaseMemberOrTypeExpression) node; Declaration bmd = bmte.getDeclaration(); if (bmd.isParameter() && bmd.getContainer() instanceof ClassAlias) { return names.name(bmd); } String path = qualifiedPath(node, bmd); if (path.length() > 0) { sb.append(path); } } return sb.toString(); } String memberAccessBase(Node node, Declaration decl, boolean setter, String lhs) { final StringBuilder sb = new StringBuilder(getMember(node, decl, lhs)); if (sb.length() > 0) { if (node instanceof BaseMemberOrTypeExpression) { Declaration bmd = ((BaseMemberOrTypeExpression)node).getDeclaration(); if (bmd.isParameter() && bmd.getContainer() instanceof ClassAlias) { return sb.toString(); } } sb.append('.'); } Scope scope = getSuperMemberScope(node); if (opts.isOptimize() && (scope != null)) { sb.append("getT$all()['"); sb.append(scope.getQualifiedNameString()); sb.append("']"); if (defineAsProperty(decl)) { return getClAlias() + (setter ? "attrSetter(" : "attrGetter(") + sb.toString() + ",'" + names.name(decl) + "')"; } sb.append(".$$.prototype."); } final String member = (accessThroughGetter(decl) && !accessDirectly(decl)) ? (setter ? names.setter(decl) : names.getter(decl)) : names.name(decl); sb.append(member); if (!opts.isOptimize() && (scope != null)) { sb.append(names.scopeSuffix(scope)); } return sb.toString(); } /** * Returns a string representing a read access to a member, as represented by * the given expression. If lhs==null and the expression is a BaseMemberExpression * then the qualified path is prepended. */ String memberAccess(final Tree.StaticMemberOrTypeExpression expr, String lhs) { Declaration decl = expr.getDeclaration(); String plainName = null; if (decl == null && dynblock > 0) { plainName = expr.getIdentifier().getText(); } else if (isNative(decl)) { // direct access to a native element plainName = decl.getName(); } if (plainName != null) { return ((lhs != null) && (lhs.length() > 0)) ? (lhs + "." + plainName) : plainName; } boolean protoCall = opts.isOptimize() && (getSuperMemberScope(expr) != null); if (accessDirectly(decl) && !(protoCall && defineAsProperty(decl))) { // direct access, without getter return memberAccessBase(expr, decl, false, lhs); } // access through getter return memberAccessBase(expr, decl, false, lhs) + (protoCall ? ".call(this)" : "()"); } @Override public void visit(final Tree.BaseTypeExpression that) { Declaration d = that.getDeclaration(); if (d == null && isInDynamicBlock()) { //It's a native js type but will be wrapped in dyntype() call String id = that.getIdentifier().getText(); out("(typeof ", id, "==='undefined'?"); generateThrow(null, "Undefined type " + id, that); out(":", id, ")"); } else { qualify(that, d); out(names.name(d)); } } @Override public void visit(final Tree.QualifiedTypeExpression that) { if (that.getMemberOperator() instanceof SafeMemberOp) { generateCallable(that, names.name(that.getDeclaration())); } else { super.visit(that); if (isInDynamicBlock() && that.getDeclaration() == null) { out(".", that.getIdentifier().getText()); } else { out(".", names.name(that.getDeclaration())); } } } public void visit(final Tree.Dynamic that) { invoker.nativeObject(that.getNamedArgumentList()); } @Override public void visit(final Tree.InvocationExpression that) { invoker.generateInvocation(that); } @Override public void visit(final Tree.PositionalArgumentList that) { invoker.generatePositionalArguments(null, that, that.getPositionalArguments(), false, false); } /** Box a term, visit it, unbox it. */ void box(final Tree.Term term) { final int t = boxStart(term); term.visit(this); if (t == 4) out("/*TODO: callable targs 4*/"); boxUnboxEnd(t); } // Make sure fromTerm is compatible with toTerm by boxing it when necessary int boxStart(final Tree.Term fromTerm) { return boxUnboxStart(fromTerm, false); } // Make sure fromTerm is compatible with toTerm by boxing or unboxing it when necessary int boxUnboxStart(final Tree.Term fromTerm, final Tree.Term toTerm) { return boxUnboxStart(fromTerm, isNative(toTerm)); } // Make sure fromTerm is compatible with toDecl by boxing or unboxing it when necessary int boxUnboxStart(final Tree.Term fromTerm, com.redhat.ceylon.compiler.typechecker.model.TypedDeclaration toDecl) { return boxUnboxStart(fromTerm, isNative(toDecl)); } int boxUnboxStart(final Tree.Term fromTerm, boolean toNative) { // Box the value final boolean fromNative = isNative(fromTerm); final ProducedType fromType = fromTerm.getTypeModel(); final String fromTypeName = Util.isTypeUnknown(fromType) ? "UNKNOWN" : fromType.getProducedTypeQualifiedName(); if (fromNative != toNative || fromTypeName.startsWith("ceylon.language::Callable<")) { if (fromNative) { // conversion from native value to Ceylon value if (fromTypeName.equals("ceylon.language::Integer")) { out("("); } else if (fromTypeName.equals("ceylon.language::Float")) { out(getClAlias(), "Float("); } else if (fromTypeName.equals("ceylon.language::Boolean")) { out("("); } else if (fromTypeName.equals("ceylon.language::Character")) { out(getClAlias(), "Character("); } else if (fromTypeName.startsWith("ceylon.language::Callable<")) { out(getClAlias(), "$JsCallable("); return 4; } else { return 0; } return 1; } else if ("ceylon.language::Float".equals(fromTypeName)) { // conversion from Ceylon Float to native value return 2; } else if (fromTypeName.startsWith("ceylon.language::Callable<")) { Term _t = fromTerm; if (_t instanceof Tree.InvocationExpression) { _t = ((Tree.InvocationExpression)_t).getPrimary(); } //Don't box callables if they're not members or anonymous if (_t instanceof Tree.MemberOrTypeExpression) { final Declaration d = ((Tree.MemberOrTypeExpression)_t).getDeclaration(); if (d != null && !(d.isClassOrInterfaceMember() || d.isAnonymous())) { return 0; } } out(getClAlias(), "$JsCallable("); return 4; } else { return 3; } } return 0; } void boxUnboxEnd(int boxType) { switch (boxType) { case 1: out(")"); break; case 2: out(".valueOf()"); break; case 4: out(")"); break; default: //nothing } } @Override public void visit(final Tree.ObjectArgument that) { if (errVisitor.hasErrors(that))return; FunctionHelper.objectArgument(that, this); } @Override public void visit(final Tree.AttributeArgument that) { if (errVisitor.hasErrors(that))return; FunctionHelper.attributeArgument(that, this); } @Override public void visit(final Tree.SequencedArgument that) { if (errVisitor.hasErrors(that))return; SequenceGenerator.sequencedArgument(that, this); } @Override public void visit(final Tree.SequenceEnumeration that) { if (errVisitor.hasErrors(that))return; SequenceGenerator.sequenceEnumeration(that, this); } @Override public void visit(final Tree.Comprehension that) { new ComprehensionGenerator(this, names, directAccess).generateComprehension(that); } @Override public void visit(final Tree.SpecifierStatement that) { // A lazy specifier expression in a class/interface should go into the // prototype in prototype style, so don't generate them here. if (!(opts.isOptimize() && (that.getSpecifierExpression() instanceof LazySpecifierExpression) && (that.getScope().getContainer() instanceof TypeDeclaration))) { specifierStatement(null, that); } } private void specifierStatement(final TypeDeclaration outer, final Tree.SpecifierStatement specStmt) { final Tree.Expression expr = specStmt.getSpecifierExpression().getExpression(); final Tree.Term term = specStmt.getBaseMemberExpression(); final Tree.StaticMemberOrTypeExpression smte = term instanceof Tree.StaticMemberOrTypeExpression ? (Tree.StaticMemberOrTypeExpression)term : null; if (dynblock > 0 && Util.isTypeUnknown(term.getTypeModel())) { if (smte != null && smte.getDeclaration() == null) { out(smte.getIdentifier().getText()); } else { term.visit(this); } out("="); int box = boxUnboxStart(expr, term); expr.visit(this); if (box == 4) out("/*TODO: callable targs 6*/"); boxUnboxEnd(box); out(";"); return; } if (smte != null) { Declaration bmeDecl = smte.getDeclaration(); if (specStmt.getSpecifierExpression() instanceof LazySpecifierExpression) { // attr => expr; final boolean property = defineAsProperty(bmeDecl); if (property) { defineAttribute(qualifiedPath(specStmt, bmeDecl), names.name(bmeDecl)); } else { if (bmeDecl.isMember()) { qualify(specStmt, bmeDecl); } else { out ("var "); } out(names.getter(bmeDecl), "=function()"); } beginBlock(); if (outer != null) { initSelf(specStmt); } out ("return "); if (!isNaturalLiteral(specStmt.getSpecifierExpression().getExpression().getTerm())) { specStmt.getSpecifierExpression().visit(this); } out(";"); endBlock(); if (property) { out(",undefined,"); TypeUtils.encodeForRuntime(specStmt, bmeDecl, this); out(")"); } endLine(true); directAccess.remove(bmeDecl); } else if (outer != null) { // "attr = expr;" in a prototype definition //since #451 we now generate an attribute here if (bmeDecl.isMember() && (bmeDecl instanceof Value) && bmeDecl.isActual()) { Value vdec = (Value)bmeDecl; final String atname = bmeDecl.isShared() ? names.name(bmeDecl)+"_" : names.privateName(bmeDecl); defineAttribute(names.self(outer), names.name(bmeDecl)); out("{"); if (vdec.isLate()) { generateUnitializedAttributeReadCheck("this."+atname, names.name(bmeDecl)); } out("return this.", atname, ";}"); if (vdec.isVariable() || vdec.isLate()) { final String par = getNames().createTempVariable(); out(",function(", par, "){"); if (vdec.isLate()) { generateImmutableAttributeReassignmentCheck("this."+atname, names.name(bmeDecl)); } out("return this.", atname, "=", par, ";}"); } else { out(",undefined"); } out(","); TypeUtils.encodeForRuntime(expr, bmeDecl, this); out(")"); endLine(true); } } else if (bmeDecl instanceof MethodOrValue) { // "attr = expr;" in an initializer or method final MethodOrValue moval = (MethodOrValue)bmeDecl; if (moval.isVariable()) { // simple assignment to a variable attribute BmeGenerator.generateMemberAccess(smte, new GenerateCallback() { @Override public void generateValue() { int boxType = boxUnboxStart(expr.getTerm(), moval); if (dynblock > 0 && !Util.isTypeUnknown(moval.getType()) && Util.isTypeUnknown(expr.getTypeModel())) { TypeUtils.generateDynamicCheck(expr, moval.getType(), GenerateJsVisitor.this, false, expr.getTypeModel().getTypeArguments()); } else { expr.visit(GenerateJsVisitor.this); } if (boxType == 4) { out(","); if (moval instanceof Method) { //Add parameters TypeUtils.encodeParameterListForRuntime(specStmt, ((Method)moval).getParameterLists().get(0), GenerateJsVisitor.this); out(","); } else { //TODO extract parameters from Value out("[/*VALUE Callable params", moval.getClass().getName(), "*/],"); } TypeUtils.printTypeArguments(expr, expr.getTypeModel().getTypeArguments(), GenerateJsVisitor.this, false, expr.getTypeModel().getVarianceOverrides()); } boxUnboxEnd(boxType); } }, qualifiedPath(smte, moval), this); out(";"); } else if (moval.isMember()) { if (moval instanceof Method) { //same as fat arrow qualify(specStmt, bmeDecl); out(names.name(moval), "=function ", names.name(moval), "("); //Build the parameter list, we'll use it several times final StringBuilder paramNames = new StringBuilder(); final List<com.redhat.ceylon.compiler.typechecker.model.Parameter> params = ((Method) moval).getParameterLists().get(0).getParameters(); for (com.redhat.ceylon.compiler.typechecker.model.Parameter p : params) { if (paramNames.length() > 0) paramNames.append(","); paramNames.append(names.name(p)); } out(paramNames.toString()); out("){"); for (com.redhat.ceylon.compiler.typechecker.model.Parameter p : params) { if (p.isDefaulted()) { out("if(", names.name(p), "===undefined)", names.name(p),"="); qualify(specStmt, moval); out(names.name(moval), "$defs$", p.getName(), "(", paramNames.toString(), ")"); endLine(true); } } out("return "); if (!isNaturalLiteral(specStmt.getSpecifierExpression().getExpression().getTerm())) { specStmt.getSpecifierExpression().visit(this); } out("(", paramNames.toString(), ");}"); endLine(true); } else { // Specifier for a member attribute. This actually defines the // member (e.g. in shortcut refinement syntax the attribute // declaration itself can be omitted), so generate the attribute. if (opts.isOptimize()) { //#451 out(names.self(Util.getContainingClassOrInterface(moval.getScope())), ".", names.name(moval)); if (!(moval.isVariable() || moval.isLate())) { out("_"); } out("="); specStmt.getSpecifierExpression().visit(this); endLine(true); } else { AttributeGenerator.generateAttributeGetter(null, moval, specStmt.getSpecifierExpression(), null, this, directAccess); } } } else { // Specifier for some other attribute, or for a method. if (opts.isOptimize() || (bmeDecl.isMember() && (bmeDecl instanceof Method))) { qualify(specStmt, bmeDecl); } out(names.name(bmeDecl), "="); if (dynblock > 0 && Util.isTypeUnknown(expr.getTypeModel()) && !Util.isTypeUnknown(((MethodOrValue) bmeDecl).getType())) { TypeUtils.generateDynamicCheck(expr, ((MethodOrValue) bmeDecl).getType(), this, false, expr.getTypeModel().getTypeArguments()); } else { specStmt.getSpecifierExpression().visit(this); } out(";"); } } } else if ((term instanceof ParameterizedExpression) && (specStmt.getSpecifierExpression() != null)) { final ParameterizedExpression paramExpr = (ParameterizedExpression)term; if (paramExpr.getPrimary() instanceof BaseMemberExpression) { // func(params) => expr; final BaseMemberExpression bme2 = (BaseMemberExpression) paramExpr.getPrimary(); final Declaration bmeDecl = bme2.getDeclaration(); if (bmeDecl.isMember()) { qualify(specStmt, bmeDecl); } else { out("var "); } out(names.name(bmeDecl), "="); FunctionHelper.singleExprFunction(paramExpr.getParameterLists(), expr, bmeDecl instanceof Scope ? (Scope)bmeDecl : null, true, true, this); out(";"); } } } private void addSpecifierToPrototype(final TypeDeclaration outer, final Tree.SpecifierStatement specStmt) { specifierStatement(outer, specStmt); } @Override public void visit(final AssignOp that) { String returnValue = null; StaticMemberOrTypeExpression lhsExpr = null; if (dynblock > 0 && Util.isTypeUnknown(that.getLeftTerm().getTypeModel())) { that.getLeftTerm().visit(this); out("="); int box = boxUnboxStart(that.getRightTerm(), that.getLeftTerm()); that.getRightTerm().visit(this); if (box == 4) out("/*TODO: callable targs 6*/"); boxUnboxEnd(box); return; } out("("); if (that.getLeftTerm() instanceof BaseMemberExpression) { BaseMemberExpression bme = (BaseMemberExpression) that.getLeftTerm(); lhsExpr = bme; Declaration bmeDecl = bme.getDeclaration(); boolean simpleSetter = hasSimpleGetterSetter(bmeDecl); if (!simpleSetter) { returnValue = memberAccess(bme, null); } } else if (that.getLeftTerm() instanceof QualifiedMemberExpression) { QualifiedMemberExpression qme = (QualifiedMemberExpression)that.getLeftTerm(); lhsExpr = qme; boolean simpleSetter = hasSimpleGetterSetter(qme.getDeclaration()); String lhsVar = null; if (!simpleSetter) { lhsVar = createRetainedTempVar(); out(lhsVar, "="); super.visit(qme); out(",", lhsVar, "."); returnValue = memberAccess(qme, lhsVar); } else { super.visit(qme); out("."); } } BmeGenerator.generateMemberAccess(lhsExpr, new GenerateCallback() { @Override public void generateValue() { if (!isNaturalLiteral(that.getRightTerm())) { int boxType = boxUnboxStart(that.getRightTerm(), that.getLeftTerm()); that.getRightTerm().visit(GenerateJsVisitor.this); if (boxType == 4) out("/*TODO: callable targs 7*/"); boxUnboxEnd(boxType); } } }, null, this); if (returnValue != null) { out(",", returnValue); } out(")"); } /** Outputs the module name for the specified declaration. Returns true if something was output. */ boolean qualify(final Node that, final Declaration d) { String path = qualifiedPath(that, d); if (path.length() > 0) { out(path, "."); } return path.length() > 0; } private String qualifiedPath(final Node that, final Declaration d) { return qualifiedPath(that, d, false); } String qualifiedPath(final Node that, final Declaration d, final boolean inProto) { boolean isMember = d.isClassOrInterfaceMember(); if (!isMember && isImported(that == null ? null : that.getUnit().getPackage(), d)) { return names.moduleAlias(d.getUnit().getPackage().getModule()); } else if (opts.isOptimize() && !inProto) { if (isMember && !(d.isParameter() && !d.isCaptured())) { TypeDeclaration id = that.getScope().getInheritingDeclaration(d); if (id == null) { //a local declaration of some kind, //perhaps in an outer scope id = (TypeDeclaration) d.getContainer(); } Scope scope = that.getScope(); if ((scope != null) && ((that instanceof ClassDeclaration) || (that instanceof InterfaceDeclaration))) { // class/interface aliases have no own "this" scope = scope.getContainer(); } final StringBuilder path = new StringBuilder(); while (scope != null) { if (scope instanceof TypeDeclaration) { if (path.length() > 0) { path.append(".outer$"); } else { path.append(names.self((TypeDeclaration) scope)); } } else { path.setLength(0); } if (scope == id) { break; } scope = scope.getContainer(); } return path.toString(); } } else { if (d != null && isMember && (d.isShared() || inProto || (!d.isParameter() && defineAsProperty(d)))) { TypeDeclaration id = d instanceof TypeAlias ? (TypeDeclaration)d : that.getScope().getInheritingDeclaration(d); if (id==null) { //a shared local declaration return names.self((TypeDeclaration)d.getContainer()); } else { //an inherited declaration that might be //inherited by an outer scope return names.self(id); } } } return ""; } /** Tells whether a declaration is in the specified package. */ boolean isImported(final Package p2, final Declaration d) { if (d == null) { return false; } Package p1 = d.getUnit().getPackage(); if (p2 == null)return p1 != null; if (p1.getModule()== null)return p2.getModule()!=null; return !p1.getModule().equals(p2.getModule()); } @Override public void visit(final Tree.ExecutableStatement that) { super.visit(that); endLine(true); } /** Creates a new temporary variable which can be used immediately, even * inside an expression. The declaration for that temporary variable will be * emitted after the current Ceylon statement has been completely processed. * The resulting code is valid because JavaScript variables may be used before * they are declared. */ String createRetainedTempVar() { String varName = names.createTempVariable(); retainedVars.add(varName); return varName; } @Override public void visit(final Tree.Return that) { out("return"); if (that.getExpression() == null) { endLine(true); return; } out(" "); if (dynblock > 0 && Util.isTypeUnknown(that.getExpression().getTypeModel())) { Scope cont = Util.getRealScope(that.getScope()).getScope(); if (cont instanceof Declaration) { final ProducedType dectype = ((Declaration)cont).getReference().getType(); if (!Util.isTypeUnknown(dectype)) { TypeUtils.generateDynamicCheck(that.getExpression(), dectype, this, false, that.getExpression().getTypeModel().getTypeArguments()); endLine(true); return; } } } if (isNaturalLiteral(that.getExpression().getTerm())) { out(";"); } else { super.visit(that); } } @Override public void visit(final Tree.AnnotationList that) {} boolean outerSelf(Declaration d) { if (d.isToplevel()) { out("ex$"); return true; } else if (d.isClassOrInterfaceMember()) { out(names.self((TypeDeclaration)d.getContainer())); return true; } return false; } @Override public void visit(final Tree.SumOp that) { Operators.simpleBinaryOp(that, null, ".plus(", ")", this); } @Override public void visit(final Tree.ScaleOp that) { final String lhs = names.createTempVariable(); Operators.simpleBinaryOp(that, "function(){var "+lhs+"=", ";return ", ".scale("+lhs+");}()", this); } @Override public void visit(final Tree.DifferenceOp that) { Operators.simpleBinaryOp(that, null, ".minus(", ")", this); } @Override public void visit(final Tree.ProductOp that) { Operators.simpleBinaryOp(that, null, ".times(", ")", this); } @Override public void visit(final Tree.QuotientOp that) { Operators.simpleBinaryOp(that, null, ".divided(", ")", this); } @Override public void visit(final Tree.RemainderOp that) { Operators.simpleBinaryOp(that, null, ".remainder(", ")", this); } @Override public void visit(final Tree.PowerOp that) { Operators.simpleBinaryOp(that, null, ".power(", ")", this); } @Override public void visit(final Tree.AddAssignOp that) { assignOp(that, "plus", null); } @Override public void visit(final Tree.SubtractAssignOp that) { assignOp(that, "minus", null); } @Override public void visit(final Tree.MultiplyAssignOp that) { assignOp(that, "times", null); } @Override public void visit(final Tree.DivideAssignOp that) { assignOp(that, "divided", null); } @Override public void visit(final Tree.RemainderAssignOp that) { assignOp(that, "remainder", null); } public void visit(Tree.ComplementAssignOp that) { assignOp(that, "complement", TypeUtils.mapTypeArgument(that, "complement", "Element", "Other")); } public void visit(Tree.UnionAssignOp that) { assignOp(that, "union", TypeUtils.mapTypeArgument(that, "union", "Element", "Other")); } public void visit(Tree.IntersectAssignOp that) { assignOp(that, "intersection", TypeUtils.mapTypeArgument(that, "intersection", "Element", "Other")); } public void visit(Tree.AndAssignOp that) { assignOp(that, "&&", null); } public void visit(Tree.OrAssignOp that) { assignOp(that, "||", null); } private void assignOp(final Tree.AssignmentOp that, final String functionName, final Map<TypeParameter, ProducedType> targs) { Term lhs = that.getLeftTerm(); final boolean isNative="||".equals(functionName)||"&&".equals(functionName); if (lhs instanceof BaseMemberExpression) { BaseMemberExpression lhsBME = (BaseMemberExpression) lhs; Declaration lhsDecl = lhsBME.getDeclaration(); final String getLHS = memberAccess(lhsBME, null); out("("); BmeGenerator.generateMemberAccess(lhsBME, new GenerateCallback() { @Override public void generateValue() { if (isNative) { out(getLHS, functionName); } else { out(getLHS, ".", functionName, "("); } if (!isNaturalLiteral(that.getRightTerm())) { that.getRightTerm().visit(GenerateJsVisitor.this); } if (!isNative) { if (targs != null) { out(","); TypeUtils.printTypeArguments(that, targs, GenerateJsVisitor.this, false, null); } out(")"); } } }, null, this); if (!hasSimpleGetterSetter(lhsDecl)) { out(",", getLHS); } out(")"); } else if (lhs instanceof QualifiedMemberExpression) { QualifiedMemberExpression lhsQME = (QualifiedMemberExpression) lhs; if (isNative(lhsQME)) { // ($1.foo = Box($1.foo).operator($2)) final String tmp = names.createTempVariable(); final String dec = isInDynamicBlock() && lhsQME.getDeclaration() == null ? lhsQME.getIdentifier().getText() : lhsQME.getDeclaration().getName(); out("(", tmp, "="); lhsQME.getPrimary().visit(this); out(",", tmp, ".", dec, "="); int boxType = boxStart(lhsQME); out(tmp, ".", dec); if (boxType == 4) out("/*TODO: callable targs 8*/"); boxUnboxEnd(boxType); out(".", functionName, "("); if (!isNaturalLiteral(that.getRightTerm())) { that.getRightTerm().visit(this); } out("))"); } else { final String lhsPrimaryVar = createRetainedTempVar(); final String getLHS = memberAccess(lhsQME, lhsPrimaryVar); out("(", lhsPrimaryVar, "="); lhsQME.getPrimary().visit(this); out(","); BmeGenerator.generateMemberAccess(lhsQME, new GenerateCallback() { @Override public void generateValue() { out(getLHS, ".", functionName, "("); if (!isNaturalLiteral(that.getRightTerm())) { that.getRightTerm().visit(GenerateJsVisitor.this); } out(")"); } }, lhsPrimaryVar, this); if (!hasSimpleGetterSetter(lhsQME.getDeclaration())) { out(",", getLHS); } out(")"); } } } @Override public void visit(final Tree.NegativeOp that) { if (that.getTerm() instanceof Tree.NaturalLiteral) { long t = parseNaturalLiteral((Tree.NaturalLiteral)that.getTerm()); out("("); if (t > 0) { out("-"); } out(Long.toString(t)); out(")"); if (t == 0) { //Force -0 out(".negated"); } return; } final TypeDeclaration d = that.getTerm().getTypeModel().getDeclaration(); final boolean isint = d.inherits(that.getUnit().getIntegerDeclaration()); Operators.unaryOp(that, isint?"(-":null, isint?")":".negated", this); } @Override public void visit(final Tree.PositiveOp that) { final TypeDeclaration d = that.getTerm().getTypeModel().getDeclaration(); final boolean nat = d.inherits(that.getUnit().getIntegerDeclaration()); //TODO if it's positive we leave it as is? Operators.unaryOp(that, nat?"(+":null, nat?")":null, this); } @Override public void visit(final Tree.EqualOp that) { if (dynblock > 0 && Util.isTypeUnknown(that.getLeftTerm().getTypeModel())) { //Try to use equals() if it exists String ltmp = names.createTempVariable(); String rtmp = names.createTempVariable(); out("(", ltmp, "="); box(that.getLeftTerm()); out(",", rtmp, "="); box(that.getRightTerm()); out(",(", ltmp, ".equals&&", ltmp, ".equals(", rtmp, "))||", ltmp, "===", rtmp, ")"); } else { final boolean usenat = canUseNativeComparator(that.getLeftTerm(), that.getRightTerm()); Operators.simpleBinaryOp(that, usenat?"((":null, usenat?").valueOf()==(":".equals(", usenat?").valueOf())":")", this); } } @Override public void visit(final Tree.NotEqualOp that) { if (dynblock > 0 && Util.isTypeUnknown(that.getLeftTerm().getTypeModel())) { //Try to use equals() if it exists String ltmp = names.createTempVariable(); String rtmp = names.createTempVariable(); out("(", ltmp, "="); box(that.getLeftTerm()); out(",", rtmp, "="); box(that.getRightTerm()); out(",(", ltmp, ".equals&&!", ltmp, ".equals(", rtmp, "))||", ltmp, "!==", rtmp, ")"); } else { final boolean usenat = canUseNativeComparator(that.getLeftTerm(), that.getRightTerm()); Operators.simpleBinaryOp(that, usenat?"!(":"(!", usenat?"==":".equals(", usenat?")":"))", this); } } @Override public void visit(final Tree.NotOp that) { final Term t = that.getTerm(); final boolean omitParens = t instanceof BaseMemberExpression || t instanceof QualifiedMemberExpression || t instanceof IsOp || t instanceof Exists || t instanceof IdenticalOp || t instanceof InOp || t instanceof Nonempty || (t instanceof InvocationExpression && ((InvocationExpression)t).getNamedArgumentList() == null); if (omitParens) { Operators.unaryOp(that, "!", null, this); } else { Operators.unaryOp(that, "(!", ")", this); } } @Override public void visit(final Tree.IdenticalOp that) { Operators.simpleBinaryOp(that, "(", "===", ")", this); } @Override public void visit(final Tree.CompareOp that) { Operators.simpleBinaryOp(that, null, ".compare(", ")", this); } /** Returns true if both Terms' types is either Integer or Boolean. */ private boolean canUseNativeComparator(final Tree.Term left, final Tree.Term right) { if (left == null || right == null || left.getTypeModel() == null || right.getTypeModel() == null) { return false; } final ProducedType lt = left.getTypeModel(); final ProducedType rt = right.getTypeModel(); final TypeDeclaration intdecl = left.getUnit().getIntegerDeclaration(); final TypeDeclaration booldecl = left.getUnit().getBooleanDeclaration(); return (intdecl.equals(lt.getDeclaration()) && intdecl.equals(rt.getDeclaration())) || (booldecl.equals(lt.getDeclaration()) && booldecl.equals(rt.getDeclaration())); } @Override public void visit(final Tree.SmallerOp that) { if (dynblock > 0 && Util.isTypeUnknown(that.getLeftTerm().getTypeModel())) { //Try to use compare() if it exists String ltmp = names.createTempVariable(); String rtmp = names.createTempVariable(); out("(", ltmp, "="); box(that.getLeftTerm()); out(",", rtmp, "="); box(that.getRightTerm()); out(",(", ltmp, ".compare&&", ltmp, ".compare(", rtmp, ").equals(", getClAlias(), "getSmaller()))||", ltmp, "<", rtmp, ")"); } else { final boolean usenat = canUseNativeComparator(that.getLeftTerm(), that.getRightTerm()); if (usenat) { Operators.simpleBinaryOp(that, "(", "<", ")", this); } else { Operators.simpleBinaryOp(that, null, ".compare(", ")", this); out(".equals(", getClAlias(), "getSmaller())"); } } } @Override public void visit(final Tree.LargerOp that) { if (dynblock > 0 && Util.isTypeUnknown(that.getLeftTerm().getTypeModel())) { //Try to use compare() if it exists String ltmp = names.createTempVariable(); String rtmp = names.createTempVariable(); out("(", ltmp, "="); box(that.getLeftTerm()); out(",", rtmp, "="); box(that.getRightTerm()); out(",(", ltmp, ".compare&&", ltmp, ".compare(", rtmp, ").equals(", getClAlias(), "getLarger()))||", ltmp, ">", rtmp, ")"); } else { final boolean usenat = canUseNativeComparator(that.getLeftTerm(), that.getRightTerm()); if (usenat) { Operators.simpleBinaryOp(that, "(", ">", ")", this); } else { Operators.simpleBinaryOp(that, null, ".compare(", ")", this); out(".equals(", getClAlias(), "getLarger())"); } } } @Override public void visit(final Tree.SmallAsOp that) { if (dynblock > 0 && Util.isTypeUnknown(that.getLeftTerm().getTypeModel())) { //Try to use compare() if it exists String ltmp = names.createTempVariable(); String rtmp = names.createTempVariable(); out("(", ltmp, "="); box(that.getLeftTerm()); out(",", rtmp, "="); box(that.getRightTerm()); out(",(", ltmp, ".compare&&", ltmp, ".compare(", rtmp, ")!==", getClAlias(), "getLarger())||", ltmp, "<=", rtmp, ")"); } else { final boolean usenat = canUseNativeComparator(that.getLeftTerm(), that.getRightTerm()); if (usenat) { Operators.simpleBinaryOp(that, "(", "<=", ")", this); } else { out("("); Operators.simpleBinaryOp(that, null, ".compare(", ")", this); out("!==", getClAlias(), "getLarger()"); out(")"); } } } @Override public void visit(final Tree.LargeAsOp that) { if (dynblock > 0 && Util.isTypeUnknown(that.getLeftTerm().getTypeModel())) { //Try to use compare() if it exists String ltmp = names.createTempVariable(); String rtmp = names.createTempVariable(); out("(", ltmp, "="); box(that.getLeftTerm()); out(",", rtmp, "="); box(that.getRightTerm()); out(",(", ltmp, ".compare&&", ltmp, ".compare(", rtmp, ")!==", getClAlias(), "getSmaller())||", ltmp, ">=", rtmp, ")"); } else { final boolean usenat = canUseNativeComparator(that.getLeftTerm(), that.getRightTerm()); if (usenat) { Operators.simpleBinaryOp(that, "(", ">=", ")", this); } else { out("("); Operators.simpleBinaryOp(that, null, ".compare(", ")", this); out("!==", getClAlias(), "getSmaller()"); out(")"); } } } public void visit(final Tree.WithinOp that) { final String ttmp = names.createTempVariable(); out("(", ttmp, "="); box(that.getTerm()); out(","); if (dynblock > 0 && Util.isTypeUnknown(that.getTerm().getTypeModel())) { final String tmpl = names.createTempVariable(); final String tmpu = names.createTempVariable(); out(tmpl, "="); box(that.getLowerBound().getTerm()); out(",", tmpu, "="); box(that.getUpperBound().getTerm()); out(",((", ttmp, ".compare&&",ttmp,".compare(", tmpl); if (that.getLowerBound() instanceof Tree.OpenBound) { out(")===", getClAlias(), "getLarger())||", ttmp, ">", tmpl, ")"); } else { out(")!==", getClAlias(), "getSmaller())||", ttmp, ">=", tmpl, ")"); } out("&&((", ttmp, ".compare&&",ttmp,".compare(", tmpu); if (that.getUpperBound() instanceof Tree.OpenBound) { out(")===", getClAlias(), "getSmaller())||", ttmp, "<", tmpu, ")"); } else { out(")!==", getClAlias(), "getLarger())||", ttmp, "<=", tmpu, ")"); } } else { out(ttmp, ".compare("); box(that.getLowerBound().getTerm()); if (that.getLowerBound() instanceof Tree.OpenBound) { out(")===", getClAlias(), "getLarger()"); } else { out(")!==", getClAlias(), "getSmaller()"); } out("&&"); out(ttmp, ".compare("); box(that.getUpperBound().getTerm()); if (that.getUpperBound() instanceof Tree.OpenBound) { out(")===", getClAlias(), "getSmaller()"); } else { out(")!==", getClAlias(), "getLarger()"); } } out(")"); } @Override public void visit(final Tree.AndOp that) { Operators.simpleBinaryOp(that, "(", "&&", ")", this); } @Override public void visit(final Tree.OrOp that) { Operators.simpleBinaryOp(that, "(", "||", ")", this); } @Override public void visit(final Tree.EntryOp that) { out(getClAlias(), "Entry("); Operators.genericBinaryOp(that, ",", that.getTypeModel().getTypeArguments(), that.getTypeModel().getVarianceOverrides(), this); } @Override public void visit(final Tree.RangeOp that) { out(getClAlias(), "span("); that.getLeftTerm().visit(this); out(","); that.getRightTerm().visit(this); out(",{Element$span:"); TypeUtils.typeNameOrList(that, Util.unionType(that.getLeftTerm().getTypeModel(), that.getRightTerm().getTypeModel(), that.getUnit()), this, false); out("})"); } @Override public void visit(final Tree.SegmentOp that) { final Tree.Term left = that.getLeftTerm(); final Tree.Term right = that.getRightTerm(); out(getClAlias(), "measure("); left.visit(this); out(","); right.visit(this); out(",{Element$measure:"); TypeUtils.typeNameOrList(that, Util.unionType(left.getTypeModel(), right.getTypeModel(), that.getUnit()), this, false); out("})"); } @Override public void visit(final Tree.ThenOp that) { Operators.simpleBinaryOp(that, "(", "?", ":null)", this); } @Override public void visit(final Tree.Element that) { out(".$_get("); if (!isNaturalLiteral(that.getExpression().getTerm())) { that.getExpression().visit(this); } out(")"); } @Override public void visit(final Tree.DefaultOp that) { String lhsVar = createRetainedTempVar(); out("(", lhsVar, "="); box(that.getLeftTerm()); out(",", getClAlias(), "nn$(", lhsVar, ")?", lhsVar, ":"); box(that.getRightTerm()); out(")"); } @Override public void visit(final Tree.IncrementOp that) { Operators.prefixIncrementOrDecrement(that.getTerm(), "successor", this); } @Override public void visit(final Tree.DecrementOp that) { Operators.prefixIncrementOrDecrement(that.getTerm(), "predecessor", this); } boolean hasSimpleGetterSetter(Declaration decl) { return (dynblock > 0 && TypeUtils.isUnknown(decl)) || !((decl instanceof Value && ((Value)decl).isTransient()) || (decl instanceof Setter) || decl.isFormal()); } @Override public void visit(final Tree.PostfixIncrementOp that) { Operators.postfixIncrementOrDecrement(that.getTerm(), "successor", this); } @Override public void visit(final Tree.PostfixDecrementOp that) { Operators.postfixIncrementOrDecrement(that.getTerm(), "predecessor", this); } @Override public void visit(final Tree.UnionOp that) { Operators.genericBinaryOp(that, ".union(", TypeUtils.mapTypeArgument(that, "union", "Element", "Other"), that.getTypeModel().getVarianceOverrides(), this); } @Override public void visit(final Tree.IntersectionOp that) { Operators.genericBinaryOp(that, ".intersection(", TypeUtils.mapTypeArgument(that, "intersection", "Element", "Other"), that.getTypeModel().getVarianceOverrides(), this); } @Override public void visit(final Tree.ComplementOp that) { Operators.genericBinaryOp(that, ".complement(", TypeUtils.mapTypeArgument(that, "complement", "Element", "Other"), that.getTypeModel().getVarianceOverrides(), this); } @Override public void visit(final Tree.Exists that) { Operators.unaryOp(that, getClAlias()+"nn$(", ")", this); } @Override public void visit(final Tree.Nonempty that) { Operators.unaryOp(that, getClAlias()+"ne$(", ")", this); } //Don't know if we'll ever see this... @Override public void visit(final Tree.ConditionList that) { System.out.println("ZOMG condition list in the wild! " + that.getLocation() + " of " + that.getUnit().getFilename()); super.visit(that); } @Override public void visit(final Tree.BooleanCondition that) { int boxType = boxStart(that.getExpression().getTerm()); super.visit(that); if (boxType == 4) out("/*TODO: callable targs 10*/"); boxUnboxEnd(boxType); } @Override public void visit(final Tree.IfStatement that) { if (errVisitor.hasErrors(that))return; conds.generateIf(that); } @Override public void visit(final Tree.IfExpression that) { if (errVisitor.hasErrors(that))return; conds.generateIfExpression(that, false); } @Override public void visit(final Tree.WhileStatement that) { conds.generateWhile(that); } /** Generates js code to check if a term is of a certain type. We solve this in JS by * checking against all types that Type satisfies (in the case of union types, matching any * type will do, and in case of intersection types, all types must be matched). * @param term The term that is to be checked against a type * @param termString (optional) a string to be used as the term to be checked * @param type The type to check against * @param tmpvar (optional) a variable to which the term is assigned * @param negate If true, negates the generated condition */ void generateIsOfType(Node term, String termString, final ProducedType type, String tmpvar, final boolean negate) { if (negate) { out("!"); } out(getClAlias(), "is$("); if (term instanceof Term) { conds.specialConditionRHS((Term)term, tmpvar); } else { conds.specialConditionRHS(termString, tmpvar); } out(","); TypeUtils.typeNameOrList(term, type, this, false); if (type.getQualifyingType() != null) { out(",["); ProducedType outer = type.getQualifyingType(); boolean first=true; while (outer != null) { if (first) { first=false; } else{ out(","); } TypeUtils.typeNameOrList(term, outer, this, false); outer = outer.getQualifyingType(); } out("]"); } out(")"); } @Override public void visit(final Tree.IsOp that) { generateIsOfType(that.getTerm(), null, that.getType().getTypeModel(), null, false); } @Override public void visit(final Tree.Break that) { if (continues.isEmpty()) { out("break;"); } else { Continuation top=continues.peek(); if (that.getScope()==top.getScope()) { top.useBreak(); out(top.getBreakName(), "=true; return;"); } else { out("break;"); } } } @Override public void visit(final Tree.Continue that) { if (continues.isEmpty()) { out("continue;"); } else { Continuation top=continues.peek(); if (that.getScope()==top.getScope()) { top.useContinue(); out(top.getContinueName(), "=true; return;"); } else { out("continue;"); } } } @Override public void visit(final Tree.ForStatement that) { if (errVisitor.hasErrors(that))return; new ForGenerator(this, directAccess).generate(that); } public void visit(final Tree.InOp that) { box(that.getRightTerm()); out(".contains("); if (!isNaturalLiteral(that.getLeftTerm())) { box(that.getLeftTerm()); } out(")"); } @Override public void visit(final Tree.TryCatchStatement that) { if (errVisitor.hasErrors(that))return; new TryCatchGenerator(this, directAccess).generate(that); } @Override public void visit(final Tree.Throw that) { out("throw ", getClAlias(), "wrapexc("); if (that.getExpression() == null) { out(getClAlias(), "Exception()"); } else { that.getExpression().visit(this); } that.getUnit().getFullPath(); out(",'", that.getLocation(), "','", that.getUnit().getRelativePath(), "');"); } private void visitIndex(final Tree.IndexExpression that) { that.getPrimary().visit(this); ElementOrRange eor = that.getElementOrRange(); if (eor instanceof Element) { final Tree.Expression _elemexpr = ((Tree.Element)eor).getExpression(); final String _end; if (Util.isTypeUnknown(that.getPrimary().getTypeModel()) && dynblock > 0) { out("["); _end = "]"; } else { out(".$_get("); _end = ")"; } if (!isNaturalLiteral(_elemexpr.getTerm())) { _elemexpr.visit(this); } out(_end); } else {//range, or spread? ElementRange er = (ElementRange)eor; Expression sexpr = er.getLength(); if (sexpr == null) { if (er.getLowerBound() == null) { out(".spanTo("); } else if (er.getUpperBound() == null) { out(".spanFrom("); } else { out(".span("); } } else { out(".measure("); } if (er.getLowerBound() != null) { if (!isNaturalLiteral(er.getLowerBound().getTerm())) { er.getLowerBound().visit(this); } if (er.getUpperBound() != null || sexpr != null) { out(","); } } if (er.getUpperBound() != null) { if (!isNaturalLiteral(er.getUpperBound().getTerm())) { er.getUpperBound().visit(this); } } else if (sexpr != null) { sexpr.visit(this); } out(")"); } } public void visit(final Tree.IndexExpression that) { visitIndex(that); } @Override public void visit(final Tree.SwitchStatement that) { if (errVisitor.hasErrors(that))return; if (opts.isComment() && !opts.isMinify()) { out("//Switch statement at ", that.getUnit().getFilename(), " (", that.getLocation(), ")"); endLine(); } conds.generateSwitch(that); if (opts.isComment() && !opts.isMinify()) { out("//End switch statement at ", that.getUnit().getFilename(), " (", that.getLocation(), ")"); endLine(); } } @Override public void visit(final Tree.SwitchExpression that) { conds.generateSwitchExpression(that); } /** Generates the code for an anonymous function defined inside an argument list. */ @Override public void visit(final Tree.FunctionArgument that) { if (errVisitor.hasErrors(that))return; FunctionHelper.functionArgument(that, this); } /** Generates the code for a function in a named argument list. */ @Override public void visit(final Tree.MethodArgument that) { if (errVisitor.hasErrors(that))return; FunctionHelper.methodArgument(that, this); } /** Determines whether the specified block should be enclosed in a function. */ public boolean shouldEncloseBlock(Block block) { // just check if the block contains a captured declaration for (Tree.Statement statement : block.getStatements()) { if (statement instanceof Tree.Declaration) { if (((Tree.Declaration) statement).getDeclarationModel().isCaptured()) { return true; } } } return false; } /** Encloses the block in a function, IF NEEDED. */ void encloseBlockInFunction(final Tree.Block block, final boolean markBlock) { final boolean wrap=shouldEncloseBlock(block); if (wrap) { if (markBlock)beginBlock(); Continuation c = new Continuation(block.getScope(), names); continues.push(c); out("var ", c.getContinueName(), "=false"); endLine(true); out("var ", c.getBreakName(), "=false"); endLine(true); out("var ", c.getReturnName(), "=(function()"); if (!markBlock)beginBlock(); } if (markBlock) { block.visit(this); } else { visitStatements(block.getStatements()); } if (wrap) { Continuation c = continues.pop(); if (!markBlock)endBlock(); out("());if(", c.getReturnName(), "!==undefined){return ", c.getReturnName(), ";}"); if (c.isContinued()) { out("else if(", c.getContinueName(),"===true){continue;}"); } if (c.isBreaked()) { out("else if(", c.getBreakName(),"===true){break;}"); } if (markBlock)endBlockNewLine(); } } private static class Continuation { private final String cvar; private final String rvar; private final String bvar; private final Scope scope; private boolean cused, bused; public Continuation(Scope scope, JsIdentifierNames names) { this.scope=scope; cvar = names.createTempVariable(); rvar = names.createTempVariable(); bvar = names.createTempVariable(); } public Scope getScope() { return scope; } public String getContinueName() { return cvar; } public String getBreakName() { return bvar; } public String getReturnName() { return rvar; } public void useContinue() { cused = true; } public void useBreak() { bused=true; } public boolean isContinued() { return cused; } public boolean isBreaked() { return bused; } //"isBroken" sounds really really bad in this case } /** This interface is used inside type initialization method. */ static interface PrototypeInitCallback { /** Generates a function that adds members to a prototype, then calls it. */ void addToPrototypeCallback(); } @Override public void visit(final Tree.Tuple that) { SequenceGenerator.tuple(that, this); } @Override public void visit(final Tree.Assertion that) { if (opts.isComment() && !opts.isMinify()) { out("//assert"); location(that); endLine(); } String custom = "Assertion failed"; //Scan for a "doc" annotation with custom message if (that.getAnnotationList() != null && that.getAnnotationList().getAnonymousAnnotation() != null) { custom = that.getAnnotationList().getAnonymousAnnotation().getStringLiteral().getText(); } else { for (Annotation ann : that.getAnnotationList().getAnnotations()) { BaseMemberExpression bme = (BaseMemberExpression)ann.getPrimary(); if ("doc".equals(bme.getDeclaration().getName())) { custom = ((Tree.ListedArgument)ann.getPositionalArgumentList().getPositionalArguments().get(0)) .getExpression().getTerm().getText(); } } } StringBuilder sb = new StringBuilder(custom).append(": '"); for (int i = that.getConditionList().getToken().getTokenIndex()+1; i < that.getConditionList().getEndToken().getTokenIndex(); i++) { sb.append(tokens.get(i).getText()); } sb.append("' at ").append(that.getUnit().getFilename()).append(" (").append( that.getConditionList().getLocation()).append(")"); conds.specialConditionsAndBlock(that.getConditionList(), null, getClAlias()+"asrt$("); //escape out(",\"", escapeStringLiteral(sb.toString()), "\",'",that.getLocation(), "','", that.getUnit().getFilename(), "');"); endLine(); } @Override public void visit(Tree.DynamicStatement that) { dynblock++; if (dynblock == 1 && !opts.isMinify()) { out("/*BEG dynblock*/"); endLine(); } for (Tree.Statement stmt : that.getDynamicClause().getBlock().getStatements()) { stmt.visit(this); } if (dynblock == 1 && !opts.isMinify()) { out("/*END dynblock*/"); endLine(); } dynblock--; } boolean isInDynamicBlock() { return dynblock > 0; } @Override public void visit(final Tree.TypeLiteral that) { //Can be an alias, class, interface or type parameter if (that.getWantsDeclaration()) { MetamodelHelper.generateOpenType(that, that.getDeclaration(), this); } else { MetamodelHelper.generateClosedTypeLiteral(that, this); } } @Override public void visit(final Tree.MemberLiteral that) { if (that.getWantsDeclaration()) { MetamodelHelper.generateOpenType(that, that.getDeclaration(), this); } else { MetamodelHelper.generateMemberLiteral(that, this); } } @Override public void visit(final Tree.PackageLiteral that) { com.redhat.ceylon.compiler.typechecker.model.Package pkg = (com.redhat.ceylon.compiler.typechecker.model.Package)that.getImportPath().getModel(); MetamodelHelper.findModule(pkg.getModule(), this); out(".findPackage('", pkg.getNameAsString(), "')"); } @Override public void visit(Tree.ModuleLiteral that) { Module m = (Module)that.getImportPath().getModel(); MetamodelHelper.findModule(m, this); } /** Call internal function "throwexc" with the specified message and source location. */ void generateThrow(String exceptionClass, String msg, Node node) { out(getClAlias(), "throwexc(", exceptionClass==null ? getClAlias() + "Exception":exceptionClass, "("); out("\"", escapeStringLiteral(msg), "\"),'", node.getLocation(), "','", node.getUnit().getFilename(), "')"); } @Override public void visit(Tree.CompilerAnnotation that) { //just ignore this } /** Outputs the initial part of an attribute definition. */ void defineAttribute(final String owner, final String name) { out(getClAlias(), "atr$(", owner, ",'", name, "',function()"); } public int getExitCode() { return exitCode; } @Override public void visit(Tree.ListedArgument that) { if (!isNaturalLiteral(that.getExpression().getTerm())) { super.visit(that); } } @Override public void visit(Tree.LetExpression that) { if (errVisitor.hasErrors(that))return; FunctionHelper.generateLet(that, directAccess, this); } boolean isNaturalLiteral(Tree.Term that) { if (that instanceof Tree.NaturalLiteral) { out(Long.toString(parseNaturalLiteral((Tree.NaturalLiteral)that))); return true; } return false; } }
src/main/java/com/redhat/ceylon/compiler/js/GenerateJsVisitor.java
package com.redhat.ceylon.compiler.js; import static com.redhat.ceylon.compiler.typechecker.analyzer.Util.eliminateParensAndWidening; import java.io.File; import java.io.IOException; import java.io.StringWriter; import java.io.Writer; import java.util.ArrayList; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.Stack; import org.antlr.runtime.CommonToken; import com.redhat.ceylon.compiler.Options; import com.redhat.ceylon.compiler.js.TypeUtils.RuntimeMetamodelAnnotationGenerator; import com.redhat.ceylon.compiler.typechecker.model.Class; import com.redhat.ceylon.compiler.typechecker.model.ClassAlias; import com.redhat.ceylon.compiler.typechecker.model.ClassOrInterface; import com.redhat.ceylon.compiler.typechecker.model.Declaration; import com.redhat.ceylon.compiler.typechecker.model.Functional; import com.redhat.ceylon.compiler.typechecker.model.Interface; import com.redhat.ceylon.compiler.typechecker.model.Method; import com.redhat.ceylon.compiler.typechecker.model.MethodOrValue; import com.redhat.ceylon.compiler.typechecker.model.Module; import com.redhat.ceylon.compiler.typechecker.model.Package; import com.redhat.ceylon.compiler.typechecker.model.ProducedType; import com.redhat.ceylon.compiler.typechecker.model.Scope; import com.redhat.ceylon.compiler.typechecker.model.Setter; import com.redhat.ceylon.compiler.typechecker.model.TypeAlias; import com.redhat.ceylon.compiler.typechecker.model.TypeDeclaration; import com.redhat.ceylon.compiler.typechecker.model.TypeParameter; import com.redhat.ceylon.compiler.typechecker.model.Util; import com.redhat.ceylon.compiler.typechecker.model.Value; import com.redhat.ceylon.compiler.typechecker.tree.*; import com.redhat.ceylon.compiler.typechecker.tree.Tree.*; public class GenerateJsVisitor extends Visitor implements NaturalVisitor { private final Stack<Continuation> continues = new Stack<>(); private final JsIdentifierNames names; private final Set<Declaration> directAccess = new HashSet<>(); private final Set<Declaration> generatedAttributes = new HashSet<>(); private final RetainedVars retainedVars = new RetainedVars(); final ConditionGenerator conds; private final InvocationGenerator invoker; private final List<CommonToken> tokens; private final ErrorVisitor errVisitor = new ErrorVisitor(); private int dynblock; private int exitCode = 0; static final class SuperVisitor extends Visitor { private final List<Declaration> decs; SuperVisitor(List<Declaration> decs) { this.decs = decs; } @Override public void visit(QualifiedMemberOrTypeExpression qe) { Term primary = eliminateParensAndWidening(qe.getPrimary()); if (primary instanceof Super) { decs.add(qe.getDeclaration()); } super.visit(qe); } @Override public void visit(QualifiedType that) { if (that.getOuterType() instanceof SuperType) { decs.add(that.getDeclarationModel()); } super.visit(that); } public void visit(Tree.ClassOrInterface qe) { //don't recurse if (qe instanceof ClassDefinition) { ExtendedType extType = ((ClassDefinition) qe).getExtendedType(); if (extType != null) { super.visit(extType); } } } } private final class OuterVisitor extends Visitor { boolean found = false; private Declaration dec; private OuterVisitor(Declaration dec) { this.dec = dec; } @Override public void visit(QualifiedMemberOrTypeExpression qe) { if (qe.getPrimary() instanceof Outer || qe.getPrimary() instanceof This) { if ( qe.getDeclaration().equals(dec) ) { found = true; } } super.visit(qe); } } private List<? extends Statement> currentStatements = null; private Writer out; private final Writer originalOut; final Options opts; private CompilationUnit root; static final String function="function "; private boolean needIndent = true; private int indentLevel = 0; Package getCurrentPackage() { return root.getUnit().getPackage(); } /** Returns the module name for the language module. */ String getClAlias() { return jsout.getLanguageModuleAlias(); } @Override public void handleException(Exception e, Node that) { that.addUnexpectedError(that.getMessage(e, this)); } private final JsOutput jsout; public GenerateJsVisitor(JsOutput out, Options options, JsIdentifierNames names, List<CommonToken> tokens) throws IOException { this.jsout = out; this.opts = options; this.out = out.getWriter(); originalOut = out.getWriter(); this.names = names; conds = new ConditionGenerator(this, names, directAccess); this.tokens = tokens; invoker = new InvocationGenerator(this, names, retainedVars); } InvocationGenerator getInvoker() { return invoker; } /** Returns the helper component to handle naming. */ JsIdentifierNames getNames() { return names; } static interface GenerateCallback { public void generateValue(); } /** Print generated code to the Writer specified at creation time. * Automatically prints indentation first if necessary. * @param code The main code * @param codez Optional additional strings to print after the main code. */ void out(String code, String... codez) { try { if (!opts.isMinify() && opts.isIndent() && needIndent) { for (int i=0;i<indentLevel;i++) { out.write(" "); } } needIndent = false; out.write(code); for (String s : codez) { out.write(s); } if (opts.isVerbose() && out == originalOut) { //Print code to console (when printing to REAL output) System.out.print(code); for (String s : codez) { System.out.print(s); } } } catch (IOException ioe) { throw new RuntimeException("Generating JS code", ioe); } } /** Prints a newline. Indentation will automatically be printed by {@link #out(String, String...)} * when the next line is started. */ void endLine() { endLine(false); } /** Prints a newline. Indentation will automatically be printed by {@link #out(String, String...)} * when the next line is started. * @param semicolon if <code>true</code> then a semicolon is printed at the end * of the previous line*/ void endLine(boolean semicolon) { if (semicolon) { out(";"); if (opts.isMinify())return; } out("\n"); needIndent = opts.isIndent() && !opts.isMinify(); } /** Calls {@link #endLine()} if the current position is not already the beginning * of a line. */ void beginNewLine() { if (!needIndent) { endLine(false); } } /** Increases indentation level, prints opening brace and newline. Indentation will * automatically be printed by {@link #out(String, String...)} when the next line is started. */ void beginBlock() { indentLevel++; out("{"); if (!opts.isMinify())endLine(false); } /** Decreases indentation level, prints a closing brace in new line (using * {@link #beginNewLine()}) and calls {@link #endLine()}. */ void endBlockNewLine() { endBlock(false, true); } /** Decreases indentation level, prints a closing brace in new line (using * {@link #beginNewLine()}) and calls {@link #endLine()}. * @param semicolon if <code>true</code> then prints a semicolon after the brace*/ void endBlockNewLine(boolean semicolon) { endBlock(semicolon, true); } /** Decreases indentation level and prints a closing brace in new line (using * {@link #beginNewLine()}). */ void endBlock() { endBlock(false, false); } /** Decreases indentation level and prints a closing brace in new line (using * {@link #beginNewLine()}). * @param semicolon if <code>true</code> then prints a semicolon after the brace * @param newline if <code>true</code> then additionally calls {@link #endLine()} */ void endBlock(boolean semicolon, boolean newline) { indentLevel--; if (!opts.isMinify())beginNewLine(); out(semicolon ? "};" : "}"); if (semicolon&&opts.isMinify())return; if (newline) { endLine(false); } } /** Prints source code location in the form "at [filename] ([location])" */ void location(Node node) { out(" at ", node.getUnit().getFilename(), " (", node.getLocation(), ")"); } private String generateToString(final GenerateCallback callback) { final Writer oldWriter = out; out = new StringWriter(); callback.generateValue(); final String str = out.toString(); out = oldWriter; return str; } @Override public void visit(final Tree.CompilationUnit that) { root = that; if (!that.getModuleDescriptors().isEmpty()) { ModuleDescriptor md = that.getModuleDescriptors().get(0); out("ex$.$mod$ans$="); TypeUtils.outputAnnotationsFunction(md.getAnnotationList(), null, this); endLine(true); if (md.getImportModuleList() != null && !md.getImportModuleList().getImportModules().isEmpty()) { out("ex$.$mod$imps=function(){return{"); if (!opts.isMinify())endLine(); boolean first=true; for (ImportModule im : md.getImportModuleList().getImportModules()) { final StringBuilder path=new StringBuilder("'"); if (im.getImportPath()==null) { if (im.getQuotedLiteral()==null) { throw new CompilerErrorException("Invalid imported module"); } else { final String ql = im.getQuotedLiteral().getText(); path.append(ql.substring(1, ql.length()-1)); } } else { for (Identifier id : im.getImportPath().getIdentifiers()) { if (path.length()>1)path.append('.'); path.append(id.getText()); } } final String qv = im.getVersion().getText(); path.append('/').append(qv.substring(1, qv.length()-1)).append("'"); if (first)first=false;else{out(",");endLine();} out(path.toString(), ":"); TypeUtils.outputAnnotationsFunction(im.getAnnotationList(), null, this); } if (!opts.isMinify())endLine(); out("};};"); if (!opts.isMinify())endLine(); } } if (!that.getPackageDescriptors().isEmpty()) { final String pknm = that.getUnit().getPackage().getNameAsString().replaceAll("\\.", "\\$"); out("ex$.$pkg$ans$", pknm, "="); TypeUtils.outputAnnotationsFunction(that.getPackageDescriptors().get(0).getAnnotationList(), null, this); endLine(true); } for (CompilerAnnotation ca: that.getCompilerAnnotations()) { ca.visit(this); } if (that.getImportList() != null) { that.getImportList().visit(this); } visitStatements(that.getDeclarations()); } public void visit(final Tree.Import that) { } @Override public void visit(final Tree.Parameter that) { out(names.name(that.getParameterModel())); } @Override public void visit(final Tree.ParameterList that) { out("("); boolean first=true; boolean ptypes = false; //Check if this is the first parameter list if (that.getScope() instanceof Method && that.getModel().isFirst()) { ptypes = ((Method)that.getScope()).getTypeParameters() != null && !((Method)that.getScope()).getTypeParameters().isEmpty(); } for (Parameter param: that.getParameters()) { if (!first) out(","); out(names.name(param.getParameterModel())); first = false; } if (ptypes) { if (!first) out(","); out("$$$mptypes"); } out(")"); } void visitStatements(List<? extends Statement> statements) { List<String> oldRetainedVars = retainedVars.reset(null); final List<? extends Statement> prevStatements = currentStatements; currentStatements = statements; for (int i=0; i<statements.size(); i++) { Statement s = statements.get(i); s.visit(this); if (!opts.isMinify())beginNewLine(); retainedVars.emitRetainedVars(this); } retainedVars.reset(oldRetainedVars); currentStatements = prevStatements; } @Override public void visit(final Tree.Body that) { visitStatements(that.getStatements()); } @Override public void visit(final Tree.Block that) { List<Statement> stmnts = that.getStatements(); if (stmnts.isEmpty()) { out("{}"); } else { beginBlock(); visitStatements(stmnts); endBlock(); } } void initSelf(Node node) { final NeedsThisVisitor ntv = new NeedsThisVisitor(node); if (ntv.needsThisReference()) { final String me=names.self(prototypeOwner); out("var ", me, "=this"); //Code inside anonymous inner types sometimes gens direct refs to the outer instance //We can detect if that's going to happen and declare the ref right here if (ntv.needsOuterReference()) { final Declaration od = Util.getContainingDeclaration(prototypeOwner); if (od instanceof TypeDeclaration) { out(",", names.self((TypeDeclaration)od), "=", me, ".outer$"); } } endLine(true); } } /** Visitor that determines if a method definition will need the "this" reference. */ class NeedsThisVisitor extends Visitor { private boolean refs=false; private boolean outerRefs=false; NeedsThisVisitor(Node n) { if (prototypeOwner != null) { n.visit(this); } } @Override public void visit(Tree.This that) { refs = true; } @Override public void visit(Tree.Outer that) { refs = true; } @Override public void visit(Tree.Super that) { refs = true; } private boolean check(final Scope origScope) { Scope s = origScope; while (s != null) { if (s == prototypeOwner || (s instanceof TypeDeclaration && prototypeOwner.inherits((TypeDeclaration)s))) { refs = true; if (prototypeOwner.isAnonymous() && prototypeOwner.isMember()) { outerRefs=true; } return true; } s = s.getContainer(); } //Check the other way around as well s = prototypeOwner; while (s != null) { if (s == origScope || (s instanceof TypeDeclaration && origScope instanceof TypeDeclaration && ((TypeDeclaration)s).inherits((TypeDeclaration)origScope))) { refs = true; return true; } s = s.getContainer(); } return false; } public void visit(Tree.MemberOrTypeExpression that) { if (refs)return; if (that.getDeclaration() == null) { //Some expressions in dynamic blocks can have null declarations super.visit(that); return; } if (!check(that.getDeclaration().getContainer())) { super.visit(that); } } public void visit(Tree.Type that) { if (!check(that.getTypeModel().getDeclaration())) { super.visit(that); } } boolean needsThisReference() { return refs; } boolean needsOuterReference() { return outerRefs; } } void comment(Tree.Declaration that) { if (!opts.isComment() || opts.isMinify()) return; endLine(); String dname = that.getNodeType(); if (dname.endsWith("Declaration") || dname.endsWith("Definition")) { dname = dname.substring(0, dname.length()-7); } out("//", dname, " ", that.getDeclarationModel().getName()); location(that); endLine(); } boolean share(Declaration d) { return share(d, true); } private boolean share(Declaration d, boolean excludeProtoMembers) { boolean shared = false; if (!(excludeProtoMembers && opts.isOptimize() && d.isClassOrInterfaceMember()) && isCaptured(d)) { beginNewLine(); outerSelf(d); String dname=names.name(d); if (dname.endsWith("()")){ dname = dname.substring(0, dname.length()-2); } out(".", dname, "=", dname); endLine(true); shared = true; } return shared; } @Override public void visit(final Tree.ClassDeclaration that) { if (opts.isOptimize() && that.getDeclarationModel().isClassOrInterfaceMember()) return; classDeclaration(that); } private void addClassDeclarationToPrototype(TypeDeclaration outer, final Tree.ClassDeclaration that) { classDeclaration(that); final String tname = names.name(that.getDeclarationModel()); out(names.self(outer), ".", tname, "=", tname); endLine(true); } private void addAliasDeclarationToPrototype(TypeDeclaration outer, Tree.TypeAliasDeclaration that) { comment(that); final TypeAlias d = that.getDeclarationModel(); String path = qualifiedPath(that, d, true); if (path.length() > 0) { path += '.'; } String tname = names.name(d); tname = tname.substring(0, tname.length()-2); String _tmp=names.createTempVariable(); out(names.self(outer), ".", tname, "=function(){var ", _tmp, "="); TypeUtils.typeNameOrList(that, that.getTypeSpecifier().getType().getTypeModel(), this, true); out(";", _tmp, ".$crtmm$="); TypeUtils.encodeForRuntime(that,d,this); out(";return ", _tmp, ";}"); endLine(true); } @Override public void visit(final Tree.InterfaceDeclaration that) { if (!(opts.isOptimize() && that.getDeclarationModel().isClassOrInterfaceMember())) { interfaceDeclaration(that); } } private void addInterfaceDeclarationToPrototype(TypeDeclaration outer, final Tree.InterfaceDeclaration that) { interfaceDeclaration(that); final String tname = names.name(that.getDeclarationModel()); out(names.self(outer), ".", tname, "=", tname); endLine(true); } private void addInterfaceToPrototype(ClassOrInterface type, final Tree.InterfaceDefinition interfaceDef) { TypeGenerator.interfaceDefinition(interfaceDef, this); Interface d = interfaceDef.getDeclarationModel(); out(names.self(type), ".", names.name(d), "=", names.name(d)); endLine(true); } @Override public void visit(final Tree.InterfaceDefinition that) { if (!(opts.isOptimize() && that.getDeclarationModel().isClassOrInterfaceMember())) { TypeGenerator.interfaceDefinition(that, this); } } private void addClassToPrototype(ClassOrInterface type, final Tree.ClassDefinition classDef) { TypeGenerator.classDefinition(classDef, this); final String tname = names.name(classDef.getDeclarationModel()); out(names.self(type), ".", tname, "=", tname); endLine(true); } @Override public void visit(final Tree.ClassDefinition that) { if (!(opts.isOptimize() && that.getDeclarationModel().isClassOrInterfaceMember())) { TypeGenerator.classDefinition(that, this); } } private void interfaceDeclaration(final Tree.InterfaceDeclaration that) { //Don't even bother with nodes that have errors if (errVisitor.hasErrors(that))return; comment(that); final Interface d = that.getDeclarationModel(); final String aname = names.name(d); Tree.StaticType ext = that.getTypeSpecifier().getType(); out(function, aname, "("); if (d.getTypeParameters() != null && !d.getTypeParameters().isEmpty()) { out("$$targs$$,"); } out(names.self(d), "){"); final ProducedType pt = ext.getTypeModel(); final TypeDeclaration aliased = pt.getDeclaration(); qualify(that,aliased); out(names.name(aliased), "("); if (!pt.getTypeArguments().isEmpty()) { TypeUtils.printTypeArguments(that, pt.getTypeArguments(), this, true, pt.getVarianceOverrides()); out(","); } out(names.self(d), ");}"); endLine(); out(aname,".$crtmm$="); TypeUtils.encodeForRuntime(that, d, this); endLine(true); share(d); } private void classDeclaration(final Tree.ClassDeclaration that) { //Don't even bother with nodes that have errors if (errVisitor.hasErrors(that))return; comment(that); final Class d = that.getDeclarationModel(); final String aname = names.name(d); final Tree.ClassSpecifier ext = that.getClassSpecifier(); out(function, aname, "("); //Generate each parameter because we need to append one at the end for (Parameter p: that.getParameterList().getParameters()) { p.visit(this); out(", "); } if (d.getTypeParameters() != null && !d.getTypeParameters().isEmpty()) { out("$$targs$$,"); } out(names.self(d), "){return "); TypeDeclaration aliased = ext.getType().getDeclarationModel(); qualify(that, aliased); out(names.name(aliased), "("); if (ext.getInvocationExpression().getPositionalArgumentList() != null) { ext.getInvocationExpression().getPositionalArgumentList().visit(this); if (!ext.getInvocationExpression().getPositionalArgumentList().getPositionalArguments().isEmpty()) { out(","); } } else { out("/*PENDIENTE NAMED ARG CLASS DECL */"); } Map<TypeParameter, ProducedType> invargs = ext.getType().getTypeModel().getTypeArguments(); if (invargs != null && !invargs.isEmpty()) { TypeUtils.printTypeArguments(that, invargs, this, true, ext.getType().getTypeModel().getVarianceOverrides()); out(","); } out(names.self(d), ");}"); endLine(); out(aname, ".$$="); qualify(that, aliased); out(names.name(aliased), ".$$"); endLine(true); out(aname,".$crtmm$="); TypeUtils.encodeForRuntime(that, d, this); endLine(true); share(d); } @Override public void visit(final Tree.TypeAliasDeclaration that) { //Don't even bother with nodes that have errors if (errVisitor.hasErrors(that))return; final TypeAlias d = that.getDeclarationModel(); if (opts.isOptimize() && d.isClassOrInterfaceMember()) return; comment(that); final String tname=names.createTempVariable(); out(function, names.name(d), "{var ", tname, "="); TypeUtils.typeNameOrList(that, that.getTypeSpecifier().getType().getTypeModel(), this, false); out(";", tname, ".$crtmm$="); TypeUtils.encodeForRuntime(that, d, this, new RuntimeMetamodelAnnotationGenerator() { @Override public void generateAnnotations() { TypeUtils.outputAnnotationsFunction(that.getAnnotationList(), d, GenerateJsVisitor.this); } }); out(";return ", tname, ";}"); endLine(); share(d); } void referenceOuter(TypeDeclaration d) { if (!d.isToplevel()) { final ClassOrInterface coi = Util.getContainingClassOrInterface(d.getContainer()); if (coi != null) { out(names.self(d), ".outer$"); if (d.isClassOrInterfaceMember()) { out("=this"); } else { out("=", names.self(coi)); } endLine(true); } } } /** Returns the name of the type or its $init$ function if it's local. */ String typeFunctionName(final Tree.StaticType type, boolean removeAlias) { TypeDeclaration d = type.getTypeModel().getDeclaration(); if ((removeAlias && d.isAlias()) || d instanceof com.redhat.ceylon.compiler.typechecker.model.Constructor) { d = d.getExtendedTypeDeclaration(); } boolean inProto = opts.isOptimize() && (type.getScope().getContainer() instanceof TypeDeclaration); String tfn = memberAccessBase(type, d, false, qualifiedPath(type, d, inProto)); if (removeAlias && !isImported(type.getUnit().getPackage(), d)) { int idx = tfn.lastIndexOf('.'); if (idx > 0) { tfn = tfn.substring(0, idx+1) + "$init$" + tfn.substring(idx+1) + "()"; } else { tfn = "$init$" + tfn + "()"; } } return tfn; } void addToPrototype(Node node, ClassOrInterface d, List<Tree.Statement> statements) { final boolean isSerial = d instanceof com.redhat.ceylon.compiler.typechecker.model.Class && ((com.redhat.ceylon.compiler.typechecker.model.Class)d).isSerializable(); boolean enter = opts.isOptimize(); ArrayList<com.redhat.ceylon.compiler.typechecker.model.Parameter> plist = null; if (enter) { enter = !statements.isEmpty(); if (d instanceof com.redhat.ceylon.compiler.typechecker.model.Class) { com.redhat.ceylon.compiler.typechecker.model.ParameterList _pl = ((com.redhat.ceylon.compiler.typechecker.model.Class)d).getParameterList(); if (_pl != null) { plist = new ArrayList<>(_pl.getParameters().size()); plist.addAll(_pl.getParameters()); enter |= !plist.isEmpty(); } } } if (enter || isSerial) { final List<? extends Statement> prevStatements = currentStatements; currentStatements = statements; out("(function(", names.self(d), ")"); beginBlock(); if (enter) { for (Statement s: statements) { addToPrototype(d, s, plist); } //Generated attributes with corresponding parameters will remove them from the list if (plist != null) { for (com.redhat.ceylon.compiler.typechecker.model.Parameter p : plist) { generateAttributeForParameter(node, (com.redhat.ceylon.compiler.typechecker.model.Class)d, p); } } if (d.isMember()) { ClassOrInterface coi = Util.getContainingClassOrInterface(d.getContainer()); if (coi != null && d.inherits(coi)) { out(names.self(d), ".", names.name(d),"=", names.name(d), ";"); } } } if (isSerial) { SerializationHelper.addSerializer(node, (com.redhat.ceylon.compiler.typechecker.model.Class)d, this); } endBlock(); out(")(", names.name(d), ".$$.prototype)"); endLine(true); currentStatements = prevStatements; } } void generateAttributeForParameter(Node node, com.redhat.ceylon.compiler.typechecker.model.Class d, com.redhat.ceylon.compiler.typechecker.model.Parameter p) { final String privname = names.name(p) + "_"; defineAttribute(names.self(d), names.name(p.getModel())); out("{"); if (p.getModel().isLate()) { generateUnitializedAttributeReadCheck("this."+privname, names.name(p)); } out("return this.", privname, ";}"); if (p.getModel().isVariable() || p.getModel().isLate()) { final String param = names.createTempVariable(); out(",function(", param, "){"); if (p.getModel().isLate() && !p.getModel().isVariable()) { generateImmutableAttributeReassignmentCheck("this."+privname, names.name(p)); } out("return this.", privname, "=", param, ";}"); } else { out(",undefined"); } out(","); TypeUtils.encodeForRuntime(node, p.getModel(), this); out(")"); endLine(true); } private ClassOrInterface prototypeOwner; private void addToPrototype(ClassOrInterface d, final Tree.Statement s, List<com.redhat.ceylon.compiler.typechecker.model.Parameter> params) { ClassOrInterface oldPrototypeOwner = prototypeOwner; prototypeOwner = d; if (s instanceof MethodDefinition) { addMethodToPrototype(d, (MethodDefinition)s); } else if (s instanceof MethodDeclaration) { //Don't even bother with nodes that have errors if (errVisitor.hasErrors(s))return; FunctionHelper.methodDeclaration(d, (MethodDeclaration) s, this); } else if (s instanceof AttributeGetterDefinition) { addGetterToPrototype(d, (AttributeGetterDefinition)s); } else if (s instanceof AttributeDeclaration) { AttributeGenerator.addGetterAndSetterToPrototype(d, (AttributeDeclaration) s, this); } else if (s instanceof ClassDefinition) { addClassToPrototype(d, (ClassDefinition) s); } else if (s instanceof InterfaceDefinition) { addInterfaceToPrototype(d, (InterfaceDefinition) s); } else if (s instanceof ObjectDefinition) { addObjectToPrototype(d, (ObjectDefinition) s); } else if (s instanceof ClassDeclaration) { addClassDeclarationToPrototype(d, (ClassDeclaration) s); } else if (s instanceof InterfaceDeclaration) { addInterfaceDeclarationToPrototype(d, (InterfaceDeclaration) s); } else if (s instanceof SpecifierStatement) { addSpecifierToPrototype(d, (SpecifierStatement) s); } else if (s instanceof TypeAliasDeclaration) { addAliasDeclarationToPrototype(d, (TypeAliasDeclaration)s); } //This fixes #231 for prototype style if (params != null && s instanceof Tree.Declaration) { Declaration m = ((Tree.Declaration)s).getDeclarationModel(); for (Iterator<com.redhat.ceylon.compiler.typechecker.model.Parameter> iter = params.iterator(); iter.hasNext();) { com.redhat.ceylon.compiler.typechecker.model.Parameter _p = iter.next(); if (m.getName() != null && m.getName().equals(_p.getName())) { iter.remove(); break; } } } prototypeOwner = oldPrototypeOwner; } void declareSelf(ClassOrInterface d) { out("if(", names.self(d), "===undefined)"); if (d instanceof com.redhat.ceylon.compiler.typechecker.model.Class && d.isAbstract()) { out(getClAlias(), "throwexc(", getClAlias(), "InvocationException$meta$model("); out("\"Cannot instantiate abstract class ", d.getQualifiedNameString(), "\"),'?','?')"); } else { out(names.self(d), "=new "); if (opts.isOptimize() && d.isClassOrInterfaceMember()) { out("this."); } out(names.name(d), ".$$;"); } endLine(); } void instantiateSelf(ClassOrInterface d) { out("var ", names.self(d), "=new "); if (opts.isOptimize() && d.isClassOrInterfaceMember()) { out("this."); } out(names.name(d), ".$$;"); } private void addObjectToPrototype(ClassOrInterface type, final Tree.ObjectDefinition objDef) { TypeGenerator.objectDefinition(objDef, this); Value d = objDef.getDeclarationModel(); Class c = (Class) d.getTypeDeclaration(); out(names.self(type), ".", names.name(c), "=", names.name(c), ";", names.self(type), ".", names.name(c), ".$crtmm$="); TypeUtils.encodeForRuntime(objDef, d, this); endLine(true); } @Override public void visit(final Tree.ObjectDefinition that) { Value d = that.getDeclarationModel(); if (!(opts.isOptimize() && d.isClassOrInterfaceMember())) { TypeGenerator.objectDefinition(that, this); } else { //Don't even bother with nodes that have errors if (errVisitor.hasErrors(that))return; Class c = (Class) d.getTypeDeclaration(); comment(that); outerSelf(d); out(".", names.privateName(d), "="); outerSelf(d); out(".", names.name(c), "()"); endLine(true); } } @Override public void visit(final Tree.ObjectExpression that) { out("function(){"); try { TypeGenerator.defineObject(that, null, that.getSatisfiedTypes(), that.getExtendedType(), that.getClassBody(), null, this); } catch (Exception e) { e.printStackTrace(); } out("}()"); } @Override public void visit(final Tree.MethodDeclaration that) { //Don't even bother with nodes that have errors if (errVisitor.hasErrors(that))return; FunctionHelper.methodDeclaration(null, that, this); } boolean shouldStitch(Declaration d) { return JsCompiler.isCompilingLanguageModule() && d.isNative(); } private File getStitchedFilename(final Declaration d, final String suffix) { String fqn = d.getQualifiedNameString(); if (fqn.startsWith("ceylon.language"))fqn = fqn.substring(15); if (fqn.startsWith("::"))fqn=fqn.substring(2); fqn = fqn.replace('.', '/').replace("::", "/"); return new File(Stitcher.LANGMOD_JS_SRC, fqn + suffix); } /** Reads a file with hand-written snippet and outputs it to the current writer. */ boolean stitchNative(final Declaration d, final Tree.Declaration n) { final File f = getStitchedFilename(d, ".js"); if (f.exists() && f.canRead()) { jsout.outputFile(f); if (d.isClassOrInterfaceMember()) { if (d instanceof Value)return true;//Native values are defined as attributes out(names.self((TypeDeclaration)d.getContainer()), "."); } out(names.name(d), ".$crtmm$="); TypeUtils.encodeForRuntime(d, n.getAnnotationList(), this); endLine(true); return true; } else { if (d instanceof ClassOrInterface==false) { final String err = "REQUIRED NATIVE FILE MISSING FOR " + d.getQualifiedNameString() + " => " + f + ", containing " + names.name(d); System.out.println(err); out("/*", err, "*/"); } return false; } } /** Stitch a snippet of code to initialize type (usually a call to initTypeProto). */ boolean stitchInitializer(TypeDeclaration d) { final File f = getStitchedFilename(d, "$init.js"); if (f.exists() && f.canRead()) { jsout.outputFile(f); return true; } return false; } boolean stitchConstructorHelper(final Tree.ClassOrInterface coi, final String partName) { final File f; if (JsCompiler.isCompilingLanguageModule()) { f = getStitchedFilename(coi.getDeclarationModel(), partName + ".js"); } else { f = new File(new File(coi.getUnit().getFullPath()).getParentFile(), String.format("%s%s.js", names.name(coi.getDeclarationModel()), partName)); } if (f.exists() && f.isFile() && f.canRead()) { if (opts.isVerbose() || JsCompiler.isCompilingLanguageModule()) { System.out.println("Stitching in " + f + ". It must contain an anonymous function " + "which will be invoked with the same arguments as the " + names.name(coi.getDeclarationModel()) + " constructor."); } out("("); jsout.outputFile(f); out(")"); TypeGenerator.generateParameters(coi.getTypeParameterList(), coi instanceof Tree.ClassDefinition ? ((Tree.ClassDefinition)coi).getParameterList() : null, coi.getDeclarationModel(), this); endLine(true); } return false; } @Override public void visit(final Tree.MethodDefinition that) { //Don't even bother with nodes that have errors if (errVisitor.hasErrors(that))return; final Method d = that.getDeclarationModel(); if (!((opts.isOptimize() && d.isClassOrInterfaceMember()) || isNative(d))) { comment(that); initDefaultedParameters(that.getParameterLists().get(0), d); FunctionHelper.methodDefinition(that, this, true); //Add reference to metamodel out(names.name(d), ".$crtmm$="); TypeUtils.encodeForRuntime(d, that.getAnnotationList(), this); endLine(true); } } /** Get the specifier expression for a Parameter, if one is available. */ private SpecifierOrInitializerExpression getDefaultExpression(final Tree.Parameter param) { final SpecifierOrInitializerExpression expr; if (param instanceof ParameterDeclaration || param instanceof InitializerParameter) { MethodDeclaration md = null; if (param instanceof ParameterDeclaration) { TypedDeclaration td = ((ParameterDeclaration) param).getTypedDeclaration(); if (td instanceof AttributeDeclaration) { expr = ((AttributeDeclaration) td).getSpecifierOrInitializerExpression(); } else if (td instanceof MethodDeclaration) { md = (MethodDeclaration)td; expr = md.getSpecifierExpression(); } else { param.addUnexpectedError("Don't know what to do with TypedDeclaration " + td.getClass().getName()); expr = null; } } else { expr = ((InitializerParameter) param).getSpecifierExpression(); } } else { param.addUnexpectedError("Don't know what to do with defaulted/sequenced param " + param); expr = null; } return expr; } /** Create special functions with the expressions for defaulted parameters in a parameter list. */ void initDefaultedParameters(final Tree.ParameterList params, Method container) { if (!container.isMember())return; for (final Parameter param : params.getParameters()) { com.redhat.ceylon.compiler.typechecker.model.Parameter pd = param.getParameterModel(); if (pd.isDefaulted()) { final SpecifierOrInitializerExpression expr = getDefaultExpression(param); if (expr == null) { continue; } qualify(params, container); out(names.name(container), "$defs$", pd.getName(), "=function"); params.visit(this); out("{"); initSelf(expr); out("return "); if (param instanceof ParameterDeclaration && ((ParameterDeclaration)param).getTypedDeclaration() instanceof MethodDeclaration) { // function parameter defaulted using "=>" FunctionHelper.singleExprFunction( ((MethodDeclaration)((ParameterDeclaration)param).getTypedDeclaration()).getParameterLists(), expr.getExpression(), null, true, true, this); } else if (!isNaturalLiteral(expr.getExpression().getTerm())) { expr.visit(this); } out(";}"); endLine(true); } } } /** Initialize the sequenced, defaulted and captured parameters in a type declaration. */ void initParameters(final Tree.ParameterList params, TypeDeclaration typeDecl, Method m) { for (final Parameter param : params.getParameters()) { com.redhat.ceylon.compiler.typechecker.model.Parameter pd = param.getParameterModel(); final String paramName = names.name(pd); if (pd.isDefaulted() || pd.isSequenced()) { out("if(", paramName, "===undefined){", paramName, "="); if (pd.isDefaulted()) { if (m !=null && m.isMember()) { qualify(params, m); out(names.name(m), "$defs$", pd.getName(), "("); boolean firstParam=true; for (com.redhat.ceylon.compiler.typechecker.model.Parameter p : m.getParameterLists().get(0).getParameters()) { if (firstParam){firstParam=false;}else out(","); out(names.name(p)); } out(")"); } else { final SpecifierOrInitializerExpression expr = getDefaultExpression(param); if (expr == null) { param.addUnexpectedError("Default expression missing for " + pd.getName()); out("null"); } else if (param instanceof ParameterDeclaration && ((ParameterDeclaration)param).getTypedDeclaration() instanceof MethodDeclaration) { // function parameter defaulted using "=>" FunctionHelper.singleExprFunction( ((MethodDeclaration)((ParameterDeclaration)param).getTypedDeclaration()).getParameterLists(), expr.getExpression(), m, true, true, this); } else { expr.visit(this); } } } else { out(getClAlias(), "getEmpty()"); } out(";}"); endLine(); } if ((typeDecl != null) && pd.getModel().isCaptured()) { out(names.self(typeDecl), ".", paramName, "_=", paramName); if (!opts.isOptimize() && pd.isHidden()) { //belt and suspenders... out(";", names.self(typeDecl), ".", paramName, "=", paramName); } endLine(true); } } } private void addMethodToPrototype(TypeDeclaration outer, final Tree.MethodDefinition that) { //Don't even bother with nodes that have errors if (errVisitor.hasErrors(that))return; Method d = that.getDeclarationModel(); if (!opts.isOptimize()||!d.isClassOrInterfaceMember()) return; comment(that); initDefaultedParameters(that.getParameterLists().get(0), d); out(names.self(outer), ".", names.name(d), "="); FunctionHelper.methodDefinition(that, this, false); //Add reference to metamodel out(names.self(outer), ".", names.name(d), ".$crtmm$="); TypeUtils.encodeForRuntime(d, that.getAnnotationList(), this); endLine(true); } @Override public void visit(final Tree.AttributeGetterDefinition that) { Value d = that.getDeclarationModel(); if (opts.isOptimize()&&d.isClassOrInterfaceMember()) return; comment(that); if (defineAsProperty(d)) { defineAttribute(names.self((TypeDeclaration)d.getContainer()), names.name(d)); AttributeGenerator.getter(that, this); final AttributeSetterDefinition setterDef = associatedSetterDefinition(d); if (setterDef == null) { out(",undefined"); } else { out(",function(", names.name(setterDef.getDeclarationModel().getParameter()), ")"); AttributeGenerator.setter(setterDef, this); } out(","); TypeUtils.encodeForRuntime(d, that.getAnnotationList(), this); if (setterDef != null) { out(","); TypeUtils.encodeForRuntime(setterDef.getDeclarationModel(), setterDef.getAnnotationList(), this); } out(");"); } else { out(function, names.getter(d), "()"); AttributeGenerator.getter(that, this); endLine(); out(names.getter(d), ".$crtmm$="); TypeUtils.encodeForRuntime(that, d, this); if (!shareGetter(d)) { out(";"); } generateAttributeMetamodel(that, true, false); } } private void addGetterToPrototype(TypeDeclaration outer, final Tree.AttributeGetterDefinition that) { Value d = that.getDeclarationModel(); if (!opts.isOptimize()||!d.isClassOrInterfaceMember()) return; comment(that); defineAttribute(names.self(outer), names.name(d)); AttributeGenerator.getter(that, this); final AttributeSetterDefinition setterDef = associatedSetterDefinition(d); if (setterDef == null) { out(",undefined"); } else { out(",function(", names.name(setterDef.getDeclarationModel().getParameter()), ")"); AttributeGenerator.setter(setterDef, this); } out(","); TypeUtils.encodeForRuntime(d, that.getAnnotationList(), this); if (setterDef != null) { out(","); TypeUtils.encodeForRuntime(setterDef.getDeclarationModel(), setterDef.getAnnotationList(), this); } out(");"); } Tree.AttributeSetterDefinition associatedSetterDefinition( final Value valueDecl) { final Setter setter = valueDecl.getSetter(); if ((setter != null) && (currentStatements != null)) { for (Statement stmt : currentStatements) { if (stmt instanceof AttributeSetterDefinition) { final AttributeSetterDefinition setterDef = (AttributeSetterDefinition) stmt; if (setterDef.getDeclarationModel() == setter) { return setterDef; } } } } return null; } /** Exports a getter function; useful in non-prototype style. */ boolean shareGetter(final MethodOrValue d) { boolean shared = false; if (isCaptured(d)) { beginNewLine(); outerSelf(d); out(".", names.getter(d), "=", names.getter(d)); endLine(true); shared = true; } return shared; } @Override public void visit(final Tree.AttributeSetterDefinition that) { Setter d = that.getDeclarationModel(); if ((opts.isOptimize()&&d.isClassOrInterfaceMember()) || defineAsProperty(d)) return; comment(that); out("function ", names.setter(d.getGetter()), "(", names.name(d.getParameter()), ")"); AttributeGenerator.setter(that, this); if (!shareSetter(d)) { out(";"); } if (!d.isToplevel())outerSelf(d); out(names.setter(d.getGetter()), ".$crtmm$="); TypeUtils.encodeForRuntime(d, that.getAnnotationList(), this); endLine(true); generateAttributeMetamodel(that, false, true); } boolean isCaptured(Declaration d) { if (d.isToplevel()||d.isClassOrInterfaceMember()) { //TODO: what about things nested inside control structures if (d.isShared() || d.isCaptured() ) { return true; } else { OuterVisitor ov = new OuterVisitor(d); ov.visit(root); return ov.found; } } else { return false; } } boolean shareSetter(final MethodOrValue d) { boolean shared = false; if (isCaptured(d)) { beginNewLine(); outerSelf(d); out(".", names.setter(d), "=", names.setter(d)); endLine(true); shared = true; } return shared; } @Override public void visit(final Tree.AttributeDeclaration that) { final Value d = that.getDeclarationModel(); //Check if the attribute corresponds to a class parameter //This is because of the new initializer syntax final com.redhat.ceylon.compiler.typechecker.model.Parameter param = d.isParameter() ? ((Functional)d.getContainer()).getParameter(d.getName()) : null; final boolean asprop = defineAsProperty(d); if (d.isFormal()) { if (!opts.isOptimize()) { generateAttributeMetamodel(that, false, false); } } else { comment(that); SpecifierOrInitializerExpression specInitExpr = that.getSpecifierOrInitializerExpression(); final boolean addGetter = (specInitExpr != null) || (param != null) || !d.isMember() || d.isVariable() || d.isLate(); final boolean addSetter = (d.isVariable() || d.isLate()) && !asprop; if (opts.isOptimize() && d.isClassOrInterfaceMember()) { if ((specInitExpr != null && !(specInitExpr instanceof LazySpecifierExpression)) || d.isLate()) { outerSelf(d); out(".", names.privateName(d), "="); if (d.isLate()) { out("undefined"); } else { super.visit(that); } endLine(true); } } else if (specInitExpr instanceof LazySpecifierExpression) { if (asprop) { defineAttribute(names.self((TypeDeclaration)d.getContainer()), names.name(d)); out("{"); } else { out(function, names.getter(d), "(){"); } initSelf(that); out("return "); if (!isNaturalLiteral(specInitExpr.getExpression().getTerm())) { int boxType = boxStart(specInitExpr.getExpression().getTerm()); specInitExpr.getExpression().visit(this); if (boxType == 4) out("/*TODO: callable targs 1*/"); boxUnboxEnd(boxType); } out(";}"); if (asprop) { Tree.AttributeSetterDefinition setterDef = null; if (d.isVariable()) { setterDef = associatedSetterDefinition(d); if (setterDef != null) { out(",function(", names.name(setterDef.getDeclarationModel().getParameter()), ")"); AttributeGenerator.setter(setterDef, this); } } if (setterDef == null) { out(",undefined"); } out(","); TypeUtils.encodeForRuntime(d, that.getAnnotationList(), this); if (setterDef != null) { out(","); TypeUtils.encodeForRuntime(setterDef.getDeclarationModel(), setterDef.getAnnotationList(), this); } out(")"); endLine(true); } else { endLine(true); shareGetter(d); } } else { if (addGetter) { AttributeGenerator.generateAttributeGetter(that, d, specInitExpr, names.name(param), this, directAccess); } if (addSetter) { AttributeGenerator.generateAttributeSetter(that, d, this); } } boolean addMeta=!opts.isOptimize() || d.isToplevel(); if (!d.isToplevel()) { addMeta |= Util.getContainingDeclaration(d).isAnonymous(); } if (addMeta) { generateAttributeMetamodel(that, addGetter, addSetter); } } } /** Generate runtime metamodel info for an attribute declaration or definition. */ void generateAttributeMetamodel(final Tree.TypedDeclaration that, final boolean addGetter, final boolean addSetter) { //No need to define all this for local values Scope _scope = that.getScope(); while (_scope != null) { //TODO this is bound to change for local decl metamodel if (_scope instanceof Declaration) { if (_scope instanceof Method)return; else break; } _scope = _scope.getContainer(); } Declaration d = that.getDeclarationModel(); if (d instanceof Setter) d = ((Setter)d).getGetter(); final String pname = names.getter(d); if (!generatedAttributes.contains(d)) { if (d.isToplevel()) { out("var "); } else if (outerSelf(d)) { out("."); } //issue 297 this is only needed in some cases out("$prop$", pname, "={$crtmm$:"); TypeUtils.encodeForRuntime(d, that.getAnnotationList(), this); out("}"); endLine(true); if (d.isToplevel()) { out("ex$.$prop$", pname, "=$prop$", pname); endLine(true); } generatedAttributes.add(d); } if (addGetter) { if (!d.isToplevel()) { if (outerSelf(d))out("."); } out("$prop$", pname, ".get="); if (isCaptured(d) && !defineAsProperty(d)) { out(pname); endLine(true); out(pname, ".$crtmm$=$prop$", pname, ".$crtmm$"); } else { out("function(){return ", names.name(d), "}"); } endLine(true); } if (addSetter) { final String pset = names.setter(d instanceof Setter ? ((Setter)d).getGetter() : d); if (!d.isToplevel()) { if (outerSelf(d))out("."); } out("$prop$", pname, ".set=", pset); endLine(true); out("if(", pset, ".$crtmm$===undefined)", pset, ".$crtmm$=$prop$", pname, ".$crtmm$"); endLine(true); } } void generateUnitializedAttributeReadCheck(String privname, String pubname) { //TODO we can later optimize this, to replace this getter with the plain one //once the value has been defined out("if(", privname, "===undefined)throw ", getClAlias(), "InitializationError('Attempt to read unitialized attribute «", pubname, "»');"); } void generateImmutableAttributeReassignmentCheck(String privname, String pubname) { out("if(", privname, "!==undefined)throw ", getClAlias(), "InitializationError('Attempt to reassign immutable attribute «", pubname, "»');"); } @Override public void visit(final Tree.CharLiteral that) { out(getClAlias(), "Character("); out(String.valueOf(that.getText().codePointAt(1))); out(",true)"); } /** Escapes a StringLiteral (needs to be quoted). */ String escapeStringLiteral(String s) { StringBuilder text = new StringBuilder(s); //Escape special chars for (int i=0; i < text.length();i++) { switch(text.charAt(i)) { case 8:text.replace(i, i+1, "\\b"); i++; break; case 9:text.replace(i, i+1, "\\t"); i++; break; case 10:text.replace(i, i+1, "\\n"); i++; break; case 12:text.replace(i, i+1, "\\f"); i++; break; case 13:text.replace(i, i+1, "\\r"); i++; break; case 34:text.replace(i, i+1, "\\\""); i++; break; case 39:text.replace(i, i+1, "\\'"); i++; break; case 92:text.replace(i, i+1, "\\\\"); i++; break; case 0x2028:text.replace(i, i+1, "\\u2028"); i++; break; case 0x2029:text.replace(i, i+1, "\\u2029"); i++; break; } } return text.toString(); } @Override public void visit(final Tree.StringLiteral that) { out("\"", escapeStringLiteral(that.getText()), "\""); } @Override public void visit(final Tree.StringTemplate that) { //TODO optimize to avoid generating initial "" and final .plus("") List<StringLiteral> literals = that.getStringLiterals(); List<Expression> exprs = that.getExpressions(); for (int i = 0; i < literals.size(); i++) { StringLiteral literal = literals.get(i); literal.visit(this); if (i>0)out(")"); if (i < exprs.size()) { out(".plus("); final Expression expr = exprs.get(i); expr.visit(this); if (expr.getTypeModel() == null || !"ceylon.language::String".equals(expr.getTypeModel().getProducedTypeQualifiedName())) { out(".string"); } out(").plus("); } } } @Override public void visit(final Tree.FloatLiteral that) { out(getClAlias(), "Float(", that.getText(), ")"); } public long parseNaturalLiteral(Tree.NaturalLiteral that) throws NumberFormatException { char prefix = that.getText().charAt(0); int radix = 10; String nt = that.getText(); if (prefix == '$' || prefix == '#') { radix = prefix == '$' ? 2 : 16; nt = nt.substring(1); } return new java.math.BigInteger(nt, radix).longValue(); } @Override public void visit(final Tree.NaturalLiteral that) { try { out("(", Long.toString(parseNaturalLiteral(that)), ")"); } catch (NumberFormatException ex) { that.addError("Invalid numeric literal " + that.getText()); } } @Override public void visit(final Tree.This that) { out(names.self(Util.getContainingClassOrInterface(that.getScope()))); } @Override public void visit(final Tree.Super that) { out(names.self(Util.getContainingClassOrInterface(that.getScope()))); } @Override public void visit(final Tree.Outer that) { boolean outer = false; if (opts.isOptimize()) { Scope scope = that.getScope(); while ((scope != null) && !(scope instanceof TypeDeclaration)) { scope = scope.getContainer(); } if (scope != null && ((TypeDeclaration)scope).isClassOrInterfaceMember()) { out(names.self((TypeDeclaration) scope), "."); outer = true; } } if (outer) { out("outer$"); } else { out(names.self(that.getTypeModel().getDeclaration())); } } @Override public void visit(final Tree.BaseMemberExpression that) { BmeGenerator.generateBme(that, this, false); } /** Tells whether a declaration can be accessed directly (using its name) or * through its getter. */ boolean accessDirectly(Declaration d) { return !accessThroughGetter(d) || directAccess.contains(d) || d.isParameter(); } private boolean accessThroughGetter(Declaration d) { return (d instanceof MethodOrValue) && !(d instanceof Method) && !defineAsProperty(d); } boolean defineAsProperty(Declaration d) { // for now, only define member attributes as properties, not toplevel attributes return d.isMember() && d instanceof MethodOrValue && !(d instanceof Method); } /** Returns true if the top-level declaration for the term is annotated "nativejs" */ static boolean isNative(final Tree.Term t) { if (t instanceof MemberOrTypeExpression) { return isNative(((MemberOrTypeExpression)t).getDeclaration()); } return false; } /** Returns true if the declaration is annotated "nativejs" */ static boolean isNative(Declaration d) { return hasAnnotationByName(getToplevel(d), "nativejs") || TypeUtils.isUnknown(d); } private static Declaration getToplevel(Declaration d) { while (d != null && !d.isToplevel()) { Scope s = d.getContainer(); // Skip any non-declaration elements while (s != null && !(s instanceof Declaration)) { s = s.getContainer(); } d = (Declaration) s; } return d; } private static boolean hasAnnotationByName(Declaration d, String name){ if (d != null) { for(com.redhat.ceylon.compiler.typechecker.model.Annotation annotation : d.getAnnotations()){ if(annotation.getName().equals(name)) return true; } } return false; } private void generateSafeOp(final Tree.QualifiedMemberOrTypeExpression that) { boolean isMethod = that.getDeclaration() instanceof Method; String lhsVar = createRetainedTempVar(); out("(", lhsVar, "="); super.visit(that); out(","); if (isMethod) { out(getClAlias(), "JsCallable(", lhsVar, ","); } out(getClAlias(),"nn$(", lhsVar, ")?"); if (isMethod && !((Method)that.getDeclaration()).getTypeParameters().isEmpty()) { //Method ref with type parameters BmeGenerator.printGenericMethodReference(this, that, lhsVar, memberAccess(that, lhsVar)); } else { out(memberAccess(that, lhsVar)); } out(":null)"); if (isMethod) { out(")"); } } void supervisit(final Tree.QualifiedMemberOrTypeExpression that) { super.visit(that); } @Override public void visit(final Tree.QualifiedMemberExpression that) { //Big TODO: make sure the member is actually // refined by the current class! if (that.getMemberOperator() instanceof SafeMemberOp) { generateSafeOp(that); } else if (that.getMemberOperator() instanceof SpreadOp) { SequenceGenerator.generateSpread(that, this); } else if (that.getDeclaration() instanceof Method && that.getSignature() == null) { //TODO right now this causes that all method invocations are done this way //we need to filter somehow to only use this pattern when the result is supposed to be a callable //looks like checking for signature is a good way (not THE way though; named arg calls don't have signature) generateCallable(that, null); } else if (that.getStaticMethodReference() && that.getDeclaration()!=null) { out("function($O$) {return "); if (that.getDeclaration() instanceof Method) { if (BmeGenerator.hasTypeParameters(that)) { BmeGenerator.printGenericMethodReference(this, that, "$O$", "$O$."+names.name(that.getDeclaration())); } else { out(getClAlias(), "JsCallable($O$,$O$.", names.name(that.getDeclaration()), ")"); } out(";}"); } else { out("$O$.", names.name(that.getDeclaration()), ";}"); } } else { final String lhs = generateToString(new GenerateCallback() { @Override public void generateValue() { GenerateJsVisitor.super.visit(that); } }); out(memberAccess(that, lhs)); } } private void generateCallable(final Tree.QualifiedMemberOrTypeExpression that, String name) { if (that.getPrimary() instanceof Tree.BaseTypeExpression) { //it's a static method ref if (name == null) { name = memberAccess(that, ""); } out("function(x){return "); if (BmeGenerator.hasTypeParameters(that)) { BmeGenerator.printGenericMethodReference(this, that, "x", "x."+name); } else { out(getClAlias(), "JsCallable(x,x.", name, ")"); } out(";}"); return; } final Declaration d = that.getDeclaration(); if (d.isToplevel() && d instanceof Method) { //Just output the name out(names.name(d)); return; } String primaryVar = createRetainedTempVar(); out("(", primaryVar, "="); that.getPrimary().visit(this); out(","); final String member = (name == null) ? memberAccess(that, primaryVar) : (primaryVar+"."+name); if (that.getDeclaration() instanceof Method && !((Method)that.getDeclaration()).getTypeParameters().isEmpty()) { //Method ref with type parameters BmeGenerator.printGenericMethodReference(this, that, primaryVar, member); } else { out(getClAlias(), "JsCallable(", primaryVar, ",", getClAlias(), "nn$(", primaryVar, ")?", member, ":null)"); } out(")"); } /** * Checks if the given node is a MemberOrTypeExpression or QualifiedType which * represents an access to a supertype member and returns the scope of that * member or null. */ Scope getSuperMemberScope(Node node) { Scope scope = null; if (node instanceof QualifiedMemberOrTypeExpression) { // Check for "super.member" QualifiedMemberOrTypeExpression qmte = (QualifiedMemberOrTypeExpression) node; final Term primary = eliminateParensAndWidening(qmte.getPrimary()); if (primary instanceof Super) { scope = qmte.getDeclaration().getContainer(); } } else if (node instanceof QualifiedType) { // Check for super.Membertype QualifiedType qtype = (QualifiedType) node; if (qtype.getOuterType() instanceof SuperType) { scope = qtype.getDeclarationModel().getContainer(); } } return scope; } String getMember(Node node, Declaration decl, String lhs) { final StringBuilder sb = new StringBuilder(); if (lhs != null) { if (lhs.length() > 0) { sb.append(lhs); } } else if (node instanceof BaseMemberOrTypeExpression) { BaseMemberOrTypeExpression bmte = (BaseMemberOrTypeExpression) node; Declaration bmd = bmte.getDeclaration(); if (bmd.isParameter() && bmd.getContainer() instanceof ClassAlias) { return names.name(bmd); } String path = qualifiedPath(node, bmd); if (path.length() > 0) { sb.append(path); } } return sb.toString(); } String memberAccessBase(Node node, Declaration decl, boolean setter, String lhs) { final StringBuilder sb = new StringBuilder(getMember(node, decl, lhs)); if (sb.length() > 0) { if (node instanceof BaseMemberOrTypeExpression) { Declaration bmd = ((BaseMemberOrTypeExpression)node).getDeclaration(); if (bmd.isParameter() && bmd.getContainer() instanceof ClassAlias) { return sb.toString(); } } sb.append('.'); } Scope scope = getSuperMemberScope(node); if (opts.isOptimize() && (scope != null)) { sb.append("getT$all()['"); sb.append(scope.getQualifiedNameString()); sb.append("']"); if (defineAsProperty(decl)) { return getClAlias() + (setter ? "attrSetter(" : "attrGetter(") + sb.toString() + ",'" + names.name(decl) + "')"; } sb.append(".$$.prototype."); } final String member = (accessThroughGetter(decl) && !accessDirectly(decl)) ? (setter ? names.setter(decl) : names.getter(decl)) : names.name(decl); sb.append(member); if (!opts.isOptimize() && (scope != null)) { sb.append(names.scopeSuffix(scope)); } return sb.toString(); } /** * Returns a string representing a read access to a member, as represented by * the given expression. If lhs==null and the expression is a BaseMemberExpression * then the qualified path is prepended. */ String memberAccess(final Tree.StaticMemberOrTypeExpression expr, String lhs) { Declaration decl = expr.getDeclaration(); String plainName = null; if (decl == null && dynblock > 0) { plainName = expr.getIdentifier().getText(); } else if (isNative(decl)) { // direct access to a native element plainName = decl.getName(); } if (plainName != null) { return ((lhs != null) && (lhs.length() > 0)) ? (lhs + "." + plainName) : plainName; } boolean protoCall = opts.isOptimize() && (getSuperMemberScope(expr) != null); if (accessDirectly(decl) && !(protoCall && defineAsProperty(decl))) { // direct access, without getter return memberAccessBase(expr, decl, false, lhs); } // access through getter return memberAccessBase(expr, decl, false, lhs) + (protoCall ? ".call(this)" : "()"); } @Override public void visit(final Tree.BaseTypeExpression that) { Declaration d = that.getDeclaration(); if (d == null && isInDynamicBlock()) { //It's a native js type but will be wrapped in dyntype() call String id = that.getIdentifier().getText(); out("(typeof ", id, "==='undefined'?"); generateThrow(null, "Undefined type " + id, that); out(":", id, ")"); } else { qualify(that, d); out(names.name(d)); } } @Override public void visit(final Tree.QualifiedTypeExpression that) { if (that.getMemberOperator() instanceof SafeMemberOp) { generateCallable(that, names.name(that.getDeclaration())); } else { super.visit(that); if (isInDynamicBlock() && that.getDeclaration() == null) { out(".", that.getIdentifier().getText()); } else { out(".", names.name(that.getDeclaration())); } } } public void visit(final Tree.Dynamic that) { invoker.nativeObject(that.getNamedArgumentList()); } @Override public void visit(final Tree.InvocationExpression that) { invoker.generateInvocation(that); } @Override public void visit(final Tree.PositionalArgumentList that) { invoker.generatePositionalArguments(null, that, that.getPositionalArguments(), false, false); } /** Box a term, visit it, unbox it. */ void box(final Tree.Term term) { final int t = boxStart(term); term.visit(this); if (t == 4) out("/*TODO: callable targs 4*/"); boxUnboxEnd(t); } // Make sure fromTerm is compatible with toTerm by boxing it when necessary int boxStart(final Tree.Term fromTerm) { return boxUnboxStart(fromTerm, false); } // Make sure fromTerm is compatible with toTerm by boxing or unboxing it when necessary int boxUnboxStart(final Tree.Term fromTerm, final Tree.Term toTerm) { return boxUnboxStart(fromTerm, isNative(toTerm)); } // Make sure fromTerm is compatible with toDecl by boxing or unboxing it when necessary int boxUnboxStart(final Tree.Term fromTerm, com.redhat.ceylon.compiler.typechecker.model.TypedDeclaration toDecl) { return boxUnboxStart(fromTerm, isNative(toDecl)); } int boxUnboxStart(final Tree.Term fromTerm, boolean toNative) { // Box the value final boolean fromNative = isNative(fromTerm); final ProducedType fromType = fromTerm.getTypeModel(); final String fromTypeName = Util.isTypeUnknown(fromType) ? "UNKNOWN" : fromType.getProducedTypeQualifiedName(); if (fromNative != toNative || fromTypeName.startsWith("ceylon.language::Callable<")) { if (fromNative) { // conversion from native value to Ceylon value if (fromTypeName.equals("ceylon.language::Integer")) { out("("); } else if (fromTypeName.equals("ceylon.language::Float")) { out(getClAlias(), "Float("); } else if (fromTypeName.equals("ceylon.language::Boolean")) { out("("); } else if (fromTypeName.equals("ceylon.language::Character")) { out(getClAlias(), "Character("); } else if (fromTypeName.startsWith("ceylon.language::Callable<")) { out(getClAlias(), "$JsCallable("); return 4; } else { return 0; } return 1; } else if ("ceylon.language::Float".equals(fromTypeName)) { // conversion from Ceylon Float to native value return 2; } else if (fromTypeName.startsWith("ceylon.language::Callable<")) { Term _t = fromTerm; if (_t instanceof Tree.InvocationExpression) { _t = ((Tree.InvocationExpression)_t).getPrimary(); } //Don't box callables if they're not members or anonymous if (_t instanceof Tree.MemberOrTypeExpression) { final Declaration d = ((Tree.MemberOrTypeExpression)_t).getDeclaration(); if (d != null && !(d.isClassOrInterfaceMember() || d.isAnonymous())) { return 0; } } out(getClAlias(), "$JsCallable("); return 4; } else { return 3; } } return 0; } void boxUnboxEnd(int boxType) { switch (boxType) { case 1: out(")"); break; case 2: out(".valueOf()"); break; case 4: out(")"); break; default: //nothing } } @Override public void visit(final Tree.ObjectArgument that) { if (errVisitor.hasErrors(that))return; FunctionHelper.objectArgument(that, this); } @Override public void visit(final Tree.AttributeArgument that) { if (errVisitor.hasErrors(that))return; FunctionHelper.attributeArgument(that, this); } @Override public void visit(final Tree.SequencedArgument that) { if (errVisitor.hasErrors(that))return; SequenceGenerator.sequencedArgument(that, this); } @Override public void visit(final Tree.SequenceEnumeration that) { if (errVisitor.hasErrors(that))return; SequenceGenerator.sequenceEnumeration(that, this); } @Override public void visit(final Tree.Comprehension that) { new ComprehensionGenerator(this, names, directAccess).generateComprehension(that); } @Override public void visit(final Tree.SpecifierStatement that) { // A lazy specifier expression in a class/interface should go into the // prototype in prototype style, so don't generate them here. if (!(opts.isOptimize() && (that.getSpecifierExpression() instanceof LazySpecifierExpression) && (that.getScope().getContainer() instanceof TypeDeclaration))) { specifierStatement(null, that); } } private void specifierStatement(final TypeDeclaration outer, final Tree.SpecifierStatement specStmt) { final Tree.Expression expr = specStmt.getSpecifierExpression().getExpression(); final Tree.Term term = specStmt.getBaseMemberExpression(); final Tree.StaticMemberOrTypeExpression smte = term instanceof Tree.StaticMemberOrTypeExpression ? (Tree.StaticMemberOrTypeExpression)term : null; if (dynblock > 0 && Util.isTypeUnknown(term.getTypeModel())) { if (smte != null && smte.getDeclaration() == null) { out(smte.getIdentifier().getText()); } else { term.visit(this); } out("="); int box = boxUnboxStart(expr, term); expr.visit(this); if (box == 4) out("/*TODO: callable targs 6*/"); boxUnboxEnd(box); out(";"); return; } if (smte != null) { Declaration bmeDecl = smte.getDeclaration(); if (specStmt.getSpecifierExpression() instanceof LazySpecifierExpression) { // attr => expr; final boolean property = defineAsProperty(bmeDecl); if (property) { defineAttribute(qualifiedPath(specStmt, bmeDecl), names.name(bmeDecl)); } else { if (bmeDecl.isMember()) { qualify(specStmt, bmeDecl); } else { out ("var "); } out(names.getter(bmeDecl), "=function()"); } beginBlock(); if (outer != null) { initSelf(specStmt); } out ("return "); if (!isNaturalLiteral(specStmt.getSpecifierExpression().getExpression().getTerm())) { specStmt.getSpecifierExpression().visit(this); } out(";"); endBlock(); if (property) { out(",undefined,"); TypeUtils.encodeForRuntime(specStmt, bmeDecl, this); out(")"); } endLine(true); directAccess.remove(bmeDecl); } else if (outer != null) { // "attr = expr;" in a prototype definition //since #451 we now generate an attribute here if (bmeDecl.isMember() && (bmeDecl instanceof Value) && bmeDecl.isActual()) { Value vdec = (Value)bmeDecl; final String atname = bmeDecl.isShared() ? names.name(bmeDecl)+"_" : names.privateName(bmeDecl); defineAttribute(names.self(outer), names.name(bmeDecl)); out("{"); if (vdec.isLate()) { generateUnitializedAttributeReadCheck("this."+atname, names.name(bmeDecl)); } out("return this.", atname, ";}"); if (vdec.isVariable() || vdec.isLate()) { final String par = getNames().createTempVariable(); out(",function(", par, "){"); if (vdec.isLate()) { generateImmutableAttributeReassignmentCheck("this."+atname, names.name(bmeDecl)); } out("return this.", atname, "=", par, ";}"); } else { out(",undefined"); } out(","); TypeUtils.encodeForRuntime(expr, bmeDecl, this); out(")"); endLine(true); } } else if (bmeDecl instanceof MethodOrValue) { // "attr = expr;" in an initializer or method final MethodOrValue moval = (MethodOrValue)bmeDecl; if (moval.isVariable()) { // simple assignment to a variable attribute BmeGenerator.generateMemberAccess(smte, new GenerateCallback() { @Override public void generateValue() { int boxType = boxUnboxStart(expr.getTerm(), moval); if (dynblock > 0 && !Util.isTypeUnknown(moval.getType()) && Util.isTypeUnknown(expr.getTypeModel())) { TypeUtils.generateDynamicCheck(expr, moval.getType(), GenerateJsVisitor.this, false, expr.getTypeModel().getTypeArguments()); } else { expr.visit(GenerateJsVisitor.this); } if (boxType == 4) { out(","); if (moval instanceof Method) { //Add parameters TypeUtils.encodeParameterListForRuntime(specStmt, ((Method)moval).getParameterLists().get(0), GenerateJsVisitor.this); out(","); } else { //TODO extract parameters from Value out("[/*VALUE Callable params", moval.getClass().getName(), "*/],"); } TypeUtils.printTypeArguments(expr, expr.getTypeModel().getTypeArguments(), GenerateJsVisitor.this, false, expr.getTypeModel().getVarianceOverrides()); } boxUnboxEnd(boxType); } }, qualifiedPath(smte, moval), this); out(";"); } else if (moval.isMember()) { if (moval instanceof Method) { //same as fat arrow qualify(specStmt, bmeDecl); out(names.name(moval), "=function ", names.name(moval), "("); //Build the parameter list, we'll use it several times final StringBuilder paramNames = new StringBuilder(); final List<com.redhat.ceylon.compiler.typechecker.model.Parameter> params = ((Method) moval).getParameterLists().get(0).getParameters(); for (com.redhat.ceylon.compiler.typechecker.model.Parameter p : params) { if (paramNames.length() > 0) paramNames.append(","); paramNames.append(names.name(p)); } out(paramNames.toString()); out("){"); for (com.redhat.ceylon.compiler.typechecker.model.Parameter p : params) { if (p.isDefaulted()) { out("if(", names.name(p), "===undefined)", names.name(p),"="); qualify(specStmt, moval); out(names.name(moval), "$defs$", p.getName(), "(", paramNames.toString(), ")"); endLine(true); } } out("return "); if (!isNaturalLiteral(specStmt.getSpecifierExpression().getExpression().getTerm())) { specStmt.getSpecifierExpression().visit(this); } out("(", paramNames.toString(), ");}"); endLine(true); } else { // Specifier for a member attribute. This actually defines the // member (e.g. in shortcut refinement syntax the attribute // declaration itself can be omitted), so generate the attribute. if (opts.isOptimize()) { //#451 out(names.self(Util.getContainingClassOrInterface(moval.getScope())), ".", names.name(moval)); if (!(moval.isVariable() || moval.isLate())) { out("_"); } out("="); specStmt.getSpecifierExpression().visit(this); endLine(true); } else { AttributeGenerator.generateAttributeGetter(null, moval, specStmt.getSpecifierExpression(), null, this, directAccess); } } } else { // Specifier for some other attribute, or for a method. if (opts.isOptimize() || (bmeDecl.isMember() && (bmeDecl instanceof Method))) { qualify(specStmt, bmeDecl); } out(names.name(bmeDecl), "="); if (dynblock > 0 && Util.isTypeUnknown(expr.getTypeModel()) && !Util.isTypeUnknown(((MethodOrValue) bmeDecl).getType())) { TypeUtils.generateDynamicCheck(expr, ((MethodOrValue) bmeDecl).getType(), this, false, expr.getTypeModel().getTypeArguments()); } else { specStmt.getSpecifierExpression().visit(this); } out(";"); } } } else if ((term instanceof ParameterizedExpression) && (specStmt.getSpecifierExpression() != null)) { final ParameterizedExpression paramExpr = (ParameterizedExpression)term; if (paramExpr.getPrimary() instanceof BaseMemberExpression) { // func(params) => expr; final BaseMemberExpression bme2 = (BaseMemberExpression) paramExpr.getPrimary(); final Declaration bmeDecl = bme2.getDeclaration(); if (bmeDecl.isMember()) { qualify(specStmt, bmeDecl); } else { out("var "); } out(names.name(bmeDecl), "="); FunctionHelper.singleExprFunction(paramExpr.getParameterLists(), expr, bmeDecl instanceof Scope ? (Scope)bmeDecl : null, true, true, this); out(";"); } } } private void addSpecifierToPrototype(final TypeDeclaration outer, final Tree.SpecifierStatement specStmt) { specifierStatement(outer, specStmt); } @Override public void visit(final AssignOp that) { String returnValue = null; StaticMemberOrTypeExpression lhsExpr = null; if (dynblock > 0 && Util.isTypeUnknown(that.getLeftTerm().getTypeModel())) { that.getLeftTerm().visit(this); out("="); int box = boxUnboxStart(that.getRightTerm(), that.getLeftTerm()); that.getRightTerm().visit(this); if (box == 4) out("/*TODO: callable targs 6*/"); boxUnboxEnd(box); return; } out("("); if (that.getLeftTerm() instanceof BaseMemberExpression) { BaseMemberExpression bme = (BaseMemberExpression) that.getLeftTerm(); lhsExpr = bme; Declaration bmeDecl = bme.getDeclaration(); boolean simpleSetter = hasSimpleGetterSetter(bmeDecl); if (!simpleSetter) { returnValue = memberAccess(bme, null); } } else if (that.getLeftTerm() instanceof QualifiedMemberExpression) { QualifiedMemberExpression qme = (QualifiedMemberExpression)that.getLeftTerm(); lhsExpr = qme; boolean simpleSetter = hasSimpleGetterSetter(qme.getDeclaration()); String lhsVar = null; if (!simpleSetter) { lhsVar = createRetainedTempVar(); out(lhsVar, "="); super.visit(qme); out(",", lhsVar, "."); returnValue = memberAccess(qme, lhsVar); } else { super.visit(qme); out("."); } } BmeGenerator.generateMemberAccess(lhsExpr, new GenerateCallback() { @Override public void generateValue() { if (!isNaturalLiteral(that.getRightTerm())) { int boxType = boxUnboxStart(that.getRightTerm(), that.getLeftTerm()); that.getRightTerm().visit(GenerateJsVisitor.this); if (boxType == 4) out("/*TODO: callable targs 7*/"); boxUnboxEnd(boxType); } } }, null, this); if (returnValue != null) { out(",", returnValue); } out(")"); } /** Outputs the module name for the specified declaration. Returns true if something was output. */ boolean qualify(final Node that, final Declaration d) { String path = qualifiedPath(that, d); if (path.length() > 0) { out(path, "."); } return path.length() > 0; } private String qualifiedPath(final Node that, final Declaration d) { return qualifiedPath(that, d, false); } String qualifiedPath(final Node that, final Declaration d, final boolean inProto) { boolean isMember = d.isClassOrInterfaceMember(); if (!isMember && isImported(that == null ? null : that.getUnit().getPackage(), d)) { return names.moduleAlias(d.getUnit().getPackage().getModule()); } else if (opts.isOptimize() && !inProto) { if (isMember && !(d.isParameter() && !d.isCaptured())) { TypeDeclaration id = that.getScope().getInheritingDeclaration(d); if (id == null) { //a local declaration of some kind, //perhaps in an outer scope id = (TypeDeclaration) d.getContainer(); } Scope scope = that.getScope(); if ((scope != null) && ((that instanceof ClassDeclaration) || (that instanceof InterfaceDeclaration))) { // class/interface aliases have no own "this" scope = scope.getContainer(); } final StringBuilder path = new StringBuilder(); while (scope != null) { if (scope instanceof TypeDeclaration) { if (path.length() > 0) { path.append(".outer$"); } else { path.append(names.self((TypeDeclaration) scope)); } } else { path.setLength(0); } if (scope == id) { break; } scope = scope.getContainer(); } return path.toString(); } } else { if (d != null && isMember && (d.isShared() || inProto || (!d.isParameter() && defineAsProperty(d)))) { TypeDeclaration id = d instanceof TypeAlias ? (TypeDeclaration)d : that.getScope().getInheritingDeclaration(d); if (id==null) { //a shared local declaration return names.self((TypeDeclaration)d.getContainer()); } else { //an inherited declaration that might be //inherited by an outer scope return names.self(id); } } } return ""; } /** Tells whether a declaration is in the specified package. */ boolean isImported(final Package p2, final Declaration d) { if (d == null) { return false; } Package p1 = d.getUnit().getPackage(); if (p2 == null)return p1 != null; if (p1.getModule()== null)return p2.getModule()!=null; return !p1.getModule().equals(p2.getModule()); } @Override public void visit(final Tree.ExecutableStatement that) { super.visit(that); endLine(true); } /** Creates a new temporary variable which can be used immediately, even * inside an expression. The declaration for that temporary variable will be * emitted after the current Ceylon statement has been completely processed. * The resulting code is valid because JavaScript variables may be used before * they are declared. */ String createRetainedTempVar() { String varName = names.createTempVariable(); retainedVars.add(varName); return varName; } @Override public void visit(final Tree.Return that) { out("return"); if (that.getExpression() == null) { endLine(true); return; } out(" "); if (dynblock > 0 && Util.isTypeUnknown(that.getExpression().getTypeModel())) { Scope cont = Util.getRealScope(that.getScope()).getScope(); if (cont instanceof Declaration) { final ProducedType dectype = ((Declaration)cont).getReference().getType(); if (!Util.isTypeUnknown(dectype)) { TypeUtils.generateDynamicCheck(that.getExpression(), dectype, this, false, that.getExpression().getTypeModel().getTypeArguments()); endLine(true); return; } } } if (isNaturalLiteral(that.getExpression().getTerm())) { out(";"); } else { super.visit(that); } } @Override public void visit(final Tree.AnnotationList that) {} boolean outerSelf(Declaration d) { if (d.isToplevel()) { out("ex$"); return true; } else if (d.isClassOrInterfaceMember()) { out(names.self((TypeDeclaration)d.getContainer())); return true; } return false; } @Override public void visit(final Tree.SumOp that) { Operators.simpleBinaryOp(that, null, ".plus(", ")", this); } @Override public void visit(final Tree.ScaleOp that) { final String lhs = names.createTempVariable(); Operators.simpleBinaryOp(that, "function(){var "+lhs+"=", ";return ", ".scale("+lhs+");}()", this); } @Override public void visit(final Tree.DifferenceOp that) { Operators.simpleBinaryOp(that, null, ".minus(", ")", this); } @Override public void visit(final Tree.ProductOp that) { Operators.simpleBinaryOp(that, null, ".times(", ")", this); } @Override public void visit(final Tree.QuotientOp that) { Operators.simpleBinaryOp(that, null, ".divided(", ")", this); } @Override public void visit(final Tree.RemainderOp that) { Operators.simpleBinaryOp(that, null, ".remainder(", ")", this); } @Override public void visit(final Tree.PowerOp that) { Operators.simpleBinaryOp(that, null, ".power(", ")", this); } @Override public void visit(final Tree.AddAssignOp that) { assignOp(that, "plus", null); } @Override public void visit(final Tree.SubtractAssignOp that) { assignOp(that, "minus", null); } @Override public void visit(final Tree.MultiplyAssignOp that) { assignOp(that, "times", null); } @Override public void visit(final Tree.DivideAssignOp that) { assignOp(that, "divided", null); } @Override public void visit(final Tree.RemainderAssignOp that) { assignOp(that, "remainder", null); } public void visit(Tree.ComplementAssignOp that) { assignOp(that, "complement", TypeUtils.mapTypeArgument(that, "complement", "Element", "Other")); } public void visit(Tree.UnionAssignOp that) { assignOp(that, "union", TypeUtils.mapTypeArgument(that, "union", "Element", "Other")); } public void visit(Tree.IntersectAssignOp that) { assignOp(that, "intersection", TypeUtils.mapTypeArgument(that, "intersection", "Element", "Other")); } public void visit(Tree.AndAssignOp that) { assignOp(that, "&&", null); } public void visit(Tree.OrAssignOp that) { assignOp(that, "||", null); } private void assignOp(final Tree.AssignmentOp that, final String functionName, final Map<TypeParameter, ProducedType> targs) { Term lhs = that.getLeftTerm(); final boolean isNative="||".equals(functionName)||"&&".equals(functionName); if (lhs instanceof BaseMemberExpression) { BaseMemberExpression lhsBME = (BaseMemberExpression) lhs; Declaration lhsDecl = lhsBME.getDeclaration(); final String getLHS = memberAccess(lhsBME, null); out("("); BmeGenerator.generateMemberAccess(lhsBME, new GenerateCallback() { @Override public void generateValue() { if (isNative) { out(getLHS, functionName); } else { out(getLHS, ".", functionName, "("); } if (!isNaturalLiteral(that.getRightTerm())) { that.getRightTerm().visit(GenerateJsVisitor.this); } if (!isNative) { if (targs != null) { out(","); TypeUtils.printTypeArguments(that, targs, GenerateJsVisitor.this, false, null); } out(")"); } } }, null, this); if (!hasSimpleGetterSetter(lhsDecl)) { out(",", getLHS); } out(")"); } else if (lhs instanceof QualifiedMemberExpression) { QualifiedMemberExpression lhsQME = (QualifiedMemberExpression) lhs; if (isNative(lhsQME)) { // ($1.foo = Box($1.foo).operator($2)) final String tmp = names.createTempVariable(); final String dec = isInDynamicBlock() && lhsQME.getDeclaration() == null ? lhsQME.getIdentifier().getText() : lhsQME.getDeclaration().getName(); out("(", tmp, "="); lhsQME.getPrimary().visit(this); out(",", tmp, ".", dec, "="); int boxType = boxStart(lhsQME); out(tmp, ".", dec); if (boxType == 4) out("/*TODO: callable targs 8*/"); boxUnboxEnd(boxType); out(".", functionName, "("); if (!isNaturalLiteral(that.getRightTerm())) { that.getRightTerm().visit(this); } out("))"); } else { final String lhsPrimaryVar = createRetainedTempVar(); final String getLHS = memberAccess(lhsQME, lhsPrimaryVar); out("(", lhsPrimaryVar, "="); lhsQME.getPrimary().visit(this); out(","); BmeGenerator.generateMemberAccess(lhsQME, new GenerateCallback() { @Override public void generateValue() { out(getLHS, ".", functionName, "("); if (!isNaturalLiteral(that.getRightTerm())) { that.getRightTerm().visit(GenerateJsVisitor.this); } out(")"); } }, lhsPrimaryVar, this); if (!hasSimpleGetterSetter(lhsQME.getDeclaration())) { out(",", getLHS); } out(")"); } } } @Override public void visit(final Tree.NegativeOp that) { if (that.getTerm() instanceof Tree.NaturalLiteral) { long t = parseNaturalLiteral((Tree.NaturalLiteral)that.getTerm()); out("("); if (t > 0) { out("-"); } out(Long.toString(t)); out(")"); if (t == 0) { //Force -0 out(".negated"); } return; } final TypeDeclaration d = that.getTerm().getTypeModel().getDeclaration(); final boolean isint = d.inherits(that.getUnit().getIntegerDeclaration()); Operators.unaryOp(that, isint?"(-":null, isint?")":".negated", this); } @Override public void visit(final Tree.PositiveOp that) { final TypeDeclaration d = that.getTerm().getTypeModel().getDeclaration(); final boolean nat = d.inherits(that.getUnit().getIntegerDeclaration()); //TODO if it's positive we leave it as is? Operators.unaryOp(that, nat?"(+":null, nat?")":null, this); } @Override public void visit(final Tree.EqualOp that) { if (dynblock > 0 && Util.isTypeUnknown(that.getLeftTerm().getTypeModel())) { //Try to use equals() if it exists String ltmp = names.createTempVariable(); String rtmp = names.createTempVariable(); out("(", ltmp, "="); box(that.getLeftTerm()); out(",", rtmp, "="); box(that.getRightTerm()); out(",(", ltmp, ".equals&&", ltmp, ".equals(", rtmp, "))||", ltmp, "===", rtmp, ")"); } else { final boolean usenat = canUseNativeComparator(that.getLeftTerm(), that.getRightTerm()); Operators.simpleBinaryOp(that, usenat?"((":null, usenat?").valueOf()==(":".equals(", usenat?").valueOf())":")", this); } } @Override public void visit(final Tree.NotEqualOp that) { if (dynblock > 0 && Util.isTypeUnknown(that.getLeftTerm().getTypeModel())) { //Try to use equals() if it exists String ltmp = names.createTempVariable(); String rtmp = names.createTempVariable(); out("(", ltmp, "="); box(that.getLeftTerm()); out(",", rtmp, "="); box(that.getRightTerm()); out(",(", ltmp, ".equals&&!", ltmp, ".equals(", rtmp, "))||", ltmp, "!==", rtmp, ")"); } else { final boolean usenat = canUseNativeComparator(that.getLeftTerm(), that.getRightTerm()); Operators.simpleBinaryOp(that, usenat?"!(":"(!", usenat?"==":".equals(", usenat?")":"))", this); } } @Override public void visit(final Tree.NotOp that) { final Term t = that.getTerm(); final boolean omitParens = t instanceof BaseMemberExpression || t instanceof QualifiedMemberExpression || t instanceof IsOp || t instanceof Exists || t instanceof IdenticalOp || t instanceof InOp || t instanceof Nonempty || (t instanceof InvocationExpression && ((InvocationExpression)t).getNamedArgumentList() == null); if (omitParens) { Operators.unaryOp(that, "!", null, this); } else { Operators.unaryOp(that, "(!", ")", this); } } @Override public void visit(final Tree.IdenticalOp that) { Operators.simpleBinaryOp(that, "(", "===", ")", this); } @Override public void visit(final Tree.CompareOp that) { Operators.simpleBinaryOp(that, null, ".compare(", ")", this); } /** Returns true if both Terms' types is either Integer or Boolean. */ private boolean canUseNativeComparator(final Tree.Term left, final Tree.Term right) { if (left == null || right == null || left.getTypeModel() == null || right.getTypeModel() == null) { return false; } final ProducedType lt = left.getTypeModel(); final ProducedType rt = right.getTypeModel(); final TypeDeclaration intdecl = left.getUnit().getIntegerDeclaration(); final TypeDeclaration booldecl = left.getUnit().getBooleanDeclaration(); return (intdecl.equals(lt.getDeclaration()) && intdecl.equals(rt.getDeclaration())) || (booldecl.equals(lt.getDeclaration()) && booldecl.equals(rt.getDeclaration())); } @Override public void visit(final Tree.SmallerOp that) { if (dynblock > 0 && Util.isTypeUnknown(that.getLeftTerm().getTypeModel())) { //Try to use compare() if it exists String ltmp = names.createTempVariable(); String rtmp = names.createTempVariable(); out("(", ltmp, "="); box(that.getLeftTerm()); out(",", rtmp, "="); box(that.getRightTerm()); out(",(", ltmp, ".compare&&", ltmp, ".compare(", rtmp, ").equals(", getClAlias(), "getSmaller()))||", ltmp, "<", rtmp, ")"); } else { final boolean usenat = canUseNativeComparator(that.getLeftTerm(), that.getRightTerm()); if (usenat) { Operators.simpleBinaryOp(that, "(", "<", ")", this); } else { Operators.simpleBinaryOp(that, null, ".compare(", ")", this); out(".equals(", getClAlias(), "getSmaller())"); } } } @Override public void visit(final Tree.LargerOp that) { if (dynblock > 0 && Util.isTypeUnknown(that.getLeftTerm().getTypeModel())) { //Try to use compare() if it exists String ltmp = names.createTempVariable(); String rtmp = names.createTempVariable(); out("(", ltmp, "="); box(that.getLeftTerm()); out(",", rtmp, "="); box(that.getRightTerm()); out(",(", ltmp, ".compare&&", ltmp, ".compare(", rtmp, ").equals(", getClAlias(), "getLarger()))||", ltmp, ">", rtmp, ")"); } else { final boolean usenat = canUseNativeComparator(that.getLeftTerm(), that.getRightTerm()); if (usenat) { Operators.simpleBinaryOp(that, "(", ">", ")", this); } else { Operators.simpleBinaryOp(that, null, ".compare(", ")", this); out(".equals(", getClAlias(), "getLarger())"); } } } @Override public void visit(final Tree.SmallAsOp that) { if (dynblock > 0 && Util.isTypeUnknown(that.getLeftTerm().getTypeModel())) { //Try to use compare() if it exists String ltmp = names.createTempVariable(); String rtmp = names.createTempVariable(); out("(", ltmp, "="); box(that.getLeftTerm()); out(",", rtmp, "="); box(that.getRightTerm()); out(",(", ltmp, ".compare&&", ltmp, ".compare(", rtmp, ")!==", getClAlias(), "getLarger())||", ltmp, "<=", rtmp, ")"); } else { final boolean usenat = canUseNativeComparator(that.getLeftTerm(), that.getRightTerm()); if (usenat) { Operators.simpleBinaryOp(that, "(", "<=", ")", this); } else { out("("); Operators.simpleBinaryOp(that, null, ".compare(", ")", this); out("!==", getClAlias(), "getLarger()"); out(")"); } } } @Override public void visit(final Tree.LargeAsOp that) { if (dynblock > 0 && Util.isTypeUnknown(that.getLeftTerm().getTypeModel())) { //Try to use compare() if it exists String ltmp = names.createTempVariable(); String rtmp = names.createTempVariable(); out("(", ltmp, "="); box(that.getLeftTerm()); out(",", rtmp, "="); box(that.getRightTerm()); out(",(", ltmp, ".compare&&", ltmp, ".compare(", rtmp, ")!==", getClAlias(), "getSmaller())||", ltmp, ">=", rtmp, ")"); } else { final boolean usenat = canUseNativeComparator(that.getLeftTerm(), that.getRightTerm()); if (usenat) { Operators.simpleBinaryOp(that, "(", ">=", ")", this); } else { out("("); Operators.simpleBinaryOp(that, null, ".compare(", ")", this); out("!==", getClAlias(), "getSmaller()"); out(")"); } } } public void visit(final Tree.WithinOp that) { final String ttmp = names.createTempVariable(); out("(", ttmp, "="); box(that.getTerm()); out(","); if (dynblock > 0 && Util.isTypeUnknown(that.getTerm().getTypeModel())) { final String tmpl = names.createTempVariable(); final String tmpu = names.createTempVariable(); out(tmpl, "="); box(that.getLowerBound().getTerm()); out(",", tmpu, "="); box(that.getUpperBound().getTerm()); out(",((", ttmp, ".compare&&",ttmp,".compare(", tmpl); if (that.getLowerBound() instanceof Tree.OpenBound) { out(")===", getClAlias(), "getLarger())||", ttmp, ">", tmpl, ")"); } else { out(")!==", getClAlias(), "getSmaller())||", ttmp, ">=", tmpl, ")"); } out("&&((", ttmp, ".compare&&",ttmp,".compare(", tmpu); if (that.getUpperBound() instanceof Tree.OpenBound) { out(")===", getClAlias(), "getSmaller())||", ttmp, "<", tmpu, ")"); } else { out(")!==", getClAlias(), "getLarger())||", ttmp, "<=", tmpu, ")"); } } else { out(ttmp, ".compare("); box(that.getLowerBound().getTerm()); if (that.getLowerBound() instanceof Tree.OpenBound) { out(")===", getClAlias(), "getLarger()"); } else { out(")!==", getClAlias(), "getSmaller()"); } out("&&"); out(ttmp, ".compare("); box(that.getUpperBound().getTerm()); if (that.getUpperBound() instanceof Tree.OpenBound) { out(")===", getClAlias(), "getSmaller()"); } else { out(")!==", getClAlias(), "getLarger()"); } } out(")"); } @Override public void visit(final Tree.AndOp that) { Operators.simpleBinaryOp(that, "(", "&&", ")", this); } @Override public void visit(final Tree.OrOp that) { Operators.simpleBinaryOp(that, "(", "||", ")", this); } @Override public void visit(final Tree.EntryOp that) { out(getClAlias(), "Entry("); Operators.genericBinaryOp(that, ",", that.getTypeModel().getTypeArguments(), that.getTypeModel().getVarianceOverrides(), this); } @Override public void visit(final Tree.RangeOp that) { out(getClAlias(), "span("); that.getLeftTerm().visit(this); out(","); that.getRightTerm().visit(this); out(",{Element$span:"); TypeUtils.typeNameOrList(that, Util.unionType(that.getLeftTerm().getTypeModel(), that.getRightTerm().getTypeModel(), that.getUnit()), this, false); out("})"); } @Override public void visit(final Tree.SegmentOp that) { final Tree.Term left = that.getLeftTerm(); final Tree.Term right = that.getRightTerm(); out(getClAlias(), "measure("); left.visit(this); out(","); right.visit(this); out(",{Element$measure:"); TypeUtils.typeNameOrList(that, Util.unionType(left.getTypeModel(), right.getTypeModel(), that.getUnit()), this, false); out("})"); } @Override public void visit(final Tree.ThenOp that) { Operators.simpleBinaryOp(that, "(", "?", ":null)", this); } @Override public void visit(final Tree.Element that) { out(".$_get("); if (!isNaturalLiteral(that.getExpression().getTerm())) { that.getExpression().visit(this); } out(")"); } @Override public void visit(final Tree.DefaultOp that) { String lhsVar = createRetainedTempVar(); out("(", lhsVar, "="); box(that.getLeftTerm()); out(",", getClAlias(), "nn$(", lhsVar, ")?", lhsVar, ":"); box(that.getRightTerm()); out(")"); } @Override public void visit(final Tree.IncrementOp that) { Operators.prefixIncrementOrDecrement(that.getTerm(), "successor", this); } @Override public void visit(final Tree.DecrementOp that) { Operators.prefixIncrementOrDecrement(that.getTerm(), "predecessor", this); } boolean hasSimpleGetterSetter(Declaration decl) { return (dynblock > 0 && TypeUtils.isUnknown(decl)) || !((decl instanceof Value && ((Value)decl).isTransient()) || (decl instanceof Setter) || decl.isFormal()); } @Override public void visit(final Tree.PostfixIncrementOp that) { Operators.postfixIncrementOrDecrement(that.getTerm(), "successor", this); } @Override public void visit(final Tree.PostfixDecrementOp that) { Operators.postfixIncrementOrDecrement(that.getTerm(), "predecessor", this); } @Override public void visit(final Tree.UnionOp that) { Operators.genericBinaryOp(that, ".union(", TypeUtils.mapTypeArgument(that, "union", "Element", "Other"), that.getTypeModel().getVarianceOverrides(), this); } @Override public void visit(final Tree.IntersectionOp that) { Operators.genericBinaryOp(that, ".intersection(", TypeUtils.mapTypeArgument(that, "intersection", "Element", "Other"), that.getTypeModel().getVarianceOverrides(), this); } @Override public void visit(final Tree.ComplementOp that) { Operators.genericBinaryOp(that, ".complement(", TypeUtils.mapTypeArgument(that, "complement", "Element", "Other"), that.getTypeModel().getVarianceOverrides(), this); } @Override public void visit(final Tree.Exists that) { Operators.unaryOp(that, getClAlias()+"nn$(", ")", this); } @Override public void visit(final Tree.Nonempty that) { Operators.unaryOp(that, getClAlias()+"ne$(", ")", this); } //Don't know if we'll ever see this... @Override public void visit(final Tree.ConditionList that) { System.out.println("ZOMG condition list in the wild! " + that.getLocation() + " of " + that.getUnit().getFilename()); super.visit(that); } @Override public void visit(final Tree.BooleanCondition that) { int boxType = boxStart(that.getExpression().getTerm()); super.visit(that); if (boxType == 4) out("/*TODO: callable targs 10*/"); boxUnboxEnd(boxType); } @Override public void visit(final Tree.IfStatement that) { if (errVisitor.hasErrors(that))return; conds.generateIf(that); } @Override public void visit(final Tree.IfExpression that) { if (errVisitor.hasErrors(that))return; conds.generateIfExpression(that, false); } @Override public void visit(final Tree.WhileStatement that) { conds.generateWhile(that); } /** Generates js code to check if a term is of a certain type. We solve this in JS by * checking against all types that Type satisfies (in the case of union types, matching any * type will do, and in case of intersection types, all types must be matched). * @param term The term that is to be checked against a type * @param termString (optional) a string to be used as the term to be checked * @param type The type to check against * @param tmpvar (optional) a variable to which the term is assigned * @param negate If true, negates the generated condition */ void generateIsOfType(Node term, String termString, final ProducedType type, String tmpvar, final boolean negate) { if (negate) { out("!"); } out(getClAlias(), "is$("); if (term instanceof Term) { conds.specialConditionRHS((Term)term, tmpvar); } else { conds.specialConditionRHS(termString, tmpvar); } out(","); out("/*", type.getQualifyingType()+"*/"); TypeUtils.typeNameOrList(term, type, this, false); if (type.getQualifyingType() != null) { out(",["); ProducedType outer = type.getQualifyingType(); while (outer != null) { TypeUtils.typeNameOrList(term, outer, this, false); outer = outer.getQualifyingType(); } out("]"); } out(")"); } @Override public void visit(final Tree.IsOp that) { generateIsOfType(that.getTerm(), null, that.getType().getTypeModel(), null, false); } @Override public void visit(final Tree.Break that) { if (continues.isEmpty()) { out("break;"); } else { Continuation top=continues.peek(); if (that.getScope()==top.getScope()) { top.useBreak(); out(top.getBreakName(), "=true; return;"); } else { out("break;"); } } } @Override public void visit(final Tree.Continue that) { if (continues.isEmpty()) { out("continue;"); } else { Continuation top=continues.peek(); if (that.getScope()==top.getScope()) { top.useContinue(); out(top.getContinueName(), "=true; return;"); } else { out("continue;"); } } } @Override public void visit(final Tree.ForStatement that) { if (errVisitor.hasErrors(that))return; new ForGenerator(this, directAccess).generate(that); } public void visit(final Tree.InOp that) { box(that.getRightTerm()); out(".contains("); if (!isNaturalLiteral(that.getLeftTerm())) { box(that.getLeftTerm()); } out(")"); } @Override public void visit(final Tree.TryCatchStatement that) { if (errVisitor.hasErrors(that))return; new TryCatchGenerator(this, directAccess).generate(that); } @Override public void visit(final Tree.Throw that) { out("throw ", getClAlias(), "wrapexc("); if (that.getExpression() == null) { out(getClAlias(), "Exception()"); } else { that.getExpression().visit(this); } that.getUnit().getFullPath(); out(",'", that.getLocation(), "','", that.getUnit().getRelativePath(), "');"); } private void visitIndex(final Tree.IndexExpression that) { that.getPrimary().visit(this); ElementOrRange eor = that.getElementOrRange(); if (eor instanceof Element) { final Tree.Expression _elemexpr = ((Tree.Element)eor).getExpression(); final String _end; if (Util.isTypeUnknown(that.getPrimary().getTypeModel()) && dynblock > 0) { out("["); _end = "]"; } else { out(".$_get("); _end = ")"; } if (!isNaturalLiteral(_elemexpr.getTerm())) { _elemexpr.visit(this); } out(_end); } else {//range, or spread? ElementRange er = (ElementRange)eor; Expression sexpr = er.getLength(); if (sexpr == null) { if (er.getLowerBound() == null) { out(".spanTo("); } else if (er.getUpperBound() == null) { out(".spanFrom("); } else { out(".span("); } } else { out(".measure("); } if (er.getLowerBound() != null) { if (!isNaturalLiteral(er.getLowerBound().getTerm())) { er.getLowerBound().visit(this); } if (er.getUpperBound() != null || sexpr != null) { out(","); } } if (er.getUpperBound() != null) { if (!isNaturalLiteral(er.getUpperBound().getTerm())) { er.getUpperBound().visit(this); } } else if (sexpr != null) { sexpr.visit(this); } out(")"); } } public void visit(final Tree.IndexExpression that) { visitIndex(that); } @Override public void visit(final Tree.SwitchStatement that) { if (errVisitor.hasErrors(that))return; if (opts.isComment() && !opts.isMinify()) { out("//Switch statement at ", that.getUnit().getFilename(), " (", that.getLocation(), ")"); endLine(); } conds.generateSwitch(that); if (opts.isComment() && !opts.isMinify()) { out("//End switch statement at ", that.getUnit().getFilename(), " (", that.getLocation(), ")"); endLine(); } } @Override public void visit(final Tree.SwitchExpression that) { conds.generateSwitchExpression(that); } /** Generates the code for an anonymous function defined inside an argument list. */ @Override public void visit(final Tree.FunctionArgument that) { if (errVisitor.hasErrors(that))return; FunctionHelper.functionArgument(that, this); } /** Generates the code for a function in a named argument list. */ @Override public void visit(final Tree.MethodArgument that) { if (errVisitor.hasErrors(that))return; FunctionHelper.methodArgument(that, this); } /** Determines whether the specified block should be enclosed in a function. */ public boolean shouldEncloseBlock(Block block) { // just check if the block contains a captured declaration for (Tree.Statement statement : block.getStatements()) { if (statement instanceof Tree.Declaration) { if (((Tree.Declaration) statement).getDeclarationModel().isCaptured()) { return true; } } } return false; } /** Encloses the block in a function, IF NEEDED. */ void encloseBlockInFunction(final Tree.Block block, final boolean markBlock) { final boolean wrap=shouldEncloseBlock(block); if (wrap) { if (markBlock)beginBlock(); Continuation c = new Continuation(block.getScope(), names); continues.push(c); out("var ", c.getContinueName(), "=false"); endLine(true); out("var ", c.getBreakName(), "=false"); endLine(true); out("var ", c.getReturnName(), "=(function()"); if (!markBlock)beginBlock(); } if (markBlock) { block.visit(this); } else { visitStatements(block.getStatements()); } if (wrap) { Continuation c = continues.pop(); if (!markBlock)endBlock(); out("());if(", c.getReturnName(), "!==undefined){return ", c.getReturnName(), ";}"); if (c.isContinued()) { out("else if(", c.getContinueName(),"===true){continue;}"); } if (c.isBreaked()) { out("else if(", c.getBreakName(),"===true){break;}"); } if (markBlock)endBlockNewLine(); } } private static class Continuation { private final String cvar; private final String rvar; private final String bvar; private final Scope scope; private boolean cused, bused; public Continuation(Scope scope, JsIdentifierNames names) { this.scope=scope; cvar = names.createTempVariable(); rvar = names.createTempVariable(); bvar = names.createTempVariable(); } public Scope getScope() { return scope; } public String getContinueName() { return cvar; } public String getBreakName() { return bvar; } public String getReturnName() { return rvar; } public void useContinue() { cused = true; } public void useBreak() { bused=true; } public boolean isContinued() { return cused; } public boolean isBreaked() { return bused; } //"isBroken" sounds really really bad in this case } /** This interface is used inside type initialization method. */ static interface PrototypeInitCallback { /** Generates a function that adds members to a prototype, then calls it. */ void addToPrototypeCallback(); } @Override public void visit(final Tree.Tuple that) { SequenceGenerator.tuple(that, this); } @Override public void visit(final Tree.Assertion that) { if (opts.isComment() && !opts.isMinify()) { out("//assert"); location(that); endLine(); } String custom = "Assertion failed"; //Scan for a "doc" annotation with custom message if (that.getAnnotationList() != null && that.getAnnotationList().getAnonymousAnnotation() != null) { custom = that.getAnnotationList().getAnonymousAnnotation().getStringLiteral().getText(); } else { for (Annotation ann : that.getAnnotationList().getAnnotations()) { BaseMemberExpression bme = (BaseMemberExpression)ann.getPrimary(); if ("doc".equals(bme.getDeclaration().getName())) { custom = ((Tree.ListedArgument)ann.getPositionalArgumentList().getPositionalArguments().get(0)) .getExpression().getTerm().getText(); } } } StringBuilder sb = new StringBuilder(custom).append(": '"); for (int i = that.getConditionList().getToken().getTokenIndex()+1; i < that.getConditionList().getEndToken().getTokenIndex(); i++) { sb.append(tokens.get(i).getText()); } sb.append("' at ").append(that.getUnit().getFilename()).append(" (").append( that.getConditionList().getLocation()).append(")"); conds.specialConditionsAndBlock(that.getConditionList(), null, getClAlias()+"asrt$("); //escape out(",\"", escapeStringLiteral(sb.toString()), "\",'",that.getLocation(), "','", that.getUnit().getFilename(), "');"); endLine(); } @Override public void visit(Tree.DynamicStatement that) { dynblock++; if (dynblock == 1 && !opts.isMinify()) { out("/*BEG dynblock*/"); endLine(); } for (Tree.Statement stmt : that.getDynamicClause().getBlock().getStatements()) { stmt.visit(this); } if (dynblock == 1 && !opts.isMinify()) { out("/*END dynblock*/"); endLine(); } dynblock--; } boolean isInDynamicBlock() { return dynblock > 0; } @Override public void visit(final Tree.TypeLiteral that) { //Can be an alias, class, interface or type parameter if (that.getWantsDeclaration()) { MetamodelHelper.generateOpenType(that, that.getDeclaration(), this); } else { MetamodelHelper.generateClosedTypeLiteral(that, this); } } @Override public void visit(final Tree.MemberLiteral that) { if (that.getWantsDeclaration()) { MetamodelHelper.generateOpenType(that, that.getDeclaration(), this); } else { MetamodelHelper.generateMemberLiteral(that, this); } } @Override public void visit(final Tree.PackageLiteral that) { com.redhat.ceylon.compiler.typechecker.model.Package pkg = (com.redhat.ceylon.compiler.typechecker.model.Package)that.getImportPath().getModel(); MetamodelHelper.findModule(pkg.getModule(), this); out(".findPackage('", pkg.getNameAsString(), "')"); } @Override public void visit(Tree.ModuleLiteral that) { Module m = (Module)that.getImportPath().getModel(); MetamodelHelper.findModule(m, this); } /** Call internal function "throwexc" with the specified message and source location. */ void generateThrow(String exceptionClass, String msg, Node node) { out(getClAlias(), "throwexc(", exceptionClass==null ? getClAlias() + "Exception":exceptionClass, "("); out("\"", escapeStringLiteral(msg), "\"),'", node.getLocation(), "','", node.getUnit().getFilename(), "')"); } @Override public void visit(Tree.CompilerAnnotation that) { //just ignore this } /** Outputs the initial part of an attribute definition. */ void defineAttribute(final String owner, final String name) { out(getClAlias(), "atr$(", owner, ",'", name, "',function()"); } public int getExitCode() { return exitCode; } @Override public void visit(Tree.ListedArgument that) { if (!isNaturalLiteral(that.getExpression().getTerm())) { super.visit(that); } } @Override public void visit(Tree.LetExpression that) { if (errVisitor.hasErrors(that))return; FunctionHelper.generateLet(that, directAccess, this); } boolean isNaturalLiteral(Tree.Term that) { if (that instanceof Tree.NaturalLiteral) { out(Long.toString(parseNaturalLiteral((Tree.NaturalLiteral)that))); return true; } return false; } }
separate outer types with commas
src/main/java/com/redhat/ceylon/compiler/js/GenerateJsVisitor.java
separate outer types with commas
<ide><path>rc/main/java/com/redhat/ceylon/compiler/js/GenerateJsVisitor.java <ide> conds.specialConditionRHS(termString, tmpvar); <ide> } <ide> out(","); <del> out("/*", type.getQualifyingType()+"*/"); <ide> TypeUtils.typeNameOrList(term, type, this, false); <ide> if (type.getQualifyingType() != null) { <ide> out(",["); <ide> ProducedType outer = type.getQualifyingType(); <add> boolean first=true; <ide> while (outer != null) { <add> if (first) { <add> first=false; <add> } else{ <add> out(","); <add> } <ide> TypeUtils.typeNameOrList(term, outer, this, false); <ide> outer = outer.getQualifyingType(); <ide> }
Java
apache-2.0
f84a9f6705d1f5c108a51bf953aae4c87d531a0a
0
thomasgalvin/Pathfinding
package pathfinding; import java.util.List; import org.junit.After; import org.junit.AfterClass; import org.junit.Assert; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * * @author galvint */ public class PathfindingTest { private static final Logger logger = LoggerFactory.getLogger( PathfindingTest.class ); public PathfindingTest() { } @BeforeClass public static void setUpClass() { } @AfterClass public static void tearDownClass() { } @Before public void setUp() { } @After public void tearDown() { } public static Node[][] makeNodes() { int multiplier = 5; int width = 10; int height = 10; Node[][] nodes = new Node[ width ][ height ]; for( int row = 0; row < height; row++ ){ for( int col = 0; col < width; col++ ){ int x = col; int xx = x * multiplier; int y = row; int yy = y * multiplier; Node node = new Node(xx, yy, x, y); nodes[col][row] = node; } } // for( int x = 0; x < width; x++ ) { // for( int y = 0; y < height; y++ ) { // int xx = x * multiplier; // int yy = y * multiplier; // Node node = new Node(xx, yy, x, y); // nodes[x][y] = node; // } // } return nodes; } @Test public void testDistance() throws Exception{ double expected = 14.142; double delta = 0.01; int x1 = 0; int y1 = 0; int x2 = 10; int y2 = 10; double distance = Vertex.distance( x1, y1, x2, y2 ); Assert.assertEquals( expected, distance, delta ); Vertex one = new Vertex( x1, y1 ); Vertex two = new Vertex( x2, y2 ); distance = Vertex.distance( one, two ); Assert.assertEquals( expected, distance, delta ); } @Test public void testOne() throws Exception { Node[][] nodes = makeNodes(); Vertex start = new Vertex(0,0); Vertex end = new Vertex( nodes.length-1, nodes[0].length-1 ); List<Node> dij = Pathfinder.dijkstra(nodes, start, end ); logger.info( "Dijkstra" ); Pathfinder.printPath( nodes, dij ); } @Test public void testTwo() throws Exception { Node[][] nodes = makeNodes(); nodes[0][1].traversable = false; nodes[1][1].traversable = false; nodes[2][1].traversable = false; nodes[3][1].traversable = false; nodes[4][1].traversable = false; nodes[5][1].traversable = false; nodes[6][1].traversable = false; nodes[7][1].traversable = false; nodes[8][1].traversable = false; Vertex start = new Vertex(0,0); Vertex end = new Vertex( nodes.length-1, nodes[0].length-1 ); List<Node> dij = Pathfinder.dijkstra(nodes, start, end ); logger.info( "Dijkstra" ); Pathfinder.printPath( nodes, dij ); } @Test public void testTwoA() throws Exception { Node[][] nodes = makeNodes(); nodes[0][1].traversable = false; nodes[1][1].traversable = false; nodes[2][1].traversable = false; nodes[3][1].traversable = false; nodes[4][1].traversable = false; nodes[5][1].traversable = false; nodes[6][1].traversable = false; nodes[7][1].traversable = false; nodes[8][1].traversable = false; Vertex start = new Vertex(0,0); Vertex end = new Vertex( nodes.length-2, nodes[0].length-1 ); List<Node> dij = Pathfinder.dijkstra(nodes, start, end ); Pathfinder.printPath( nodes, dij ); } @Test public void testTwoB() throws Exception { Node[][] nodes = makeNodes(); nodes[0][1].traversable = false; nodes[1][1].traversable = false; nodes[2][1].traversable = false; nodes[3][1].traversable = false; nodes[4][1].traversable = false; nodes[5][1].traversable = false; nodes[6][1].traversable = false; nodes[7][1].traversable = false; nodes[8][1].traversable = false; Vertex start = new Vertex(0,0); Vertex end = new Vertex( 5, 3 ); List<Node> dij = Pathfinder.dijkstra(nodes, start, end ); Pathfinder.printPath( nodes, dij ); } @Test public void testThree() throws Exception { Node[][] nodes = makeNodes(); nodes[0][8].traversable = false; nodes[1][8].traversable = false; nodes[2][8].traversable = false; nodes[3][8].traversable = false; nodes[9][2].traversable = false; nodes[8][2].traversable = false; nodes[7][2].traversable = false; nodes[6][2].traversable = false; nodes[2][4].traversable = false; nodes[3][4].traversable = false; nodes[4][4].traversable = false; nodes[5][4].traversable = false; Vertex start = new Vertex(9,0); Vertex end = new Vertex(0,9); List<Node> dij = Pathfinder.dijkstra(nodes, start, end ); logger.info( "Dijkstra" ); Pathfinder.printPath( nodes, dij ); } @Test public void testFour() throws Exception { Node[][] nodes = makeNodes(); nodes[0][1].traversable = false; nodes[1][1].traversable = false; nodes[2][1].traversable = false; nodes[3][1].traversable = false; nodes[4][1].traversable = false; nodes[5][1].traversable = false; nodes[5][2].traversable = false; nodes[5][3].traversable = false; nodes[5][4].traversable = false; nodes[5][5].traversable = false; Vertex start = new Vertex(0,2); Vertex end = new Vertex(9,9); List<Node> dij = Pathfinder.dijkstra(nodes, start, end ); logger.info( "Dijkstra" ); Pathfinder.printPath( nodes, dij ); } @Test public void testFive() throws Exception { Node[][] nodes = makeNodes(); nodes[0][1].traversable = false; nodes[1][1].traversable = false; nodes[2][1].traversable = false; nodes[3][1].traversable = false; nodes[4][1].traversable = false; nodes[5][1].traversable = false; nodes[6][1].traversable = false; nodes[7][1].traversable = false; nodes[8][1].traversable = false; nodes[1][2].traversable = false; nodes[1][3].traversable = false; nodes[1][4].traversable = false; nodes[1][5].traversable = false; nodes[1][6].traversable = false; nodes[1][7].traversable = false; nodes[1][8].traversable = false; Vertex start = new Vertex(0,0); Vertex end = new Vertex(2,0); List<Node> dij = Pathfinder.dijkstra(nodes, start, end ); logger.info( "Dijkstra" ); Pathfinder.printPath( nodes, dij ); } @Test public void testSix() throws Exception { Node[][] nodes = makeNodes(); Vertex start = new Vertex(0,0); Vertex end = new Vertex( 1,1 ); List<Node> dij = Pathfinder.dijkstra(nodes, start, end ); logger.info( "Dijkstra" ); Pathfinder.printPath( nodes, dij ); } }
src/test/java/pathfinding/PathfindingTest.java
package pathfinding; import java.util.List; import org.junit.After; import org.junit.AfterClass; import org.junit.Assert; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * * @author galvint */ public class PathfindingTest { private static final Logger logger = LoggerFactory.getLogger( PathfindingTest.class ); public PathfindingTest() { } @BeforeClass public static void setUpClass() { } @AfterClass public static void tearDownClass() { } @Before public void setUp() { } @After public void tearDown() { } public static Node[][] makeNodes() { int multiplier = 5; int width = 10; int height = 10; Node[][] nodes = new Node[ width ][ height ]; for( int row = 0; row < height; row++ ){ for( int col = 0; col < width; col++ ){ int x = col; int xx = x * multiplier; int y = row; int yy = y * multiplier; Node node = new Node(xx, yy, x, y); nodes[col][row] = node; } } // for( int x = 0; x < width; x++ ) { // for( int y = 0; y < height; y++ ) { // int xx = x * multiplier; // int yy = y * multiplier; // Node node = new Node(xx, yy, x, y); // nodes[x][y] = node; // } // } return nodes; } @Test public void testDistance() throws Exception{ double expected = 14.142; double delta = 0.01; int x1 = 0; int y1 = 0; int x2 = 10; int y2 = 10; double distance = Vertex.distance( x1, y1, x2, y2 ); Assert.assertEquals( expected, distance, delta ); Vertex one = new Vertex( x1, y1 ); Vertex two = new Vertex( x2, y2 ); distance = Vertex.distance( one, two ); Assert.assertEquals( expected, distance, delta ); } @Test public void testOne() throws Exception { Node[][] nodes = makeNodes(); Vertex start = new Vertex(0,0); Vertex end = new Vertex( nodes.length-1, nodes[0].length-1 ); List<Node> dij = Pathfinder.dijkstra(nodes, start, end ); logger.info( "Dijkstra" ); Pathfinder.printPath( nodes, dij ); } @Test public void testTwo() throws Exception { Node[][] nodes = makeNodes(); nodes[0][1].traversable = false; nodes[1][1].traversable = false; nodes[2][1].traversable = false; nodes[3][1].traversable = false; nodes[4][1].traversable = false; nodes[5][1].traversable = false; nodes[6][1].traversable = false; nodes[7][1].traversable = false; nodes[8][1].traversable = false; Vertex start = new Vertex(0,0); Vertex end = new Vertex( nodes.length-1, nodes[0].length-1 ); List<Node> dij = Pathfinder.dijkstra(nodes, start, end ); logger.info( "Dijkstra" ); Pathfinder.printPath( nodes, dij ); } @Test public void testTwoA() throws Exception { Node[][] nodes = makeNodes(); nodes[0][1].traversable = false; nodes[1][1].traversable = false; nodes[2][1].traversable = false; nodes[3][1].traversable = false; nodes[4][1].traversable = false; nodes[5][1].traversable = false; nodes[6][1].traversable = false; nodes[7][1].traversable = false; nodes[8][1].traversable = false; Vertex start = new Vertex(0,0); Vertex end = new Vertex( nodes.length-2, nodes[0].length-1 ); logger.info( "*** *** ***" ); logger.info( "*** *** ***" ); logger.info( "*** *** ***" ); logger.info( "*** *** ***" ); logger.info( "*** *** ***" ); logger.info( "*** *** ***" ); logger.info( "*** *** ***" ); logger.info( "*** *** ***" ); logger.info( "*** *** ***" ); logger.info( "*** *** ***" ); logger.info( "*** *** ***" ); logger.info( "*** *** ***" ); logger.info( "*** *** ***" ); logger.info( "Dijkstra" ); List<Node> dij = Pathfinder.dijkstra(nodes, start, end ); Pathfinder.printPath( nodes, dij ); } @Test public void testTwoB() throws Exception { Node[][] nodes = makeNodes(); nodes[0][1].traversable = false; nodes[1][1].traversable = false; nodes[2][1].traversable = false; nodes[3][1].traversable = false; nodes[4][1].traversable = false; nodes[5][1].traversable = false; nodes[6][1].traversable = false; nodes[7][1].traversable = false; nodes[8][1].traversable = false; Vertex start = new Vertex(0,0); Vertex end = new Vertex( 5, 3 ); logger.info( "*** *** ***" ); logger.info( "*** *** ***" ); logger.info( "*** *** ***" ); logger.info( "*** *** ***" ); logger.info( "*** *** ***" ); logger.info( "*** *** ***" ); logger.info( "*** *** ***" ); logger.info( "*** *** ***" ); logger.info( "*** *** ***" ); logger.info( "*** *** ***" ); logger.info( "*** *** ***" ); logger.info( "*** *** ***" ); logger.info( "*** *** ***" ); logger.info( "Dijkstra" ); List<Node> dij = Pathfinder.dijkstra(nodes, start, end ); Pathfinder.printPath( nodes, dij ); } @Test public void testThree() throws Exception { Node[][] nodes = makeNodes(); nodes[0][8].traversable = false; nodes[1][8].traversable = false; nodes[2][8].traversable = false; nodes[3][8].traversable = false; nodes[9][2].traversable = false; nodes[8][2].traversable = false; nodes[7][2].traversable = false; nodes[6][2].traversable = false; nodes[2][4].traversable = false; nodes[3][4].traversable = false; nodes[4][4].traversable = false; nodes[5][4].traversable = false; Vertex start = new Vertex(9,0); Vertex end = new Vertex(0,9); List<Node> dij = Pathfinder.dijkstra(nodes, start, end ); logger.info( "Dijkstra" ); Pathfinder.printPath( nodes, dij ); } @Test public void testFour() throws Exception { Node[][] nodes = makeNodes(); nodes[0][1].traversable = false; nodes[1][1].traversable = false; nodes[2][1].traversable = false; nodes[3][1].traversable = false; nodes[4][1].traversable = false; nodes[5][1].traversable = false; nodes[5][2].traversable = false; nodes[5][3].traversable = false; nodes[5][4].traversable = false; nodes[5][5].traversable = false; Vertex start = new Vertex(0,2); Vertex end = new Vertex(9,9); List<Node> dij = Pathfinder.dijkstra(nodes, start, end ); logger.info( "Dijkstra" ); Pathfinder.printPath( nodes, dij ); } @Test public void testFive() throws Exception { Node[][] nodes = makeNodes(); nodes[0][1].traversable = false; nodes[1][1].traversable = false; nodes[2][1].traversable = false; nodes[3][1].traversable = false; nodes[4][1].traversable = false; nodes[5][1].traversable = false; nodes[6][1].traversable = false; nodes[7][1].traversable = false; nodes[8][1].traversable = false; nodes[1][2].traversable = false; nodes[1][3].traversable = false; nodes[1][4].traversable = false; nodes[1][5].traversable = false; nodes[1][6].traversable = false; nodes[1][7].traversable = false; nodes[1][8].traversable = false; Vertex start = new Vertex(0,0); Vertex end = new Vertex(2,0); List<Node> dij = Pathfinder.dijkstra(nodes, start, end ); logger.info( "Dijkstra" ); Pathfinder.printPath( nodes, dij ); } @Test public void testSix() throws Exception { Node[][] nodes = makeNodes(); Vertex start = new Vertex(0,0); Vertex end = new Vertex( 1,1 ); List<Node> dij = Pathfinder.dijkstra(nodes, start, end ); logger.info( "Dijkstra" ); Pathfinder.printPath( nodes, dij ); } }
Now indexing array as nodes[x][y]
src/test/java/pathfinding/PathfindingTest.java
Now indexing array as nodes[x][y]
<ide><path>rc/test/java/pathfinding/PathfindingTest.java <ide> Vertex start = new Vertex(0,0); <ide> Vertex end = new Vertex( nodes.length-2, nodes[0].length-1 ); <ide> <del> logger.info( "*** *** ***" ); <del> logger.info( "*** *** ***" ); <del> logger.info( "*** *** ***" ); <del> logger.info( "*** *** ***" ); <del> logger.info( "*** *** ***" ); <del> logger.info( "*** *** ***" ); <del> logger.info( "*** *** ***" ); <del> logger.info( "*** *** ***" ); <del> logger.info( "*** *** ***" ); <del> logger.info( "*** *** ***" ); <del> logger.info( "*** *** ***" ); <del> logger.info( "*** *** ***" ); <del> logger.info( "*** *** ***" ); <del> logger.info( "Dijkstra" ); <ide> List<Node> dij = Pathfinder.dijkstra(nodes, start, end ); <ide> Pathfinder.printPath( nodes, dij ); <ide> } <ide> <ide> Vertex start = new Vertex(0,0); <ide> Vertex end = new Vertex( 5, 3 ); <del> <del> logger.info( "*** *** ***" ); <del> logger.info( "*** *** ***" ); <del> logger.info( "*** *** ***" ); <del> logger.info( "*** *** ***" ); <del> logger.info( "*** *** ***" ); <del> logger.info( "*** *** ***" ); <del> logger.info( "*** *** ***" ); <del> logger.info( "*** *** ***" ); <del> logger.info( "*** *** ***" ); <del> logger.info( "*** *** ***" ); <del> logger.info( "*** *** ***" ); <del> logger.info( "*** *** ***" ); <del> logger.info( "*** *** ***" ); <del> logger.info( "Dijkstra" ); <add> <ide> List<Node> dij = Pathfinder.dijkstra(nodes, start, end ); <ide> Pathfinder.printPath( nodes, dij ); <ide> }
Java
mit
42f3f08a6c1d92505ebdbfdbc57293a11ede6568
0
FunnyMan3595/mcp_deobfuscate,FunnyMan3595/mcp_deobfuscate
package org.ldg.mcpd; import org.objectweb.asm.*; import org.objectweb.asm.commons.*; import java.io.*; import java.util.*; public class MCPDRemapper extends Remapper implements MCPDClassHandler { List<String> exemptions; MCPDInheritanceGraph inheritance; String default_package = null; Map<String, String> packages = new HashMap<String, String>(); Map<String, String> classes = new HashMap<String, String>(); Map<String, String> fields = new HashMap<String, String>(); Map<String, String> methods = new HashMap<String, String>(); public MCPDRemapper(File configfile, List<String> exclude, MCPDInheritanceGraph inheritanceGraph) throws IOException { exemptions = exclude; if (exemptions == null) { exemptions = new ArrayList<String>(); } inheritance = inheritanceGraph; FileInputStream fis = new FileInputStream(configfile); InputStreamReader isr = new InputStreamReader(fis); BufferedReader config = new BufferedReader(isr); String line = config.readLine(); while (line != null) { String[] pieces = line.trim().split(" "); if (pieces[0].equals("PK:")) { if (pieces.length != 3) { System.out.println("Bad config line: " + line); } String sourcePackage = pieces[1]; String destPackage = pieces[2]; if (sourcePackage.equals(".")) { default_package = destPackage; } else { packages.put(sourcePackage, destPackage); } } else if (pieces[0].equals("CL:")) { if (pieces.length != 3) { System.out.println("Bad config line: " + line); } String sourceClass = pieces[1]; String destClass = pieces[2]; classes.put(sourceClass, destClass); } else if (pieces[0].equals("FD:")) { if (pieces.length != 3) { System.out.println("Bad config line: " + line); } String sourceField = pieces[1]; // Trim off the class name. String[] subpieces = pieces[2].split("/"); String destField = subpieces[subpieces.length - 1]; fields.put(sourceField, destField); } else if (pieces[0].equals("MD:")) { if (pieces.length != 5) { System.out.println("Bad config line: " + line); } String sourceMethod = pieces[1]; String sourceSignature = pieces[2]; // Trim off the class name. String[] subpieces = pieces[3].split("/"); String destMethod = subpieces[subpieces.length - 1]; methods.put(sourceMethod + ";" + sourceSignature, destMethod); } line = config.readLine(); } } public String map(String name) { if (classes.containsKey(name)) { return classes.get(name); } else if (default_package != null && !name.contains("/")) { return default_package + "/" + name; } else { String best_match = ""; for (String pkg : packages.keySet()) { if (pkg.length() > best_match.length() && name.startsWith(pkg + "/")) { best_match = pkg; } } if (best_match.length() > 0) { String mapping = packages.get(best_match); if (mapping.equals(".")) { return name.substring(best_match.length() + 1); } else { return mapping + name.substring(best_match.length()); } } } return name; } public String mapFieldName(String cls, String name, String descriptor) { // Check the class itself first. String key = cls + "/" + name; if (fields.containsKey(key)) { return fields.get(key); } // Then all of its ancestors for (String ancestor : inheritance.getAncestors(cls)) { key = ancestor + "/" + name; if (fields.containsKey(key)) { return fields.get(key); } } return name; } public String mapMethodName(String cls, String name, String descriptor) { // Check the class itself first. String key = cls + "/" + name + ";" + descriptor; if (methods.containsKey(key)) { return methods.get(key); } // Then all of its ancestors for (String ancestor : inheritance.getAncestors(cls)) { key = ancestor + "/" + name + ";" + descriptor; if (methods.containsKey(key)) { return methods.get(key); } } return name; } public String mapFilename(String infile) { // Trim ".class" String inclass = infile.substring(0, infile.length() - 6); // Apply standard remapping. String outclass = map(inclass); return outclass + ".class"; } public boolean isExempt(String infile) { if (infile.toLowerCase().endsWith(".class")) { String inclass = infile.substring(0, infile.length() - 6); for (String exempt : exemptions) { if (inclass.startsWith(exempt + "/")) { return true; } } // Non-exempt class file. return false; } // Non-class files are always exempt. return true; } public boolean needsOutput() { return true; } public String processZippedFilename(String filename) { if (isExempt(filename)) { return null; // Do not process this file; copy it directly. } else { return mapFilename(filename); } } public void handleClass(InputStream in, OutputStream out) throws IOException { // Set up the ASM prerequisites. ClassReader cr = new ClassReader(in); ClassWriter cw = new ClassWriter(0); RemappingClassAdapter visitor = new RemappingClassAdapter(cw, this); // Do the actual remapping. cr.accept(visitor, cr.EXPAND_FRAMES); // Write out the translated class. out.write(cw.toByteArray()); } }
src/main/java/org/ldg/mcpd/MCPDRemapper.java
package org.ldg.mcpd; import org.objectweb.asm.*; import org.objectweb.asm.commons.*; import java.io.*; import java.util.*; public class MCPDRemapper extends Remapper implements MCPDClassHandler { List<String> exemptions; MCPDInheritanceGraph inheritance; String default_package = null; Map<String, String> packages = new HashMap<String, String>(); Map<String, String> classes = new HashMap<String, String>(); Map<String, String> fields = new HashMap<String, String>(); Map<String, String> methods = new HashMap<String, String>(); public MCPDRemapper(File configfile, List<String> exclude, MCPDInheritanceGraph inheritanceGraph) throws IOException { exemptions = exclude; inheritance = inheritanceGraph; FileInputStream fis = new FileInputStream(configfile); InputStreamReader isr = new InputStreamReader(fis); BufferedReader config = new BufferedReader(isr); String line = config.readLine(); while (line != null) { String[] pieces = line.trim().split(" "); if (pieces[0].equals("PK:")) { if (pieces.length != 3) { System.out.println("Bad config line: " + line); } String sourcePackage = pieces[1]; String destPackage = pieces[2]; if (sourcePackage.equals(".")) { default_package = destPackage; } else { packages.put(sourcePackage, destPackage); } } else if (pieces[0].equals("CL:")) { if (pieces.length != 3) { System.out.println("Bad config line: " + line); } String sourceClass = pieces[1]; String destClass = pieces[2]; classes.put(sourceClass, destClass); } else if (pieces[0].equals("FD:")) { if (pieces.length != 3) { System.out.println("Bad config line: " + line); } String sourceField = pieces[1]; // Trim off the class name. String[] subpieces = pieces[2].split("/"); String destField = subpieces[subpieces.length - 1]; fields.put(sourceField, destField); } else if (pieces[0].equals("MD:")) { if (pieces.length != 5) { System.out.println("Bad config line: " + line); } String sourceMethod = pieces[1]; String sourceSignature = pieces[2]; // Trim off the class name. String[] subpieces = pieces[3].split("/"); String destMethod = subpieces[subpieces.length - 1]; methods.put(sourceMethod + ";" + sourceSignature, destMethod); } line = config.readLine(); } } public String map(String name) { if (classes.containsKey(name)) { return classes.get(name); } else if (default_package != null && !name.contains("/")) { return default_package + "/" + name; } else { String best_match = ""; for (String pkg : packages.keySet()) { if (pkg.length() > best_match.length() && name.startsWith(pkg + "/")) { best_match = pkg; } } if (best_match.length() > 0) { return packages.get(best_match) + name.substring(best_match.length()); } } return name; } public String mapFieldName(String cls, String name, String descriptor) { // Check the class itself first. String key = cls + "/" + name; if (fields.containsKey(key)) { return fields.get(key); } // Then all of its ancestors for (String ancestor : inheritance.getAncestors(cls)) { key = ancestor + "/" + name; if (fields.containsKey(key)) { return fields.get(key); } } return name; } public String mapMethodName(String cls, String name, String descriptor) { // Check the class itself first. String key = cls + "/" + name + ";" + descriptor; if (methods.containsKey(key)) { return methods.get(key); } // Then all of its ancestors for (String ancestor : inheritance.getAncestors(cls)) { key = ancestor + "/" + name + ";" + descriptor; if (methods.containsKey(key)) { return methods.get(key); } } return name; } public String mapFilename(String infile) { // Trim ".class" String inclass = infile.substring(0, infile.length() - 6); // Apply standard remapping. String outclass = map(inclass); return outclass + ".class"; } public boolean isExempt(String infile) { if (infile.toLowerCase().endsWith(".class")) { String inclass = infile.substring(0, infile.length() - 6); for (String exempt : exemptions) { if (inclass.startsWith(exempt + "/")) { return true; } } // Non-exempt class file. return false; } // Non-class files are always exempt. return true; } public boolean needsOutput() { return true; } public String processZippedFilename(String filename) { if (isExempt(filename)) { return null; // Do not process this file; copy it directly. } else { return mapFilename(filename); } } public void handleClass(InputStream in, OutputStream out) throws IOException { // Set up the ASM prerequisites. ClassReader cr = new ClassReader(in); ClassWriter cw = new ClassWriter(0); RemappingClassAdapter visitor = new RemappingClassAdapter(cw, this); // Do the actual remapping. cr.accept(visitor, cr.EXPAND_FRAMES); // Write out the translated class. out.write(cw.toByteArray()); } }
Fixed a couple small bugs that were hampering reobfuscation.
src/main/java/org/ldg/mcpd/MCPDRemapper.java
Fixed a couple small bugs that were hampering reobfuscation.
<ide><path>rc/main/java/org/ldg/mcpd/MCPDRemapper.java <ide> <ide> public MCPDRemapper(File configfile, List<String> exclude, MCPDInheritanceGraph inheritanceGraph) throws IOException { <ide> exemptions = exclude; <add> if (exemptions == null) { <add> exemptions = new ArrayList<String>(); <add> } <ide> inheritance = inheritanceGraph; <ide> <ide> FileInputStream fis = new FileInputStream(configfile); <ide> } <ide> <ide> if (best_match.length() > 0) { <del> return packages.get(best_match) <del> + name.substring(best_match.length()); <add> String mapping = packages.get(best_match); <add> if (mapping.equals(".")) { <add> return name.substring(best_match.length() + 1); <add> } else { <add> return mapping + name.substring(best_match.length()); <add> } <ide> } <ide> } <ide>
JavaScript
mit
7015ef60cd0315a17473e6791a4376f9a69bc110
0
iamchathu/brackets,Live4Code/brackets,m66n/brackets,simon66/brackets,veveykocute/brackets,shal1y/brackets,alexkid64/brackets,zaggino/brackets-electron,IAmAnubhavSaini/brackets,pomadgw/brackets,ropik/brackets,massimiliano76/brackets,massimiliano76/brackets,kilroy23/brackets,gcommetti/brackets,goldcase/brackets,ecwebservices/brackets,emanziano/brackets,MarcelGerber/brackets,Rynaro/brackets,Denisov21/brackets,resir014/brackets,Andrey-Pavlov/brackets,pratts/brackets,alexkid64/brackets,fashionsun/brackets,adrianhartanto0/brackets,pratts/brackets,michaeljayt/brackets,rafaelstz/brackets,fronzec/brackets,Mosoc/brackets,richmondgozarin/brackets,jiawenbo/brackets,goldcase/brackets,y12uc231/brackets,Rynaro/brackets,fvntr/brackets,MarcelGerber/brackets,ecwebservices/brackets,chrismoulton/brackets,siddharta1337/brackets,wangjun/brackets,Th30/brackets,sophiacaspar/brackets,robertkarlsson/brackets,zaggino/brackets-electron,bidle/brackets,Jonavin/brackets,abhisekp/brackets,eric-stanley/brackets,adrianhartanto0/brackets,zhukaixy/brackets,NickersF/brackets,gcommetti/brackets,stowball/brackets,treejames/brackets,ggusman/present,2youyouo2/cocoslite,mat-mcloughlin/brackets,massimiliano76/brackets,cosmosgenius/brackets,lovewitty/brackets,wangjun/brackets,adobe/brackets,dtcom/MyPSDBracket,andrewnc/brackets,srinivashappy/brackets,show0017/brackets,thr0w/brackets,hanmichael/brackets,shal1y/brackets,Free-Technology-Guild/brackets,shal1y/brackets,kolipka/brackets,jiawenbo/brackets,show0017/brackets,riselabs-ufba/RiPLE-HC-ExperimentalData,netlams/brackets,nucliweb/brackets,gwynndesign/brackets,lunode/brackets,ChaofengZhou/brackets,falcon1812/brackets,ricciozhang/brackets,ecwebservices/brackets,phillipalexander/brackets,resir014/brackets,mat-mcloughlin/brackets,MarcelGerber/brackets,2youyouo2/cocoslite,82488059/brackets,tan9/brackets,adrianhartanto0/brackets,revi/brackets,Th30/brackets,wakermahmud/brackets,keir-rex/brackets,abhisekp/brackets,Free-Technology-Guild/brackets,cosmosgenius/brackets,y12uc231/brackets,chinnyannieb/brackets,srhbinion/brackets,albertinad/brackets,Fcmam5/brackets,SidBala/brackets,wakermahmud/brackets,wesleifreitas/brackets,ropik/brackets,Rajat-dhyani/brackets,ForkedRepos/brackets,udhayam/brackets,revi/brackets,jacobnash/brackets,ralic/brackets,shiyamkumar/brackets,srhbinion/brackets,MahadevanSrinivasan/brackets,IAmAnubhavSaini/brackets,jacobnash/brackets,chambej/brackets,RobertJGabriel/brackets,pomadgw/brackets,pratts/brackets,mjurczyk/brackets,gwynndesign/brackets,abhisekp/brackets,L0g1k/brackets,ScalaInc/brackets,ChaofengZhou/brackets,bidle/brackets,kilroy23/brackets,m66n/brackets,Denisov21/brackets,sophiacaspar/brackets,brianjking/brackets,StephanieMak/brackets,wesleifreitas/brackets,Real-Currents/brackets,NKcentinel/brackets,busykai/brackets,pkdevbox/brackets,weebygames/brackets,Lojsan123/brackets,RamirezWillow/brackets,Andrey-Pavlov/brackets,FTG-003/brackets,alicoding/nimble,chinnyannieb/brackets,hanmichael/brackets,stowball/brackets,CapeSepias/brackets,ChaofengZhou/brackets,riselabs-ufba/RiPLE-HC-ExperimentalData,Pomax/brackets,ficristo/brackets,youprofit/brackets,ChaofengZhou/brackets,Rajat-dhyani/brackets,Jonavin/brackets,Andrey-Pavlov/brackets,TylerL-uxai/brackets,rlugojr/brackets,Lojsan123/brackets,eric-stanley/brackets,flukeout/brackets,ls2uper/brackets,Cartman0/brackets,simon66/brackets,rlugojr/brackets,JordanTheriault/brackets,jiimaho/brackets,IAmAnubhavSaini/brackets,sophiacaspar/brackets,ForkedRepos/brackets,petetnt/brackets,michaeljayt/brackets,Denisov21/brackets,Wikunia/brackets,sgupta7857/brackets,michaeljayt/brackets,Real-Currents/brackets,kolipka/brackets,srhbinion/brackets,ficristo/brackets,veveykocute/brackets,keir-rex/brackets,veveykocute/brackets,gupta-tarun/brackets,lunode/brackets,zhukaixy/brackets,riselabs-ufba/RiPLE-HC-ExperimentalData,thehogfather/brackets,Rynaro/brackets,iamchathu/brackets,andrewnc/brackets,rlugojr/brackets,SebastianBoyd/sebastianboyd.github.io-OLD,alicoding/nimble,siddharta1337/brackets,Wikunia/brackets,Free-Technology-Guild/brackets,NKcentinel/brackets,riselabs-ufba/RiPLE-HC-ExperimentalData,jacobnash/brackets,pomadgw/brackets,SebastianBoyd/sebastianboyd.github.io-OLD,amrelnaggar/brackets,chrisle/brackets,malinkie/brackets,zLeonjo/brackets,wangjun/brackets,Pomax/brackets,wangjun/brackets,udhayam/brackets,TylerL-uxai/brackets,dangkhue27/brackets,tan9/brackets,zhukaixy/brackets,mcanthony/brackets,udhayam/brackets,treejames/brackets,ralic/brackets,TylerL-uxai/brackets,CapeSepias/brackets,L0g1k/brackets,lovewitty/brackets,ScalaInc/brackets,robertkarlsson/brackets,Rynaro/brackets,sedge/nimble,RamirezWillow/brackets,iamchathu/brackets,Live4Code/brackets,Mosoc/brackets,adrianhartanto0/brackets,flukeout/brackets,ricciozhang/brackets,CapeSepias/brackets,chambej/brackets,karevn/brackets,sophiacaspar/brackets,gcommetti/brackets,gideonthomas/brackets,No9/brackets,chambej/brackets,iamchathu/brackets,sgupta7857/brackets,fastrde/brackets,Th30/brackets,Rajat-dhyani/brackets,pkdevbox/brackets,thehogfather/brackets,Live4Code/brackets,raygervais/brackets,CapeSepias/brackets,treejames/brackets,fvntr/brackets,TylerL-uxai/brackets,srinivashappy/brackets,phillipalexander/brackets,StephanieMak/brackets,fcjailybo/brackets,show0017/brackets,MarcelGerber/brackets,jiawenbo/brackets,rlugojr/brackets,simon66/brackets,sprintr/brackets,netlams/brackets,mozilla/brackets,shal1y/brackets,kolipka/brackets,adobe/brackets,xantage/brackets,malinkie/brackets,No9/brackets,fabricadeaplicativos/brackets,amrelnaggar/brackets,sedge/nimble,RamirezWillow/brackets,albertinad/brackets,SebastianBoyd/sebastianboyd.github.io-OLD,cdot-brackets-extensions/nimble-htmlLint,raygervais/brackets,NGHGithub/brackets,mjurczyk/brackets,youprofit/brackets,ecwebservices/brackets,macdg/brackets,jacobnash/brackets,srinivashappy/brackets,SebastianBoyd/sebastianboyd.github.io-OLD,keir-rex/brackets,richmondgozarin/brackets,Lojsan123/brackets,y12uc231/brackets,Cartman0/brackets,ls2uper/brackets,uwsd/brackets,RobertJGabriel/brackets,karevn/brackets,alicoding/nimble,wakermahmud/brackets,iamchathu/brackets,fabricadeaplicativos/brackets,No9/brackets,pkdevbox/brackets,zaggino/brackets-electron,fcjailybo/brackets,albertinad/brackets,MahadevanSrinivasan/brackets,jmarkina/brackets,rafaelstz/brackets,weebygames/brackets,emanziano/brackets,ForkedRepos/brackets,nucliweb/brackets,gideonthomas/brackets,eric-stanley/brackets,ls2uper/brackets,SidBala/brackets,goldcase/brackets,karevn/brackets,kilroy23/brackets,Live4Code/brackets,emanziano/brackets,treejames/brackets,Mosoc/brackets,y12uc231/brackets,eric-stanley/brackets,pomadgw/brackets,xantage/brackets,StephanieMak/brackets,brianjking/brackets,JordanTheriault/brackets,IAmAnubhavSaini/brackets,ashleygwilliams/brackets,fastrde/brackets,Rajat-dhyani/brackets,busykai/brackets,tan9/brackets,fashionsun/brackets,raygervais/brackets,brianjking/brackets,thehogfather/brackets,MantisWare/brackets,quasto/ArduinoStudio,alexkid64/brackets,fastrde/brackets,pkdevbox/brackets,JordanTheriault/brackets,Wikunia/brackets,falcon1812/brackets,humphd/brackets,marcominetti/brackets,jiimaho/brackets,cdot-brackets-extensions/nimble-htmlLint,adobe/brackets,fronzec/brackets,michaeljayt/brackets,alexkid64/brackets,chinnyannieb/brackets,fastrde/brackets,jmarkina/brackets,2youyouo2/cocoslite,ficristo/brackets,keir-rex/brackets,ggusman/present,cosmosgenius/brackets,gupta-tarun/brackets,sedge/nimble,flukeout/brackets,uwsd/brackets,zLeonjo/brackets,fabricadeaplicativos/brackets,veveykocute/brackets,arduino-org/ArduinoStudio,massimiliano76/brackets,sgupta7857/brackets,ForkedRepos/brackets,kilroy23/brackets,fvntr/brackets,ficristo/brackets,youprofit/brackets,zaggino/brackets-electron,FTG-003/brackets,revi/brackets,baig/brackets,wesleifreitas/brackets,amrelnaggar/brackets,fronzec/brackets,gupta-tarun/brackets,xantage/brackets,Denisov21/brackets,netlams/brackets,GHackAnonymous/brackets,No9/brackets,chambej/brackets,gideonthomas/brackets,resir014/brackets,lovewitty/brackets,ggusman/present,raygervais/brackets,rafaelstz/brackets,flukeout/brackets,busykai/brackets,fabricadeaplicativos/brackets,show0017/brackets,amrelnaggar/brackets,siddharta1337/brackets,simon66/brackets,GHackAnonymous/brackets,baig/brackets,falcon1812/brackets,gupta-tarun/brackets,siddharta1337/brackets,quasto/ArduinoStudio,gupta-tarun/brackets,youprofit/brackets,Andrey-Pavlov/brackets,mjurczyk/brackets,2youyouo2/cocoslite,cdot-brackets-extensions/nimble-htmlLint,MantisWare/brackets,NGHGithub/brackets,arduino-org/ArduinoStudio,RamirezWillow/brackets,fronzec/brackets,ricciozhang/brackets,flukeout/brackets,pratts/brackets,thr0w/brackets,albertinad/brackets,lovewitty/brackets,Fcmam5/brackets,FTG-003/brackets,phillipalexander/brackets,mozilla/brackets,GHackAnonymous/brackets,treejames/brackets,mjurczyk/brackets,jiimaho/brackets,ashleygwilliams/brackets,rlugojr/brackets,ficristo/brackets,mcanthony/brackets,sprintr/brackets,goldcase/brackets,zhukaixy/brackets,dangkhue27/brackets,L0g1k/brackets,mozilla/brackets,dtcom/MyPSDBracket,brianjking/brackets,RobertJGabriel/brackets,Lojsan123/brackets,ecwebservices/brackets,fashionsun/brackets,resir014/brackets,resir014/brackets,srinivashappy/brackets,humphd/brackets,jmarkina/brackets,ls2uper/brackets,ScalaInc/brackets,Pomax/brackets,weebygames/brackets,82488059/brackets,netlams/brackets,simon66/brackets,bidle/brackets,Cartman0/brackets,gwynndesign/brackets,Wikunia/brackets,baig/brackets,pkdevbox/brackets,fcjailybo/brackets,Th30/brackets,82488059/brackets,jiimaho/brackets,andrewnc/brackets,mcanthony/brackets,malinkie/brackets,thr0w/brackets,humphd/brackets,Real-Currents/brackets,mozilla/brackets,chrismoulton/brackets,MahadevanSrinivasan/brackets,macdg/brackets,bidle/brackets,lunode/brackets,82488059/brackets,shal1y/brackets,tan9/brackets,Real-Currents/brackets,massimiliano76/brackets,falcon1812/brackets,malinkie/brackets,thr0w/brackets,Jonavin/brackets,dtcom/MyPSDBracket,GHackAnonymous/brackets,MahadevanSrinivasan/brackets,chinnyannieb/brackets,uwsd/brackets,goldcase/brackets,andrewnc/brackets,fashionsun/brackets,stowball/brackets,MarcelGerber/brackets,ropik/brackets,jiawenbo/brackets,Mosoc/brackets,karevn/brackets,srinivashappy/brackets,shiyamkumar/brackets,siddharta1337/brackets,NGHGithub/brackets,MantisWare/brackets,RobertJGabriel/brackets,kolipka/brackets,petetnt/brackets,FTG-003/brackets,arduino-org/ArduinoStudio,stowball/brackets,RamirezWillow/brackets,Cartman0/brackets,sgupta7857/brackets,youprofit/brackets,zLeonjo/brackets,Pomax/brackets,NickersF/brackets,humphd/brackets,stowball/brackets,riselabs-ufba/RiPLE-HC-ExperimentalData,Lojsan123/brackets,Jonavin/brackets,revi/brackets,wesleifreitas/brackets,Th30/brackets,fabricadeaplicativos/brackets,busykai/brackets,Andrey-Pavlov/brackets,richmondgozarin/brackets,SidBala/brackets,fcjailybo/brackets,robertkarlsson/brackets,phillipalexander/brackets,Real-Currents/brackets,Cartman0/brackets,fronzec/brackets,ScalaInc/brackets,zhukaixy/brackets,udhayam/brackets,malinkie/brackets,michaeljayt/brackets,chrismoulton/brackets,lunode/brackets,m66n/brackets,gideonthomas/brackets,Mosoc/brackets,chrismoulton/brackets,keir-rex/brackets,StephanieMak/brackets,emanziano/brackets,jiimaho/brackets,fcjailybo/brackets,ls2uper/brackets,nucliweb/brackets,thr0w/brackets,wesleifreitas/brackets,sophiacaspar/brackets,ashleygwilliams/brackets,Pomax/brackets,dangkhue27/brackets,shiyamkumar/brackets,FTG-003/brackets,SidBala/brackets,ScalaInc/brackets,udhayam/brackets,Denisov21/brackets,fashionsun/brackets,amrelnaggar/brackets,zaggino/brackets-electron,NKcentinel/brackets,StephanieMak/brackets,chrisle/brackets,richmondgozarin/brackets,pratts/brackets,falcon1812/brackets,lunode/brackets,mcanthony/brackets,RobertJGabriel/brackets,gcommetti/brackets,NickersF/brackets,Rajat-dhyani/brackets,ricciozhang/brackets,ashleygwilliams/brackets,veveykocute/brackets,quasto/ArduinoStudio,zLeonjo/brackets,ralic/brackets,ralic/brackets,cdot-brackets-extensions/nimble-htmlLint,xantage/brackets,phillipalexander/brackets,jiawenbo/brackets,wakermahmud/brackets,petetnt/brackets,gideonthomas/brackets,humphd/brackets,zLeonjo/brackets,quasto/ArduinoStudio,arduino-org/ArduinoStudio,rafaelstz/brackets,jacobnash/brackets,jmarkina/brackets,robertkarlsson/brackets,chambej/brackets,marcominetti/brackets,karevn/brackets,wangjun/brackets,macdg/brackets,ricciozhang/brackets,NGHGithub/brackets,NKcentinel/brackets,mjurczyk/brackets,JordanTheriault/brackets,wakermahmud/brackets,shiyamkumar/brackets,MantisWare/brackets,macdg/brackets,ropik/brackets,gwynndesign/brackets,macdg/brackets,sprintr/brackets,dangkhue27/brackets,sgupta7857/brackets,chrisle/brackets,JordanTheriault/brackets,IAmAnubhavSaini/brackets,chrisle/brackets,zaggino/brackets-electron,nucliweb/brackets,sedge/nimble,y12uc231/brackets,sprintr/brackets,raygervais/brackets,MantisWare/brackets,hanmichael/brackets,baig/brackets,revi/brackets,weebygames/brackets,adobe/brackets,andrewnc/brackets,emanziano/brackets,robertkarlsson/brackets,ChaofengZhou/brackets,MahadevanSrinivasan/brackets,Free-Technology-Guild/brackets,abhisekp/brackets,netlams/brackets,eric-stanley/brackets,srhbinion/brackets,No9/brackets,albertinad/brackets,tan9/brackets,alicoding/nimble,busykai/brackets,rafaelstz/brackets,gcommetti/brackets,sprintr/brackets,petetnt/brackets,82488059/brackets,srhbinion/brackets,lovewitty/brackets,Jonavin/brackets,chinnyannieb/brackets,L0g1k/brackets,mat-mcloughlin/brackets,thehogfather/brackets,petetnt/brackets,Real-Currents/brackets,nucliweb/brackets,ralic/brackets,adrianhartanto0/brackets,hanmichael/brackets,uwsd/brackets,Wikunia/brackets,pomadgw/brackets,fvntr/brackets,mat-mcloughlin/brackets,weebygames/brackets,bidle/brackets,Free-Technology-Guild/brackets,abhisekp/brackets,arduino-org/ArduinoStudio,baig/brackets,Fcmam5/brackets,Rynaro/brackets,dtcom/MyPSDBracket,hanmichael/brackets,mcanthony/brackets,kolipka/brackets,alexkid64/brackets,NickersF/brackets,adobe/brackets,ggusman/present,mozilla/brackets,brianjking/brackets,jmarkina/brackets,SidBala/brackets,Fcmam5/brackets,SebastianBoyd/sebastianboyd.github.io-OLD,thehogfather/brackets,chrisle/brackets,Fcmam5/brackets,cosmosgenius/brackets,TylerL-uxai/brackets,ashleygwilliams/brackets,GHackAnonymous/brackets,Live4Code/brackets,riselabs-ufba/RiPLE-HC-ExperimentalData,dangkhue27/brackets,NickersF/brackets,richmondgozarin/brackets,quasto/ArduinoStudio,sedge/nimble,uwsd/brackets,xantage/brackets,chrismoulton/brackets,kilroy23/brackets,ForkedRepos/brackets,fastrde/brackets,fvntr/brackets,m66n/brackets,m66n/brackets,NGHGithub/brackets,NKcentinel/brackets,shiyamkumar/brackets,CapeSepias/brackets,2youyouo2/cocoslite
/* * Copyright (c) 2012 Adobe Systems Incorporated. All rights reserved. * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. * */ /*jslint vars: true, plusplus: true, devel: true, nomen: true, indent: 4, maxerr: 50 */ /*global define, $, window */ define(function (require, exports, module) { "use strict"; var _ = require("thirdparty/lodash"); var SCROLL_SHADOW_HEIGHT = 5; /** * @private */ var _resizeHandlers = []; /** * Positions shadow background elements to indicate vertical scrolling. * @param {!DOMElement} $displayElement the DOMElement that displays the shadow * @param {!Object} $scrollElement the object that is scrolled * @param {!DOMElement} $shadowTop div .scroller-shadow.top * @param {!DOMElement} $shadowBottom div .scroller-shadow.bottom * @param {boolean} isPositionFixed When using absolute position, top remains at 0. */ function _updateScrollerShadow($displayElement, $scrollElement, $shadowTop, $shadowBottom, isPositionFixed) { var offsetTop = 0, scrollElement = $scrollElement.get(0), scrollTop = scrollElement.scrollTop, topShadowOffset = Math.min(scrollTop - SCROLL_SHADOW_HEIGHT, 0), displayElementWidth = $displayElement.width(); if ($shadowTop) { $shadowTop.css("background-position", "0px " + topShadowOffset + "px"); if (isPositionFixed) { offsetTop = $displayElement.offset().top; $shadowTop.css("top", offsetTop); } if (isPositionFixed) { $shadowTop.css("width", displayElementWidth); } } if ($shadowBottom) { var clientHeight = scrollElement.clientHeight, outerHeight = $displayElement.outerHeight(), scrollHeight = scrollElement.scrollHeight, bottomOffset = outerHeight - clientHeight, bottomShadowOffset = SCROLL_SHADOW_HEIGHT; // outside of shadow div viewport if (scrollHeight > clientHeight) { bottomShadowOffset -= Math.min(SCROLL_SHADOW_HEIGHT, (scrollHeight - (scrollTop + clientHeight))); } $shadowBottom.css("background-position", "0px " + bottomShadowOffset + "px"); $shadowBottom.css("top", offsetTop + outerHeight - SCROLL_SHADOW_HEIGHT); $shadowBottom.css("width", displayElementWidth); } } function getOrCreateShadow($displayElement, position, isPositionFixed) { var $findShadow = $displayElement.find(".scroller-shadow." + position); if ($findShadow.length === 0) { $findShadow = $(window.document.createElement("div")).addClass("scroller-shadow " + position); $displayElement.append($findShadow); } if (!isPositionFixed) { // position is fixed by default $findShadow.css("position", "absolute"); $findShadow.css(position, "0"); } return $findShadow; } /** * Installs event handlers for updatng shadow background elements to indicate vertical scrolling. * @param {!DOMElement} displayElement the DOMElement that displays the shadow. Must fire * "contentChanged" events when the element is resized or repositioned. * @param {?Object} scrollElement the object that is scrolled. Must fire "scroll" events * when the element is scrolled. If null, the displayElement is used. * @param {?boolean} showBottom optionally show the bottom shadow */ function addScrollerShadow(displayElement, scrollElement, showBottom) { // use fixed positioning when the display and scroll elements are the same var isPositionFixed = false; if (!scrollElement) { scrollElement = displayElement; isPositionFixed = true; } // update shadows when the scrolling element is scrolled var $displayElement = $(displayElement), $scrollElement = $(scrollElement); var $shadowTop = getOrCreateShadow($displayElement, "top", isPositionFixed); var $shadowBottom = (showBottom) ? getOrCreateShadow($displayElement, "bottom", isPositionFixed) : null; var doUpdate = function () { _updateScrollerShadow($displayElement, $scrollElement, $shadowTop, $shadowBottom, isPositionFixed); }; $scrollElement.on("scroll.scroller-shadow", doUpdate); $displayElement.on("contentChanged.scroller-shadow", doUpdate); // update immediately doUpdate(); } /** * Remove scroller-shadow effect. * @param {!DOMElement} displayElement the DOMElement that displays the shadow * @param {?Object} scrollElement the object that is scrolled */ function removeScrollerShadow(displayElement, scrollElement) { if (!scrollElement) { scrollElement = displayElement; } var $displayElement = $(displayElement), $scrollElement = $(scrollElement); // remove scrollerShadow elements from DOM $displayElement.find(".scroller-shadow.top").remove(); $displayElement.find(".scroller-shadow.bottom").remove(); // remove event handlers $scrollElement.off("scroll.scroller-shadow"); $displayElement.off("contentChanged.scroller-shadow"); } /** * Utility function to replace jQuery.toggleClass when used with the second argument, which needs to be a true boolean for jQuery * @param {!jQueryObject} $domElement The jQueryObject to toggle the Class on * @param {!string} className Class name or names (separated by spaces) to toggle * @param {!boolean} addClass A truthy value to add the class and a falsy value to remove the class */ function toggleClass($domElement, className, addClass) { if (addClass) { $domElement.addClass(className); } else { $domElement.removeClass(className); } } /** * Within a scrolling DOMElement, creates and positions a styled selection * div to align a single selected list item from a ul list element. * * Assumptions: * - scrollerElement is a child of the #sidebar div * - ul list element fires a "selectionChanged" event after the * selectedClassName is assigned to a new list item * * @param {!DOMElement} scrollElement A DOMElement containing a ul list element * @param {!string} selectedClassName A CSS class name on at most one list item in the contained list */ function sidebarList($scrollerElement, selectedClassName, leafClassName) { var $listElement = $scrollerElement.find("ul"), $selectionMarker, $selectionTriangle, $sidebar = $("#sidebar"), showTriangle = true; // build selectionMarker and position absolute within the scroller $selectionMarker = $(window.document.createElement("div")).addClass("sidebar-selection"); $scrollerElement.prepend($selectionMarker); // enable scrolling $scrollerElement.css("overflow", "auto"); // use relative postioning for clipping the selectionMarker within the scrollElement $scrollerElement.css("position", "relative"); // build selectionTriangle and position fixed to the window $selectionTriangle = $(window.document.createElement("div")).addClass("sidebar-selection-triangle"); $scrollerElement.append($selectionTriangle); selectedClassName = "." + (selectedClassName || "selected"); var updateSelectionTriangle = function () { var selectionMarkerHeight = $selectionMarker.height(), selectionMarkerOffset = $selectionMarker.offset(), // offset relative to *document* scrollerOffset = $scrollerElement.offset(), triangleHeight = $selectionTriangle.outerHeight(), scrollerTop = scrollerOffset.top, scrollerBottom = scrollerTop + $scrollerElement.outerHeight(), scrollerLeft = scrollerOffset.left, triangleTop = selectionMarkerOffset.top; $selectionTriangle.css("top", triangleTop); $selectionTriangle.css("left", $sidebar.width() - $selectionTriangle.outerWidth()); toggleClass($selectionTriangle, "triangle-visible", showTriangle); var triangleClipOffsetYBy = Math.floor((selectionMarkerHeight - triangleHeight) / 2), triangleBottom = triangleTop + triangleHeight + triangleClipOffsetYBy; if (triangleTop < scrollerTop || triangleBottom > scrollerBottom) { $selectionTriangle.css("clip", "rect(" + Math.max(scrollerTop - triangleTop - triangleClipOffsetYBy, 0) + "px, auto, " + (triangleHeight - Math.max(triangleBottom - scrollerBottom, 0)) + "px, auto)"); } else { $selectionTriangle.css("clip", ""); } }; var updateSelectionMarker = function (event, reveal) { // find the selected list item var $listItem = $listElement.find(selectedClassName).closest("li"); if (leafClassName) { showTriangle = $listItem.hasClass(leafClassName); } // always hide selection visuals first to force layout (issue #719) $selectionTriangle.hide(); $selectionMarker.hide(); if ($listItem.length === 1) { // list item position is relative to scroller var selectionMarkerTop = $listItem.offset().top - $scrollerElement.offset().top + $scrollerElement.get(0).scrollTop; // force selection width to match scroller $selectionMarker.width($scrollerElement.get(0).scrollWidth); // move the selectionMarker position to align with the list item $selectionMarker.css("top", selectionMarkerTop); $selectionMarker.show(); updateSelectionTriangle(); $selectionTriangle.show(); // fully scroll to the selectionMarker if it's not initially in the viewport var scrollerElement = $scrollerElement.get(0), scrollerHeight = scrollerElement.clientHeight, selectionMarkerHeight = $selectionMarker.height(), selectionMarkerBottom = selectionMarkerTop + selectionMarkerHeight, currentScrollBottom = scrollerElement.scrollTop + scrollerHeight; // update scrollTop to reveal the selected list item if (reveal) { if (selectionMarkerTop >= currentScrollBottom) { $listItem.get(0).scrollIntoView(false); } else if (selectionMarkerBottom <= scrollerElement.scrollTop) { $listItem.get(0).scrollIntoView(true); } } } }; $listElement.on("selectionChanged", updateSelectionMarker); $scrollerElement.on("scroll", updateSelectionTriangle); $scrollerElement.on("selectionRedraw", updateSelectionTriangle); // update immediately updateSelectionMarker(); // update clipping when the window resizes _resizeHandlers.push(updateSelectionTriangle); } /** * @private */ function _handleResize() { _resizeHandlers.forEach(function (f) { f.apply(); }); } /** * Determine how much of an element rect is clipped in view. * * @param {!DOMElement} $view - A jQuery scrolling container * @param {!{top: number, left: number, height: number, width: number}} * elementRect - rectangle of element's default position/size * @return {{top: number, right: number, bottom: number, left: number}} * amount element rect is clipped in each direction */ function getElementClipSize($view, elementRect) { var delta, clip = { top: 0, right: 0, bottom: 0, left: 0 }, viewOffset = $view.offset() || { top: 0, left: 0}, viewScroller = $view.get(0); // Check if element extends below viewport delta = (elementRect.top + elementRect.height) - (viewOffset.top + $view.height()); if (delta > 0) { clip.bottom = delta; } // Check if element extends above viewport delta = viewOffset.top - elementRect.top; if (delta > 0) { clip.top = delta; } // Check if element extends to the left of viewport delta = viewOffset.left - elementRect.left; if (delta > 0) { clip.left = delta; } // Check if element extends to the right of viewport delta = (elementRect.left + elementRect.width) - (viewOffset.left + $view.width()); if (delta > 0) { clip.right = delta; } return clip; } /** * Within a scrolling DOMElement, if necessary, scroll element into viewport. * * To Perform the minimum amount of scrolling necessary, cases should be handled as follows: * - element already completely in view : no scrolling * - element above viewport : scroll view so element is at top * - element left of viewport : scroll view so element is at left * - element below viewport : scroll view so element is at bottom * - element right of viewport : scroll view so element is at right * * Assumptions: * - $view is a scrolling container * * @param {!DOMElement} $view - A jQuery scrolling container * @param {!DOMElement} $element - A jQuery element * @param {?boolean} scrollHorizontal - whether to also scroll horizontally */ function scrollElementIntoView($view, $element, scrollHorizontal) { var viewOffset = $view.offset(), viewScroller = $view.get(0), element = $element.get(0), elementOffset = $element.offset(); // scroll minimum amount var elementRect = { top: elementOffset.top, left: elementOffset.left, height: $element.height(), width: $element.width() }, clip = getElementClipSize($view, elementRect); if (clip.bottom > 0) { // below viewport $view.scrollTop($view.scrollTop() + clip.bottom); } else if (clip.top > 0) { // above viewport $view.scrollTop($view.scrollTop() - clip.top); } if (scrollHorizontal) { if (clip.left > 0) { $view.scrollLeft($view.scrollLeft() - clip.left); } else if (clip.right > 0) { $view.scrollLeft($view.scrollLeft() + clip.right); } } } /** * HTML formats a file entry name for display in the sidebar. * @param {!File} entry File entry to display * @return {string} HTML formatted string */ function getFileEntryDisplay(entry) { var name = entry.name, i = name.lastIndexOf("."); if (i >= 0) { // Escape all HTML-sensitive characters in filename. name = _.escape(name.substring(0, i)) + "<span class='extension'>" + _.escape(name.substring(i)) + "</span>"; } else { name = _.escape(name); } return name; } /** * Determine the minimum directory path to distinguish duplicate file names * for each file in list. * * @param {Array.<File>} files - list of Files with the same filename * @return {Array.<string>} directory paths to match list of files */ function getDirNamesForDuplicateFiles(files) { // Must have at least two files in list for this to make sense if (files.length <= 1) { return []; } // First collect paths from the list of files and fill map with them var map = {}, filePaths = [], displayPaths = []; files.forEach(function (file, index) { var fp = file.fullPath.split("/"); fp.pop(); // Remove the filename itself displayPaths[index] = fp.pop(); filePaths[index] = fp; if (!map[displayPaths[index]]) { map[displayPaths[index]] = [index]; } else { map[displayPaths[index]].push(index); } }); // This function is used to loop through map and resolve duplicate names var processMap = function (map) { var didSomething = false; _.forEach(map, function (arr, key) { // length > 1 means we have duplicates that need to be resolved if (arr.length > 1) { arr.forEach(function (index) { if (filePaths[index].length !== 0) { displayPaths[index] = filePaths[index].pop() + "/" + displayPaths[index]; didSomething = true; if (!map[displayPaths[index]]) { map[displayPaths[index]] = [index]; } else { map[displayPaths[index]].push(index); } } }); } delete map[key]; }); return didSomething; }; var repeat; do { repeat = processMap(map); } while (repeat); return displayPaths; } // handle all resize handlers in a single listener $(window).resize(_handleResize); // Define public API exports.SCROLL_SHADOW_HEIGHT = SCROLL_SHADOW_HEIGHT; exports.addScrollerShadow = addScrollerShadow; exports.removeScrollerShadow = removeScrollerShadow; exports.sidebarList = sidebarList; exports.scrollElementIntoView = scrollElementIntoView; exports.getElementClipSize = getElementClipSize; exports.getFileEntryDisplay = getFileEntryDisplay; exports.toggleClass = toggleClass; exports.getDirNamesForDuplicateFiles = getDirNamesForDuplicateFiles; });
src/utils/ViewUtils.js
/* * Copyright (c) 2012 Adobe Systems Incorporated. All rights reserved. * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. * */ /*jslint vars: true, plusplus: true, devel: true, nomen: true, indent: 4, maxerr: 50 */ /*global define, $, window */ define(function (require, exports, module) { "use strict"; var _ = require("thirdparty/lodash"); var SCROLL_SHADOW_HEIGHT = 5; /** * @private */ var _resizeHandlers = []; /** * Positions shadow background elements to indicate vertical scrolling. * @param {!DOMElement} $displayElement the DOMElement that displays the shadow * @param {!Object} $scrollElement the object that is scrolled * @param {!DOMElement} $shadowTop div .scroller-shadow.top * @param {!DOMElement} $shadowBottom div .scroller-shadow.bottom * @param {boolean} isPositionFixed When using absolute position, top remains at 0. */ function _updateScrollerShadow($displayElement, $scrollElement, $shadowTop, $shadowBottom, isPositionFixed) { var offsetTop = 0, scrollElement = $scrollElement.get(0), scrollTop = scrollElement.scrollTop, topShadowOffset = Math.min(scrollTop - SCROLL_SHADOW_HEIGHT, 0), displayElementWidth = $displayElement.width(); if ($shadowTop) { $shadowTop.css("background-position", "0px " + topShadowOffset + "px"); if (isPositionFixed) { offsetTop = $displayElement.offset().top; $shadowTop.css("top", offsetTop); } if (isPositionFixed) { $shadowTop.css("width", displayElementWidth); } } if ($shadowBottom) { var clientHeight = scrollElement.clientHeight, outerHeight = $displayElement.outerHeight(), scrollHeight = scrollElement.scrollHeight, bottomOffset = outerHeight - clientHeight, bottomShadowOffset = SCROLL_SHADOW_HEIGHT; // outside of shadow div viewport if (scrollHeight > clientHeight) { bottomShadowOffset -= Math.min(SCROLL_SHADOW_HEIGHT, (scrollHeight - (scrollTop + clientHeight))); } $shadowBottom.css("background-position", "0px " + bottomShadowOffset + "px"); $shadowBottom.css("top", offsetTop + outerHeight - SCROLL_SHADOW_HEIGHT); $shadowBottom.css("width", displayElementWidth); } } function getOrCreateShadow($displayElement, position, isPositionFixed) { var $findShadow = $displayElement.find(".scroller-shadow." + position); if ($findShadow.length === 0) { $findShadow = $(window.document.createElement("div")).addClass("scroller-shadow " + position); $displayElement.append($findShadow); } if (!isPositionFixed) { // position is fixed by default $findShadow.css("position", "absolute"); $findShadow.css(position, "0"); } return $findShadow; } /** * Installs event handlers for updatng shadow background elements to indicate vertical scrolling. * @param {!DOMElement} displayElement the DOMElement that displays the shadow. Must fire * "contentChanged" events when the element is resized or repositioned. * @param {?Object} scrollElement the object that is scrolled. Must fire "scroll" events * when the element is scrolled. If null, the displayElement is used. * @param {?boolean} showBottom optionally show the bottom shadow */ function addScrollerShadow(displayElement, scrollElement, showBottom) { // use fixed positioning when the display and scroll elements are the same var isPositionFixed = false; if (!scrollElement) { scrollElement = displayElement; isPositionFixed = true; } // update shadows when the scrolling element is scrolled var $displayElement = $(displayElement), $scrollElement = $(scrollElement); var $shadowTop = getOrCreateShadow($displayElement, "top", isPositionFixed); var $shadowBottom = (showBottom) ? getOrCreateShadow($displayElement, "bottom", isPositionFixed) : null; var doUpdate = function () { _updateScrollerShadow($displayElement, $scrollElement, $shadowTop, $shadowBottom, isPositionFixed); }; $scrollElement.on("scroll.scroller-shadow", doUpdate); $displayElement.on("contentChanged.scroller-shadow", doUpdate); // update immediately doUpdate(); } /** * Remove scroller-shadow effect. * @param {!DOMElement} displayElement the DOMElement that displays the shadow * @param {?Object} scrollElement the object that is scrolled */ function removeScrollerShadow(displayElement, scrollElement) { if (!scrollElement) { scrollElement = displayElement; } var $displayElement = $(displayElement), $scrollElement = $(scrollElement); // remove scrollerShadow elements from DOM $displayElement.find(".scroller-shadow.top").remove(); $displayElement.find(".scroller-shadow.bottom").remove(); // remove event handlers $scrollElement.off("scroll.scroller-shadow"); $displayElement.off("contentChanged.scroller-shadow"); } /** * Utility function to replace jQuery.toggleClass when used with the second argument, which needs to be a true boolean for jQuery * @param {!jQueryObject} $domElement The jQueryObject to toggle the Class on * @param {!string} className Class name or names (separated by spaces) to toggle * @param {!boolean} addClass A truthy value to add the class and a falsy value to remove the class */ function toggleClass($domElement, className, addClass) { if (addClass) { $domElement.addClass(className); } else { $domElement.removeClass(className); } } /** * Within a scrolling DOMElement, creates and positions a styled selection * div to align a single selected list item from a ul list element. * * Assumptions: * - scrollerElement is a child of the #sidebar div * - ul list element fires a "selectionChanged" event after the * selectedClassName is assigned to a new list item * * @param {!DOMElement} scrollElement A DOMElement containing a ul list element * @param {!string} selectedClassName A CSS class name on at most one list item in the contained list */ function sidebarList($scrollerElement, selectedClassName, leafClassName) { var $listElement = $scrollerElement.find("ul"), $selectionMarker, $selectionTriangle, $sidebar = $("#sidebar"), showTriangle = true; // build selectionMarker and position absolute within the scroller $selectionMarker = $(window.document.createElement("div")).addClass("sidebar-selection"); $scrollerElement.prepend($selectionMarker); // enable scrolling $scrollerElement.css("overflow", "auto"); // use relative postioning for clipping the selectionMarker within the scrollElement $scrollerElement.css("position", "relative"); // build selectionTriangle and position fixed to the window $selectionTriangle = $(window.document.createElement("div")).addClass("sidebar-selection-triangle"); $scrollerElement.append($selectionTriangle); selectedClassName = "." + (selectedClassName || "selected"); var updateSelectionTriangle = function () { var selectionMarkerHeight = $selectionMarker.height(), selectionMarkerOffset = $selectionMarker.offset(), // offset relative to *document* scrollerOffset = $scrollerElement.offset(), triangleHeight = $selectionTriangle.outerHeight(), scrollerTop = scrollerOffset.top, scrollerBottom = scrollerTop + $scrollerElement.outerHeight(), scrollerLeft = scrollerOffset.left, triangleTop = selectionMarkerOffset.top; $selectionTriangle.css("top", triangleTop); $selectionTriangle.css("left", $sidebar.width() - $selectionTriangle.outerWidth()); toggleClass($selectionTriangle, "triangle-visible", showTriangle); var triangleClipOffsetYBy = Math.floor((selectionMarkerHeight - triangleHeight) / 2), triangleBottom = triangleTop + triangleHeight + triangleClipOffsetYBy; if (triangleTop < scrollerTop || triangleBottom > scrollerBottom) { $selectionTriangle.css("clip", "rect(" + Math.max(scrollerTop - triangleTop - triangleClipOffsetYBy, 0) + "px, auto, " + (triangleHeight - Math.max(triangleBottom - scrollerBottom, 0)) + "px, auto)"); } else { $selectionTriangle.css("clip", ""); } }; var updateSelectionMarker = function (event, reveal) { // find the selected list item var $listItem = $listElement.find(selectedClassName).closest("li"); if (leafClassName) { showTriangle = $listItem.hasClass(leafClassName); } // always hide selection visuals first to force layout (issue #719) $selectionTriangle.hide(); $selectionMarker.hide(); if ($listItem.length === 1) { // list item position is relative to scroller var selectionMarkerTop = $listItem.offset().top - $scrollerElement.offset().top + $scrollerElement.get(0).scrollTop; // force selection width to match scroller $selectionMarker.width($scrollerElement.get(0).scrollWidth); // move the selectionMarker position to align with the list item $selectionMarker.css("top", selectionMarkerTop); $selectionMarker.show(); updateSelectionTriangle(); $selectionTriangle.show(); // fully scroll to the selectionMarker if it's not initially in the viewport var scrollerElement = $scrollerElement.get(0), scrollerHeight = scrollerElement.clientHeight, selectionMarkerHeight = $selectionMarker.height(), selectionMarkerBottom = selectionMarkerTop + selectionMarkerHeight, currentScrollBottom = scrollerElement.scrollTop + scrollerHeight; // update scrollTop to reveal the selected list item if (reveal) { if (selectionMarkerTop >= currentScrollBottom) { $listItem.get(0).scrollIntoView(false); } else if (selectionMarkerBottom <= scrollerElement.scrollTop) { $listItem.get(0).scrollIntoView(true); } } } }; $listElement.on("selectionChanged", updateSelectionMarker); $scrollerElement.on("scroll", updateSelectionTriangle); $scrollerElement.on("selectionRedraw", updateSelectionTriangle); // update immediately updateSelectionMarker(); // update clipping when the window resizes _resizeHandlers.push(updateSelectionTriangle); } /** * @private */ function _handleResize() { _resizeHandlers.forEach(function (f) { f.apply(); }); } /** * Determine how much of an element rect is clipped in view. * * @param {!DOMElement} $view - A jQuery scrolling container * @param {!{top: number, left: number, height: number, width: number}} * elementRect - rectangle of element's default position/size * @return {{top: number, right: number, bottom: number, left: number}} * amount element rect is clipped in each direction */ function getElementClipSize($view, elementRect) { var delta, clip = { top: 0, right: 0, bottom: 0, left: 0 }, viewOffset = $view.offset() || { top: 0, left: 0}, viewScroller = $view.get(0); // Check if element extends below viewport delta = (elementRect.top + elementRect.height) - (viewOffset.top + $view.height()); if (delta > 0) { clip.bottom = delta; } // Check if element extends above viewport delta = viewOffset.top - elementRect.top; if (delta > 0) { clip.top = delta; } // Check if element extends to the left of viewport delta = viewOffset.left - elementRect.left; if (delta > 0) { clip.left = delta; } // Check if element extends to the right of viewport delta = (elementRect.left + elementRect.width) - (viewOffset.left + $view.width()); if (delta > 0) { clip.right = delta; } return clip; } /** * Within a scrolling DOMElement, if necessary, scroll element into viewport. * * To Perform the minimum amount of scrolling necessary, cases should be handled as follows: * - element already completely in view : no scrolling * - element above viewport : scroll view so element is at top * - element left of viewport : scroll view so element is at left * - element below viewport : scroll view so element is at bottom * - element right of viewport : scroll view so element is at right * * Assumptions: * - $view is a scrolling container * * @param {!DOMElement} $view - A jQuery scrolling container * @param {!DOMElement} $element - A jQuery element * @param {?boolean} scrollHorizontal - whether to also scroll horizontally */ function scrollElementIntoView($view, $element, scrollHorizontal) { var viewOffset = $view.offset(), viewScroller = $view.get(0), element = $element.get(0), elementOffset = $element.offset(); // scroll minimum amount var elementRect = { top: elementOffset.top, left: elementOffset.left, height: $element.height(), width: $element.width() }, clip = getElementClipSize($view, elementRect); if (clip.bottom > 0) { // below viewport $view.scrollTop($view.scrollTop() + clip.bottom); } else if (clip.top > 0) { // above viewport $view.scrollTop($view.scrollTop() - clip.top); } if (scrollHorizontal) { if (clip.left > 0) { $view.scrollLeft($view.scrollLeft() - clip.left); } else if (clip.right > 0) { $view.scrollLeft($view.scrollLeft() + clip.right); } } } /** * HTML formats a file entry name for display in the sidebar. * @param {!File} entry File entry to display * @return {string} HTML formatted string */ function getFileEntryDisplay(entry) { var name = entry.name, i = name.lastIndexOf("."); if (i >= 0) { // Escape all HTML-sensitive characters in filename. name = _.escape(name.substring(0, i)) + "<span class='extension'>" + _.escape(name.substring(i)) + "</span>"; } return name; } /** * Determine the minimum directory path to distinguish duplicate file names * for each file in list. * * @param {Array.<File>} files - list of Files with the same filename * @return {Array.<string>} directory paths to match list of files */ function getDirNamesForDuplicateFiles(files) { // Must have at least two files in list for this to make sense if (files.length <= 1) { return []; } // First collect paths from the list of files and fill map with them var map = {}, filePaths = [], displayPaths = []; files.forEach(function (file, index) { var fp = file.fullPath.split("/"); fp.pop(); // Remove the filename itself displayPaths[index] = fp.pop(); filePaths[index] = fp; if (!map[displayPaths[index]]) { map[displayPaths[index]] = [index]; } else { map[displayPaths[index]].push(index); } }); // This function is used to loop through map and resolve duplicate names var processMap = function (map) { var didSomething = false; _.forEach(map, function (arr, key) { // length > 1 means we have duplicates that need to be resolved if (arr.length > 1) { arr.forEach(function (index) { if (filePaths[index].length !== 0) { displayPaths[index] = filePaths[index].pop() + "/" + displayPaths[index]; didSomething = true; if (!map[displayPaths[index]]) { map[displayPaths[index]] = [index]; } else { map[displayPaths[index]].push(index); } } }); } delete map[key]; }); return didSomething; }; var repeat; do { repeat = processMap(map); } while (repeat); return displayPaths; } // handle all resize handlers in a single listener $(window).resize(_handleResize); // Define public API exports.SCROLL_SHADOW_HEIGHT = SCROLL_SHADOW_HEIGHT; exports.addScrollerShadow = addScrollerShadow; exports.removeScrollerShadow = removeScrollerShadow; exports.sidebarList = sidebarList; exports.scrollElementIntoView = scrollElementIntoView; exports.getElementClipSize = getElementClipSize; exports.getFileEntryDisplay = getFileEntryDisplay; exports.toggleClass = toggleClass; exports.getDirNamesForDuplicateFiles = getDirNamesForDuplicateFiles; });
Escape html-sensitive characters for any file/folder without the extension.
src/utils/ViewUtils.js
Escape html-sensitive characters for any file/folder without the extension.
<ide><path>rc/utils/ViewUtils.js <ide> if (i >= 0) { <ide> // Escape all HTML-sensitive characters in filename. <ide> name = _.escape(name.substring(0, i)) + "<span class='extension'>" + _.escape(name.substring(i)) + "</span>"; <add> } else { <add> name = _.escape(name); <ide> } <ide> <ide> return name;
Java
apache-2.0
9627a784495d4b078660db743b4757b3606954df
0
javalite/activejdbc,javalite/activejdbc,javalite/activejdbc,javalite/activejdbc
/* Copyright 2009-2010 Igor Polevoy Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package org.javalite.activeweb; import org.javalite.common.Convert; import org.javalite.common.Util; import org.apache.commons.fileupload.FileItemIterator; import org.apache.commons.fileupload.servlet.ServletFileUpload; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.servlet.http.HttpServletRequest; import java.io.*; import java.net.URL; import java.security.Key; import java.util.*; import static java.util.Arrays.asList; import static org.javalite.common.Collections.list; import static org.javalite.common.Collections.map; /** * @author Igor Polevoy */ public class HttpSupport { private Logger logger = LoggerFactory.getLogger(getClass().getName()); protected void logInfo(String info){ logger.info(info); } protected void logDebug(String info){ logger.debug(info); } protected void logWarning(String info){ logger.warn(info); } protected void logWarning(String info, Throwable e){ logger.warn(info, e); } protected void logError(String info){ logger.error(info); } protected void logError(Throwable e){ logger.error("", e); } protected void logError(String info, Throwable e){ logger.error(info, e); } /** * Assigns a value for a view. * * @param name name of value * @param value value. */ protected void assign(String name, Object value) { KeyWords.check(name); Context.getHttpRequest().setAttribute(name, value); } /** * Alias to {@link #assign(String, Object)}. * * @param name name of object to be passed to view * @param value object to be passed to view */ protected void view(String name, Object value) { assign(name, value); } /** * Convenience method, calls {@link #assign(String, Object)} internally. * The keys in teh map are converted to String values. * * @param values map with values to pass to view. */ protected void view(Map values){ for(Object key:values.keySet() ){ assign(key.toString(), values.get(key)); } } /** * Convenience method, calls {@link #assign(String, Object)} internally. * * */ protected void view(Object ... values){ view(map(values)); } public class HttpBuilder { private ControllerResponse controllerResponse; private HttpBuilder(ControllerResponse controllerResponse){ this.controllerResponse = controllerResponse; } protected ControllerResponse getControllerResponse() { return controllerResponse; } /** * Sets content type of response. * These can be "text/html". Value "text/html" is set by default. * * @param contentType content type value. * @return HTTP Object */ public HttpBuilder contentType(String contentType) { controllerResponse.setContentType(contentType); return this; } /** * Sets a HTTP header on response. * * @param name name of header. * @param value value of header. */ public HttpBuilder header(String name, String value){ Context.getHttpResponse().setHeader(name, value); return this; } /** * Overrides HTTP status with a different value. * For values and more information, look here: * <a href='http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html'>HTTP Status Codes</a>. * * By default, the status is set to 200, OK. * * @param status HTTP status code. */ public void status(int status){ controllerResponse.setStatus(status); } } public class RenderBuilder extends HttpBuilder { private RenderBuilder(RenderTemplateResponse response){ super(response); } /** * Use this method to override a default layout configured. * * @param layout name of another layout. */ public RenderBuilder layout(String layout){ getRenderTemplateResponse().setLayout(layout); return this; } protected RenderTemplateResponse getRenderTemplateResponse(){ return (RenderTemplateResponse)getControllerResponse(); } /** * call this method to turn off all layouts. The view will be rendered raw - no layouts. */ public RenderBuilder noLayout(){ getRenderTemplateResponse().setLayout(null); return this; } } /** * Renders results with a template. * * This call must be the last call in the action. * * @param template - template name, must be "absolute", starting with slash, * such as: "/controller_dir/action_template". * @param values map with values to pass to view. * @return instance of {@link RenderBuilder}, which is used to provide additional parameters. */ protected RenderBuilder render(String template, Map values) { RenderTemplateResponse resp = new RenderTemplateResponse(values, template); Context.setControllerResponse(resp); return new RenderBuilder(resp); } /** * Redirects to a an action of this controller, or an action of a different controller. * This method does not expect a full URL. * * @param path - expected to be a path within the application. * @return instance of {@link HttpSupport.HttpBuilder} to accept additional information. */ protected HttpBuilder redirect(String path) { RedirectResponse resp = new RedirectResponse(path); Context.setControllerResponse(resp); return new HttpBuilder(resp); } /** * Redirects to another URL (usually another site). * * @param url absolute URL: <code>http://domain/path...</code>. * @return {@link HttpSupport.HttpBuilder}, to accept additional information. */ protected HttpBuilder redirect(URL url) { RedirectResponse resp = new RedirectResponse(url); Context.setControllerResponse(resp); return new HttpBuilder(resp); } /** * Redirects to referrer if one exists. If a referrer does not exist, it will be redirected to * the <code>defaultReference</code>. * * @param defaultReference where to redirect - can be absolute or relative; this will be used in case * the request does not provide a "Referrer" header. * @return {@link HttpSupport.HttpBuilder}, to accept additional information. */ protected HttpBuilder redirectToReferrer(String defaultReference) { String referrer = Context.getHttpRequest().getHeader("Referer"); referrer = referrer == null? defaultReference: referrer; RedirectResponse resp = new RedirectResponse(referrer); Context.setControllerResponse(resp); return new HttpBuilder(resp); } /** * Redirects to referrer if one exists. If a referrer does not exist, it will be redirected to * the root of the application. * * @return {@link HttpSupport.HttpBuilder}, to accept additional information. */ protected HttpBuilder redirectToReferrer() { String referrer = Context.getHttpRequest().getHeader("Referer"); referrer = referrer == null? Context.getHttpRequest().getContextPath(): referrer; RedirectResponse resp = new RedirectResponse(referrer); Context.setControllerResponse(resp); return new HttpBuilder(resp); } /** * Convenience method for {@link #redirect(Class, java.util.Map)}. * * @param controllerClass controller class where to send redirect. * @param action action to redirect to. * @param id id to redirect to. * @return {@link HttpSupport.HttpBuilder}, to accept additional information. */ protected <T extends AppController> HttpBuilder redirect(Class<T> controllerClass, String action, Object id){ return redirect(controllerClass, map("action", action, "id", id)); } /** * Convenience method for {@link #redirect(Class, java.util.Map)}. * * @param controllerClass controller class where to send redirect. * @param id id to redirect to. * @return {@link HttpSupport.HttpBuilder}, to accept additional information. */ protected <T extends AppController> HttpBuilder redirect(Class<T> controllerClass, Object id){ return redirect(controllerClass, map("id", id)); } /** * Convenience method for {@link #redirect(Class, java.util.Map)}. * * @param controllerClass controller class where to send redirect. * @param action action to redirect to. * @return {@link HttpSupport.HttpBuilder}, to accept additional information. */ protected <T extends AppController> HttpBuilder redirect(Class<T> controllerClass, String action){ return redirect(controllerClass, map("action", action)); } /** * Convenience method for {@link #redirect(Class, java.util.Map)}. * * @param controllerClass controller class where to send redirect. * @return {@link HttpSupport.HttpBuilder}, to accept additional information. */ protected <T extends AppController> HttpBuilder redirect(Class<T> controllerClass){ return redirect(controllerClass, new HashMap()); } /** * Redirects to a controller, generates appropriate redirect path. There are two keyword keys expected in * the params map: "action" and "id". Both are optional. This method will generate appropriate URLs for regular as * well as RESTful controllers. The "action" and "id" values in the map will be treated as parts of URI such as: * <pre> * <code> * /controller/action/id * </code> * </pre> * for regular controllers, and: * <pre> * <code> * /controller/id/action * </code> * </pre> * for RESTful controllers. For RESTful controllers, the action names are limited to those described in * {@link org.javalite.activeweb.annotations.RESTful} and allowed on a GET URLs, which are: "edit_form" and "new_form". * * <p/> * The map may contain any number of other key/value pairs, which will be converted to a query string for * the redirect URI. Example: * <p/> * Method: * <pre> * <code> * redirect(app.controllers.PersonController.class, javalite.collections.map("action", "show", "id", 123, "format", "json", "restrict", "true")); * </code> * </pre> * will generate the following URI: * <pre> * <code> * /person/show/123?format=json&restrict=true * </code> * </pre> * * This method will also perform URL - encoding of special characters if necessary. * * * @param controllerClass controller class * @param params map with request parameters. * @return {@link HttpSupport.HttpBuilder}, to accept additional information. */ protected <T extends AppController> HttpBuilder redirect(Class<T> controllerClass, Map params){ String controllerPath = Router.getControllerPath(controllerClass); String contextPath = Context.getHttpRequest().getContextPath(); String action = params.get("action") != null? params.get("action").toString() : null; String id = params.get("id") != null? params.get("id").toString() : null; boolean restful= AppController.restful(controllerClass); params.remove("action"); params.remove("id"); String uri = contextPath + Router.generate(controllerPath, action, id, restful, params); RedirectResponse resp = new RedirectResponse(uri); Context.setControllerResponse(resp); return new HttpBuilder(resp); } /** * This method will send the text to a client verbatim. It will not use any layouts. Use it to build app.services * and to support AJAX. * * @param text text of response. * @return {@link HttpSupport.HttpBuilder}, to accept additional information. */ protected HttpBuilder respond(String text){ DirectResponse resp = new DirectResponse(text); Context.setControllerResponse(resp); return new HttpBuilder(resp); } /** * Convenience method for downloading files. This method will force the browser to find a handler(external program) * for this file (content type) and will provide a name of file to the browser. This method sets an HTTP header * "Content-Disposition" based on a file name. * * @param file file to download. * @return builder instance. * @throws FileNotFoundException thrown if file not found. */ protected HttpBuilder sendFile(File file) throws FileNotFoundException { try{ StreamResponse resp = new StreamResponse(new FileInputStream(file)); Context.setControllerResponse(resp); HttpBuilder builder = new HttpBuilder(resp); builder.header("Content-Disposition", "attachment; filename=" + file.getName()); return builder; }catch(Exception e){ throw new ControllerException(e); } } /** * Returns value of one named parameter from request. If this name represents multiple values, this * call will result in {@link IllegalArgumentException}. * * @param name name of parameter. * @return value of request parameter. */ protected String param(String name){ if(name.equals("id")){ return getId(); }else if(Context.getRequestContext().getUserSegments().get(name) != null){ return Context.getRequestContext().getUserSegments().get(name); }else{ return Context.getHttpRequest().getParameter(name); } } /** * Returns local host name on which request was received. * * @return local host name on which request was received. */ protected String host() { return Context.getHttpRequest().getLocalName(); } /** * Returns local IP address on which request was received. * * @return local IP address on which request was received. */ protected String ipAddress() { return Context.getHttpRequest().getLocalAddr(); } /** * This method returns a protocol of a request to web server if this container is fronted by one, such that * it sets a header <code>X-Forwarded-Proto</code> on the request and forwards it to the Java container. * If such header is not present, than the {@link #protocol()} method is used. * * @return protocol of web server request if <code>X-Forwarded-Proto</code> header is found, otherwise current * protocol. */ protected String getRequestProtocol(){ String protocol = header("X-Forwarded-Proto"); return Util.blank(protocol)? protocol(): protocol; } /** * This method returns a port of a web server if this Java container is fronted by one, such that * it sets a header <code>X-Forwarded-Port</code> on the request and forwards it to the Java container. * If such header is not present, than the {@link #port()} method is used. * * @return port of web server request if <code>X-Forwarded-Port</code> header is found, otherwise port of the Java container. */ protected int getRequestPort(){ String port = header("X-Forwarded-Port"); return Util.blank(port)? port(): Integer.parseInt(port); } /** * Returns port on which the of the server received current request. * * @return port on which the of the server received current request. */ protected int port(){ return Context.getHttpRequest().getLocalPort(); } /** * Returns protocol of request, for example: HTTP/1.1. * * @return protocol of request */ protected String protocol(){ return Context.getHttpRequest().getProtocol(); } //TODO: provide methods for: X-Forwarded-Proto and X-Forwarded-Port /** * This method returns a host name of a web server if this container is fronted by one, such that * it sets a header <code>X-Forwarded-Host</code> on the request and forwards it to the Java container. * If such header is not present, than the {@link #host()} method is used. * * @return host name of web server if <code>X-Forwarded-Host</code> header is found, otherwise local host name. */ protected String getRequestHost() { String forwarded = header("X-Forwarded-Host"); if (Util.blank(forwarded)) { return host(); } String[] forwards = forwarded.split(","); return forwards[0].trim(); } /** * Returns value of ID if one is present on a URL. Id is usually a part of a URI, such as: <code>/controller/action/id</code>. * This depends on a type of a URI, and whether controller is RESTful or not. * * @return ID value from URI is one exists, null if not. */ protected String getId(){ String paramId = Context.getHttpRequest().getParameter("id"); if(paramId != null && Context.getHttpRequest().getAttribute("id") != null){ logger.warn("WARNING: probably you have 'id' supplied both as a HTTP parameter, as well as in the URI. Choosing parameter over URI value."); } String theId; if(paramId != null){ theId = paramId; }else{ Object id = Context.getHttpRequest().getAttribute("id"); theId = id != null ? id.toString() : null; } return Util.blank(theId) ? null : theId; } /** * Returns a collection of uploaded files from a multi-part port request. * * @return a collection of uploaded files from a multi-part port request. */ protected Iterator<FormItem> uploadedFiles() { HttpServletRequest req = Context.getHttpRequest(); Iterator<FormItem> iterator; if(req instanceof AWMockMultipartHttpServletRequest){//running inside a test, and simulating upload. iterator = ((AWMockMultipartHttpServletRequest)req).getFormItemIterator(); }else{ if (!ServletFileUpload.isMultipartContent(req)) throw new ControllerException("this is not a multipart request, be sure to add this attribute to the form: ... enctype=\"multipart/form-data\" ..."); ServletFileUpload upload = new ServletFileUpload(); try { FileItemIterator it = upload.getItemIterator(Context.getHttpRequest()); iterator = new FormItemIterator(it); } catch (Exception e) { throw new ControllerException(e); } } return iterator; } /** * Returns multiple request values for a name. * * @param name name of multiple values from request. * @return multiple request values for a name. */ protected List<String> params(String name){ if (name.equals("id")) { String id = getId(); return id != null ? asList(id) : Collections.<String>emptyList(); } else { String[] values = Context.getHttpRequest().getParameterValues(name); List<String>valuesList = values == null? new ArrayList<String>() : list(values); String userSegment = Context.getRequestContext().getUserSegments().get(name); if(userSegment != null){ valuesList.add(userSegment); } return valuesList; } } /** * Returns an instance of <code>java.util.Map</code> containing parameter names as keys and parameter values as map values. * The keys in the parameter map are of type String. The values in the parameter map are of type String array. * * @return an instance <code>java.util.Map</code> containing parameter names as keys and parameter values as map values. * The keys in the parameter map are of type String. The values in the parameter map are of type String array. */ protected Map<String, String[]> params(){ SimpleHash params = new SimpleHash(Context.getHttpRequest().getParameterMap()); if(getId() != null) params.put("id", new String[]{getId()}); Map<String, String> userSegments = Context.getRequestContext().getUserSegments(); for(String name:userSegments.keySet()){ params.put(name, new String[]{userSegments.get(name)}); } return params; } /** * Sets character encoding on the response. * * @param encoding character encoding for response. */ protected void setEncoding(String encoding){ Context.getHttpResponse().setCharacterEncoding(encoding); } /** * Sets content length of response. * * @param length content length of response. */ protected void setContentLength(int length){ Context.getHttpResponse().setContentLength(length); } /** * Sets locale on response. * * @param locale locale for response. */ protected void setLocale(Locale locale){ Context.getHttpResponse().setLocale(locale); } /** * Returns a map where keys are names of all parameters, while values are first value for each parameter, even * if such parameter has more than one value submitted. * * @return a map where keys are names of all parameters, while values are first value for each parameter, even * if such parameter has more than one value submitted. */ protected Map<String, String> params1st(){ //TODO: candidate for performance optimization Map<String, String> params = new HashMap<String, String>(); Enumeration names = Context.getHttpRequest().getParameterNames(); while (names.hasMoreElements()) { String name = names.nextElement().toString(); params.put(name, Context.getHttpRequest().getParameter(name)); } if(getId() != null) params.put("id", getId()); Map<String, String> userSegments = Context.getRequestContext().getUserSegments(); params.putAll(userSegments); return params; } /** * Returns reference to a current session. Creates a new session of one does not exist. * @return reference to a current session. */ protected SessionFacade session(){ return new SessionFacade(); } /** * Convenience method, sets an object on a session. Equivalent of: * <pre> * <code> * session().put(name, value) * </code> * </pre> * * @param name name of object * @param value object itself. */ protected void session(String name, Serializable value){ session().put(name, value); } /** * Convenience method, returns object from session, equivalent of: * <pre> * <code> * session().get(name) * </code> * </pre> * * @param name name of object, * @return session object. */ protected Object sessionObject(String name){ return session().get(name); } /** * Convenience method, returns object from session, equivalent of: * <pre> * <code> * String val = (String)session().get(name) * </code> * </pre> * * @param name name of object * @return value */ protected String sessionString(String name){ return (String)session().get(name); } /** * Convenience method, returns object from session, equivalent of: * <pre> * <code> * Integer val = (Integer)session().get(name) * </code> * </pre> * * @param name name of object * @return value */ protected Integer sessionInteger(String name){ return Convert.toInteger(session().get(name)); } /** * Convenience method, returns object from session, equivalent of: * <pre> * <code> * Boolean val = (Boolean)session().get(name) * </code> * </pre> * * @param name name of object * @return value */ protected Boolean sessionBoolean(String name){ return Convert.toBoolean(session().get(name)); } /** * Convenience method, returns object from session, equivalent of: * <pre> * <code> * Double val = (Double)session().get(name) * </code> * </pre> * * @param name name of object * @return value */ protected Double sessionDouble(String name){ return Convert.toDouble(session().get(name)); } /** * Convenience method, returns object from session, equivalent of: * <pre> * <code> * Float val = (Float)session().get(name) * </code> * </pre> * * @param name name of object * @return value */ protected Float sessionFloat(String name){ return Convert.toFloat(session().get(name)); } /** * Convenience method, returns object from session, equivalent of: * <pre> * <code> * Long val = (Long)session().get(name) * </code> * </pre> * * @param name name of object * @return value */ protected Long sessionLong(String name){ return Convert.toLong(session().get(name)); } /** * Returns true if session has named object, false if not. * * @param name name of object. * @return true if session has named object, false if not. */ protected boolean sessionHas(String name){ return session().get(name) != null; } /** * Returns collection of all cookies browser sent. * * @return collection of all cookies browser sent. */ public List<Cookie> cookies(){ javax.servlet.http.Cookie[] servletCookies = Context.getHttpRequest().getCookies(); List<Cookie> cookies = new ArrayList<Cookie>(); for (javax.servlet.http.Cookie servletCookie: servletCookies) { Cookie cookie = Cookie.fromServletCookie(servletCookie); cookies.add(cookie); } return cookies; } /** * Returns a cookie by name, null if not found. * * @param name name of a cookie. * @return a cookie by name, null if not found. */ public Cookie cookie(String name){ javax.servlet.http.Cookie[] servletCookies = Context.getHttpRequest().getCookies(); if (servletCookies != null) { for (javax.servlet.http.Cookie servletCookie : servletCookies) { if (servletCookie.getName().equals(name)) { return Cookie.fromServletCookie(servletCookie); } } } return null; } /** * Convenience method, returns cookie value. * * @param name name of cookie. * @return cookie value. */ protected String cookieValue(String name){ return cookie(name).getValue(); } /** * Sends cookie to browse with response. * * @param cookie cookie to send. */ public void sendCookie(Cookie cookie){ Context.getHttpResponse().addCookie(Cookie.toServletCookie(cookie)); } /** * Sends cookie to browse with response. * * @param name name of cookie * @param value value of cookie. */ public void sendCookie(String name, String value) { Context.getHttpResponse().addCookie(Cookie.toServletCookie(new Cookie(name, value))); } /** * Sends long to live cookie to browse with response. This cookie will be asked to live for 20 years. * * @param name name of cookie * @param value value of cookie. */ public void sendPermanentCookie(String name, String value) { Cookie cookie = new Cookie(name, value); cookie.setMaxAge(60*60*24*365*20); Context.getHttpResponse().addCookie(Cookie.toServletCookie(cookie)); } /** * Returns a path of the request. It does not include protocol, host, port or context. Just a path. * Example: <code>/controller/action/id</code> * * @return a path of the request. */ protected String path(){ return Context.getHttpRequest().getServletPath(); } /** * Returns a full URL of the request, all except a query string. * * @return a full URL of the request, all except a query string. */ protected String url(){ return Context.getHttpRequest().getRequestURL().toString(); } /** * Returns query string of the request. * * @return query string of the request. */ protected String queryString(){ return Context.getHttpRequest().getQueryString(); } /** * Returns an HTTP method from the request. * * @return an HTTP method from the request. */ protected String method(){ return Context.getHttpRequest().getMethod(); } /** * Provides a context of the request - usually an app name (as seen on URL of request). Example: * <code>/mywebapp</code> * * @return a context of the request - usually an app name (as seen on URL of request). */ protected String context(){ return Context.getHttpRequest().getContextPath(); } /** * Returns URI, or a full path of request. This does not include protocol, host or port. Just context and path. * Examlpe: <code>/mywebapp/controller/action/id</code> * @return URI, or a full path of request. */ protected String uri(){ return Context.getHttpRequest().getRequestURI(); } /** * Host name of the requesting client. * * @return host name of the requesting client. */ protected String remoteHost(){ return Context.getHttpRequest().getRemoteHost(); } /** * IP address of the requesting client. * * @return IP address of the requesting client. */ protected String remoteAddress(){ return Context.getHttpRequest().getRemoteAddr(); } /** * Returns a request header by name. * * @param name name of header * @return header value. */ protected String header(String name){ return Context.getHttpRequest().getHeader(name); } /** * Returns all headers from a request keyed by header name. * * @return all headers from a request keyed by header name. */ protected Map<String, String> headers(){ Map<String, String> headers = new HashMap<String, String>(); Enumeration<String> names = Context.getHttpRequest().getHeaderNames(); while (names.hasMoreElements()) { String name = names.nextElement(); headers.put(name, Context.getHttpRequest().getHeader(name)); } return headers; } /** * Adds a header to response. * * @param name name of header. * @param value value of header. */ protected void header(String name, String value){ Context.getHttpResponse().addHeader(name, value); } /** * Adds a header to response. * * @param name name of header. * @param value value of header. */ protected void header(String name, Object value){ if(value == null) throw new NullPointerException("value cannot be null"); header(name, value.toString()); } /** * Streams content of the <code>reader</code> to the HTTP client. * * @param in input stream to read bytes from. * @return {@link HttpSupport.HttpBuilder}, to accept additional information. */ protected HttpBuilder streamOut(InputStream in) { StreamResponse resp = new StreamResponse(in); Context.setControllerResponse(resp); return new HttpBuilder(resp); } /** * Returns a String containing the real path for a given virtual path. For example, the path "/index.html" returns * the absolute file path on the server's filesystem would be served by a request for * "http://host/contextPath/index.html", where contextPath is the context path of this ServletContext.. * <p/> * The real path returned will be in a form appropriate to the computer and operating system on which the servlet * <p/> * container is running, including the proper path separators. This method returns null if the servlet container * cannot translate the virtual path to a real path for any reason (such as when the content is being made * available from a .war archive). * * <p/> * JavaDoc copied from: <a href="http://download.oracle.com/javaee/1.3/api/javax/servlet/ServletContext.html#getRealPath%28java.lang.String%29"> * http://download.oracle.com/javaee/1.3/api/javax/servlet/ServletContext.html#getRealPath%28java.lang.String%29</a> * * @param path a String specifying a virtual path * @return a String specifying the real path, or null if the translation cannot be performed */ protected String getRealPath(String path) { return Context.getFilterConfig().getServletContext().getRealPath(path); } /** * Use to send raw data to HTTP client. Content type and headers will not be set. * Response code will be set to 200. * * @return instance of output stream to send raw data directly to HTTP client. */ protected OutputStream outputStream(){ return outputStream(null, null, 200); } /** * Use to send raw data to HTTP client. Status will be set to 200. * * @param contentType content type * @return instance of output stream to send raw data directly to HTTP client. */ protected OutputStream outputStream(String contentType) { return outputStream(contentType, null, 200); } /** * Use to send raw data to HTTP client. * * @param contentType content type * @param headers set of headers. * @param status status. * @return instance of output stream to send raw data directly to HTTP client. */ protected OutputStream outputStream(String contentType, Map headers, int status) { try { Context.setControllerResponse(new NopResponse(contentType, status)); if (headers != null) { for (Object key : headers.keySet()) { if (headers.get(key) != null) Context.getHttpResponse().addHeader(key.toString(), headers.get(key).toString()); } } return Context.getHttpResponse().getOutputStream(); }catch(Exception e){ throw new ControllerException(e); } } /** * Produces a writer for sending raw data to HTTP clients. * * Content type content type not be set on the response. Headers will not be send to client. Status will be * set to 200. * @return instance of a writer for writing content to HTTP client. */ protected PrintWriter writer(){ return writer(null, null, 200); } /** * Produces a writer for sending raw data to HTTP clients. * * @param contentType content type. If null - will not be set on the response * @param headers headers. If null - will not be set on the response * @param status will be sent to browser. * @return instance of a writer for writing content to HTTP client. */ protected PrintWriter writer(String contentType, Map headers, int status){ try{ Context.setControllerResponse(new NopResponse(contentType, status)); if (headers != null) { for (Object key : headers.keySet()) { if (headers.get(key) != null) Context.getHttpResponse().addHeader(key.toString(), headers.get(key).toString()); } } return Context.getHttpResponse().getWriter(); }catch(Exception e){ throw new ControllerException(e); } } /** * Returns true if any named request parameter is blank. * * @param names names of request parameters. * @return true if any request parameter is blank. */ protected boolean blank(String ... names){ //TODO: write test, move elsewhere - some helper for(String name:names){ if(Util.blank(param(name))){ return true; } } return false; } /** * Returns true if this request is Ajax. * * @return true if this request is Ajax. */ protected boolean isXhr(){ return header("X-Requested-With") != null || header("x-requested-with") != null; } /** * Synonym for {@link #isXhr()}. */ protected boolean xhr(){ return isXhr(); } /** * Returns instance of {@link AppContext}. * * @return */ protected AppContext appContext(){ return Context.getAppContext(); } }
activeweb/src/main/java/org/javalite/activeweb/HttpSupport.java
/* Copyright 2009-2010 Igor Polevoy Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package org.javalite.activeweb; import org.javalite.common.Convert; import org.javalite.common.Util; import org.apache.commons.fileupload.FileItemIterator; import org.apache.commons.fileupload.servlet.ServletFileUpload; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.servlet.http.HttpServletRequest; import java.io.*; import java.net.URL; import java.security.Key; import java.util.*; import static java.util.Arrays.asList; import static org.javalite.common.Collections.list; import static org.javalite.common.Collections.map; /** * @author Igor Polevoy */ public class HttpSupport { private Logger logger = LoggerFactory.getLogger(getClass().getName()); protected void logInfo(String info){ logger.info(info); } protected void logDebug(String info){ logger.debug(info); } protected void logWarning(String info){ logger.warn(info); } protected void logWarning(String info, Throwable e){ logger.warn(info, e); } protected void logError(String info){ logger.error(info); } protected void logError(String info, Throwable e){ logger.error(info, e); } /** * Assigns a value for a view. * * @param name name of value * @param value value. */ protected void assign(String name, Object value) { KeyWords.check(name); Context.getHttpRequest().setAttribute(name, value); } /** * Alias to {@link #assign(String, Object)}. * * @param name name of object to be passed to view * @param value object to be passed to view */ protected void view(String name, Object value) { assign(name, value); } /** * Convenience method, calls {@link #assign(String, Object)} internally. * The keys in teh map are converted to String values. * * @param values map with values to pass to view. */ protected void view(Map values){ for(Object key:values.keySet() ){ assign(key.toString(), values.get(key)); } } /** * Convenience method, calls {@link #assign(String, Object)} internally. * * */ protected void view(Object ... values){ view(map(values)); } public class HttpBuilder { private ControllerResponse controllerResponse; private HttpBuilder(ControllerResponse controllerResponse){ this.controllerResponse = controllerResponse; } protected ControllerResponse getControllerResponse() { return controllerResponse; } /** * Sets content type of response. * These can be "text/html". Value "text/html" is set by default. * * @param contentType content type value. * @return HTTP Object */ public HttpBuilder contentType(String contentType) { controllerResponse.setContentType(contentType); return this; } /** * Sets a HTTP header on response. * * @param name name of header. * @param value value of header. */ public HttpBuilder header(String name, String value){ Context.getHttpResponse().setHeader(name, value); return this; } /** * Overrides HTTP status with a different value. * For values and more information, look here: * <a href='http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html'>HTTP Status Codes</a>. * * By default, the status is set to 200, OK. * * @param status HTTP status code. */ public void status(int status){ controllerResponse.setStatus(status); } } public class RenderBuilder extends HttpBuilder { private RenderBuilder(RenderTemplateResponse response){ super(response); } /** * Use this method to override a default layout configured. * * @param layout name of another layout. */ public RenderBuilder layout(String layout){ getRenderTemplateResponse().setLayout(layout); return this; } protected RenderTemplateResponse getRenderTemplateResponse(){ return (RenderTemplateResponse)getControllerResponse(); } /** * call this method to turn off all layouts. The view will be rendered raw - no layouts. */ public RenderBuilder noLayout(){ getRenderTemplateResponse().setLayout(null); return this; } } /** * Renders results with a template. * * This call must be the last call in the action. * * @param template - template name, must be "absolute", starting with slash, * such as: "/controller_dir/action_template". * @param values map with values to pass to view. * @return instance of {@link RenderBuilder}, which is used to provide additional parameters. */ protected RenderBuilder render(String template, Map values) { RenderTemplateResponse resp = new RenderTemplateResponse(values, template); Context.setControllerResponse(resp); return new RenderBuilder(resp); } /** * Redirects to a an action of this controller, or an action of a different controller. * This method does not expect a full URL. * * @param path - expected to be a path within the application. * @return instance of {@link HttpSupport.HttpBuilder} to accept additional information. */ protected HttpBuilder redirect(String path) { RedirectResponse resp = new RedirectResponse(path); Context.setControllerResponse(resp); return new HttpBuilder(resp); } /** * Redirects to another URL (usually another site). * * @param url absolute URL: <code>http://domain/path...</code>. * @return {@link HttpSupport.HttpBuilder}, to accept additional information. */ protected HttpBuilder redirect(URL url) { RedirectResponse resp = new RedirectResponse(url); Context.setControllerResponse(resp); return new HttpBuilder(resp); } /** * Redirects to referrer if one exists. If a referrer does not exist, it will be redirected to * the <code>defaultReference</code>. * * @param defaultReference where to redirect - can be absolute or relative; this will be used in case * the request does not provide a "Referrer" header. * @return {@link HttpSupport.HttpBuilder}, to accept additional information. */ protected HttpBuilder redirectToReferrer(String defaultReference) { String referrer = Context.getHttpRequest().getHeader("Referer"); referrer = referrer == null? defaultReference: referrer; RedirectResponse resp = new RedirectResponse(referrer); Context.setControllerResponse(resp); return new HttpBuilder(resp); } /** * Redirects to referrer if one exists. If a referrer does not exist, it will be redirected to * the root of the application. * * @return {@link HttpSupport.HttpBuilder}, to accept additional information. */ protected HttpBuilder redirectToReferrer() { String referrer = Context.getHttpRequest().getHeader("Referer"); referrer = referrer == null? Context.getHttpRequest().getContextPath(): referrer; RedirectResponse resp = new RedirectResponse(referrer); Context.setControllerResponse(resp); return new HttpBuilder(resp); } /** * Convenience method for {@link #redirect(Class, java.util.Map)}. * * @param controllerClass controller class where to send redirect. * @param action action to redirect to. * @param id id to redirect to. * @return {@link HttpSupport.HttpBuilder}, to accept additional information. */ protected <T extends AppController> HttpBuilder redirect(Class<T> controllerClass, String action, Object id){ return redirect(controllerClass, map("action", action, "id", id)); } /** * Convenience method for {@link #redirect(Class, java.util.Map)}. * * @param controllerClass controller class where to send redirect. * @param id id to redirect to. * @return {@link HttpSupport.HttpBuilder}, to accept additional information. */ protected <T extends AppController> HttpBuilder redirect(Class<T> controllerClass, Object id){ return redirect(controllerClass, map("id", id)); } /** * Convenience method for {@link #redirect(Class, java.util.Map)}. * * @param controllerClass controller class where to send redirect. * @param action action to redirect to. * @return {@link HttpSupport.HttpBuilder}, to accept additional information. */ protected <T extends AppController> HttpBuilder redirect(Class<T> controllerClass, String action){ return redirect(controllerClass, map("action", action)); } /** * Convenience method for {@link #redirect(Class, java.util.Map)}. * * @param controllerClass controller class where to send redirect. * @return {@link HttpSupport.HttpBuilder}, to accept additional information. */ protected <T extends AppController> HttpBuilder redirect(Class<T> controllerClass){ return redirect(controllerClass, new HashMap()); } /** * Redirects to a controller, generates appropriate redirect path. There are two keyword keys expected in * the params map: "action" and "id". Both are optional. This method will generate appropriate URLs for regular as * well as RESTful controllers. The "action" and "id" values in the map will be treated as parts of URI such as: * <pre> * <code> * /controller/action/id * </code> * </pre> * for regular controllers, and: * <pre> * <code> * /controller/id/action * </code> * </pre> * for RESTful controllers. For RESTful controllers, the action names are limited to those described in * {@link org.javalite.activeweb.annotations.RESTful} and allowed on a GET URLs, which are: "edit_form" and "new_form". * * <p/> * The map may contain any number of other key/value pairs, which will be converted to a query string for * the redirect URI. Example: * <p/> * Method: * <pre> * <code> * redirect(app.controllers.PersonController.class, javalite.collections.map("action", "show", "id", 123, "format", "json", "restrict", "true")); * </code> * </pre> * will generate the following URI: * <pre> * <code> * /person/show/123?format=json&restrict=true * </code> * </pre> * * This method will also perform URL - encoding of special characters if necessary. * * * @param controllerClass controller class * @param params map with request parameters. * @return {@link HttpSupport.HttpBuilder}, to accept additional information. */ protected <T extends AppController> HttpBuilder redirect(Class<T> controllerClass, Map params){ String controllerPath = Router.getControllerPath(controllerClass); String contextPath = Context.getHttpRequest().getContextPath(); String action = params.get("action") != null? params.get("action").toString() : null; String id = params.get("id") != null? params.get("id").toString() : null; boolean restful= AppController.restful(controllerClass); params.remove("action"); params.remove("id"); String uri = contextPath + Router.generate(controllerPath, action, id, restful, params); RedirectResponse resp = new RedirectResponse(uri); Context.setControllerResponse(resp); return new HttpBuilder(resp); } /** * This method will send the text to a client verbatim. It will not use any layouts. Use it to build app.services * and to support AJAX. * * @param text text of response. * @return {@link HttpSupport.HttpBuilder}, to accept additional information. */ protected HttpBuilder respond(String text){ DirectResponse resp = new DirectResponse(text); Context.setControllerResponse(resp); return new HttpBuilder(resp); } /** * Convenience method for downloading files. This method will force the browser to find a handler(external program) * for this file (content type) and will provide a name of file to the browser. This method sets an HTTP header * "Content-Disposition" based on a file name. * * @param file file to download. * @return builder instance. * @throws FileNotFoundException thrown if file not found. */ protected HttpBuilder sendFile(File file) throws FileNotFoundException { try{ StreamResponse resp = new StreamResponse(new FileInputStream(file)); Context.setControllerResponse(resp); HttpBuilder builder = new HttpBuilder(resp); builder.header("Content-Disposition", "attachment; filename=" + file.getName()); return builder; }catch(Exception e){ throw new ControllerException(e); } } /** * Returns value of one named parameter from request. If this name represents multiple values, this * call will result in {@link IllegalArgumentException}. * * @param name name of parameter. * @return value of request parameter. */ protected String param(String name){ if(name.equals("id")){ return getId(); }else if(Context.getRequestContext().getUserSegments().get(name) != null){ return Context.getRequestContext().getUserSegments().get(name); }else{ return Context.getHttpRequest().getParameter(name); } } /** * Returns local host name on which request was received. * * @return local host name on which request was received. */ protected String host() { return Context.getHttpRequest().getLocalName(); } /** * Returns local IP address on which request was received. * * @return local IP address on which request was received. */ protected String ipAddress() { return Context.getHttpRequest().getLocalAddr(); } /** * This method returns a protocol of a request to web server if this container is fronted by one, such that * it sets a header <code>X-Forwarded-Proto</code> on the request and forwards it to the Java container. * If such header is not present, than the {@link #protocol()} method is used. * * @return protocol of web server request if <code>X-Forwarded-Proto</code> header is found, otherwise current * protocol. */ protected String getRequestProtocol(){ String protocol = header("X-Forwarded-Proto"); return Util.blank(protocol)? protocol(): protocol; } /** * This method returns a port of a web server if this Java container is fronted by one, such that * it sets a header <code>X-Forwarded-Port</code> on the request and forwards it to the Java container. * If such header is not present, than the {@link #port()} method is used. * * @return port of web server request if <code>X-Forwarded-Port</code> header is found, otherwise port of the Java container. */ protected int getRequestPort(){ String port = header("X-Forwarded-Port"); return Util.blank(port)? port(): Integer.parseInt(port); } /** * Returns port on which the of the server received current request. * * @return port on which the of the server received current request. */ protected int port(){ return Context.getHttpRequest().getLocalPort(); } /** * Returns protocol of request, for example: HTTP/1.1. * * @return protocol of request */ protected String protocol(){ return Context.getHttpRequest().getProtocol(); } //TODO: provide methods for: X-Forwarded-Proto and X-Forwarded-Port /** * This method returns a host name of a web server if this container is fronted by one, such that * it sets a header <code>X-Forwarded-Host</code> on the request and forwards it to the Java container. * If such header is not present, than the {@link #host()} method is used. * * @return host name of web server if <code>X-Forwarded-Host</code> header is found, otherwise local host name. */ protected String getRequestHost() { String forwarded = header("X-Forwarded-Host"); if (Util.blank(forwarded)) { return host(); } String[] forwards = forwarded.split(","); return forwards[0].trim(); } /** * Returns value of ID if one is present on a URL. Id is usually a part of a URI, such as: <code>/controller/action/id</code>. * This depends on a type of a URI, and whether controller is RESTful or not. * * @return ID value from URI is one exists, null if not. */ protected String getId(){ String paramId = Context.getHttpRequest().getParameter("id"); if(paramId != null && Context.getHttpRequest().getAttribute("id") != null){ logger.warn("WARNING: probably you have 'id' supplied both as a HTTP parameter, as well as in the URI. Choosing parameter over URI value."); } String theId; if(paramId != null){ theId = paramId; }else{ Object id = Context.getHttpRequest().getAttribute("id"); theId = id != null ? id.toString() : null; } return Util.blank(theId) ? null : theId; } /** * Returns a collection of uploaded files from a multi-part port request. * * @return a collection of uploaded files from a multi-part port request. */ protected Iterator<FormItem> uploadedFiles() { HttpServletRequest req = Context.getHttpRequest(); Iterator<FormItem> iterator; if(req instanceof AWMockMultipartHttpServletRequest){//running inside a test, and simulating upload. iterator = ((AWMockMultipartHttpServletRequest)req).getFormItemIterator(); }else{ if (!ServletFileUpload.isMultipartContent(req)) throw new ControllerException("this is not a multipart request, be sure to add this attribute to the form: ... enctype=\"multipart/form-data\" ..."); ServletFileUpload upload = new ServletFileUpload(); try { FileItemIterator it = upload.getItemIterator(Context.getHttpRequest()); iterator = new FormItemIterator(it); } catch (Exception e) { throw new ControllerException(e); } } return iterator; } /** * Returns multiple request values for a name. * * @param name name of multiple values from request. * @return multiple request values for a name. */ protected List<String> params(String name){ if (name.equals("id")) { String id = getId(); return id != null ? asList(id) : Collections.<String>emptyList(); } else { String[] values = Context.getHttpRequest().getParameterValues(name); List<String>valuesList = values == null? new ArrayList<String>() : list(values); String userSegment = Context.getRequestContext().getUserSegments().get(name); if(userSegment != null){ valuesList.add(userSegment); } return valuesList; } } /** * Returns an instance of <code>java.util.Map</code> containing parameter names as keys and parameter values as map values. * The keys in the parameter map are of type String. The values in the parameter map are of type String array. * * @return an instance <code>java.util.Map</code> containing parameter names as keys and parameter values as map values. * The keys in the parameter map are of type String. The values in the parameter map are of type String array. */ protected Map<String, String[]> params(){ SimpleHash params = new SimpleHash(Context.getHttpRequest().getParameterMap()); if(getId() != null) params.put("id", new String[]{getId()}); Map<String, String> userSegments = Context.getRequestContext().getUserSegments(); for(String name:userSegments.keySet()){ params.put(name, new String[]{userSegments.get(name)}); } return params; } /** * Sets character encoding on the response. * * @param encoding character encoding for response. */ protected void setEncoding(String encoding){ Context.getHttpResponse().setCharacterEncoding(encoding); } /** * Sets content length of response. * * @param length content length of response. */ protected void setContentLength(int length){ Context.getHttpResponse().setContentLength(length); } /** * Sets locale on response. * * @param locale locale for response. */ protected void setLocale(Locale locale){ Context.getHttpResponse().setLocale(locale); } /** * Returns a map where keys are names of all parameters, while values are first value for each parameter, even * if such parameter has more than one value submitted. * * @return a map where keys are names of all parameters, while values are first value for each parameter, even * if such parameter has more than one value submitted. */ protected Map<String, String> params1st(){ //TODO: candidate for performance optimization Map<String, String> params = new HashMap<String, String>(); Enumeration names = Context.getHttpRequest().getParameterNames(); while (names.hasMoreElements()) { String name = names.nextElement().toString(); params.put(name, Context.getHttpRequest().getParameter(name)); } if(getId() != null) params.put("id", getId()); Map<String, String> userSegments = Context.getRequestContext().getUserSegments(); params.putAll(userSegments); return params; } /** * Returns reference to a current session. Creates a new session of one does not exist. * @return reference to a current session. */ protected SessionFacade session(){ return new SessionFacade(); } /** * Convenience method, sets an object on a session. Equivalent of: * <pre> * <code> * session().put(name, value) * </code> * </pre> * * @param name name of object * @param value object itself. */ protected void session(String name, Serializable value){ session().put(name, value); } /** * Convenience method, returns object from session, equivalent of: * <pre> * <code> * session().get(name) * </code> * </pre> * * @param name name of object, * @return session object. */ protected Object sessionObject(String name){ return session().get(name); } /** * Convenience method, returns object from session, equivalent of: * <pre> * <code> * String val = (String)session().get(name) * </code> * </pre> * * @param name name of object * @return value */ protected String sessionString(String name){ return (String)session().get(name); } /** * Convenience method, returns object from session, equivalent of: * <pre> * <code> * Integer val = (Integer)session().get(name) * </code> * </pre> * * @param name name of object * @return value */ protected Integer sessionInteger(String name){ return Convert.toInteger(session().get(name)); } /** * Convenience method, returns object from session, equivalent of: * <pre> * <code> * Boolean val = (Boolean)session().get(name) * </code> * </pre> * * @param name name of object * @return value */ protected Boolean sessionBoolean(String name){ return Convert.toBoolean(session().get(name)); } /** * Convenience method, returns object from session, equivalent of: * <pre> * <code> * Double val = (Double)session().get(name) * </code> * </pre> * * @param name name of object * @return value */ protected Double sessionDouble(String name){ return Convert.toDouble(session().get(name)); } /** * Convenience method, returns object from session, equivalent of: * <pre> * <code> * Float val = (Float)session().get(name) * </code> * </pre> * * @param name name of object * @return value */ protected Float sessionFloat(String name){ return Convert.toFloat(session().get(name)); } /** * Convenience method, returns object from session, equivalent of: * <pre> * <code> * Long val = (Long)session().get(name) * </code> * </pre> * * @param name name of object * @return value */ protected Long sessionLong(String name){ return Convert.toLong(session().get(name)); } /** * Returns true if session has named object, false if not. * * @param name name of object. * @return true if session has named object, false if not. */ protected boolean sessionHas(String name){ return session().get(name) != null; } /** * Returns collection of all cookies browser sent. * * @return collection of all cookies browser sent. */ public List<Cookie> cookies(){ javax.servlet.http.Cookie[] servletCookies = Context.getHttpRequest().getCookies(); List<Cookie> cookies = new ArrayList<Cookie>(); for (javax.servlet.http.Cookie servletCookie: servletCookies) { Cookie cookie = Cookie.fromServletCookie(servletCookie); cookies.add(cookie); } return cookies; } /** * Returns a cookie by name, null if not found. * * @param name name of a cookie. * @return a cookie by name, null if not found. */ public Cookie cookie(String name){ javax.servlet.http.Cookie[] servletCookies = Context.getHttpRequest().getCookies(); if (servletCookies != null) { for (javax.servlet.http.Cookie servletCookie : servletCookies) { if (servletCookie.getName().equals(name)) { return Cookie.fromServletCookie(servletCookie); } } } return null; } /** * Convenience method, returns cookie value. * * @param name name of cookie. * @return cookie value. */ protected String cookieValue(String name){ return cookie(name).getValue(); } /** * Sends cookie to browse with response. * * @param cookie cookie to send. */ public void sendCookie(Cookie cookie){ Context.getHttpResponse().addCookie(Cookie.toServletCookie(cookie)); } /** * Sends cookie to browse with response. * * @param name name of cookie * @param value value of cookie. */ public void sendCookie(String name, String value) { Context.getHttpResponse().addCookie(Cookie.toServletCookie(new Cookie(name, value))); } /** * Sends long to live cookie to browse with response. This cookie will be asked to live for 20 years. * * @param name name of cookie * @param value value of cookie. */ public void sendPermanentCookie(String name, String value) { Cookie cookie = new Cookie(name, value); cookie.setMaxAge(60*60*24*365*20); Context.getHttpResponse().addCookie(Cookie.toServletCookie(cookie)); } /** * Returns a path of the request. It does not include protocol, host, port or context. Just a path. * Example: <code>/controller/action/id</code> * * @return a path of the request. */ protected String path(){ return Context.getHttpRequest().getServletPath(); } /** * Returns a full URL of the request, all except a query string. * * @return a full URL of the request, all except a query string. */ protected String url(){ return Context.getHttpRequest().getRequestURL().toString(); } /** * Returns query string of the request. * * @return query string of the request. */ protected String queryString(){ return Context.getHttpRequest().getQueryString(); } /** * Returns an HTTP method from the request. * * @return an HTTP method from the request. */ protected String method(){ return Context.getHttpRequest().getMethod(); } /** * Provides a context of the request - usually an app name (as seen on URL of request). Example: * <code>/mywebapp</code> * * @return a context of the request - usually an app name (as seen on URL of request). */ protected String context(){ return Context.getHttpRequest().getContextPath(); } /** * Returns URI, or a full path of request. This does not include protocol, host or port. Just context and path. * Examlpe: <code>/mywebapp/controller/action/id</code> * @return URI, or a full path of request. */ protected String uri(){ return Context.getHttpRequest().getRequestURI(); } /** * Host name of the requesting client. * * @return host name of the requesting client. */ protected String remoteHost(){ return Context.getHttpRequest().getRemoteHost(); } /** * IP address of the requesting client. * * @return IP address of the requesting client. */ protected String remoteAddress(){ return Context.getHttpRequest().getRemoteAddr(); } /** * Returns a request header by name. * * @param name name of header * @return header value. */ protected String header(String name){ return Context.getHttpRequest().getHeader(name); } /** * Returns all headers from a request keyed by header name. * * @return all headers from a request keyed by header name. */ protected Map<String, String> headers(){ Map<String, String> headers = new HashMap<String, String>(); Enumeration<String> names = Context.getHttpRequest().getHeaderNames(); while (names.hasMoreElements()) { String name = names.nextElement(); headers.put(name, Context.getHttpRequest().getHeader(name)); } return headers; } /** * Adds a header to response. * * @param name name of header. * @param value value of header. */ protected void header(String name, String value){ Context.getHttpResponse().addHeader(name, value); } /** * Adds a header to response. * * @param name name of header. * @param value value of header. */ protected void header(String name, Object value){ if(value == null) throw new NullPointerException("value cannot be null"); header(name, value.toString()); } /** * Streams content of the <code>reader</code> to the HTTP client. * * @param in input stream to read bytes from. * @return {@link HttpSupport.HttpBuilder}, to accept additional information. */ protected HttpBuilder streamOut(InputStream in) { StreamResponse resp = new StreamResponse(in); Context.setControllerResponse(resp); return new HttpBuilder(resp); } /** * Returns a String containing the real path for a given virtual path. For example, the path "/index.html" returns * the absolute file path on the server's filesystem would be served by a request for * "http://host/contextPath/index.html", where contextPath is the context path of this ServletContext.. * <p/> * The real path returned will be in a form appropriate to the computer and operating system on which the servlet * <p/> * container is running, including the proper path separators. This method returns null if the servlet container * cannot translate the virtual path to a real path for any reason (such as when the content is being made * available from a .war archive). * * <p/> * JavaDoc copied from: <a href="http://download.oracle.com/javaee/1.3/api/javax/servlet/ServletContext.html#getRealPath%28java.lang.String%29"> * http://download.oracle.com/javaee/1.3/api/javax/servlet/ServletContext.html#getRealPath%28java.lang.String%29</a> * * @param path a String specifying a virtual path * @return a String specifying the real path, or null if the translation cannot be performed */ protected String getRealPath(String path) { return Context.getFilterConfig().getServletContext().getRealPath(path); } /** * Use to send raw data to HTTP client. Content type and headers will not be set. * Response code will be set to 200. * * @return instance of output stream to send raw data directly to HTTP client. */ protected OutputStream outputStream(){ return outputStream(null, null, 200); } /** * Use to send raw data to HTTP client. Status will be set to 200. * * @param contentType content type * @return instance of output stream to send raw data directly to HTTP client. */ protected OutputStream outputStream(String contentType) { return outputStream(contentType, null, 200); } /** * Use to send raw data to HTTP client. * * @param contentType content type * @param headers set of headers. * @param status status. * @return instance of output stream to send raw data directly to HTTP client. */ protected OutputStream outputStream(String contentType, Map headers, int status) { try { Context.setControllerResponse(new NopResponse(contentType, status)); if (headers != null) { for (Object key : headers.keySet()) { if (headers.get(key) != null) Context.getHttpResponse().addHeader(key.toString(), headers.get(key).toString()); } } return Context.getHttpResponse().getOutputStream(); }catch(Exception e){ throw new ControllerException(e); } } /** * Produces a writer for sending raw data to HTTP clients. * * Content type content type not be set on the response. Headers will not be send to client. Status will be * set to 200. * @return instance of a writer for writing content to HTTP client. */ protected PrintWriter writer(){ return writer(null, null, 200); } /** * Produces a writer for sending raw data to HTTP clients. * * @param contentType content type. If null - will not be set on the response * @param headers headers. If null - will not be set on the response * @param status will be sent to browser. * @return instance of a writer for writing content to HTTP client. */ protected PrintWriter writer(String contentType, Map headers, int status){ try{ Context.setControllerResponse(new NopResponse(contentType, status)); if (headers != null) { for (Object key : headers.keySet()) { if (headers.get(key) != null) Context.getHttpResponse().addHeader(key.toString(), headers.get(key).toString()); } } return Context.getHttpResponse().getWriter(); }catch(Exception e){ throw new ControllerException(e); } } /** * Returns true if any named request parameter is blank. * * @param names names of request parameters. * @return true if any request parameter is blank. */ protected boolean blank(String ... names){ //TODO: write test, move elsewhere - some helper for(String name:names){ if(Util.blank(param(name))){ return true; } } return false; } /** * Returns true if this request is Ajax. * * @return true if this request is Ajax. */ protected boolean isXhr(){ return header("X-Requested-With") != null || header("x-requested-with") != null; } /** * Synonym for {@link #isXhr()}. */ protected boolean xhr(){ return isXhr(); } /** * Returns instance of {@link AppContext}. * * @return */ protected AppContext appContext(){ return Context.getAppContext(); } }
added logError(Throwable) convenience method
activeweb/src/main/java/org/javalite/activeweb/HttpSupport.java
added logError(Throwable) convenience method
<ide><path>ctiveweb/src/main/java/org/javalite/activeweb/HttpSupport.java <ide> <ide> protected void logError(String info){ <ide> logger.error(info); <add> } <add> <add> protected void logError(Throwable e){ <add> logger.error("", e); <ide> } <ide> <ide> protected void logError(String info, Throwable e){
Java
apache-2.0
8b09f8a34354a5a4c15a5885e0513c18c5144005
0
Uni-Sol/batik,apache/batik,Uni-Sol/batik,apache/batik,Uni-Sol/batik,Uni-Sol/batik,Uni-Sol/batik,apache/batik,apache/batik
/***************************************************************************** * Copyright (C) The Apache Software Foundation. All rights reserved. * * ------------------------------------------------------------------------- * * This software is published under the terms of the Apache Software License * * version 1.1, a copy of which has been included with this distribution in * * the LICENSE file. * *****************************************************************************/ package org.apache.batik.refimpl.gvt; import java.awt.Cursor; import java.awt.Composite; import java.awt.AlphaComposite; import java.awt.Rectangle; import java.awt.Shape; import java.awt.Graphics2D; import java.awt.RenderingHints; import java.awt.geom.AffineTransform; import java.awt.geom.GeneralPath; import java.awt.geom.NoninvertibleTransformException; import java.awt.geom.Rectangle2D; import java.awt.geom.Point2D; import java.awt.image.RenderedImage; import java.awt.image.renderable.RenderContext; import java.awt.image.renderable.RenderableImage; import java.util.HashMap; import java.util.Map; import java.util.List; import java.util.Vector; import java.util.EventListener; import java.lang.reflect.Array; import java.beans.PropertyChangeListener; import java.beans.PropertyChangeSupport; import javax.swing.event.EventListenerList; import org.apache.batik.gvt.GraphicsNode; import org.apache.batik.gvt.RootGraphicsNode; import org.apache.batik.gvt.CompositeGraphicsNode; import org.apache.batik.gvt.GraphicsNodeRenderContext; import org.apache.batik.gvt.GraphicsNodeHitDetector; import org.apache.batik.gvt.event.GraphicsNodeEvent; import org.apache.batik.gvt.event.GraphicsNodeMouseEvent; import org.apache.batik.gvt.event.GraphicsNodeMouseListener; import org.apache.batik.gvt.event.GraphicsNodeKeyEvent; import org.apache.batik.gvt.event.GraphicsNodeKeyListener; import org.apache.batik.gvt.event.GraphicsNodeEventFilter; import org.apache.batik.gvt.event.CompositeGraphicsNodeEvent; import org.apache.batik.gvt.event.CompositeGraphicsNodeListener; import org.apache.batik.gvt.filter.Filter; import org.apache.batik.gvt.filter.Mask; import org.apache.batik.gvt.filter.PadMode; /** * A partial implementation of the <tt>GraphicsNode</tt> interface. * * @author <a href="mailto:[email protected]">Thierry Kormann</a> * @author <a href="mailto:[email protected]">Emmanuel Tissandier</a> * @version $Id$ */ public abstract class AbstractGraphicsNode implements GraphicsNode { /** * Used to draw renderable images */ static final AffineTransform IDENTITY = new AffineTransform(); /** * The Map used to store mememto objects. */ protected Map mememtos; /** * The listeners list. */ protected EventListenerList listeners; /** * Used to manage and fire property change listeners. */ private PropertyChangeSupport pcs = new PropertyChangeSupport(this); /** * The filter used to filter graphics node events. */ protected GraphicsNodeEventFilter eventFilter; /** * The hit detector used to filter mouse events. */ protected GraphicsNodeHitDetector hitDetector; /** * The cursor attached to this graphics node. */ protected Cursor cursor; /** * The transform of this graphics node. */ protected AffineTransform transform; /** * The compositing operation to be used when a graphics node is * painted on top of another one. */ protected Composite composite; /** * This flag bit indicates whether or not this graphics node is visible. */ protected boolean isVisible = true; /** * The clipping area of this graphics node. */ protected Shape clip; /** * The rendering hints that control the quality to use when rendering * this graphics node. */ protected RenderingHints hints; /** * The mask of this graphics node. */ protected Mask mask; /** * The parent of this graphics node. */ protected CompositeGraphicsNode parent; /** * The root of the GVT tree. */ protected RootGraphicsNode root; /** * The filter of this graphics node. */ protected Filter filter; /** * Cache: node bounds */ private Rectangle2D bounds; /** * Constructs a new graphics node. */ public AbstractGraphicsNode() {} // // fire property change methods. // protected void firePropertyChange(String propertyName, boolean oldValue, boolean newValue){ // First fire to local listeners pcs.firePropertyChange(propertyName, oldValue, newValue); // fire to root node listeners if possible. if (root != null) { ConcreteRootGraphicsNode node = (ConcreteRootGraphicsNode) root; node.fireGlobalPropertyChange(this, propertyName, oldValue, newValue); } } protected void firePropertyChange(String propertyName, int oldValue, int newValue){ // First fire to local listeners pcs.firePropertyChange(propertyName, oldValue, newValue); // fire to root node listeners if possible. if (root != null) { ConcreteRootGraphicsNode node = (ConcreteRootGraphicsNode) root; node.fireGlobalPropertyChange(this, propertyName, oldValue, newValue); } } protected void firePropertyChange(String propertyName, Object oldValue, Object newValue){ // First fire to local listeners pcs.firePropertyChange(propertyName, oldValue, newValue); // fire to root node listeners if possible. if (root != null) { ConcreteRootGraphicsNode node = (ConcreteRootGraphicsNode) root; node.fireGlobalPropertyChange(this, propertyName, oldValue, newValue); } } // // Properties methods // public void setCursor(Cursor newCursor) { Cursor oldCursor = cursor; this.cursor = newCursor; firePropertyChange("cursor", oldCursor, newCursor); } public Cursor getCursor() { return cursor; } public void setTransform(AffineTransform newTransform) { AffineTransform oldTransform = transform; this.transform = newTransform; firePropertyChange("transform", oldTransform, newTransform); } public AffineTransform getTransform() { return transform; } public void setComposite(Composite newComposite) { invalidateGeometryCache(); Composite oldComposite = composite; this.composite = newComposite; firePropertyChange("composite", oldComposite, newComposite); } public Composite getComposite() { return composite; } public void setVisible(boolean isVisible) { boolean oldIsVisible = this.isVisible; this.isVisible = isVisible; firePropertyChange("visible", oldIsVisible, isVisible); } public boolean isVisible() { return isVisible; } public void setClippingArea(Shape newClippingArea) { invalidateGeometryCache(); Shape oldClip = clip; this.clip = newClippingArea; firePropertyChange("clippingArea", oldClip, newClippingArea); } public Shape getClippingArea() { return clip; } public void setRenderingHint(RenderingHints.Key key, Object value) { if (this.hints == null) { this.hints = new RenderingHints(key, value); } else { hints.put(key, value); } } public void setRenderingHints(Map hints) { if (this.hints == null) { this.hints = new RenderingHints(hints); } else { this.hints.putAll(hints); } } public void setRenderingHints(RenderingHints newHints) { this.hints = newHints; } public RenderingHints getRenderingHints() { return hints; } public void setMask(Mask newMask) { invalidateGeometryCache(); Mask oldMask = mask; this.mask = newMask; firePropertyChange("mask", oldMask, newMask); } public Mask getMask() { return mask; } public void setFilter(Filter newFilter) { invalidateGeometryCache(); Filter oldFilter = filter; this.filter = newFilter; firePropertyChange("filter", oldFilter, newFilter); } public Filter getFilter() { return filter; } // // Drawing methods // public void paint(Graphics2D g2d, GraphicsNodeRenderContext rc) { // // Set up graphic context. It is important to setup the // transform first, because the clip is defined in this // node's user space. // Shape defaultClip = g2d.getClip(); Composite defaultComposite = g2d.getComposite(); AffineTransform defaultTransform = g2d.getTransform(); RenderingHints defaultHints = g2d.getRenderingHints(); if (hints != null) { g2d.addRenderingHints(hints); } if (transform != null) { g2d.transform(transform); } if (clip != null) { g2d.clip(clip); } if (composite != null) { g2d.setComposite(composite); } rc.setTransform(g2d.getTransform()); rc.setAreaOfInterest(g2d.getClip()); rc.setRenderingHints(g2d.getRenderingHints()); // // Check if any painting is needed at all. Get the clip (in user space) // and see if it intersects with this node's bounds (in user space). // boolean paintNeeded = true; Rectangle2D bounds = getBounds(); Shape clip = g2d.getClip(); if(clip != null){ Rectangle2D clipBounds = clip.getBounds(); if(!bounds.intersects(clipBounds.getX(), clipBounds.getY(), clipBounds.getWidth(), clipBounds.getHeight())){ paintNeeded = false; } } // // Only paint if needed. // // paintNeeded = true; if (paintNeeded){ if (!isOffscreenBufferNeeded()) { // Render directly on the canvas primitivePaint(g2d, rc); } else{ Filter filteredImage = null; if(filter == null){ filteredImage = rc.getGraphicsNodeRableFactory(). createGraphicsNodeRable(this); } else { traceFilter(filter, "=====>> "); filteredImage = filter; } if (mask != null) { if (mask.getSource() != filteredImage){ mask.setSource(filteredImage); } filteredImage = mask; System.out.println("YYYYYYYY Masking.... "); } // Create the render context for drawing this node. AffineTransform usr2dev = g2d.getTransform(); // RenderContext context = new RenderContext(usr2dev, g2d.getClip(), rc.getRenderingHints()); RenderedImage renderedNodeImage = filteredImage.createRendering(rc); Rectangle2D filterBounds = filteredImage.getBounds2D(); g2d.clip(filterBounds); if(renderedNodeImage != null){ g2d.setTransform(IDENTITY); g2d.drawRenderedImage(renderedNodeImage, IDENTITY); } } } // Restore default rendering attributes g2d.setRenderingHints(defaultHints); g2d.setTransform(defaultTransform); g2d.setClip(defaultClip); g2d.setComposite(defaultComposite); } /** * DEBUG: Trace filter chain */ private void traceFilter(Filter filter, String prefix){ System.out.println(prefix + filter.getClass().getName()); System.out.println(prefix + filter.getBounds2D()); java.util.Vector sources = filter.getSources(); int nSources = sources != null ? sources.size() : 0; prefix += "\t"; for(int i=0; i<nSources; i++){ Filter source = (Filter)sources.elementAt(i); traceFilter(source, prefix); } System.out.flush(); } /** * Returns true of an offscreen buffer is needed to render this * node, false otherwise. */ protected boolean isOffscreenBufferNeeded() { return ((filter != null) || (mask != null) || (composite != null && !AlphaComposite.SrcOver.equals(composite))); } // // Event support methods // public void addGraphicsNodeMouseListener(GraphicsNodeMouseListener l) { if (listeners == null) { listeners = new EventListenerList(); } listeners.add(GraphicsNodeMouseListener.class, l); } public void removeGraphicsNodeMouseListener(GraphicsNodeMouseListener l) { if (listeners != null) { listeners.remove(GraphicsNodeMouseListener.class, l); } } public void addGraphicsNodeKeyListener(GraphicsNodeKeyListener l) { if (listeners == null) { listeners = new EventListenerList(); } listeners.add(GraphicsNodeKeyListener.class, l); } public void removeGraphicsNodeKeyListener(GraphicsNodeKeyListener l) { if (listeners != null) { listeners.remove(GraphicsNodeKeyListener.class, l); } } public void setGraphicsNodeEventFilter(GraphicsNodeEventFilter evtFilter) { GraphicsNodeEventFilter oldFilter = eventFilter; this.eventFilter = evtFilter; firePropertyChange("graphicsNodeEventFilter", oldFilter, evtFilter); } public GraphicsNodeEventFilter getGraphicsNodeEventFilter() { return eventFilter; } public void setGraphicsNodeHitDetector( GraphicsNodeHitDetector hitDetector) { GraphicsNodeHitDetector oldDetector = this.hitDetector; this.hitDetector = hitDetector; firePropertyChange("graphicsNodeHitDetector", oldDetector, hitDetector); } public GraphicsNodeHitDetector getGraphicsNodeHitDetector() { return hitDetector; } public void addPropertyChangeListener(PropertyChangeListener l) { pcs.addPropertyChangeListener(l); } public void addPropertyChangeListener(String propertyName, PropertyChangeListener l) { pcs.addPropertyChangeListener(propertyName, l); } public void removePropertyChangeListener(PropertyChangeListener l) { pcs.removePropertyChangeListener(l); } public void dispatch(GraphicsNodeEvent evt) { // <!> FIXME : TO DO } public EventListener [] getListeners(Class listenerType) { Object array = Array.newInstance(listenerType, listeners.getListenerCount(listenerType)); Object[] pairElements = listeners.getListenerList(); for (int i=0, j=0;i<pairElements.length-1;i+=2) { if (pairElements[i].equals(listenerType)) { Array.set(array, j, pairElements[i+1]); ++j; } } return (EventListener[]) array; // XXX: Code below is a jdk 1.3 dependency! Should be removed. //return listeners.getListeners(listenerType); } // // Structural methods // public CompositeGraphicsNode getParent() { return parent; } public RootGraphicsNode getRoot() { return root; } protected void setRoot(RootGraphicsNode newRoot) { this.root = newRoot; } void setParent(CompositeGraphicsNode newParent) { this. parent = newParent; } public void putMemento(Object key, Object mememto) { if (mememtos == null) { mememtos = new HashMap(); } mememtos.put(key, mememto); } public Object getMemento(Object key) { return (mememtos != null)? mememtos.get(key) : null; } public void removeMemento(Object key) { if (mememtos != null) { mememtos.remove(key); if (mememtos.isEmpty()) { mememtos = null; } } } // // Geometric methods // /** * Invalidates the cached geometric bounds. This method is called * each time an attribute that affects the bounds of this node * changed. */ protected void invalidateGeometryCache() { if (parent != null) { ((AbstractGraphicsNode) parent).invalidateGeometryCache(); } bounds = null; } /** * Compute the rendered bounds of this node based on it's * renderBounds, i.e., the area painted by its primitivePaint * method. This is used in addition to the mask, clip and filter * to compute the area actually rendered by this node. */ public Rectangle2D getBounds(){ // Get the primitive bounds // Rectangle2D bounds = null; if(bounds == null){ // The painted region, before cliping, masking // and compositing is either the area painted // by the primitive paint or the area painted // by the filter. if(filter == null){ bounds = getPrimitiveBounds(); } else { bounds = filter.getBounds2D(); } // Factor in the clipping area, if any if(clip != null) { bounds.intersect(bounds, clip.getBounds2D(), bounds); } // Factor in the mask, if any if(mask != null) { bounds.intersect(bounds, mask.getBounds2D(), bounds); } } return bounds; } public boolean contains(Point2D p) { return getBounds().contains(p); } public GraphicsNode nodeHitAt(Point2D p) { if (hitDetector != null) { if (hitDetector.isHit(this, p)) { return this; } else { return null; } } else { return (contains(p) ? this : null); } } public boolean intersects(Rectangle2D r) { return getBounds().intersects(r); } public void processMouseEvent(GraphicsNodeMouseEvent evt) { if ((listeners != null) && acceptEvent(evt)) { GraphicsNodeMouseListener[] listeners = (GraphicsNodeMouseListener[]) getListeners(GraphicsNodeMouseListener.class); switch (evt.getID()) { case GraphicsNodeMouseEvent.MOUSE_MOVED: for (int i=0; i<listeners.length; ++i) { listeners[i].mouseMoved((GraphicsNodeMouseEvent) evt.clone()); } break; case GraphicsNodeMouseEvent.MOUSE_DRAGGED: for (int i=0; i<listeners.length; ++i) { listeners[i].mouseDragged((GraphicsNodeMouseEvent) evt.clone()); } break; case GraphicsNodeMouseEvent.MOUSE_ENTERED: for (int i=0; i<listeners.length; ++i) { listeners[i].mouseEntered((GraphicsNodeMouseEvent) evt.clone()); } break; case GraphicsNodeMouseEvent.MOUSE_EXITED: for (int i=0; i<listeners.length; ++i) { listeners[i].mouseExited((GraphicsNodeMouseEvent) evt.clone()); } break; case GraphicsNodeMouseEvent.MOUSE_CLICKED: for (int i=0; i<listeners.length; ++i) { listeners[i].mouseClicked((GraphicsNodeMouseEvent) evt.clone()); } break; case GraphicsNodeMouseEvent.MOUSE_PRESSED: for (int i=0; i<listeners.length; ++i) { listeners[i].mousePressed((GraphicsNodeMouseEvent) evt.clone()); } break; case GraphicsNodeMouseEvent.MOUSE_RELEASED: for (int i=0; i<listeners.length; ++i) { listeners[i].mouseReleased((GraphicsNodeMouseEvent) evt.clone()); } break; default: throw new Error("Unknown Mouse Event type: "+evt.getID()); } } evt.consume(); } public void processKeyEvent(GraphicsNodeKeyEvent evt) { if ((listeners != null) && acceptEvent(evt)) { GraphicsNodeKeyListener[] listeners = (GraphicsNodeKeyListener[]) getListeners(GraphicsNodeKeyListener.class); switch (evt.getID()) { case GraphicsNodeKeyEvent.KEY_PRESSED: for (int i=0; i<listeners.length; ++i) { listeners[i].keyPressed((GraphicsNodeKeyEvent) evt.clone()); } case GraphicsNodeKeyEvent.KEY_RELEASED: for (int i=0; i<listeners.length; ++i) { listeners[i].keyReleased((GraphicsNodeKeyEvent) evt.clone()); } break; case GraphicsNodeKeyEvent.KEY_TYPED: for (int i=0; i<listeners.length; ++i) { listeners[i].keyTyped((GraphicsNodeKeyEvent) evt.clone()); } break; default: throw new Error("Unknown Key Event type: "+evt.getID()); } } evt.consume(); } public void processChangeEvent(CompositeGraphicsNodeEvent evt) { if ((listeners != null) && acceptEvent(evt)) { CompositeGraphicsNodeListener[] listeners = (CompositeGraphicsNodeListener[]) getListeners(CompositeGraphicsNodeListener.class); switch (evt.getID()) { case CompositeGraphicsNodeEvent.GRAPHICS_NODE_ADDED: for (int i=0; i<listeners.length; ++i) { listeners[i].graphicsNodeAdded((CompositeGraphicsNodeEvent) evt.clone()); } case CompositeGraphicsNodeEvent.GRAPHICS_NODE_REMOVED: for (int i=0; i<listeners.length; ++i) { listeners[i].graphicsNodeRemoved((CompositeGraphicsNodeEvent) evt.clone()); } break; default: throw new Error("Unknown Key Event type: "+evt.getID()); } } evt.consume(); } protected boolean acceptEvent(GraphicsNodeEvent evt) { if (eventFilter != null) { return eventFilter.accept(this, evt); } return true; } }
sources/org/apache/batik/refimpl/gvt/AbstractGraphicsNode.java
/***************************************************************************** * Copyright (C) The Apache Software Foundation. All rights reserved. * * ------------------------------------------------------------------------- * * This software is published under the terms of the Apache Software License * * version 1.1, a copy of which has been included with this distribution in * * the LICENSE file. * *****************************************************************************/ package org.apache.batik.refimpl.gvt; import java.awt.Cursor; import java.awt.Composite; import java.awt.AlphaComposite; import java.awt.Rectangle; import java.awt.Shape; import java.awt.Graphics2D; import java.awt.RenderingHints; import java.awt.geom.AffineTransform; import java.awt.geom.GeneralPath; import java.awt.geom.NoninvertibleTransformException; import java.awt.geom.Rectangle2D; import java.awt.geom.Point2D; import java.awt.image.RenderedImage; import java.awt.image.renderable.RenderContext; import java.awt.image.renderable.RenderableImage; import java.util.HashMap; import java.util.Map; import java.util.List; import java.util.Vector; import java.util.EventListener; import java.lang.reflect.Array; import java.beans.PropertyChangeListener; import java.beans.PropertyChangeSupport; import javax.swing.event.EventListenerList; import org.apache.batik.gvt.GraphicsNode; import org.apache.batik.gvt.RootGraphicsNode; import org.apache.batik.gvt.CompositeGraphicsNode; import org.apache.batik.gvt.GraphicsNodeRenderContext; import org.apache.batik.gvt.GraphicsNodeHitDetector; import org.apache.batik.gvt.event.GraphicsNodeEvent; import org.apache.batik.gvt.event.GraphicsNodeMouseEvent; import org.apache.batik.gvt.event.GraphicsNodeMouseListener; import org.apache.batik.gvt.event.GraphicsNodeKeyEvent; import org.apache.batik.gvt.event.GraphicsNodeKeyListener; import org.apache.batik.gvt.event.GraphicsNodeEventFilter; import org.apache.batik.gvt.event.CompositeGraphicsNodeEvent; import org.apache.batik.gvt.event.CompositeGraphicsNodeListener; import org.apache.batik.gvt.filter.Filter; import org.apache.batik.gvt.filter.Mask; import org.apache.batik.gvt.filter.PadMode; /** * A partial implementation of the <tt>GraphicsNode</tt> interface. * * @author <a href="mailto:[email protected]">Thierry Kormann</a> * @author <a href="mailto:[email protected]">Emmanuel Tissandier</a> * @version $Id$ */ public abstract class AbstractGraphicsNode implements GraphicsNode { /** * Used to draw renderable images */ static final AffineTransform IDENTITY = new AffineTransform(); /** * The Map used to store mememto objects. */ protected Map mememtos; /** * The listeners list. */ protected EventListenerList listeners; /** * Used to manage and fire property change listeners. */ private PropertyChangeSupport pcs = new PropertyChangeSupport(this); /** * The filter used to filter graphics node events. */ protected GraphicsNodeEventFilter eventFilter; /** * The hit detector used to filter mouse events. */ protected GraphicsNodeHitDetector hitDetector; /** * The cursor attached to this graphics node. */ protected Cursor cursor; /** * The transform of this graphics node. */ protected AffineTransform transform; /** * The compositing operation to be used when a graphics node is * painted on top of another one. */ protected Composite composite; /** * This flag bit indicates whether or not this graphics node is visible. */ protected boolean isVisible = true; /** * The clipping area of this graphics node. */ protected Shape clip; /** * The rendering hints that control the quality to use when rendering * this graphics node. */ protected RenderingHints hints; /** * The mask of this graphics node. */ protected Mask mask; /** * The parent of this graphics node. */ protected CompositeGraphicsNode parent; /** * The root of the GVT tree. */ protected RootGraphicsNode root; /** * The filter of this graphics node. */ protected Filter filter; /** * Cache: node bounds */ private Rectangle2D bounds; /** * Constructs a new graphics node. */ public AbstractGraphicsNode() {} // // fire property change methods. // protected void firePropertyChange(String propertyName, boolean oldValue, boolean newValue){ // First fire to local listeners pcs.firePropertyChange(propertyName, oldValue, newValue); // fire to root node listeners if possible. if (root != null) { ConcreteRootGraphicsNode node = (ConcreteRootGraphicsNode) root; node.fireGlobalPropertyChange(this, propertyName, oldValue, newValue); } } protected void firePropertyChange(String propertyName, int oldValue, int newValue){ // First fire to local listeners pcs.firePropertyChange(propertyName, oldValue, newValue); // fire to root node listeners if possible. if (root != null) { ConcreteRootGraphicsNode node = (ConcreteRootGraphicsNode) root; node.fireGlobalPropertyChange(this, propertyName, oldValue, newValue); } } protected void firePropertyChange(String propertyName, Object oldValue, Object newValue){ // First fire to local listeners pcs.firePropertyChange(propertyName, oldValue, newValue); // fire to root node listeners if possible. if (root != null) { ConcreteRootGraphicsNode node = (ConcreteRootGraphicsNode) root; node.fireGlobalPropertyChange(this, propertyName, oldValue, newValue); } } // // Properties methods // public void setCursor(Cursor newCursor) { Cursor oldCursor = cursor; this.cursor = newCursor; firePropertyChange("cursor", oldCursor, newCursor); } public Cursor getCursor() { return cursor; } public void setTransform(AffineTransform newTransform) { AffineTransform oldTransform = transform; this.transform = newTransform; firePropertyChange("transform", oldTransform, newTransform); } public AffineTransform getTransform() { return transform; } public void setComposite(Composite newComposite) { invalidateGeometryCache(); Composite oldComposite = composite; this.composite = newComposite; firePropertyChange("composite", oldComposite, newComposite); } public Composite getComposite() { return composite; } public void setVisible(boolean isVisible) { boolean oldIsVisible = this.isVisible; this.isVisible = isVisible; firePropertyChange("visible", oldIsVisible, isVisible); } public boolean isVisible() { return isVisible; } public void setClippingArea(Shape newClippingArea) { invalidateGeometryCache(); Shape oldClip = clip; this.clip = newClippingArea; firePropertyChange("clippingArea", oldClip, newClippingArea); } public Shape getClippingArea() { return clip; } public void setRenderingHint(RenderingHints.Key key, Object value) { if (this.hints == null) { this.hints = new RenderingHints(key, value); } else { hints.put(key, value); } } public void setRenderingHints(Map hints) { if (this.hints == null) { this.hints = new RenderingHints(hints); } else { this.hints.putAll(hints); } } public void setRenderingHints(RenderingHints newHints) { this.hints = newHints; } public RenderingHints getRenderingHints() { return hints; } public void setMask(Mask newMask) { invalidateGeometryCache(); Mask oldMask = mask; this.mask = newMask; firePropertyChange("mask", oldMask, newMask); } public Mask getMask() { return mask; } public void setFilter(Filter newFilter) { invalidateGeometryCache(); Filter oldFilter = filter; this.filter = newFilter; firePropertyChange("filter", oldFilter, newFilter); } public Filter getFilter() { return filter; } // // Drawing methods // public void paint(Graphics2D g2d, GraphicsNodeRenderContext rc) { // // Set up graphic context. It is important to setup the // transform first, because the clip is defined in this // node's user space. // Shape defaultClip = g2d.getClip(); Composite defaultComposite = g2d.getComposite(); AffineTransform defaultTransform = g2d.getTransform(); RenderingHints defaultHints = g2d.getRenderingHints(); if (hints != null) { g2d.addRenderingHints(hints); } if (transform != null) { g2d.transform(transform); } if (clip != null) { g2d.clip(clip); // Work around clipping issue. DO NOT REMOVE, EVEN // if it looks stupid. g2d.setClip(new GeneralPath(g2d.getClip())); } if (composite != null) { g2d.setComposite(composite); } rc.setTransform(g2d.getTransform()); rc.setAreaOfInterest(g2d.getClip()); rc.setRenderingHints(g2d.getRenderingHints()); // // Check if any painting is needed at all. Get the clip (in user space) // and see if it intersects with this node's bounds (in user space). // boolean paintNeeded = true; Rectangle2D bounds = getBounds(); Shape clip = g2d.getClip(); if(clip != null){ Rectangle2D clipBounds = clip.getBounds(); if(!bounds.intersects(clipBounds.getX(), clipBounds.getY(), clipBounds.getWidth(), clipBounds.getHeight())){ paintNeeded = false; } } // // Only paint if needed. // // paintNeeded = true; if (paintNeeded){ if (!isOffscreenBufferNeeded()) { // Render directly on the canvas primitivePaint(g2d, rc); } else{ Filter filteredImage = null; if(filter == null){ filteredImage = rc.getGraphicsNodeRableFactory(). createGraphicsNodeRable(this); } else { traceFilter(filter, "=====>> "); filteredImage = filter; } if (mask != null) { if (mask.getSource() != filteredImage){ mask.setSource(filteredImage); } filteredImage = mask; System.out.println("YYYYYYYY Masking.... "); } // Create the render context for drawing this node. AffineTransform usr2dev = g2d.getTransform(); // RenderContext context = new RenderContext(usr2dev, g2d.getClip(), rc.getRenderingHints()); RenderedImage renderedNodeImage = filteredImage.createRendering(rc); Rectangle2D filterBounds = filteredImage.getBounds2D(); g2d.clip(filterBounds); if(renderedNodeImage != null){ g2d.setTransform(IDENTITY); g2d.drawRenderedImage(renderedNodeImage, IDENTITY); } } } // Restore default rendering attributes g2d.setRenderingHints(defaultHints); g2d.setTransform(defaultTransform); g2d.setClip(defaultClip); g2d.setComposite(defaultComposite); } /** * DEBUG: Trace filter chain */ private void traceFilter(Filter filter, String prefix){ System.out.println(prefix + filter.getClass().getName()); System.out.println(prefix + filter.getBounds2D()); java.util.Vector sources = filter.getSources(); int nSources = sources != null ? sources.size() : 0; prefix += "\t"; for(int i=0; i<nSources; i++){ Filter source = (Filter)sources.elementAt(i); traceFilter(source, prefix); } System.out.flush(); } /** * Returns true of an offscreen buffer is needed to render this * node, false otherwise. */ protected boolean isOffscreenBufferNeeded() { return ((filter != null) || (mask != null) || (composite != null && !AlphaComposite.SrcOver.equals(composite))); } // // Event support methods // public void addGraphicsNodeMouseListener(GraphicsNodeMouseListener l) { if (listeners == null) { listeners = new EventListenerList(); } listeners.add(GraphicsNodeMouseListener.class, l); } public void removeGraphicsNodeMouseListener(GraphicsNodeMouseListener l) { if (listeners != null) { listeners.remove(GraphicsNodeMouseListener.class, l); } } public void addGraphicsNodeKeyListener(GraphicsNodeKeyListener l) { if (listeners == null) { listeners = new EventListenerList(); } listeners.add(GraphicsNodeKeyListener.class, l); } public void removeGraphicsNodeKeyListener(GraphicsNodeKeyListener l) { if (listeners != null) { listeners.remove(GraphicsNodeKeyListener.class, l); } } public void setGraphicsNodeEventFilter(GraphicsNodeEventFilter evtFilter) { GraphicsNodeEventFilter oldFilter = eventFilter; this.eventFilter = evtFilter; firePropertyChange("graphicsNodeEventFilter", oldFilter, evtFilter); } public GraphicsNodeEventFilter getGraphicsNodeEventFilter() { return eventFilter; } public void setGraphicsNodeHitDetector( GraphicsNodeHitDetector hitDetector) { GraphicsNodeHitDetector oldDetector = this.hitDetector; this.hitDetector = hitDetector; firePropertyChange("graphicsNodeHitDetector", oldDetector, hitDetector); } public GraphicsNodeHitDetector getGraphicsNodeHitDetector() { return hitDetector; } public void addPropertyChangeListener(PropertyChangeListener l) { pcs.addPropertyChangeListener(l); } public void addPropertyChangeListener(String propertyName, PropertyChangeListener l) { pcs.addPropertyChangeListener(propertyName, l); } public void removePropertyChangeListener(PropertyChangeListener l) { pcs.removePropertyChangeListener(l); } public void dispatch(GraphicsNodeEvent evt) { // <!> FIXME : TO DO } public EventListener [] getListeners(Class listenerType) { Object array = Array.newInstance(listenerType, listeners.getListenerCount(listenerType)); Object[] pairElements = listeners.getListenerList(); for (int i=0, j=0;i<pairElements.length-1;i+=2) { if (pairElements[i].equals(listenerType)) { Array.set(array, j, pairElements[i+1]); ++j; } } return (EventListener[]) array; // XXX: Code below is a jdk 1.3 dependency! Should be removed. //return listeners.getListeners(listenerType); } // // Structural methods // public CompositeGraphicsNode getParent() { return parent; } public RootGraphicsNode getRoot() { return root; } protected void setRoot(RootGraphicsNode newRoot) { this.root = newRoot; } void setParent(CompositeGraphicsNode newParent) { this. parent = newParent; } public void putMemento(Object key, Object mememto) { if (mememtos == null) { mememtos = new HashMap(); } mememtos.put(key, mememto); } public Object getMemento(Object key) { return (mememtos != null)? mememtos.get(key) : null; } public void removeMemento(Object key) { if (mememtos != null) { mememtos.remove(key); if (mememtos.isEmpty()) { mememtos = null; } } } // // Geometric methods // /** * Invalidates the cached geometric bounds. This method is called * each time an attribute that affects the bounds of this node * changed. */ protected void invalidateGeometryCache() { if (parent != null) { ((AbstractGraphicsNode) parent).invalidateGeometryCache(); } bounds = null; } /** * Compute the rendered bounds of this node based on it's * renderBounds, i.e., the area painted by its primitivePaint * method. This is used in addition to the mask, clip and filter * to compute the area actually rendered by this node. */ public Rectangle2D getBounds(){ // Get the primitive bounds // Rectangle2D bounds = null; if(bounds == null){ // The painted region, before cliping, masking // and compositing is either the area painted // by the primitive paint or the area painted // by the filter. if(filter == null){ bounds = getPrimitiveBounds(); } else { bounds = filter.getBounds2D(); } // Factor in the clipping area, if any if(clip != null) { bounds.intersect(bounds, clip.getBounds2D(), bounds); } // Factor in the mask, if any if(mask != null) { bounds.intersect(bounds, mask.getBounds2D(), bounds); } } return bounds; } public boolean contains(Point2D p) { return getBounds().contains(p); } public GraphicsNode nodeHitAt(Point2D p) { if (hitDetector != null) { if (hitDetector.isHit(this, p)) { return this; } else { return null; } } else { return (contains(p) ? this : null); } } public boolean intersects(Rectangle2D r) { return getBounds().intersects(r); } public void processMouseEvent(GraphicsNodeMouseEvent evt) { if ((listeners != null) && acceptEvent(evt)) { GraphicsNodeMouseListener[] listeners = (GraphicsNodeMouseListener[]) getListeners(GraphicsNodeMouseListener.class); switch (evt.getID()) { case GraphicsNodeMouseEvent.MOUSE_MOVED: for (int i=0; i<listeners.length; ++i) { listeners[i].mouseMoved((GraphicsNodeMouseEvent) evt.clone()); } break; case GraphicsNodeMouseEvent.MOUSE_DRAGGED: for (int i=0; i<listeners.length; ++i) { listeners[i].mouseDragged((GraphicsNodeMouseEvent) evt.clone()); } break; case GraphicsNodeMouseEvent.MOUSE_ENTERED: for (int i=0; i<listeners.length; ++i) { listeners[i].mouseEntered((GraphicsNodeMouseEvent) evt.clone()); } break; case GraphicsNodeMouseEvent.MOUSE_EXITED: for (int i=0; i<listeners.length; ++i) { listeners[i].mouseExited((GraphicsNodeMouseEvent) evt.clone()); } break; case GraphicsNodeMouseEvent.MOUSE_CLICKED: for (int i=0; i<listeners.length; ++i) { listeners[i].mouseClicked((GraphicsNodeMouseEvent) evt.clone()); } break; case GraphicsNodeMouseEvent.MOUSE_PRESSED: for (int i=0; i<listeners.length; ++i) { listeners[i].mousePressed((GraphicsNodeMouseEvent) evt.clone()); } break; case GraphicsNodeMouseEvent.MOUSE_RELEASED: for (int i=0; i<listeners.length; ++i) { listeners[i].mouseReleased((GraphicsNodeMouseEvent) evt.clone()); } break; default: throw new Error("Unknown Mouse Event type: "+evt.getID()); } } evt.consume(); } public void processKeyEvent(GraphicsNodeKeyEvent evt) { if ((listeners != null) && acceptEvent(evt)) { GraphicsNodeKeyListener[] listeners = (GraphicsNodeKeyListener[]) getListeners(GraphicsNodeKeyListener.class); switch (evt.getID()) { case GraphicsNodeKeyEvent.KEY_PRESSED: for (int i=0; i<listeners.length; ++i) { listeners[i].keyPressed((GraphicsNodeKeyEvent) evt.clone()); } case GraphicsNodeKeyEvent.KEY_RELEASED: for (int i=0; i<listeners.length; ++i) { listeners[i].keyReleased((GraphicsNodeKeyEvent) evt.clone()); } break; case GraphicsNodeKeyEvent.KEY_TYPED: for (int i=0; i<listeners.length; ++i) { listeners[i].keyTyped((GraphicsNodeKeyEvent) evt.clone()); } break; default: throw new Error("Unknown Key Event type: "+evt.getID()); } } evt.consume(); } public void processChangeEvent(CompositeGraphicsNodeEvent evt) { if ((listeners != null) && acceptEvent(evt)) { CompositeGraphicsNodeListener[] listeners = (CompositeGraphicsNodeListener[]) getListeners(CompositeGraphicsNodeListener.class); switch (evt.getID()) { case CompositeGraphicsNodeEvent.GRAPHICS_NODE_ADDED: for (int i=0; i<listeners.length; ++i) { listeners[i].graphicsNodeAdded((CompositeGraphicsNodeEvent) evt.clone()); } case CompositeGraphicsNodeEvent.GRAPHICS_NODE_REMOVED: for (int i=0; i<listeners.length; ++i) { listeners[i].graphicsNodeRemoved((CompositeGraphicsNodeEvent) evt.clone()); } break; default: throw new Error("Unknown Key Event type: "+evt.getID()); } } evt.consume(); } protected boolean acceptEvent(GraphicsNodeEvent evt) { if (eventFilter != null) { return eventFilter.accept(this, evt); } return true; } }
Remove clipping optimization (moved to ConcreteTextNode). PR: Obtained from: Submitted by: Reviewed by: git-svn-id: e944db0f7b5c8f0ae3e1ad43ca99b026751ef0c2@198988 13f79535-47bb-0310-9956-ffa450edef68
sources/org/apache/batik/refimpl/gvt/AbstractGraphicsNode.java
Remove clipping optimization (moved to ConcreteTextNode). PR: Obtained from: Submitted by: Reviewed by:
<ide><path>ources/org/apache/batik/refimpl/gvt/AbstractGraphicsNode.java <ide> } <ide> if (clip != null) { <ide> g2d.clip(clip); <del> // Work around clipping issue. DO NOT REMOVE, EVEN <del> // if it looks stupid. <del> g2d.setClip(new GeneralPath(g2d.getClip())); <ide> } <ide> if (composite != null) { <ide> g2d.setComposite(composite);
JavaScript
apache-2.0
51c7d2da9558fe21d883688d6f960bd5ad287886
0
asha-nepal/AshaFusionCross,asha-nepal/AshaFusionCross,asha-nepal/AshaFusionCross,asha-nepal/AshaFusionCross,asha-nepal/AshaFusionCross
/* @flow */ import { createSelector } from 'reselect'; import _get from 'lodash.get'; import moment from 'moment'; export { getIsLoggedIn, getLoggedInUser, getIsAdmin, } from './auth'; export { getRecordFormStyles, getDefaultRecordFormStyleId, getRecordFormStyleId, getRecordFormStyle, getPatientFormStyle, } from './dform'; export { getRecordList, getRecordListForStats, } from './stats'; export { getPatientMax, } from './patient-list'; export const getPatientList = (state: Object) => state.patientList; export const getPatientSelectFilter = (state: Object) => state.patientSelect.filter.trim().toLowerCase(); export const getPatientSelectTimeRange = (state: Object) => state.patientSelect.filterDate; export const getPatientSelectQueryList = (state: Object) => getPatientSelectFilter(state).split(' ').filter(q => q.length > 0); export const checkPatientMatchesQueries = (queries: Array<string>, patient: PatientObject) => queries.every(query => { if (patient.name) { const _query = ` ${query}`; const _name = ` ${patient.name.toLowerCase()}`; if (_name.indexOf(_query) !== -1) return true; } if (patient.number) { if (patient.number === query) return true; } return false; }); function patientInTimeRange(timeRange, patient) { const startDate = timeRange.startDate; const endDate = timeRange.endDate; const patientCreatedMoment = moment(patient.$updated_at); if (!startDate && !endDate) { const currentMoment = moment(); return currentMoment.isSame(patientCreatedMoment, 'day'); } const conditions = []; if (startDate) conditions.push(patientCreatedMoment.isSameOrAfter(startDate, 'day')); if (endDate) conditions.push(patientCreatedMoment.isSameOrBefore(endDate, 'day')); return conditions.reduce((conclusion, b) => conclusion & b); } export const getFilteredPatientList = createSelector( [getPatientList, getPatientSelectQueryList, getPatientSelectTimeRange], (patientList, queryList, timeRange) => { if (queryList.length === 0) { return patientList.filter(patient => patientInTimeRange(timeRange, patient)); } return patientList.filter(patient => checkPatientMatchesQueries(queryList, patient)); } ); // TODO: 名付けの一貫性 export const getPatientSortField = (state: Object) => state.patientSelect.sortBy; export const getPatientSortOrder = (state: Object) => state.patientSelect.sortInAsc; export const getSortedFilteredPatientList = createSelector( [getFilteredPatientList, getPatientSortField, getPatientSortOrder], (filteredPatientList, sortBy, sortInAsc) => { const x = sortInAsc ? -1 : 1; const _x = -x; return filteredPatientList .slice().sort((a, b) => { // sort()は破壊的なので,slice()を挟む if (!a[sortBy]) { return 1; } // 空データはASC, DESC問わず末尾にする if (!b[sortBy]) { return -1; } const _a = a[sortBy].toLowerCase(); const _b = b[sortBy].toLowerCase(); if (_a < _b) { return x; } else if (_a > _b) { return _x; } return 0; }); } ); export const getActivePatient = (state: Object) => state.activePatient; export const makeGetDuplicatedPatients = (field: string) => createSelector( [ (state) => state.activePatient._id, (state) => state.activePatient[field], getPatientList, ], (activePatientId, activePatientField, patientList) => { if (!activePatientField) { return []; } return patientList.filter(p => p._id !== activePatientId && p[field] === activePatientField); } ); export const getActiveRecords = (state: Object) => state.activeRecords; export const getSelectedActiveRecordId = (state: Object) => state.patientView.selectedActiveRecordId; export const getSelectedActiveRecord = createSelector( [getActiveRecords, getSelectedActiveRecordId], (activeRecords, selectedActiveRecordId) => activeRecords.find(r => r._id === selectedActiveRecordId) ); export const getSelectedActiveRecordIndex = createSelector( [getActiveRecords, getSelectedActiveRecordId], (activeRecords, selectedActiveRecordId) => activeRecords.findIndex(r => r._id === selectedActiveRecordId) ); function isFormPristine(formState, path) { const result = _get(formState, path, {}); if ('$form' in result) return result.$form.pristine; return true; } export const getActiveRecordsForm = (state: Object) => state.activeRecordsForm; export const getActiveRecordsFormPristineness = createSelector( [getActiveRecords, getActiveRecordsForm], (activeRecords, activeRecordsForm) => activeRecords.map((r, i) => isFormPristine(activeRecordsForm, `[${i}]`)), );
src/selectors/index.js
/* @flow */ import { createSelector } from 'reselect'; import _get from 'lodash.get'; import moment from 'moment'; export { getIsLoggedIn, getLoggedInUser, getIsAdmin, } from './auth'; export { getRecordFormStyles, getDefaultRecordFormStyleId, getRecordFormStyleId, getRecordFormStyle, getPatientFormStyle, } from './dform'; export { getRecordList, getRecordListForStats, } from './stats'; export { getPatientMax, } from './patient-list'; export const getPatientList = (state: Object) => state.patientList; export const getPatientSelectFilter = (state: Object) => state.patientSelect.filter.trim().toLowerCase(); export const getPatientSelectTimeRange = (state: Object) => state.patientSelect.filterDate; export const getPatientSelectQueryList = (state: Object) => getPatientSelectFilter(state).split(' ').filter(q => q.length > 0); export const checkPatientMatchesQueries = (queries: Array<string>, patient: PatientObject) => queries.every(query => { if (patient.name) { const _query = ` ${query}`; const _name = ` ${patient.name.toLowerCase()}`; if (_name.indexOf(_query) !== -1) return true; } if (patient.number) { if (patient.number === query) return true; } return false; }); function patientInTimeRange(timeRange, patient) { const startDate = timeRange.startDate; const endDate = timeRange.endDate; const patientCreatedMoment = moment(patient.$updated_at); if (!startDate && !endDate) { const currentMoment = moment(); return currentMoment.isSame(patientCreatedMoment, 'day'); } const conditions = []; if (startDate) conditions.push(patientCreatedMoment.isAfter(startDate)); if (endDate) { conditions.push(patientCreatedMoment.isBefore(endDate) || patientCreatedMoment.isSame(endDate, 'day')); } return conditions.reduce((conclusion, b) => conclusion & b); } export const getFilteredPatientList = createSelector( [getPatientList, getPatientSelectQueryList, getPatientSelectTimeRange], (patientList, queryList, timeRange) => { if (queryList.length === 0) { return patientList.filter(patient => patientInTimeRange(timeRange, patient)); } return patientList.filter(patient => checkPatientMatchesQueries(queryList, patient)); } ); // TODO: 名付けの一貫性 export const getPatientSortField = (state: Object) => state.patientSelect.sortBy; export const getPatientSortOrder = (state: Object) => state.patientSelect.sortInAsc; export const getSortedFilteredPatientList = createSelector( [getFilteredPatientList, getPatientSortField, getPatientSortOrder], (filteredPatientList, sortBy, sortInAsc) => { const x = sortInAsc ? -1 : 1; const _x = -x; return filteredPatientList .slice().sort((a, b) => { // sort()は破壊的なので,slice()を挟む if (!a[sortBy]) { return 1; } // 空データはASC, DESC問わず末尾にする if (!b[sortBy]) { return -1; } const _a = a[sortBy].toLowerCase(); const _b = b[sortBy].toLowerCase(); if (_a < _b) { return x; } else if (_a > _b) { return _x; } return 0; }); } ); export const getActivePatient = (state: Object) => state.activePatient; export const makeGetDuplicatedPatients = (field: string) => createSelector( [ (state) => state.activePatient._id, (state) => state.activePatient[field], getPatientList, ], (activePatientId, activePatientField, patientList) => { if (!activePatientField) { return []; } return patientList.filter(p => p._id !== activePatientId && p[field] === activePatientField); } ); export const getActiveRecords = (state: Object) => state.activeRecords; export const getSelectedActiveRecordId = (state: Object) => state.patientView.selectedActiveRecordId; export const getSelectedActiveRecord = createSelector( [getActiveRecords, getSelectedActiveRecordId], (activeRecords, selectedActiveRecordId) => activeRecords.find(r => r._id === selectedActiveRecordId) ); export const getSelectedActiveRecordIndex = createSelector( [getActiveRecords, getSelectedActiveRecordId], (activeRecords, selectedActiveRecordId) => activeRecords.findIndex(r => r._id === selectedActiveRecordId) ); function isFormPristine(formState, path) { const result = _get(formState, path, {}); if ('$form' in result) return result.$form.pristine; return true; } export const getActiveRecordsForm = (state: Object) => state.activeRecordsForm; export const getActiveRecordsFormPristineness = createSelector( [getActiveRecords, getActiveRecordsForm], (activeRecords, activeRecordsForm) => activeRecords.map((r, i) => isFormPristine(activeRecordsForm, `[${i}]`)), );
(refs #457) Modified patient selector
src/selectors/index.js
(refs #457) Modified patient selector
<ide><path>rc/selectors/index.js <ide> return currentMoment.isSame(patientCreatedMoment, 'day'); <ide> } <ide> const conditions = []; <del> if (startDate) conditions.push(patientCreatedMoment.isAfter(startDate)); <del> if (endDate) { <del> conditions.push(patientCreatedMoment.isBefore(endDate) || <del> patientCreatedMoment.isSame(endDate, 'day')); <del> } <add> if (startDate) conditions.push(patientCreatedMoment.isSameOrAfter(startDate, 'day')); <add> if (endDate) conditions.push(patientCreatedMoment.isSameOrBefore(endDate, 'day')); <ide> return conditions.reduce((conclusion, b) => conclusion & b); <ide> } <ide>
Java
mit
32cf5ea6234f752f676cc10304556484b71d634f
0
elliottsj/ftw-android
package com.afollestad.cardsuisample; import android.app.Activity; import android.graphics.drawable.ColorDrawable; import android.os.Bundle; import android.view.MenuItem; import android.widget.Toast; import com.afollestad.cardsui.Card; import com.afollestad.cardsui.CardHeader; import com.afollestad.cardsui.CardListView; public class CustomActivity extends Activity implements Card.CardMenuListener<Card> { @Override public void onCreate(Bundle savedInstanceState) { // This is quick way of theming the action bar without using styles.xml (e.g. using ActionBar Style Generator) getActionBar().setBackgroundDrawable(new ColorDrawable(getResources().getColor(android.R.color.holo_red_dark))); getActionBar().setDisplayShowHomeEnabled(false); getActionBar().setDisplayHomeAsUpEnabled(true); super.onCreate(savedInstanceState); setContentView(R.layout.activity_card_list); // Initializes a CustomCardAdapter with a basic popup menu for each card // The adapter's accent color is set in its constructor, along with the custom card layout and image downloading logic CustomCardAdapter customAdapter = new CustomCardAdapter(this); customAdapter.setPopupMenu(R.menu.card_popup, this); CardListView cardsList = (CardListView) findViewById(R.id.cardsList); cardsList.setAdapter(customAdapter); customAdapter.add(new CardHeader("Custom Sample", "Using larger card layouts")); for (int i = 1; i <= 3; i++) customAdapter.add(new Card("Example #" + i, "Hello")); } @Override public void onMenuItemClick(Card card, MenuItem item) { Toast.makeText(this, card.getTitle() + ": " + item.getTitle(), Toast.LENGTH_SHORT).show(); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: finish(); return true; } return super.onOptionsItemSelected(item); } }
sample/src/com/afollestad/cardsuisample/CustomActivity.java
package com.afollestad.cardsuisample; import android.app.Activity; import android.graphics.drawable.ColorDrawable; import android.os.Bundle; import android.view.MenuItem; import android.widget.Toast; import com.afollestad.cardsui.Card; import com.afollestad.cardsui.CardHeader; import com.afollestad.cardsui.CardListView; public class CustomActivity extends Activity implements Card.CardMenuListener<Card> { @Override public void onCreate(Bundle savedInstanceState) { // This is quick way of theming the action bar without using styles.xml (e.g. using ActionBar Style Generator) getActionBar().setBackgroundDrawable(new ColorDrawable(getResources().getColor(android.R.color.holo_red_dark))); getActionBar().setDisplayShowHomeEnabled(false); getActionBar().setDisplayHomeAsUpEnabled(true); super.onCreate(savedInstanceState); setContentView(R.layout.activity_card_list); // Initializes a CardAdapter with a red accent color (set in the adapter's constructor) and basic popup menu for each card CustomCardAdapter customAdapter = new CustomCardAdapter(this); customAdapter.setPopupMenu(R.menu.card_popup, this); CardListView cardsList = (CardListView) findViewById(R.id.cardsList); cardsList.setAdapter(customAdapter); customAdapter.add(new CardHeader("Custom Sample", "Using larger card layouts")); for (int i = 1; i <= 3; i++) customAdapter.add(new Card("Example #" + i, "Hello")); } @Override public void onMenuItemClick(Card card, MenuItem item) { Toast.makeText(this, card.getTitle() + ": " + item.getTitle(), Toast.LENGTH_SHORT).show(); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: finish(); return true; } return super.onOptionsItemSelected(item); } }
Updates to the sample
sample/src/com/afollestad/cardsuisample/CustomActivity.java
Updates to the sample
<ide><path>ample/src/com/afollestad/cardsuisample/CustomActivity.java <ide> super.onCreate(savedInstanceState); <ide> setContentView(R.layout.activity_card_list); <ide> <del> // Initializes a CardAdapter with a red accent color (set in the adapter's constructor) and basic popup menu for each card <add> // Initializes a CustomCardAdapter with a basic popup menu for each card <add> // The adapter's accent color is set in its constructor, along with the custom card layout and image downloading logic <ide> CustomCardAdapter customAdapter = new CustomCardAdapter(this); <ide> customAdapter.setPopupMenu(R.menu.card_popup, this); <ide>
Java
bsd-3-clause
629b480eaa48cf79dd7e1255732cbb9673077277
0
JensErat/basex,deshmnnit04/basex,deshmnnit04/basex,joansmith/basex,BaseXdb/basex,ksclarke/basex,drmacro/basex,dimitarp/basex,drmacro/basex,BaseXdb/basex,JensErat/basex,ksclarke/basex,vincentml/basex,dimitarp/basex,deshmnnit04/basex,BaseXdb/basex,vincentml/basex,deshmnnit04/basex,drmacro/basex,BaseXdb/basex,deshmnnit04/basex,JensErat/basex,dimitarp/basex,ksclarke/basex,vincentml/basex,deshmnnit04/basex,joansmith/basex,dimitarp/basex,deshmnnit04/basex,JensErat/basex,ksclarke/basex,joansmith/basex,BaseXdb/basex,deshmnnit04/basex,joansmith/basex,dimitarp/basex,vincentml/basex,joansmith/basex,JensErat/basex,drmacro/basex,vincentml/basex,JensErat/basex,dimitarp/basex,dimitarp/basex,JensErat/basex,vincentml/basex,ksclarke/basex,BaseXdb/basex,ksclarke/basex,deshmnnit04/basex,joansmith/basex,BaseXdb/basex,vincentml/basex,ksclarke/basex,deshmnnit04/basex,JensErat/basex,drmacro/basex,ksclarke/basex,joansmith/basex,drmacro/basex,dimitarp/basex,drmacro/basex,ksclarke/basex,BaseXdb/basex,ksclarke/basex,dimitarp/basex,drmacro/basex,drmacro/basex,BaseXdb/basex,JensErat/basex,joansmith/basex,joansmith/basex,drmacro/basex,drmacro/basex,dimitarp/basex,ksclarke/basex,vincentml/basex,joansmith/basex,deshmnnit04/basex,vincentml/basex,ksclarke/basex,JensErat/basex,joansmith/basex,drmacro/basex,vincentml/basex,dimitarp/basex,BaseXdb/basex,JensErat/basex,dimitarp/basex,deshmnnit04/basex,vincentml/basex,JensErat/basex,joansmith/basex,BaseXdb/basex,vincentml/basex,BaseXdb/basex
package org.basex.gui.view.map; import java.util.ArrayList; import org.basex.data.Data; import org.basex.gui.view.ViewRect; import org.basex.util.IntList; import org.basex.util.Token; /** * Uses simple slice and dice layout to split rectangles. * * @author Workgroup DBIS, University of Konstanz 2005-08, ISC License * @author Joerg Hauser */ public final class SliceDiceLayout extends MapLayout { @Override void calcMap(final Data data, final ViewRect r, final ArrayList<ViewRect> mainRects, final IntList l, final int ns, final int ne, final int level) { // one rectangle left.. continue with this child if(ne - ns == 1) { putRect(data, r, mainRects, l, ns, level); } else { // determine direction final boolean v = (level % 2) == 0 ? true : false; // final boolean v = r.w < r.h; // some more nodes have to be positioned on the first level if(level == 0) { splitUniformly(data, r, mainRects, l, ns, ne, level, v); } else { int par = data.parent(l.list[ns], data.kind(l.list[ns]));; long parsize = data.fs != null ? Token.toLong(data.attValue(data.sizeID, par)) : 0; int parchilds = l.list[ne] - l.list[ns]; // setting initial proportions double xx = r.x; double yy = r.y; double ww = 0; double hh = 0; // calculate map for each rectangel on this level for(int i = 0; i < l.size - 1; i++) { int[] liste = new int[1]; liste[0] = l.list[i]; // draw map taking sizes into account long size = data.fs != null ? Token.toLong(data.attValue(data.sizeID, l.list[i])) : 0; int childs = l.list[i + 1] - l.list[i]; double weight = calcWeight(size, childs, parsize, parchilds, data); if(v) { yy += hh; hh = weight * r.h; ww = r.w; } else { xx += ww; ww = weight * r.w; hh = r.h; } if(ww > 0 && hh > 0) calcMap(data, new ViewRect((int) xx, (int) yy, (int) ww, (int) hh, 0, r.level), mainRects, new IntList(liste), 0, 1, level); } } } } @Override String getType() { return "SliceAndDice Layout"; } }
src/org/basex/gui/view/map/SliceDiceLayout.java
package org.basex.gui.view.map; import java.util.ArrayList; import org.basex.data.Data; import org.basex.gui.GUIProp; import org.basex.gui.view.ViewRect; import org.basex.util.IntList; import org.basex.util.Token; /** * Uses simple slice and dice layout to split rectangles. * * @author Workgroup DBIS, University of Konstanz 2005-08, ISC License * @author Joerg Hauser */ public final class SliceDiceLayout extends MapLayout { @Override void calcMap(final Data data, final ViewRect r, final ArrayList<ViewRect> mainRects, final IntList l, final int ns, final int ne, final int level) { // one rectangle left.. continue with this child if(ne - ns == 1) { putRect(data, r, mainRects, l, ns, level); } else { // determine direction final boolean v = (level % 2) == 0 ? true : false; // final boolean v = (r.w > r.h) ? false : true; // some more nodes have to be positioned on the first level if(level == 0) { splitUniformly(data, r, mainRects, l, ns, ne, level, v); } else { // number of nodes used to calculate rect size int nn = ne - ns; long parsize = 1; int par; par = data.parent(l.list[ns], data.kind(l.list[ns])); int parchilds = l.list[ne] - l.list[ns]; // setting initial proportions double xx = r.x; double yy = r.y; double ww, hh; // use filesize to calculate rect sizes if(data.fs != null && GUIProp.mapaggr) { parsize = data.fs != null ? Token.toLong(data.attValue(data.sizeID, par)) : 0; hh = 0; ww = 0; // [JH] remove this and use number of childs if not a fs // problems occur while zooming into to thin rectangles } else { if(v) { ww = r.w; hh = (double) r.h / nn; } else { ww = (double) r.w / nn; hh = r.h; } } // calculate map for each rectangel on this level for(int i = 0; i < l.size - 1; i++) { int[] liste = new int[1]; liste[0] = l.list[i]; // draw map taking sizes into account // [JH] remove else statement if(data.fs != null && GUIProp.mapaggr) { long size = data.fs != null ? Token.toLong(data.attValue(data.sizeID, l.list[i])) : 0; int childs = l.list[i + 1] - l.list[i]; double weight = calcWeight(size, childs, parsize, parchilds, data); // if(Double.isNaN(weight)) System.out.println("[" + l.list[i] + "]" // + "(" + size + ";" + childs + "/" + parsize + ";" // + parchilds + ")" + weight); if(v) { yy += hh; hh = weight * r.h; ww = r.w; } else { xx += ww; ww = weight * r.w; hh = r.h; } if(ww > 0 && hh > 0) calcMap(data, new ViewRect((int) xx, (int) yy, (int) ww, (int) hh, 0, r.level), mainRects, new IntList(liste), 0, 1, level); } else { if(ww > 0 && hh > 0) { if(v) { calcMap(data, new ViewRect((int) xx, (int) yy, (int) ww, (int) hh, 0, r.level), mainRects, new IntList(liste), 0, 1, level); yy += hh; } else { calcMap(data, new ViewRect((int) xx, (int) yy, (int) ww, (int) hh, 0, r.level), mainRects, new IntList(liste), 0, 1, level); xx += ww; } } } } } } } @Override String getType() { return "SliceAndDice Layout"; } }
slider and number of descendants update slice and dice layout
src/org/basex/gui/view/map/SliceDiceLayout.java
slider and number of descendants update slice and dice layout
<ide><path>rc/org/basex/gui/view/map/SliceDiceLayout.java <ide> <ide> import java.util.ArrayList; <ide> import org.basex.data.Data; <del>import org.basex.gui.GUIProp; <ide> import org.basex.gui.view.ViewRect; <ide> import org.basex.util.IntList; <ide> import org.basex.util.Token; <ide> } else { <ide> // determine direction <ide> final boolean v = (level % 2) == 0 ? true : false; <del>// final boolean v = (r.w > r.h) ? false : true; <add>// final boolean v = r.w < r.h; <add> <ide> // some more nodes have to be positioned on the first level <ide> if(level == 0) { <ide> splitUniformly(data, r, mainRects, l, ns, ne, level, v); <del> } else { <del> // number of nodes used to calculate rect size <del> int nn = ne - ns; <del> <del> long parsize = 1; <del> int par; <del> par = data.parent(l.list[ns], data.kind(l.list[ns])); <add> } else { <add> int par = data.parent(l.list[ns], data.kind(l.list[ns]));; <add> long parsize = data.fs != null ? <add> Token.toLong(data.attValue(data.sizeID, par)) : 0; <ide> int parchilds = l.list[ne] - l.list[ns]; <ide> <ide> // setting initial proportions <ide> double xx = r.x; <ide> double yy = r.y; <del> double ww, hh; <del> <del> // use filesize to calculate rect sizes <del> if(data.fs != null && GUIProp.mapaggr) { <del> parsize = data.fs != null ? <del> Token.toLong(data.attValue(data.sizeID, par)) : 0; <del> hh = 0; <del> ww = 0; <del> // [JH] remove this and use number of childs if not a fs <del> // problems occur while zooming into to thin rectangles <del> } else { <del> if(v) { <del> ww = r.w; <del> hh = (double) r.h / nn; <del> } else { <del> ww = (double) r.w / nn; <del> hh = r.h; <del> } <del> } <add> double ww = 0; <add> double hh = 0; <ide> <ide> // calculate map for each rectangel on this level <ide> for(int i = 0; i < l.size - 1; i++) { <ide> liste[0] = l.list[i]; <ide> <ide> // draw map taking sizes into account <del> // [JH] remove else statement <del> if(data.fs != null && GUIProp.mapaggr) { <del> long size = data.fs != null ? <del> Token.toLong(data.attValue(data.sizeID, l.list[i])) : 0; <del> int childs = l.list[i + 1] - l.list[i]; <del> double weight = calcWeight(size, childs, parsize, parchilds, data); <del> <del> // if(Double.isNaN(weight)) System.out.println("[" + l.list[i] + "]" <del> // + "(" + size + ";" + childs + "/" + parsize + ";" <del>// + parchilds + ")" + weight); <del> if(v) { <del> yy += hh; <del> hh = weight * r.h; <del> ww = r.w; <del> } else { <del> xx += ww; <del> ww = weight * r.w; <del> hh = r.h; <del> } <del> if(ww > 0 && hh > 0) calcMap(data, <del> new ViewRect((int) xx, (int) yy, (int) ww, (int) hh, 0, r.level), <del> mainRects, new IntList(liste), 0, 1, level); <add> long size = data.fs != null ? <add> Token.toLong(data.attValue(data.sizeID, l.list[i])) : 0; <add> int childs = l.list[i + 1] - l.list[i]; <add> double weight = calcWeight(size, childs, parsize, parchilds, data); <add> <add> if(v) { <add> yy += hh; <add> hh = weight * r.h; <add> ww = r.w; <ide> } else { <del> if(ww > 0 && hh > 0) { <del> if(v) { <del> calcMap(data, new ViewRect((int) xx, (int) yy, (int) ww, <del> (int) hh, 0, r.level), mainRects, <del> new IntList(liste), 0, 1, level); <del> yy += hh; <del> } else { <del> calcMap(data, new ViewRect((int) xx, (int) yy, (int) ww, <del> (int) hh, 0, r.level), mainRects, <del> new IntList(liste), 0, 1, level); <del> xx += ww; <del> } <del> } <add> xx += ww; <add> ww = weight * r.w; <add> hh = r.h; <ide> } <add> if(ww > 0 && hh > 0) calcMap(data, <add> new ViewRect((int) xx, (int) yy, (int) ww, (int) hh, 0, r.level), <add> mainRects, new IntList(liste), 0, 1, level); <ide> } <ide> } <ide> }
Java
apache-2.0
error: pathspec 'src/test/java/neon/core/AspectTest.java' did not match any file(s) known to git
f5477ee1d9ab41da70e7ecdb1b57872ca71dc900
1
54k/neon
package neon.core; import org.testng.Assert; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; public class AspectTest extends Assert { @DataProvider(name = "aspects") public static Object[][] aspects() { return new Object[][]{ {getAspectForAll(A.class, B.class, C.class)}, {getAspectForAllNodes(ANode.class, BNode.class, CNode.class)} }; } @Test(dataProvider = "aspects") public void testAspect(Aspect aspect) throws Exception { Entity entity = new Entity(); entity.addComponent(new A()).addComponent(new B()).addComponent(new C()); assertTrue(aspect.matches(entity)); entity.removeComponent(A.class); assertFalse(aspect.matches(entity)); } @SafeVarargs private static Aspect getAspectForAll(Class<? extends Component>... componentClasses) { return Aspect.all(componentClasses).get(); } @SafeVarargs private static Aspect getAspectForAllNodes(Class<? extends Node>... nodeClasses) { return Aspect.allNodes(nodeClasses).get(); } private static class A extends Component { } private static class B extends Component { } private static class C extends Component { } private static interface ANode extends Node { A a(); } private static interface BNode extends Node { B b(); } private static interface CNode extends Node { C c(); } }
src/test/java/neon/core/AspectTest.java
added simple aspect tests
src/test/java/neon/core/AspectTest.java
added simple aspect tests
<ide><path>rc/test/java/neon/core/AspectTest.java <add>package neon.core; <add> <add>import org.testng.Assert; <add>import org.testng.annotations.DataProvider; <add>import org.testng.annotations.Test; <add> <add>public class AspectTest extends Assert { <add> <add> @DataProvider(name = "aspects") <add> public static Object[][] aspects() { <add> return new Object[][]{ <add> {getAspectForAll(A.class, B.class, C.class)}, <add> {getAspectForAllNodes(ANode.class, BNode.class, CNode.class)} <add> }; <add> } <add> <add> @Test(dataProvider = "aspects") <add> public void testAspect(Aspect aspect) throws Exception { <add> Entity entity = new Entity(); <add> entity.addComponent(new A()).addComponent(new B()).addComponent(new C()); <add> assertTrue(aspect.matches(entity)); <add> entity.removeComponent(A.class); <add> assertFalse(aspect.matches(entity)); <add> } <add> <add> @SafeVarargs <add> private static Aspect getAspectForAll(Class<? extends Component>... componentClasses) { <add> return Aspect.all(componentClasses).get(); <add> } <add> <add> @SafeVarargs <add> private static Aspect getAspectForAllNodes(Class<? extends Node>... nodeClasses) { <add> return Aspect.allNodes(nodeClasses).get(); <add> } <add> <add> private static class A extends Component { <add> } <add> <add> private static class B extends Component { <add> } <add> <add> private static class C extends Component { <add> } <add> <add> private static interface ANode extends Node { <add> A a(); <add> } <add> <add> private static interface BNode extends Node { <add> B b(); <add> } <add> <add> private static interface CNode extends Node { <add> C c(); <add> } <add>}
Java
apache-2.0
8f09027e33ecca8c67c66584d71283f18db40547
0
tmaret/sling,roele/sling,cleliameneghin/sling,mikibrv/sling,mcdan/sling,mikibrv/sling,wimsymons/sling,labertasch/sling,Nimco/sling,ist-dresden/sling,cleliameneghin/sling,anchela/sling,roele/sling,headwirecom/sling,trekawek/sling,mikibrv/sling,labertasch/sling,mcdan/sling,ieb/sling,Nimco/sling,awadheshv/sling,JEBailey/sling,ist-dresden/sling,awadheshv/sling,vladbailescu/sling,Nimco/sling,headwirecom/sling,roele/sling,tmaret/sling,labertasch/sling,tmaret/sling,trekawek/sling,headwirecom/sling,awadheshv/sling,vladbailescu/sling,labertasch/sling,anchela/sling,JEBailey/sling,awadheshv/sling,ieb/sling,roele/sling,ieb/sling,vladbailescu/sling,mikibrv/sling,mikibrv/sling,mcdan/sling,vladbailescu/sling,awadheshv/sling,tmaret/sling,headwirecom/sling,cleliameneghin/sling,wimsymons/sling,labertasch/sling,tmaret/sling,awadheshv/sling,cleliameneghin/sling,cleliameneghin/sling,wimsymons/sling,anchela/sling,Nimco/sling,JEBailey/sling,Nimco/sling,trekawek/sling,anchela/sling,ist-dresden/sling,JEBailey/sling,wimsymons/sling,anchela/sling,vladbailescu/sling,ist-dresden/sling,headwirecom/sling,mcdan/sling,roele/sling,mikibrv/sling,wimsymons/sling,trekawek/sling,trekawek/sling,JEBailey/sling,ieb/sling,ieb/sling,mcdan/sling,ist-dresden/sling,mcdan/sling,wimsymons/sling,Nimco/sling,trekawek/sling,ieb/sling
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.sling.event.impl.jobs.scheduling; import java.io.Serializable; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.concurrent.atomic.AtomicBoolean; import org.apache.sling.api.SlingConstants; import org.apache.sling.api.resource.ModifiableValueMap; import org.apache.sling.api.resource.PersistenceException; import org.apache.sling.api.resource.Resource; import org.apache.sling.api.resource.ResourceResolver; import org.apache.sling.commons.scheduler.JobContext; import org.apache.sling.commons.scheduler.ScheduleOptions; import org.apache.sling.commons.scheduler.Scheduler; import org.apache.sling.event.impl.jobs.JobManagerImpl; import org.apache.sling.event.impl.jobs.Utility; import org.apache.sling.event.impl.jobs.config.ConfigurationChangeListener; import org.apache.sling.event.impl.jobs.config.JobManagerConfiguration; import org.apache.sling.event.impl.jobs.config.TopologyCapabilities; import org.apache.sling.event.impl.support.ResourceHelper; import org.apache.sling.event.impl.support.ScheduleInfoImpl; import org.apache.sling.event.jobs.JobBuilder; import org.apache.sling.event.jobs.ScheduleInfo; import org.apache.sling.event.jobs.ScheduleInfo.ScheduleType; import org.apache.sling.event.jobs.ScheduledJobInfo; import org.osgi.service.event.Event; import org.osgi.service.event.EventHandler; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * The scheduler for managing scheduled jobs. * * This is not a component by itself, it's directly created from the job manager. * The job manager is also registering itself as an event handler and forwards * the events to this service. */ public class JobSchedulerImpl implements EventHandler, ConfigurationChangeListener, org.apache.sling.commons.scheduler.Job { private static final String PROPERTY_READ_JOB = "properties"; private static final String PROPERTY_SCHEDULE_INDEX = "index"; /** Default logger */ private final Logger logger = LoggerFactory.getLogger(this.getClass()); /** Is this active? */ private final AtomicBoolean active = new AtomicBoolean(false); /** Central job handling configuration. */ private final JobManagerConfiguration configuration; /** Scheduler service. */ private final Scheduler scheduler; /** Job manager. */ private final JobManagerImpl jobManager; /** Scheduled job handler. */ private final ScheduledJobHandler scheduledJobHandler; /** All scheduled jobs, by scheduler name */ private final Map<String, ScheduledJobInfoImpl> scheduledJobs = new HashMap<String, ScheduledJobInfoImpl>(); /** * Create the scheduler * @param configuration Central job manager configuration * @param scheduler The scheduler service * @param jobManager The job manager */ public JobSchedulerImpl(final JobManagerConfiguration configuration, final Scheduler scheduler, final JobManagerImpl jobManager) { this.configuration = configuration; this.scheduler = scheduler; this.jobManager = jobManager; this.configuration.addListener(this); this.scheduledJobHandler = new ScheduledJobHandler(configuration, this); } /** * Deactivate this component. */ public void deactivate() { this.configuration.removeListener(this); this.scheduledJobHandler.deactivate(); if ( this.active.compareAndSet(true, false) ) { this.stopScheduling(); } synchronized ( this.scheduledJobs ) { this.scheduledJobs.clear(); } } /** * @see org.apache.sling.event.impl.jobs.config.ConfigurationChangeListener#configurationChanged(boolean) */ @Override public void configurationChanged(final boolean processingActive) { // scheduling is only active if // - processing is active and // - configuration is still available and active // - and current instance is leader final boolean schedulingActive; if ( processingActive ) { final TopologyCapabilities caps = this.configuration.getTopologyCapabilities(); if ( caps != null && caps.isActive() ) { schedulingActive = caps.isLeader(); } else { schedulingActive = false; } } else { schedulingActive = false; } // switch activation based on current state and new state if ( schedulingActive ) { // activate if inactive if ( this.active.compareAndSet(false, true) ) { this.startScheduling(); } } else { // deactivate if active if ( this.active.compareAndSet(true, false) ) { this.stopScheduling(); } } } /** * Start all scheduled jobs */ private void startScheduling() { synchronized ( this.scheduledJobs ) { for(final ScheduledJobInfo info : this.scheduledJobs.values()) { this.startScheduledJob(((ScheduledJobInfoImpl)info)); } } } /** * Stop all scheduled jobs. */ private void stopScheduling() { synchronized ( this.scheduledJobs ) { for(final ScheduledJobInfo info : this.scheduledJobs.values()) { this.stopScheduledJob((ScheduledJobInfoImpl)info); } } } /** * Add a scheduled job */ public void scheduleJob(final ScheduledJobInfoImpl info) { synchronized ( this.scheduledJobs ) { this.scheduledJobs.put(info.getName(), info); this.startScheduledJob(info); } } /** * Unschedule a scheduled job */ public void unscheduleJob(final ScheduledJobInfoImpl info) { synchronized ( this.scheduledJobs ) { if ( this.scheduledJobs.remove(info.getName()) != null ) { this.stopScheduledJob(info); } } } /** * Remove a scheduled job */ public void removeJob(final ScheduledJobInfoImpl info) { this.unscheduleJob(info); this.scheduledJobHandler.remove(info); } /** * Start a scheduled job * @param info The scheduling info */ private void startScheduledJob(final ScheduledJobInfoImpl info) { if ( this.active.get() ) { if ( !info.isSuspended() ) { this.configuration.getAuditLogger().debug("SCHEDULED OK name={}, topic={}, properties={} : {}", new Object[] {info.getName(), info.getJobTopic(), info.getJobProperties()}, info.getSchedules()); int index = 0; for(final ScheduleInfo si : info.getSchedules()) { final String name = info.getSchedulerJobId() + "-" + String.valueOf(index); ScheduleOptions options = null; switch ( si.getType() ) { case DAILY: case WEEKLY: case HOURLY: case MONTHLY: case YEARLY: case CRON: options = this.scheduler.EXPR(((ScheduleInfoImpl)si).getCronExpression()); break; case DATE: options = this.scheduler.AT(((ScheduleInfoImpl)si).getNextScheduledExecution()); break; } // Create configuration for scheduled job final Map<String, Serializable> config = new HashMap<String, Serializable>(); config.put(PROPERTY_READ_JOB, info); config.put(PROPERTY_SCHEDULE_INDEX, index); this.scheduler.schedule(this, options.name(name).config(config).canRunConcurrently(false)); index++; } } else { this.configuration.getAuditLogger().debug("SCHEDULED SUSPENDED name={}, topic={}, properties={} : {}", new Object[] {info.getName(), info.getJobTopic(), info.getJobProperties(), info.getSchedules()}); } } } /** * Stop a scheduled job * @param info The scheduling info */ private void stopScheduledJob(final ScheduledJobInfoImpl info) { final Scheduler localScheduler = this.scheduler; if ( localScheduler != null ) { this.configuration.getAuditLogger().debug("SCHEDULED STOP name={}, topic={}, properties={} : {}", new Object[] {info.getName(), info.getJobTopic(), info.getJobProperties(), info.getSchedules()}); for(int index = 0; index<info.getSchedules().size(); index++) { final String name = info.getSchedulerJobId() + "-" + String.valueOf(index); localScheduler.unschedule(name); } } } /** * @see org.apache.sling.commons.scheduler.Job#execute(org.apache.sling.commons.scheduler.JobContext) */ @Override public void execute(final JobContext context) { if ( !active.get() ) { // not active anymore, simply return return; } final ScheduledJobInfoImpl info = (ScheduledJobInfoImpl) context.getConfiguration().get(PROPERTY_READ_JOB); if ( info.isSuspended() ) { return; } this.jobManager.addJob(info.getJobTopic(), info.getJobProperties()); final int index = (Integer)context.getConfiguration().get(PROPERTY_SCHEDULE_INDEX); final Iterator<ScheduleInfo> iter = info.getSchedules().iterator(); ScheduleInfo si = iter.next(); for(int i=0; i<index; i++) { si = iter.next(); } // if scheduled once (DATE), remove from schedule if ( si.getType() == ScheduleType.DATE ) { if ( index == 0 && info.getSchedules().size() == 1 ) { // remove this.scheduledJobHandler.remove(info); } else { // update schedule list final List<ScheduleInfo> infos = new ArrayList<ScheduleInfo>(); for(final ScheduleInfo i : info.getSchedules() ) { if ( i != si ) { // no need to use equals infos.add(i); } } info.update(infos); this.scheduledJobHandler.updateSchedule(info.getName(), infos); } } } /** * @see org.osgi.service.event.EventHandler#handleEvent(org.osgi.service.event.Event) */ @Override public void handleEvent(final Event event) { if ( ResourceHelper.BUNDLE_EVENT_STARTED.equals(event.getTopic()) || ResourceHelper.BUNDLE_EVENT_UPDATED.equals(event.getTopic()) ) { this.scheduledJobHandler.bundleEvent(); } else { // resource event final String path = (String)event.getProperty(SlingConstants.PROPERTY_PATH); if ( path != null && path.startsWith(this.configuration.getScheduledJobsPath(true)) ) { if ( SlingConstants.TOPIC_RESOURCE_REMOVED.equals(event.getTopic()) ) { // removal logger.debug("Remove scheduled job {}, event {}", path, event.getTopic()); this.scheduledJobHandler.handleRemove(path); } else { // add or update logger.debug("Add or update scheduled job {}, event {}", path, event.getTopic()); this.scheduledJobHandler.handleAddUpdate(path); } } } } /** * Helper method which just logs the exception in debug mode. * @param e */ private void ignoreException(final Exception e) { if ( this.logger.isDebugEnabled() ) { this.logger.debug("Ignored exception " + e.getMessage(), e); } } /** * Create a schedule builder for a currently scheduled job */ public JobBuilder.ScheduleBuilder createJobBuilder(final ScheduledJobInfoImpl info) { final JobBuilder.ScheduleBuilder sb = new JobScheduleBuilderImpl(info.getJobTopic(), info.getJobProperties(), info.getName(), this); return (info.isSuspended() ? sb.suspend() : sb); } private enum Operation { LESS, LESS_OR_EQUALS, EQUALS, GREATER_OR_EQUALS, GREATER } /** * Check if the job matches the template */ private boolean match(final ScheduledJobInfoImpl job, final Map<String, Object> template) { if ( template != null ) { for(final Map.Entry<String, Object> current : template.entrySet()) { final String key = current.getKey(); final char firstChar = key.length() > 0 ? key.charAt(0) : 0; final String propName; final Operation op; if ( firstChar == '=' ) { propName = key.substring(1); op = Operation.EQUALS; } else if ( firstChar == '<' ) { final char secondChar = key.length() > 1 ? key.charAt(1) : 0; if ( secondChar == '=' ) { op = Operation.LESS_OR_EQUALS; propName = key.substring(2); } else { op = Operation.LESS; propName = key.substring(1); } } else if ( firstChar == '>' ) { final char secondChar = key.length() > 1 ? key.charAt(1) : 0; if ( secondChar == '=' ) { op = Operation.GREATER_OR_EQUALS; propName = key.substring(2); } else { op = Operation.GREATER; propName = key.substring(1); } } else { propName = key; op = Operation.EQUALS; } final Object value = current.getValue(); if ( op == Operation.EQUALS ) { if ( !value.equals(job.getJobProperties().get(propName)) ) { return false; } } else { if ( value instanceof Comparable ) { @SuppressWarnings({ "unchecked", "rawtypes" }) final int result = ((Comparable)value).compareTo(job.getJobProperties().get(propName)); if ( op == Operation.LESS && result > -1 ) { return false; } else if ( op == Operation.LESS_OR_EQUALS && result > 0 ) { return false; } else if ( op == Operation.GREATER_OR_EQUALS && result < 0 ) { return false; } else if ( op == Operation.GREATER && result < 1 ) { return false; } } else { // if the value is not comparable we simply don't match return false; } } } } return true; } /** * Get all scheduled jobs */ public Collection<ScheduledJobInfo> getScheduledJobs(final String topic, final long limit, final Map<String, Object>... templates) { final List<ScheduledJobInfo> jobs = new ArrayList<ScheduledJobInfo>(); long count = 0; synchronized ( this.scheduledJobs ) { for(final ScheduledJobInfoImpl job : this.scheduledJobs.values() ) { boolean add = true; if ( topic != null && !topic.equals(job.getJobTopic()) ) { add = false; } if ( add && templates != null && templates.length != 0 ) { add = false; for (Map<String,Object> template : templates) { add = this.match(job, template); if ( add ) { break; } } } if ( add ) { jobs.add(job); count++; if ( limit > 0 && count == limit ) { break; } } } } return jobs; } /** * Change the suspended flag for a scheduled job * @param info The schedule info * @param flag The corresponding flag */ public void setSuspended(final ScheduledJobInfoImpl info, final boolean flag) { final ResourceResolver resolver = configuration.createResourceResolver(); try { final StringBuilder sb = new StringBuilder(this.configuration.getScheduledJobsPath(true)); sb.append(ResourceHelper.filterName(info.getName())); final String path = sb.toString(); final Resource eventResource = resolver.getResource(path); if ( eventResource != null ) { final ModifiableValueMap mvm = eventResource.adaptTo(ModifiableValueMap.class); if ( flag ) { mvm.put(ResourceHelper.PROPERTY_SCHEDULE_SUSPENDED, Boolean.TRUE); } else { mvm.remove(ResourceHelper.PROPERTY_SCHEDULE_SUSPENDED); } resolver.commit(); } if ( flag ) { this.stopScheduledJob(info); } else { this.startScheduledJob(info); } } catch (final PersistenceException pe) { // we ignore the exception if removing fails ignoreException(pe); } finally { resolver.close(); } } /** * Add a scheduled job * @param topic The job topic * @param properties The job properties * @param scheduleName The schedule name * @param isSuspended Whether it is suspended * @param scheduleInfos The scheduling information * @param errors Optional list to contain potential errors * @return A new job info or {@code null} */ public ScheduledJobInfo addScheduledJob(final String topic, final Map<String, Object> properties, final String scheduleName, final boolean isSuspended, final List<ScheduleInfoImpl> scheduleInfos, final List<String> errors) { final List<String> msgs = new ArrayList<String>(); if ( scheduleName == null || scheduleName.length() == 0 ) { msgs.add("Schedule name not specified"); } final String errorMessage = Utility.checkJob(topic, properties); if ( errorMessage != null ) { msgs.add(errorMessage); } if ( scheduleInfos.size() == 0 ) { msgs.add("No schedule defined for " + scheduleName); } for(final ScheduleInfoImpl info : scheduleInfos) { info.check(msgs); } if ( msgs.size() == 0 ) { try { final ScheduledJobInfo info = this.scheduledJobHandler.addOrUpdateJob(topic, properties, scheduleName, isSuspended, scheduleInfos); if ( info != null ) { return info; } msgs.add("Unable to persist scheduled job."); } catch ( final PersistenceException pe) { msgs.add("Unable to persist scheduled job: " + scheduleName); logger.warn("Unable to persist scheduled job", pe); } } else { for(final String msg : msgs) { logger.warn(msg); } } if ( errors != null ) { errors.addAll(msgs); } return null; } public void maintenance() { this.scheduledJobHandler.maintenance(); } }
bundles/extensions/event/src/main/java/org/apache/sling/event/impl/jobs/scheduling/JobSchedulerImpl.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.sling.event.impl.jobs.scheduling; import java.io.Serializable; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.concurrent.atomic.AtomicBoolean; import org.apache.sling.api.SlingConstants; import org.apache.sling.api.resource.ModifiableValueMap; import org.apache.sling.api.resource.PersistenceException; import org.apache.sling.api.resource.Resource; import org.apache.sling.api.resource.ResourceResolver; import org.apache.sling.commons.scheduler.JobContext; import org.apache.sling.commons.scheduler.ScheduleOptions; import org.apache.sling.commons.scheduler.Scheduler; import org.apache.sling.event.impl.jobs.JobManagerImpl; import org.apache.sling.event.impl.jobs.Utility; import org.apache.sling.event.impl.jobs.config.ConfigurationChangeListener; import org.apache.sling.event.impl.jobs.config.JobManagerConfiguration; import org.apache.sling.event.impl.jobs.config.TopologyCapabilities; import org.apache.sling.event.impl.support.ResourceHelper; import org.apache.sling.event.impl.support.ScheduleInfoImpl; import org.apache.sling.event.jobs.JobBuilder; import org.apache.sling.event.jobs.ScheduleInfo; import org.apache.sling.event.jobs.ScheduleInfo.ScheduleType; import org.apache.sling.event.jobs.ScheduledJobInfo; import org.osgi.service.event.Event; import org.osgi.service.event.EventHandler; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * The scheduler for managing scheduled jobs. * * This is not a component by itself, it's directly created from the job manager. * The job manager is also registering itself as an event handler and forwards * the events to this service. */ public class JobSchedulerImpl implements EventHandler, ConfigurationChangeListener, org.apache.sling.commons.scheduler.Job { private static final String PROPERTY_READ_JOB = "properties"; private static final String PROPERTY_SCHEDULE_INDEX = "index"; /** Default logger */ private final Logger logger = LoggerFactory.getLogger(this.getClass()); /** Is this active? */ private final AtomicBoolean active = new AtomicBoolean(false); /** Central job handling configuration. */ private final JobManagerConfiguration configuration; /** Scheduler service. */ private final Scheduler scheduler; /** Job manager. */ private final JobManagerImpl jobManager; /** Scheduled job handler. */ private final ScheduledJobHandler scheduledJobHandler; /** All scheduled jobs, by scheduler name */ private final Map<String, ScheduledJobInfoImpl> scheduledJobs = new HashMap<String, ScheduledJobInfoImpl>(); /** * Create the scheduler * @param configuration Central job manager configuration * @param scheduler The scheduler service * @param jobManager The job manager */ public JobSchedulerImpl(final JobManagerConfiguration configuration, final Scheduler scheduler, final JobManagerImpl jobManager) { this.configuration = configuration; this.scheduler = scheduler; this.jobManager = jobManager; this.configuration.addListener(this); this.scheduledJobHandler = new ScheduledJobHandler(configuration, this); } /** * Deactivate this component. */ public void deactivate() { this.configuration.removeListener(this); this.scheduledJobHandler.deactivate(); if ( this.active.compareAndSet(true, false) ) { this.stopScheduling(); } synchronized ( this.scheduledJobs ) { this.scheduledJobs.clear(); } } /** * @see org.apache.sling.event.impl.jobs.config.ConfigurationChangeListener#configurationChanged(boolean) */ @Override public void configurationChanged(final boolean processingActive) { // scheduling is only active if // - processing is active and // - configuration is still available and active // - and current instance is leader final boolean schedulingActive; if ( processingActive ) { final TopologyCapabilities caps = this.configuration.getTopologyCapabilities(); if ( caps != null && caps.isActive() ) { schedulingActive = caps.isLeader(); } else { schedulingActive = false; } } else { schedulingActive = false; } // switch activation based on current state and new state if ( schedulingActive ) { // activate if inactive if ( this.active.compareAndSet(false, true) ) { this.startScheduling(); } } else { // deactivate if active if ( this.active.compareAndSet(true, false) ) { this.stopScheduling(); } } } /** * Start all scheduled jobs */ private void startScheduling() { synchronized ( this.scheduledJobs ) { for(final ScheduledJobInfo info : this.scheduledJobs.values()) { this.startScheduledJob(((ScheduledJobInfoImpl)info)); } } } /** * Stop all scheduled jobs. */ private void stopScheduling() { synchronized ( this.scheduledJobs ) { for(final ScheduledJobInfo info : this.scheduledJobs.values()) { this.stopScheduledJob((ScheduledJobInfoImpl)info); } } } /** * Add a scheduled job */ public void scheduleJob(final ScheduledJobInfoImpl info) { synchronized ( this.scheduledJobs ) { this.scheduledJobs.put(info.getName(), info); this.startScheduledJob(info); } } /** * Unschedule a scheduled job */ public void unscheduleJob(final ScheduledJobInfoImpl info) { synchronized ( this.scheduledJobs ) { if ( this.scheduledJobs.remove(info.getName()) != null ) { this.stopScheduledJob(info); } } } /** * Remove a scheduled job */ public void removeJob(final ScheduledJobInfoImpl info) { this.unscheduleJob(info); this.scheduledJobHandler.remove(info); } /** * Start a scheduled job * @param info The scheduling info */ private void startScheduledJob(final ScheduledJobInfoImpl info) { if ( this.active.get() ) { if ( !info.isSuspended() ) { this.configuration.getAuditLogger().debug("SCHEDULED OK name={}, topic={}, properties={} : {}", new Object[] {info.getName(), info.getJobTopic(), info.getJobProperties()}, info.getSchedules()); int index = 0; for(final ScheduleInfo si : info.getSchedules()) { final String name = info.getSchedulerJobId() + "-" + String.valueOf(index); ScheduleOptions options = null; switch ( si.getType() ) { case DAILY: case WEEKLY: case HOURLY: case MONTHLY: case YEARLY: case CRON: options = this.scheduler.EXPR(((ScheduleInfoImpl)si).getCronExpression()); break; case DATE: options = this.scheduler.AT(((ScheduleInfoImpl)si).getNextScheduledExecution()); break; } // Create configuration for scheduled job final Map<String, Serializable> config = new HashMap<String, Serializable>(); config.put(PROPERTY_READ_JOB, info); config.put(PROPERTY_SCHEDULE_INDEX, index); this.scheduler.schedule(this, options.name(name).config(config).canRunConcurrently(false)); index++; } } else { this.configuration.getAuditLogger().debug("SCHEDULED SUSPENDED name={}, topic={}, properties={} : {}", new Object[] {info.getName(), info.getJobTopic(), info.getJobProperties(), info.getSchedules()}); } } } /** * Stop a scheduled job * @param info The scheduling info */ private void stopScheduledJob(final ScheduledJobInfoImpl info) { final Scheduler localScheduler = this.scheduler; if ( localScheduler != null ) { this.configuration.getAuditLogger().debug("SCHEDULED STOP name={}, topic={}, properties={} : {}", new Object[] {info.getName(), info.getJobTopic(), info.getJobProperties(), info.getSchedules()}); for(int index = 0; index<info.getSchedules().size(); index++) { final String name = info.getSchedulerJobId() + "-" + String.valueOf(index); localScheduler.unschedule(name); } } } /** * @see org.apache.sling.commons.scheduler.Job#execute(org.apache.sling.commons.scheduler.JobContext) */ @Override public void execute(final JobContext context) { final ScheduledJobInfoImpl info = (ScheduledJobInfoImpl) context.getConfiguration().get(PROPERTY_READ_JOB); if ( info.isSuspended() ) { return; } this.jobManager.addJob(info.getJobTopic(), info.getJobProperties()); final int index = (Integer)context.getConfiguration().get(PROPERTY_SCHEDULE_INDEX); final Iterator<ScheduleInfo> iter = info.getSchedules().iterator(); ScheduleInfo si = iter.next(); for(int i=0; i<index; i++) { si = iter.next(); } // if scheduled once (DATE), remove from schedule if ( si.getType() == ScheduleType.DATE ) { if ( index == 0 && info.getSchedules().size() == 1 ) { // remove this.scheduledJobHandler.remove(info); } else { // update schedule list final List<ScheduleInfo> infos = new ArrayList<ScheduleInfo>(); for(final ScheduleInfo i : info.getSchedules() ) { if ( i != si ) { // no need to use equals infos.add(i); } } info.update(infos); this.scheduledJobHandler.updateSchedule(info.getName(), infos); } } } /** * @see org.osgi.service.event.EventHandler#handleEvent(org.osgi.service.event.Event) */ @Override public void handleEvent(final Event event) { if ( ResourceHelper.BUNDLE_EVENT_STARTED.equals(event.getTopic()) || ResourceHelper.BUNDLE_EVENT_UPDATED.equals(event.getTopic()) ) { this.scheduledJobHandler.bundleEvent(); } else { // resource event final String path = (String)event.getProperty(SlingConstants.PROPERTY_PATH); if ( path != null && path.startsWith(this.configuration.getScheduledJobsPath(true)) ) { if ( SlingConstants.TOPIC_RESOURCE_REMOVED.equals(event.getTopic()) ) { // removal logger.debug("Remove scheduled job {}, event {}", path, event.getTopic()); this.scheduledJobHandler.handleRemove(path); } else { // add or update logger.debug("Add or update scheduled job {}, event {}", path, event.getTopic()); this.scheduledJobHandler.handleAddUpdate(path); } } } } /** * Helper method which just logs the exception in debug mode. * @param e */ private void ignoreException(final Exception e) { if ( this.logger.isDebugEnabled() ) { this.logger.debug("Ignored exception " + e.getMessage(), e); } } /** * Create a schedule builder for a currently scheduled job */ public JobBuilder.ScheduleBuilder createJobBuilder(final ScheduledJobInfoImpl info) { final JobBuilder.ScheduleBuilder sb = new JobScheduleBuilderImpl(info.getJobTopic(), info.getJobProperties(), info.getName(), this); return (info.isSuspended() ? sb.suspend() : sb); } private enum Operation { LESS, LESS_OR_EQUALS, EQUALS, GREATER_OR_EQUALS, GREATER } /** * Check if the job matches the template */ private boolean match(final ScheduledJobInfoImpl job, final Map<String, Object> template) { if ( template != null ) { for(final Map.Entry<String, Object> current : template.entrySet()) { final String key = current.getKey(); final char firstChar = key.length() > 0 ? key.charAt(0) : 0; final String propName; final Operation op; if ( firstChar == '=' ) { propName = key.substring(1); op = Operation.EQUALS; } else if ( firstChar == '<' ) { final char secondChar = key.length() > 1 ? key.charAt(1) : 0; if ( secondChar == '=' ) { op = Operation.LESS_OR_EQUALS; propName = key.substring(2); } else { op = Operation.LESS; propName = key.substring(1); } } else if ( firstChar == '>' ) { final char secondChar = key.length() > 1 ? key.charAt(1) : 0; if ( secondChar == '=' ) { op = Operation.GREATER_OR_EQUALS; propName = key.substring(2); } else { op = Operation.GREATER; propName = key.substring(1); } } else { propName = key; op = Operation.EQUALS; } final Object value = current.getValue(); if ( op == Operation.EQUALS ) { if ( !value.equals(job.getJobProperties().get(propName)) ) { return false; } } else { if ( value instanceof Comparable ) { @SuppressWarnings({ "unchecked", "rawtypes" }) final int result = ((Comparable)value).compareTo(job.getJobProperties().get(propName)); if ( op == Operation.LESS && result > -1 ) { return false; } else if ( op == Operation.LESS_OR_EQUALS && result > 0 ) { return false; } else if ( op == Operation.GREATER_OR_EQUALS && result < 0 ) { return false; } else if ( op == Operation.GREATER && result < 1 ) { return false; } } else { // if the value is not comparable we simply don't match return false; } } } } return true; } /** * Get all scheduled jobs */ public Collection<ScheduledJobInfo> getScheduledJobs(final String topic, final long limit, final Map<String, Object>... templates) { final List<ScheduledJobInfo> jobs = new ArrayList<ScheduledJobInfo>(); long count = 0; synchronized ( this.scheduledJobs ) { for(final ScheduledJobInfoImpl job : this.scheduledJobs.values() ) { boolean add = true; if ( topic != null && !topic.equals(job.getJobTopic()) ) { add = false; } if ( add && templates != null && templates.length != 0 ) { add = false; for (Map<String,Object> template : templates) { add = this.match(job, template); if ( add ) { break; } } } if ( add ) { jobs.add(job); count++; if ( limit > 0 && count == limit ) { break; } } } } return jobs; } /** * Change the suspended flag for a scheduled job * @param info The schedule info * @param flag The corresponding flag */ public void setSuspended(final ScheduledJobInfoImpl info, final boolean flag) { final ResourceResolver resolver = configuration.createResourceResolver(); try { final StringBuilder sb = new StringBuilder(this.configuration.getScheduledJobsPath(true)); sb.append(ResourceHelper.filterName(info.getName())); final String path = sb.toString(); final Resource eventResource = resolver.getResource(path); if ( eventResource != null ) { final ModifiableValueMap mvm = eventResource.adaptTo(ModifiableValueMap.class); if ( flag ) { mvm.put(ResourceHelper.PROPERTY_SCHEDULE_SUSPENDED, Boolean.TRUE); } else { mvm.remove(ResourceHelper.PROPERTY_SCHEDULE_SUSPENDED); } resolver.commit(); } if ( flag ) { this.stopScheduledJob(info); } else { this.startScheduledJob(info); } } catch (final PersistenceException pe) { // we ignore the exception if removing fails ignoreException(pe); } finally { resolver.close(); } } /** * Add a scheduled job * @param topic The job topic * @param properties The job properties * @param scheduleName The schedule name * @param isSuspended Whether it is suspended * @param scheduleInfos The scheduling information * @param errors Optional list to contain potential errors * @return A new job info or {@code null} */ public ScheduledJobInfo addScheduledJob(final String topic, final Map<String, Object> properties, final String scheduleName, final boolean isSuspended, final List<ScheduleInfoImpl> scheduleInfos, final List<String> errors) { final List<String> msgs = new ArrayList<String>(); if ( scheduleName == null || scheduleName.length() == 0 ) { msgs.add("Schedule name not specified"); } final String errorMessage = Utility.checkJob(topic, properties); if ( errorMessage != null ) { msgs.add(errorMessage); } if ( scheduleInfos.size() == 0 ) { msgs.add("No schedule defined for " + scheduleName); } for(final ScheduleInfoImpl info : scheduleInfos) { info.check(msgs); } if ( msgs.size() == 0 ) { try { final ScheduledJobInfo info = this.scheduledJobHandler.addOrUpdateJob(topic, properties, scheduleName, isSuspended, scheduleInfos); if ( info != null ) { return info; } msgs.add("Unable to persist scheduled job."); } catch ( final PersistenceException pe) { msgs.add("Unable to persist scheduled job: " + scheduleName); logger.warn("Unable to persist scheduled job", pe); } } else { for(final String msg : msgs) { logger.warn(msg); } } if ( errors != null ) { errors.addAll(msgs); } return null; } public void maintenance() { this.scheduledJobHandler.maintenance(); } }
SLING-5805 : NPE in JobSchedulerImpl when shutting down instance git-svn-id: 6eed74fe9a15c8da84b9a8d7f2960c0406113ece@1750277 13f79535-47bb-0310-9956-ffa450edef68
bundles/extensions/event/src/main/java/org/apache/sling/event/impl/jobs/scheduling/JobSchedulerImpl.java
SLING-5805 : NPE in JobSchedulerImpl when shutting down instance
<ide><path>undles/extensions/event/src/main/java/org/apache/sling/event/impl/jobs/scheduling/JobSchedulerImpl.java <ide> */ <ide> @Override <ide> public void execute(final JobContext context) { <add> if ( !active.get() ) { <add> // not active anymore, simply return <add> return; <add> } <ide> final ScheduledJobInfoImpl info = (ScheduledJobInfoImpl) context.getConfiguration().get(PROPERTY_READ_JOB); <ide> <ide> if ( info.isSuspended() ) {
Java
apache-2.0
e6bd701a9610cd028aee550a6ac3007e703684a5
0
jvasileff/ceylon-module-resolver,ceylon/ceylon-module-resolver,jvasileff/ceylon-module-resolver,alesj/ceylon-module-resolver,ceylon/ceylon-module-resolver,alesj/ceylon-module-resolver
package com.redhat.ceylon.cmr.ceylon; import java.io.File; import java.io.IOException; import java.net.URI; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.NavigableMap; import java.util.ResourceBundle; import com.redhat.ceylon.cmr.api.ArtifactContext; import com.redhat.ceylon.cmr.api.ArtifactResult; import com.redhat.ceylon.cmr.api.ModuleQuery; import com.redhat.ceylon.cmr.api.ModuleVersionDetails; import com.redhat.ceylon.cmr.api.ModuleVersionQuery; import com.redhat.ceylon.cmr.api.ModuleVersionResult; import com.redhat.ceylon.cmr.api.RepositoryManager; import com.redhat.ceylon.common.Messages; import com.redhat.ceylon.common.ModuleDescriptorReader; import com.redhat.ceylon.common.tool.CeylonBaseTool; import com.redhat.ceylon.common.tool.Description; import com.redhat.ceylon.common.tool.Option; import com.redhat.ceylon.common.tool.OptionArgument; import com.redhat.ceylon.common.tool.ServiceToolLoader; import com.redhat.ceylon.common.tool.StandardArgumentParsers; import com.redhat.ceylon.common.tool.Tool; import com.redhat.ceylon.common.tool.ToolFactory; import com.redhat.ceylon.common.tool.ToolLoader; import com.redhat.ceylon.common.tool.ToolModel; public abstract class RepoUsingTool extends CeylonBaseTool { protected List<URI> repo; protected String systemRepo; protected boolean offline; private RepositoryManager rm; private Appendable out = System.out; private Appendable error = System.err; private ResourceBundle bundle; private static final List<String> EMPTY_STRINGS = new ArrayList<String>(0); private static final List<URI> EMPTY_URIS = new ArrayList<URI>(0); public RepoUsingTool(ResourceBundle bundle) { this.bundle = bundle; } public List<String> getRepositoryAsStrings() { if (repo != null) { List<String> result = new ArrayList<String>(repo.size()); for (URI uri : repo) { result.add(uri.toString()); } return result; } else { return EMPTY_STRINGS; } } public void setRepositoryAsStrings(List<String> repo) throws Exception { if (repo != null) { List<URI> result = new ArrayList<URI>(repo.size()); for (String r : repo) { result.add(StandardArgumentParsers.URI_PARSER.parse(r, this)); } setRepository(result); } else { setRepository(EMPTY_URIS); } } @OptionArgument(longName="rep", argumentName="url") @Description("Specifies a module repository containing dependencies. Can be specified multiple times. " + "(default: `modules`, `~/.ceylon/repo`, http://modules.ceylon-lang.org)") public void setRepository(List<URI> repo) { this.repo = repo; } @OptionArgument(longName="sysrep", argumentName="url") @Description("Specifies the system repository containing essential modules. " + "(default: `$CEYLON_HOME/repo`)") public void setSystemRepository(String systemRepo) { this.systemRepo = systemRepo; } @Option(longName="offline") @Description("Enables offline mode that will prevent the module loader from connecting to remote repositories.") public void setOffline(boolean offline) { this.offline = offline; } public void setOut(Appendable out) { this.out = out; } protected synchronized RepositoryManager getRepositoryManager() { if (rm == null) { CeylonUtils.CeylonRepoManagerBuilder rmb = CeylonUtils.repoManager() .systemRepo(systemRepo) .userRepos(getRepositoryAsStrings()) .offline(offline); rm = rmb.buildManager(); } return rm; } protected Collection<ModuleVersionDetails> getModuleVersions(String name, String version, ModuleQuery.Type type, Integer binaryVersion) { return getModuleVersions(getRepositoryManager(), name, version, type, binaryVersion); } protected Collection<ModuleVersionDetails> getModuleVersions(RepositoryManager repoMgr, String name, String version, ModuleQuery.Type type, Integer binaryVersion) { ModuleVersionQuery query = new ModuleVersionQuery(name, version, type); if (binaryVersion != null) { query.setBinaryMajor(binaryVersion); } ModuleVersionResult result = repoMgr.completeVersions(query); NavigableMap<String, ModuleVersionDetails> versionMap = result.getVersions(); return versionMap.values(); } protected String checkModuleVersionsOrShowSuggestions(RepositoryManager repoMgr, String name, String version, ModuleQuery.Type type, Integer binaryVersion) throws IOException { return checkModuleVersionsOrShowSuggestions(repoMgr, name, version, type, binaryVersion, false); } protected String checkModuleVersionsOrShowSuggestions(RepositoryManager repoMgr, String name, String version, ModuleQuery.Type type, Integer binaryVersion, boolean allowCompilation) throws IOException { if ("default".equals(name) || version != null) { // If we have the default module or a version we first try it the quick way ArtifactContext ac = new ArtifactContext(name, version, type.getSuffixes()); ac.setFetchSingleArtifact(true); ac.setThrowErrorIfMissing(false); ArtifactResult result = repoMgr.getArtifactResult(ac); if (result != null) { return (result.version() != null) ? result.version() : ""; } if ("default".equals(name)) { errorMsg("module.not.found", name, repoMgr.getRepositoriesDisplayString()); return null; } } boolean suggested = false; Collection<ModuleVersionDetails> versions = getModuleVersions(repoMgr, name, version, type, binaryVersion); if (version != null) { // Here we either have a single version or none if (versions.isEmpty()) { if (allowCompilation) { Collection<ModuleVersionDetails> srcVersions = getVersionFromSource(name); if (!srcVersions.isEmpty() && version.equals(srcVersions.iterator().next().getVersion())) { // There seems to be source code that has the proper version // Let's see if we can compile it... if (runCompiler(repoMgr, name, type)) { // All okay it seems, let's use this version versions = srcVersions; } } } if (versions.isEmpty()) { // Maybe the user specified the wrong version? // Let's see if we can find any and suggest them versions = getModuleVersions(repoMgr, name, null, type, binaryVersion); suggested = true; } } } else { // Here we can have any number of versions, including none if ((versions.isEmpty() || onlyRemote(versions)) && allowCompilation) { // If there are no versions at all or only in remote repositories we // first check if there's local code we could compile before giving up Collection<ModuleVersionDetails> srcVersions = getVersionFromSource(name); if (!srcVersions.isEmpty()) { // There seems to be source code // Let's see if we can compile it... if (runCompiler(repoMgr, name, type)) { // All okay it seems, let's use this version versions = srcVersions; } } } } if (versions.isEmpty()) { errorMsg("module.not.found", name, repoMgr.getRepositoriesDisplayString()); return null; } if (versions.size() > 1 || suggested) { if (version == null) { errorMsg("missing.version", name, repoMgr.getRepositoriesDisplayString()); } else { errorMsg("version.not.found", version, name); } msg(error, "try.versions"); boolean first = true; for (ModuleVersionDetails mvd : versions) { if (!first) { append(error, ", "); } append(error, mvd.getVersion()); if (mvd.isRemote()) { append(error, " (*)"); } first = false; } newline(error); return null; } return versions.iterator().next().getVersion(); } private boolean onlyRemote(Collection<ModuleVersionDetails> versions) { for (ModuleVersionDetails version : versions) { if (!version.isRemote()) { return false; } } return true; } private Collection<ModuleVersionDetails> getVersionFromSource(String name) { Collection<ModuleVersionDetails> result = new ArrayList<ModuleVersionDetails>(); try { File srcDir = new File("source"); ModuleDescriptorReader mdr = new ModuleDescriptorReader(name, srcDir); String version = mdr.getModuleVersion(); if (version != null) { ModuleVersionDetails mvd = new ModuleVersionDetails(version); mvd.setLicense(mdr.getModuleLicense()); List<String> by = mdr.getModuleAuthors(); if (by != null) { mvd.getAuthors().addAll(by); } mvd.setRemote(false); mvd.setOrigin("Local source folder"); result.add(mvd); } } catch (Exception ex) { // Just continue as if nothing happened } return result; } private boolean runCompiler(RepositoryManager repoMgr, String name, ModuleQuery.Type type) { List<String> args = new ArrayList<String>(); if (systemRepo != null) { args.add("--sysrep"); args.add(systemRepo); } if (repo != null) { for (URI r : repo) { args.add("--rep"); args.add(r.toString()); } } if (offline) { args.add("--offline"); } args.add(name); ToolFactory pluginFactory = new ToolFactory(); ToolLoader pluginLoader = new ServiceToolLoader(Tool.class) { @Override public String getToolName(String className) { return camelCaseToDashes(className.replaceAll("^(.*\\.)?Ceylon(.*)Tool$", "$2")); } }; String toolName; if (type == ModuleQuery.Type.JVM) { toolName = "compile"; } else if (type == ModuleQuery.Type.JS) { toolName = "compile-js"; } else { throw new IllegalArgumentException("Unknown compile flags passed"); } ToolModel<Tool> model = pluginLoader.loadToolModel(toolName); Tool tool = pluginFactory.bindArguments(model, args); try { msg("compiling").newline(); tool.run(); // Make sure we can find the newly created module repoMgr.refresh(false); } catch (Exception e) { return false; } return true; } public RepoUsingTool errorMsg(String msgKey, Object...msgArgs) throws IOException { error.append(Messages.msg(bundle, msgKey, msgArgs)); error.append(System.lineSeparator()); return this; } public RepoUsingTool msg(Appendable out, String msgKey, Object...msgArgs) throws IOException { out.append(Messages.msg(bundle, msgKey, msgArgs)); return this; } public RepoUsingTool msg(String msgKey, Object...msgArgs) throws IOException { return msg(out, msgKey, msgArgs); } public RepoUsingTool append(Appendable out, Object s) throws IOException { out.append(String.valueOf(s)); return this; } public RepoUsingTool append(Object s) throws IOException { return append(out, s); } public RepoUsingTool newline(Appendable out) throws IOException { out.append(System.lineSeparator()); return this; } public RepoUsingTool newline() throws IOException { return newline(out); } }
ceylon/src/main/java/com/redhat/ceylon/cmr/ceylon/RepoUsingTool.java
package com.redhat.ceylon.cmr.ceylon; import java.io.File; import java.io.IOException; import java.net.URI; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.NavigableMap; import java.util.ResourceBundle; import com.redhat.ceylon.cmr.api.ArtifactContext; import com.redhat.ceylon.cmr.api.ArtifactResult; import com.redhat.ceylon.cmr.api.ModuleQuery; import com.redhat.ceylon.cmr.api.ModuleVersionDetails; import com.redhat.ceylon.cmr.api.ModuleVersionQuery; import com.redhat.ceylon.cmr.api.ModuleVersionResult; import com.redhat.ceylon.cmr.api.RepositoryManager; import com.redhat.ceylon.common.Messages; import com.redhat.ceylon.common.ModuleDescriptorReader; import com.redhat.ceylon.common.tool.Description; import com.redhat.ceylon.common.tool.Option; import com.redhat.ceylon.common.tool.OptionArgument; import com.redhat.ceylon.common.tool.ServiceToolLoader; import com.redhat.ceylon.common.tool.StandardArgumentParsers; import com.redhat.ceylon.common.tool.Tool; import com.redhat.ceylon.common.tool.ToolFactory; import com.redhat.ceylon.common.tool.ToolLoader; import com.redhat.ceylon.common.tool.ToolModel; public abstract class RepoUsingTool implements Tool { protected List<URI> repo; protected String systemRepo; protected boolean offline; private RepositoryManager rm; private Appendable out = System.out; private Appendable error = System.err; private ResourceBundle bundle; private static final List<String> EMPTY_STRINGS = new ArrayList<String>(0); private static final List<URI> EMPTY_URIS = new ArrayList<URI>(0); public RepoUsingTool(ResourceBundle bundle) { this.bundle = bundle; } public List<String> getRepositoryAsStrings() { if (repo != null) { List<String> result = new ArrayList<String>(repo.size()); for (URI uri : repo) { result.add(uri.toString()); } return result; } else { return EMPTY_STRINGS; } } public void setRepositoryAsStrings(List<String> repo) throws Exception { if (repo != null) { List<URI> result = new ArrayList<URI>(repo.size()); for (String r : repo) { result.add(StandardArgumentParsers.URI_PARSER.parse(r, this)); } setRepository(result); } else { setRepository(EMPTY_URIS); } } @OptionArgument(longName="rep", argumentName="url") @Description("Specifies a module repository containing dependencies. Can be specified multiple times. " + "(default: `modules`, `~/.ceylon/repo`, http://modules.ceylon-lang.org)") public void setRepository(List<URI> repo) { this.repo = repo; } @OptionArgument(longName="sysrep", argumentName="url") @Description("Specifies the system repository containing essential modules. " + "(default: `$CEYLON_HOME/repo`)") public void setSystemRepository(String systemRepo) { this.systemRepo = systemRepo; } @Option(longName="offline") @Description("Enables offline mode that will prevent the module loader from connecting to remote repositories.") public void setOffline(boolean offline) { this.offline = offline; } public void setOut(Appendable out) { this.out = out; } protected synchronized RepositoryManager getRepositoryManager() { if (rm == null) { CeylonUtils.CeylonRepoManagerBuilder rmb = CeylonUtils.repoManager() .systemRepo(systemRepo) .userRepos(getRepositoryAsStrings()) .offline(offline); rm = rmb.buildManager(); } return rm; } protected Collection<ModuleVersionDetails> getModuleVersions(String name, String version, ModuleQuery.Type type, Integer binaryVersion) { return getModuleVersions(getRepositoryManager(), name, version, type, binaryVersion); } protected Collection<ModuleVersionDetails> getModuleVersions(RepositoryManager repoMgr, String name, String version, ModuleQuery.Type type, Integer binaryVersion) { ModuleVersionQuery query = new ModuleVersionQuery(name, version, type); if (binaryVersion != null) { query.setBinaryMajor(binaryVersion); } ModuleVersionResult result = repoMgr.completeVersions(query); NavigableMap<String, ModuleVersionDetails> versionMap = result.getVersions(); return versionMap.values(); } protected String checkModuleVersionsOrShowSuggestions(RepositoryManager repoMgr, String name, String version, ModuleQuery.Type type, Integer binaryVersion) throws IOException { return checkModuleVersionsOrShowSuggestions(repoMgr, name, version, type, binaryVersion, false); } protected String checkModuleVersionsOrShowSuggestions(RepositoryManager repoMgr, String name, String version, ModuleQuery.Type type, Integer binaryVersion, boolean allowCompilation) throws IOException { if ("default".equals(name) || version != null) { // If we have the default module or a version we first try it the quick way ArtifactContext ac = new ArtifactContext(name, version, type.getSuffixes()); ac.setFetchSingleArtifact(true); ac.setThrowErrorIfMissing(false); ArtifactResult result = repoMgr.getArtifactResult(ac); if (result != null) { return (result.version() != null) ? result.version() : ""; } if ("default".equals(name)) { errorMsg("module.not.found", name, repoMgr.getRepositoriesDisplayString()); return null; } } boolean suggested = false; Collection<ModuleVersionDetails> versions = getModuleVersions(repoMgr, name, version, type, binaryVersion); if (version != null) { // Here we either have a single version or none if (versions.isEmpty()) { if (allowCompilation) { Collection<ModuleVersionDetails> srcVersions = getVersionFromSource(name); if (!srcVersions.isEmpty() && version.equals(srcVersions.iterator().next().getVersion())) { // There seems to be source code that has the proper version // Let's see if we can compile it... if (runCompiler(repoMgr, name, type)) { // All okay it seems, let's use this version versions = srcVersions; } } } if (versions.isEmpty()) { // Maybe the user specified the wrong version? // Let's see if we can find any and suggest them versions = getModuleVersions(repoMgr, name, null, type, binaryVersion); suggested = true; } } } else { // Here we can have any number of versions, including none if ((versions.isEmpty() || onlyRemote(versions)) && allowCompilation) { // If there are no versions at all or only in remote repositories we // first check if there's local code we could compile before giving up Collection<ModuleVersionDetails> srcVersions = getVersionFromSource(name); if (!srcVersions.isEmpty()) { // There seems to be source code // Let's see if we can compile it... if (runCompiler(repoMgr, name, type)) { // All okay it seems, let's use this version versions = srcVersions; } } } } if (versions.isEmpty()) { errorMsg("module.not.found", name, repoMgr.getRepositoriesDisplayString()); return null; } if (versions.size() > 1 || suggested) { if (version == null) { errorMsg("missing.version", name, repoMgr.getRepositoriesDisplayString()); } else { errorMsg("version.not.found", version, name); } msg(error, "try.versions"); boolean first = true; for (ModuleVersionDetails mvd : versions) { if (!first) { append(error, ", "); } append(error, mvd.getVersion()); if (mvd.isRemote()) { append(error, " (*)"); } first = false; } newline(error); return null; } return versions.iterator().next().getVersion(); } private boolean onlyRemote(Collection<ModuleVersionDetails> versions) { for (ModuleVersionDetails version : versions) { if (!version.isRemote()) { return false; } } return true; } private Collection<ModuleVersionDetails> getVersionFromSource(String name) { Collection<ModuleVersionDetails> result = new ArrayList<ModuleVersionDetails>(); try { File srcDir = new File("source"); ModuleDescriptorReader mdr = new ModuleDescriptorReader(name, srcDir); String version = mdr.getModuleVersion(); if (version != null) { ModuleVersionDetails mvd = new ModuleVersionDetails(version); mvd.setLicense(mdr.getModuleLicense()); List<String> by = mdr.getModuleAuthors(); if (by != null) { mvd.getAuthors().addAll(by); } mvd.setRemote(false); mvd.setOrigin("Local source folder"); result.add(mvd); } } catch (Exception ex) { // Just continue as if nothing happened } return result; } private boolean runCompiler(RepositoryManager repoMgr, String name, ModuleQuery.Type type) { List<String> args = new ArrayList<String>(); if (systemRepo != null) { args.add("--sysrep"); args.add(systemRepo); } if (repo != null) { for (URI r : repo) { args.add("--rep"); args.add(r.toString()); } } if (offline) { args.add("--offline"); } args.add(name); ToolFactory pluginFactory = new ToolFactory(); ToolLoader pluginLoader = new ServiceToolLoader(Tool.class) { @Override public String getToolName(String className) { return camelCaseToDashes(className.replaceAll("^(.*\\.)?Ceylon(.*)Tool$", "$2")); } }; String toolName; if (type == ModuleQuery.Type.JVM) { toolName = "compile"; } else if (type == ModuleQuery.Type.JS) { toolName = "compile-js"; } else { throw new IllegalArgumentException("Unknown compile flags passed"); } ToolModel<Tool> model = pluginLoader.loadToolModel(toolName); Tool tool = pluginFactory.bindArguments(model, args); try { msg("compiling").newline(); tool.run(); // Make sure we can find the newly created module repoMgr.refresh(false); } catch (Exception e) { return false; } return true; } public RepoUsingTool errorMsg(String msgKey, Object...msgArgs) throws IOException { error.append(Messages.msg(bundle, msgKey, msgArgs)); error.append(System.lineSeparator()); return this; } public RepoUsingTool msg(Appendable out, String msgKey, Object...msgArgs) throws IOException { out.append(Messages.msg(bundle, msgKey, msgArgs)); return this; } public RepoUsingTool msg(String msgKey, Object...msgArgs) throws IOException { return msg(out, msgKey, msgArgs); } public RepoUsingTool append(Appendable out, Object s) throws IOException { out.append(String.valueOf(s)); return this; } public RepoUsingTool append(Object s) throws IOException { return append(out, s); } public RepoUsingTool newline(Appendable out) throws IOException { out.append(System.lineSeparator()); return this; } public RepoUsingTool newline() throws IOException { return newline(out); } }
Now using the ceylon tool base class for all repo using commands (ceylon/ceylon-runtime#26)
ceylon/src/main/java/com/redhat/ceylon/cmr/ceylon/RepoUsingTool.java
Now using the ceylon tool base class for all repo using commands (ceylon/ceylon-runtime#26)
<ide><path>eylon/src/main/java/com/redhat/ceylon/cmr/ceylon/RepoUsingTool.java <ide> import com.redhat.ceylon.cmr.api.RepositoryManager; <ide> import com.redhat.ceylon.common.Messages; <ide> import com.redhat.ceylon.common.ModuleDescriptorReader; <add>import com.redhat.ceylon.common.tool.CeylonBaseTool; <ide> import com.redhat.ceylon.common.tool.Description; <ide> import com.redhat.ceylon.common.tool.Option; <ide> import com.redhat.ceylon.common.tool.OptionArgument; <ide> import com.redhat.ceylon.common.tool.ToolLoader; <ide> import com.redhat.ceylon.common.tool.ToolModel; <ide> <del>public abstract class RepoUsingTool implements Tool { <add>public abstract class RepoUsingTool extends CeylonBaseTool { <ide> protected List<URI> repo; <ide> protected String systemRepo; <ide> protected boolean offline;
Java
epl-1.0
7af4c3bfde9a4db29dcc361621151695101ffe97
0
saeg/ba-dua
/** * Copyright (c) 2014, 2016 University of Sao Paulo and Contributors. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Roberto Araujo - initial API and implementation and/or initial documentation */ package br.usp.each.saeg.badua.cli; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.FilenameFilter; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.text.MessageFormat; import java.util.List; import java.util.concurrent.TimeUnit; import org.kohsuke.args4j.CmdLineException; import org.kohsuke.args4j.CmdLineParser; import br.usp.each.saeg.badua.agent.rt.internal.Offline; import br.usp.each.saeg.badua.core.instr.Instrumenter; import br.usp.each.saeg.commons.io.Files; import br.usp.each.saeg.commons.time.TimeWatch; public class Instrument { private final File src; private final File dest; private final Instrumenter instrumenter; public Instrument(final InstrumentOptions options) { this.src = options.getSource(); this.dest = options.getDestination(); instrumenter = new Instrumenter(Offline.class.getName()); } public int instrument() throws IOException { if (src.equals(dest)) { throw new IOException("'src' and 'dest' can't be the same folder"); } if (src.isFile()) { return instrument(src, new File(dest, src.getName())); } final List<File> files = Files.listRecursive(src, new FilenameFilter() { @Override public boolean accept(final File dir, final String name) { return new File(dir, name).isFile(); } }); int n = 0; for (final File file : files) { n += instrument(file, new File(dest, relativize(src, file))); } return n; } private int instrument(final File src, final File dest) throws IOException { final File destParent = dest.getParentFile(); if (!destParent.mkdirs() && !destParent.exists()) { throw new IOException("failed to create directory: " + destParent); } final InputStream input = new FileInputStream(src); try { final OutputStream output = new FileOutputStream(dest); try { return instrumenter.instrumentAll(input, output, src.getPath()); } finally { output.close(); } } catch (final IOException e) { dest.delete(); throw e; } finally { input.close(); } } private String relativize(final File a, final File b) { return a.toURI().relativize(b.toURI()).getPath(); } public static void main(final String[] args) { final InstrumentOptions options = new InstrumentOptions(); final CmdLineParser parser = new CmdLineParser(options); try { parser.parseArgument(args); } catch (final CmdLineException e) { System.err.println(e.getLocalizedMessage()); parser.printUsage(System.err); System.exit(1); } try { final TimeWatch tw = TimeWatch.start(); final int total = new Instrument(options).instrument(); final long seconds = tw.time(TimeUnit.SECONDS); System.out.println(MessageFormat.format( "{0} classes instrumented in {1} seconds", total, seconds)); } catch (final IOException e) { System.err.println("Failed: " + e.getLocalizedMessage()); System.exit(1); } } }
ba-dua-cli/src/main/java/br/usp/each/saeg/badua/cli/Instrument.java
/** * Copyright (c) 2014, 2016 University of Sao Paulo and Contributors. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Roberto Araujo - initial API and implementation and/or initial documentation */ package br.usp.each.saeg.badua.cli; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.FilenameFilter; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.text.MessageFormat; import java.util.List; import java.util.concurrent.TimeUnit; import org.kohsuke.args4j.CmdLineException; import org.kohsuke.args4j.CmdLineParser; import br.usp.each.saeg.badua.agent.rt.internal.Offline; import br.usp.each.saeg.badua.core.instr.Instrumenter; import br.usp.each.saeg.commons.io.Files; import br.usp.each.saeg.commons.time.TimeWatch; public class Instrument { private final File src; private final File dest; private final Instrumenter instrumenter; public Instrument(final InstrumentOptions options) { this.src = options.getSource(); this.dest = options.getDestination(); instrumenter = new Instrumenter(Offline.class.getName()); } public int instrument() throws IOException { if (src.isFile()) { return instrument(src, new File(dest, src.getName())); } final List<File> files = Files.listRecursive(src, new FilenameFilter() { @Override public boolean accept(final File dir, final String name) { return new File(dir, name).isFile(); } }); int n = 0; for (final File file : files) { n += instrument(file, new File(dest, relativize(src, file))); } return n; } private int instrument(final File src, final File dest) throws IOException { final File destParent = dest.getParentFile(); if (!destParent.mkdirs() && !destParent.exists()) { throw new IOException("failed to create directory: " + destParent); } final InputStream input = new FileInputStream(src); try { final OutputStream output = new FileOutputStream(dest); try { return instrumenter.instrumentAll(input, output, src.getPath()); } finally { output.close(); } } catch (final IOException e) { dest.delete(); throw e; } finally { input.close(); } } private String relativize(final File a, final File b) { return a.toURI().relativize(b.toURI()).getPath(); } public static void main(final String[] args) { final InstrumentOptions options = new InstrumentOptions(); final CmdLineParser parser = new CmdLineParser(options); try { parser.parseArgument(args); } catch (final CmdLineException e) { System.err.println(e.getLocalizedMessage()); parser.printUsage(System.err); System.exit(1); } try { final TimeWatch tw = TimeWatch.start(); final int total = new Instrument(options).instrument(); final long seconds = tw.time(TimeUnit.SECONDS); System.out.println(MessageFormat.format( "{0} classes instrumented in {1} seconds", total, seconds)); } catch (final IOException e) { System.err.println("Failed: " + e.getLocalizedMessage()); System.exit(1); } } }
Bugfix: files are truncated when 'instrument' src folder and dest folder are the same This bugfix prevent this error by throwing an exception
ba-dua-cli/src/main/java/br/usp/each/saeg/badua/cli/Instrument.java
Bugfix: files are truncated when 'instrument' src folder and dest folder are the same
<ide><path>a-dua-cli/src/main/java/br/usp/each/saeg/badua/cli/Instrument.java <ide> } <ide> <ide> public int instrument() throws IOException { <add> <add> if (src.equals(dest)) { <add> throw new IOException("'src' and 'dest' can't be the same folder"); <add> } <ide> <ide> if (src.isFile()) { <ide> return instrument(src, new File(dest, src.getName()));
Java
apache-2.0
0963dc68631d1dded80ee62fc7dd458c4b900879
0
Stratio/cassandra-lucene-index,Stratio/cassandra-lucene-index
/* * Copyright (C) 2014 Stratio (http://stratio.com) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.stratio.cassandra.lucene.testsAT.udt; import com.datastax.driver.core.exceptions.InvalidQueryException; import com.stratio.cassandra.lucene.testsAT.BaseIT; import com.stratio.cassandra.lucene.testsAT.util.CassandraUtils; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import java.util.Collections; import java.util.HashMap; import java.util.Map; import static com.stratio.cassandra.lucene.builder.Builder.*; import static com.stratio.cassandra.lucene.testsAT.util.CassandraUtils.builder; /** * @author Eduardo Alonso {@literal <[email protected]>} */ @RunWith(JUnit4.class) public class UDTPartialUpdateIT extends BaseIT { private static Map<String, String> insertData1 = Collections.unmodifiableMap( new HashMap<String, String>() { { put("id", "1"); put("address", "{ address:'fifth avenue', number:2}"); } }); private static Map<String, String> insertData2 = Collections.unmodifiableMap( new HashMap<String, String>() { { put("id", "2"); put("address", "{ address:'eliot ave', number:45}"); } }); private static Map<String, String> insertData3 = Collections.unmodifiableMap( new HashMap<String, String>() { { put("id", "3"); put("address", "{ address:'69th Ln', number:45}"); } }); private static Map<String, String> insertData4 = Collections.unmodifiableMap( new HashMap<String, String>() { { put("id", "4"); put("address", "{ address:'HoneyWell st', number:105}"); } }); @Test public void testNonFrozenPartialUpdate() { CassandraUtils utils = builder("udt_partial_update") .withTable("partial_updates_table") .withUDT("address_t", "postal_code", "bigint") .withUDT("address_t", "number", "bigint") .withUDT("address_t", "address", "text") .withColumn("id", "bigint") .withColumn("address", "address_t") .withMapper("address.address", stringMapper()) .withMapper("address.number", bigIntegerMapper()) .withMapper("address.postal_code", bigIntegerMapper()) .withIndexColumn("lucene") .withPartitionKey("id") .build() .createKeyspace() .createUDTs(); try { utils.createTable(); } catch (InvalidQueryException e) { if (e.getMessage().equals("Non-frozen User-Defined types are not supported, please use frozen<>")) { logger.info("Ignoring UDT partial update test because it isn't supported by current Cassandra version"); utils.dropKeyspace(); return; } } utils.createIndex() .insert(insertData1) .insert(insertData2) .insert(insertData3) .insert(insertData4); utils.filter(match("address.address", "fifth avenue")).refresh(true).checkUnorderedColumns("id", 1L) .filter(match("address.number", 2)).checkUnorderedColumns("id", 1L) .filter(match("address.postal_code", 10021)).check(0); utils.execute("UPDATE %s SET address.postal_code = 10021 WHERE id =1; ", utils.getQualifiedTable()); utils.filter(match("address.address", "fifth avenue")).refresh(true).checkUnorderedColumns("id", 1L) .filter(match("address.number", 2)).checkUnorderedColumns("id", 1L) .filter(match("address.postal_code", 10021)).checkUnorderedColumns("id", 1L); utils.filter(match("address.address", "eliot ave")).refresh(true).checkUnorderedColumns("id", 2L) .filter(match("address.number", 45)).checkUnorderedColumns("id", 2L, 3L) .filter(match("address.postal_code", 50004)).check(0) .filter(match("address.address", "69th Ln")).refresh(true).checkUnorderedColumns("id", 3L) .filter(match("address.number", 45)).checkUnorderedColumns("id", 2L, 3L) .filter(match("address.postal_code", 558)).check(0) .filter(match("address.address", "HoneyWell st")).refresh(true).checkUnorderedColumns("id", 4L) .filter(match("address.number", 105)).checkUnorderedColumns("id", 4L) .filter(match("address.postal_code", 10020)).check(0); utils.dropTable().dropKeyspace(); } }
testsAT/src/test/java/com/stratio/cassandra/lucene/testsAT/udt/UDTPartialUpdateIT.java
/* * Copyright (C) 2014 Stratio (http://stratio.com) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.stratio.cassandra.lucene.testsAT.udt; import com.datastax.driver.core.exceptions.InvalidQueryException; import com.stratio.cassandra.lucene.testsAT.BaseIT; import com.stratio.cassandra.lucene.testsAT.util.CassandraUtils; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import java.util.Collections; import java.util.HashMap; import java.util.Map; import static com.stratio.cassandra.lucene.builder.Builder.*; import static com.stratio.cassandra.lucene.testsAT.util.CassandraUtils.builder; /** * @author Eduardo Alonso {@literal <[email protected]>} */ @RunWith(JUnit4.class) public class UDTPartialUpdateIT extends BaseIT { private static Map<String, String> insertData1 = Collections.unmodifiableMap( new HashMap<String, String>() { { put("id", "1"); put("address", "{ address:'fifth avenue', number:2}"); } }); private static Map<String, String> insertData2 = Collections.unmodifiableMap( new HashMap<String, String>() { { put("id", "2"); put("address", "{ address:'eliot ave', number:45}"); } }); private static Map<String, String> insertData3 = Collections.unmodifiableMap( new HashMap<String, String>() { { put("id", "3"); put("address", "{ address:'69th Ln', number:45}"); } }); private static Map<String, String> insertData4 = Collections.unmodifiableMap( new HashMap<String, String>() { { put("id", "4"); put("address", "{ address:'HoneyWell st', number:105}"); } }); @Test public void testNonFrozenPartialUpdate() { CassandraUtils utils = builder("udt_partial_update") .withTable("partial_updates_table") .withUDT("address_t", "postal_code", "bigint") .withUDT("address_t", "number", "bigint") .withUDT("address_t", "address", "text") .withColumn("id", "bigint") .withColumn("address", "address_t") .withMapper("address.address", stringMapper()) .withMapper("address.number", bigIntegerMapper()) .withMapper("address.postal_code", bigIntegerMapper()) .withIndexColumn("lucene") .withPartitionKey("id") .build() .createKeyspace() .createUDTs(); try { utils.createTable(); } catch (InvalidQueryException e) { if (e.getMessage().equals("Non-frozen User-Defined types are not supported, please use frozen<>")) { logger.info("Ignoring UDT partial update test because it isn't supported by current Cassandra version"); return; } } utils.createIndex() .insert(insertData1) .insert(insertData2) .insert(insertData3) .insert(insertData4); utils.filter(match("address.address", "fifth avenue")).refresh(true).checkUnorderedColumns("id", 1L) .filter(match("address.number", 2)).checkUnorderedColumns("id", 1L) .filter(match("address.postal_code", 10021)).check(0); utils.execute("UPDATE %s SET address.postal_code = 10021 WHERE id =1; ", utils.getQualifiedTable()); utils.filter(match("address.address", "fifth avenue")).refresh(true).checkUnorderedColumns("id", 1L) .filter(match("address.number", 2)).checkUnorderedColumns("id", 1L) .filter(match("address.postal_code", 10021)).checkUnorderedColumns("id", 1L); utils.filter(match("address.address", "eliot ave")).refresh(true).checkUnorderedColumns("id", 2L) .filter(match("address.number", 45)).checkUnorderedColumns("id", 2L, 3L) .filter(match("address.postal_code", 50004)).check(0) .filter(match("address.address", "69th Ln")).refresh(true).checkUnorderedColumns("id", 3L) .filter(match("address.number", 45)).checkUnorderedColumns("id", 2L, 3L) .filter(match("address.postal_code", 558)).check(0) .filter(match("address.address", "HoneyWell st")).refresh(true).checkUnorderedColumns("id", 4L) .filter(match("address.number", 105)).checkUnorderedColumns("id", 4L) .filter(match("address.postal_code", 10020)).check(0); utils.dropTable().dropKeyspace(); } }
Fix partial UDT update test to cleanup resources after test success.
testsAT/src/test/java/com/stratio/cassandra/lucene/testsAT/udt/UDTPartialUpdateIT.java
Fix partial UDT update test to cleanup resources after test success.
<ide><path>estsAT/src/test/java/com/stratio/cassandra/lucene/testsAT/udt/UDTPartialUpdateIT.java <ide> } catch (InvalidQueryException e) { <ide> if (e.getMessage().equals("Non-frozen User-Defined types are not supported, please use frozen<>")) { <ide> logger.info("Ignoring UDT partial update test because it isn't supported by current Cassandra version"); <add> utils.dropKeyspace(); <ide> return; <ide> } <ide> }
JavaScript
agpl-3.0
f0f6772b01a916d9f38b297529dfbe975503a4a4
0
adunning/zotero,gracile-fr/zotero,gracile-fr/zotero,rmzelle/zotero,gracile-fr/zotero,fbennett/zotero,egh/zotero,LinuxMercedes/zotero,hoehnp/zotero,aurimasv/zotero,retorquere/zotero,LinuxMercedes/zotero,retorquere/zotero,hoehnp/zotero,sendecomp/zotero,egh/zotero,robamler/zotero,sendecomp/zotero,retorquere/zotero,rmzelle/zotero,egh/zotero,adunning/zotero,rmzelle/zotero,robamler/zotero,adunning/zotero,LinuxMercedes/zotero,hoehnp/zotero,robamler/zotero,sendecomp/zotero
/* ***** BEGIN LICENSE BLOCK ***** Copyright © 2009 Center for History and New Media George Mason University, Fairfax, Virginia, USA http://zotero.org This file is part of Zotero. Zotero is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Zotero is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with Zotero. If not, see <http://www.gnu.org/licenses/>. ***** END LICENSE BLOCK ***** */ //////////////////////////////////////////////////////////////////////////////// /// /// ItemTreeView /// -- handles the link between an individual tree and the data layer /// -- displays only items (no collections, no hierarchy) /// //////////////////////////////////////////////////////////////////////////////// /* * Constructor for the ItemTreeView object */ Zotero.ItemTreeView = function(itemGroup, sourcesOnly) { this.wrappedJSObject = this; this.rowCount = 0; this._initialized = false; this._skipKeypress = false; this._itemGroup = itemGroup; this._sourcesOnly = sourcesOnly; this._callbacks = []; this._treebox = null; this._ownerDocument = null; this._needsSort = false; this._dataItems = []; this._itemImages = {}; this._unregisterID = Zotero.Notifier.registerObserver(this, ['item', 'collection-item', 'share-items', 'bucket']); } Zotero.ItemTreeView.prototype.addCallback = function(callback) { this._callbacks.push(callback); } Zotero.ItemTreeView.prototype._runCallbacks = function() { for each(var cb in this._callbacks) { cb(); } } /** * Called by the tree itself */ Zotero.ItemTreeView.prototype.setTree = function(treebox) { var generator = this._setTreeGenerator(treebox); if(generator.next()) { Zotero.pumpGenerator(generator); } } /** * Generator used internally for setting the tree */ Zotero.ItemTreeView.prototype._setTreeGenerator = function(treebox) { try { //Zotero.debug("Calling setTree()"); var start = Date.now(); // Try to set the window document if not yet set if (treebox && !this._ownerDocument) { try { this._ownerDocument = treebox.treeBody.ownerDocument; } catch (e) {} } if (this._treebox) { if (this._needsSort) { this.sort(); } yield false; } if (!treebox) { Components.utils.reportError("Passed treebox empty in setTree()"); } this._treebox = treebox; if (this._ownerDocument.defaultView.ZoteroPane_Local) { this._ownerDocument.defaultView.ZoteroPane_Local.setItemsPaneMessage(Zotero.getString('pane.items.loading')); this._waitAfter = start + 100; } if (Zotero.locked) { var msg = "Zotero is locked -- not loading items tree"; Zotero.debug(msg, 2); if (this._ownerDocument.defaultView.ZoteroPane_Local) { this._ownerDocument.defaultView.ZoteroPane_Local.clearItemsPaneMessage(); } yield false; } // If a DB transaction is open, display error message and bail if (!Zotero.stateCheck()) { if (this._ownerDocument.defaultView.ZoteroPane_Local) { this._ownerDocument.defaultView.ZoteroPane_Local.displayErrorMessage(); } yield false; } var generator = this._refreshGenerator(); while(generator.next()) yield true; // Add a keypress listener for expand/collapse var tree = this._treebox.treeBody.parentNode; var self = this; var coloredTagsRE = new RegExp("^[1-" + Zotero.Tags.MAX_COLORED_TAGS + "]{1}$"); var listener = function(event) { if (self._skipKeyPress) { self._skipKeyPress = false; return; } // Handle arrow keys specially on multiple selection, since // otherwise the tree just applies it to the last-selected row if (event.keyCode == 39 || event.keyCode == 37) { if (self._treebox.view.selection.count > 1) { switch (event.keyCode) { case 39: self.expandSelectedRows(); break; case 37: self.collapseSelectedRows(); break; } event.preventDefault(); } return; } // Ignore other non-character keypresses if (!event.charCode) { return; } event.preventDefault(); Q.fcall(function () { var key = String.fromCharCode(event.which); if (key == '+' && !(event.ctrlKey || event.altKey || event.metaKey)) { self.expandAllRows(); return false; } else if (key == '-' && !(event.shiftKey || event.ctrlKey || event.altKey || event.metaKey)) { self.collapseAllRows(); return false; } else if (coloredTagsRE.test(key)) { let libraryID = self._itemGroup.libraryID; libraryID = libraryID ? parseInt(libraryID) : 0; let position = parseInt(key) - 1; return Zotero.Tags.getColorByPosition(libraryID, position) .then(function (colorData) { // If a color isn't assigned to this number or any // other numbers, allow key navigation if (!colorData) { return Zotero.Tags.getColors(libraryID) .then(function (colors) { return !Object.keys(colors).length; }); } var items = self.getSelectedItems(); return Zotero.Tags.toggleItemsListTags(libraryID, items, colorData.name) .then(function () { return false; }); }); } return true; }) // We have to disable key navigation on the tree in order to // keep it from acting on the 1-6 keys used for colored tags. // To allow navigation with other keys, we temporarily enable // key navigation and recreate the keyboard event. Since // that will trigger this listener again, we set a flag to // ignore the event, and then clear the flag above when the // event comes in. I see no way this could go wrong... .then(function (resend) { if (!resend) { return; } tree.disableKeyNavigation = false; self._skipKeyPress = true; var nsIDWU = Components.interfaces.nsIDOMWindowUtils; var domWindowUtils = event.originalTarget.ownerDocument.defaultView .QueryInterface(Components.interfaces.nsIInterfaceRequestor) .getInterface(nsIDWU); var modifiers = 0; if (event.altKey) { modifiers |= nsIDWU.MODIFIER_ALT; } if (event.ctrlKey) { modifiers |= nsIDWU.MODIFIER_CONTROL; } if (event.shiftKey) { modifiers |= nsIDWU.MODIFIER_SHIFT; } if (event.metaKey) { modifiers |= nsIDWU.MODIFIER_META; } domWindowUtils.sendKeyEvent( 'keypress', event.keyCode, event.charCode, modifiers ); tree.disableKeyNavigation = true; }) .catch(function (e) { Zotero.debug(e, 1); Components.utils.reportError(e); }) .done(); }; // Store listener so we can call removeEventListener() // in overlay.js::onCollectionSelected() this.listener = listener; tree.addEventListener('keypress', listener); // This seems to be the only way to prevent Enter/Return // from toggle row open/close. The event is handled by // handleKeyPress() in zoteroPane.js. tree._handleEnter = function () {}; this.sort(); // Only yield if there are callbacks; otherwise, we're almost done if(this._callbacks.length && this._waitAfter && Date.now() > this._waitAfter) yield true; this.expandMatchParents(); //Zotero.debug('Running callbacks in itemTreeView.setTree()', 4); this._runCallbacks(); if (this._ownerDocument.defaultView.ZoteroPane_Local) { this._ownerDocument.defaultView.ZoteroPane_Local.clearItemsPaneMessage(); } // Select a queued item from selectItem() if (this._itemGroup && this._itemGroup.itemToSelect) { var item = this._itemGroup.itemToSelect; this.selectItem(item['id'], item['expand']); this._itemGroup.itemToSelect = null; } delete this._waitAfter; Zotero.debug("Set tree in "+(Date.now()-start)+" ms"); } catch(e) { Zotero.logError(e); } yield false; } /** * Reload the rows from the data access methods * (doesn't call the tree.invalidate methods, etc.) */ Zotero.ItemTreeView.prototype.refresh = function() { var generator = this._refreshGenerator(); while(generator.next()) {}; } /** * Generator used internally for refresh */ Zotero.ItemTreeView._haveCachedFields = false; Zotero.ItemTreeView.prototype._refreshGenerator = function() { Zotero.debug('Refreshing items list'); if(!Zotero.ItemTreeView._haveCachedFields) yield true; var usiDisabled = Zotero.UnresponsiveScriptIndicator.disable(); this._searchMode = this._itemGroup.isSearchMode(); if (!this.selection.selectEventsSuppressed) { var unsuppress = this.selection.selectEventsSuppressed = true; //this._treebox.beginUpdateBatch(); } var savedSelection = this.saveSelection(); var savedOpenState = this.saveOpenState(); var oldRows = this.rowCount; this._dataItems = []; this._searchItemIDs = {}; // items matching the search this._searchParentIDs = {}; this.rowCount = 0; var cacheFields = ['title', 'date']; // Cache the visible fields so they don't load individually try { var visibleFields = this.getVisibleFields(); } // If treebox isn't ready, skip refresh catch (e) { yield false; } for (var i=0; i<visibleFields.length; i++) { var field = visibleFields[i]; switch (field) { case 'hasAttachment': case 'numNotes': continue; case 'year': field = 'date'; break; } if (cacheFields.indexOf(field) == -1) { cacheFields = cacheFields.concat(field); } } Zotero.DB.beginTransaction(); Zotero.Items.cacheFields(cacheFields); Zotero.ItemTreeView._haveCachedFields = true; var newRows = this._itemGroup.getItems(); var added = 0; for (var i=0, len=newRows.length; i < len; i++) { // Only add regular items if sourcesOnly is set if (this._sourcesOnly && !newRows[i].isRegularItem()) { continue; } // Don't add child items directly (instead mark their parents for // inclusion below) var sourceItemID = newRows[i].getSource(); if (sourceItemID) { this._searchParentIDs[sourceItemID] = true; } // Add top-level items else { this._showItem(new Zotero.ItemTreeView.TreeRow(newRows[i], 0, false), added + 1); //item ref, before row added++; } this._searchItemIDs[newRows[i].id] = true; } // Add parents of matches if not matches themselves for (var id in this._searchParentIDs) { if (!this._searchItemIDs[id]) { var item = Zotero.Items.get(id); this._showItem(new Zotero.ItemTreeView.TreeRow(item, 0, false), added + 1); //item ref, before row added++; } } Zotero.DB.commitTransaction(); if(this._waitAfter && Date.now() > this._waitAfter) yield true; this._refreshHashMap(); // Update the treebox's row count // this.rowCount isn't always up-to-date, so use the view's count var diff = this._treebox.view.rowCount - oldRows; if (diff != 0) { this._treebox.rowCountChanged(0, diff); } if (usiDisabled) { Zotero.UnresponsiveScriptIndicator.enable(); } this.rememberOpenState(savedOpenState); this.rememberSelection(savedSelection); this.expandMatchParents(); if (unsuppress) { // This causes a problem with the row count being wrong between views //this._treebox.endUpdateBatch(); this.selection.selectEventsSuppressed = false; } yield false; } /* * Called by Zotero.Notifier on any changes to items in the data layer */ Zotero.ItemTreeView.prototype.notify = function(action, type, ids, extraData) { if (!this._treebox || !this._treebox.treeBody) { Components.utils.reportError("Treebox didn't exist in itemTreeView.notify()"); return; } if (!this._itemRowMap) { Zotero.debug("Item row map didn't exist in itemTreeView.notify()"); return; } var itemGroup = this._itemGroup; var madeChanges = false; var sort = false; var savedSelection = this.saveSelection(); var previousRow = false; // Redraw the tree (for tag color and progress changes) if (action == 'redraw') { // Redraw specific rows if (type == 'item' && ids.length) { // Redraw specific cells if (extraData && extraData.column) { var col = this._treebox.columns.getNamedColumn( 'zotero-items-column-' + extraData.column ); for each(var id in ids) { if (extraData.column == 'title') { delete this._itemImages[id]; } this._treebox.invalidateCell(this._itemRowMap[id], col); } } else { for each(var id in ids) { delete this._itemImages[id]; this._treebox.invalidateRow(this._itemRowMap[id]); } } } // Redraw the whole tree else { this._itemImages = {}; this._treebox.invalidate(); } return; } // If refreshing a single item, just unselect and reselect it if (action == 'refresh') { if (type == 'share-items') { if (itemGroup.isShare()) { this.refresh(); } } else if (type == 'bucket') { if (itemGroup.isBucket()) { this.refresh(); } } else if (savedSelection.length == 1 && savedSelection[0] == ids[0]) { this.selection.clearSelection(); this.rememberSelection(savedSelection); } return; } if (itemGroup.isShare()) { return; } // See if we're in the active window var zp = Zotero.getActiveZoteroPane(); var activeWindow = zp && zp.itemsView == this; var quicksearch = this._ownerDocument.getElementById('zotero-tb-search'); // 'collection-item' ids are in the form collectionID-itemID if (type == 'collection-item') { if (!itemGroup.isCollection()) { return; } var splitIDs = []; for each(var id in ids) { var split = id.split('-'); // Skip if not an item in this collection if (split[0] != itemGroup.ref.id) { continue; } splitIDs.push(split[1]); } ids = splitIDs; // Select the last item even if there are no changes (e.g. if the tag // selector is open and already refreshed the pane) if (splitIDs.length > 0 && (action == 'add' || action == 'modify')) { var selectItem = splitIDs[splitIDs.length - 1]; } } this.selection.selectEventsSuppressed = true; this._treebox.beginUpdateBatch(); if ((action == 'remove' && !itemGroup.isLibrary(true)) || action == 'delete' || action == 'trash') { // On a delete in duplicates mode, just refresh rather than figuring // out what to remove if (itemGroup.isDuplicates()) { previousRow = this._itemRowMap[ids[0]]; this.refresh(); madeChanges = true; sort = true; } else { // Since a remove involves shifting of rows, we have to do it in order, // so sort the ids by row var rows = []; for (var i=0, len=ids.length; i<len; i++) { if (action == 'delete' || action == 'trash' || !itemGroup.ref.hasItem(ids[i])) { // Row might already be gone (e.g. if this is a child and // 'modify' was sent to parent) if (this._itemRowMap[ids[i]] != undefined) { rows.push(this._itemRowMap[ids[i]]); } } } if (rows.length > 0) { rows.sort(function(a,b) { return a-b }); for(var i=0, len=rows.length; i<len; i++) { var row = rows[i]; if(row != null) { this._hideItem(row-i); this._treebox.rowCountChanged(row-i,-1); } } madeChanges = true; sort = true; } } } else if (action == 'modify') { // If trash or saved search, just re-run search if (itemGroup.isTrash() || itemGroup.isSearch()) { Zotero.ItemGroupCache.clear(); this.refresh(); madeChanges = true; sort = true; } // If no quicksearch, process modifications manually else if (!quicksearch || quicksearch.value == '') { var items = Zotero.Items.get(ids); for each(var item in items) { var id = item.id; // Make sure row map is up to date // if we made changes in a previous loop if (madeChanges) { this._refreshHashMap(); } var row = this._itemRowMap[id]; // Clear item type icon and tag colors delete this._itemImages[id]; // Deleted items get a modify that we have to ignore when // not viewing the trash if (item.deleted) { continue; } // Item already exists in this view if( row != null) { var sourceItemID = this._getItemAtRow(row).ref.getSource(); var parentIndex = this.getParentIndex(row); if (this.isContainer(row) && this.isContainerOpen(row)) { this.toggleOpenState(row); this.toggleOpenState(row); sort = id; } // If item moved from top-level to under another item, // remove the old row -- the container refresh above // takes care of adding the new row else if (!this.isContainer(row) && parentIndex == -1 && sourceItemID) { this._hideItem(row); this._treebox.rowCountChanged(row+1, -1) } // If moved from under another item to top level, add row else if (!this.isContainer(row) && parentIndex != -1 && !sourceItemID) { this._showItem(new Zotero.ItemTreeView.TreeRow(item, 0, false), this.rowCount); this._treebox.rowCountChanged(this.rowCount-1, 1); sort = id; } // If not moved from under one item to another, resort the row else if (!(sourceItemID && parentIndex != -1 && this._itemRowMap[sourceItemID] != parentIndex)) { sort = id; } madeChanges = true; } else if (((itemGroup.isLibrary() || itemGroup.isGroup()) && itemGroup.ref.libraryID == item.libraryID) || (itemGroup.isCollection() && item.inCollection(itemGroup.ref.id))) { // Otherwise the item has to be added if(item.isRegularItem() || !item.getSource()) { //most likely, the note or attachment's parent was removed. this._showItem(new Zotero.ItemTreeView.TreeRow(item,0,false),this.rowCount); this._treebox.rowCountChanged(this.rowCount-1,1); madeChanges = true; sort = true; } } } if (sort && ids.length != 1) { sort = true; } } // If quicksearch, re-run it, since the results may have changed else { // If not viewing trash and all items were deleted, ignore modify var allDeleted = true; if (!itemGroup.isTrash()) { var items = Zotero.Items.get(ids); for each(var item in items) { if (!item.deleted) { allDeleted = false; break; } } } if (!allDeleted) { quicksearch.doCommand(); madeChanges = true; sort = true; } } } else if(action == 'add') { // If saved search or trash, just re-run search if (itemGroup.isSearch() || itemGroup.isTrash()) { this.refresh(); madeChanges = true; sort = true; } // If not a quicksearch and not background window saved search, // process new items manually else if (quicksearch && quicksearch.value == '') { var items = Zotero.Items.get(ids); for each(var item in items) { // if the item belongs in this collection if ((((itemGroup.isLibrary() || itemGroup.isGroup()) && itemGroup.ref.libraryID == item.libraryID) || (itemGroup.isCollection() && item.inCollection(itemGroup.ref.id))) // if we haven't already added it to our hash map && this._itemRowMap[item.id] == null // Regular item or standalone note/attachment && (item.isRegularItem() || !item.getSource())) { this._showItem(new Zotero.ItemTreeView.TreeRow(item, 0, false), this.rowCount); this._treebox.rowCountChanged(this.rowCount-1,1); madeChanges = true; } } if (madeChanges) { sort = (items.length == 1) ? items[0].id : true; } } // Otherwise re-run the search, which refreshes the item list else { // For item adds, clear the quicksearch, unless all the new items // are child items if (activeWindow && type == 'item') { var clear = false; var items = Zotero.Items.get(ids); for each(var item in items) { if (!item.getSource()) { clear = true; break; } } if (clear) { quicksearch.value = ''; } } quicksearch.doCommand(); madeChanges = true; sort = true; } } if(madeChanges) { var singleSelect = false; // If adding a single top-level item and this is the active window, select it if (action == 'add' && activeWindow) { if (ids.length == 1) { singleSelect = ids[0]; } // If there's only one parent item in the set of added items, // mark that for selection in the UI // // Only bother checking for single parent item if 1-5 total items, // since a translator is unlikely to save more than 4 child items else if (ids.length <= 5) { var items = Zotero.Items.get(ids); if (items) { var found = false; for each(var item in items) { // Check for note and attachment type, since it's quicker // than checking for parent item if (item.itemTypeID == 1 || item.itemTypeID == 14) { continue; } // We already found a top-level item, so cancel the // single selection if (found) { singleSelect = false; break; } found = true; singleSelect = item.id; } } } } if (singleSelect) { if (sort) { this.sort(typeof sort == 'number' ? sort : false); } else { this._refreshHashMap(); } // Reset to Info tab this._ownerDocument.getElementById('zotero-view-tabbox').selectedIndex = 0; this.selectItem(singleSelect); } // If single item is selected and was modified else if (action == 'modify' && ids.length == 1 && savedSelection.length == 1 && savedSelection[0] == ids[0]) { // If the item no longer matches the search term, clear the search if (quicksearch && this._itemRowMap[ids[0]] == undefined) { Zotero.debug('Selected item no longer matches quicksearch -- clearing'); quicksearch.value = ''; quicksearch.doCommand(); } if (sort) { this.sort(typeof sort == 'number' ? sort : false); } else { this._refreshHashMap(); } if (activeWindow) { this.selectItem(ids[0]); } else { this.rememberSelection(savedSelection); } } else { if (previousRow === false) { previousRow = this._itemRowMap[ids[0]]; } if (sort) { this.sort(typeof sort == 'number' ? sort : false); } else { this._refreshHashMap(); } // On removal of a row, select item at previous position if (action == 'remove' || action == 'trash' || action == 'delete') { // In duplicates view, select the next set on delete if (itemGroup.isDuplicates()) { if (this._dataItems[previousRow]) { // Mirror ZoteroPane.onTreeMouseDown behavior var itemID = this._dataItems[previousRow].ref.id; var setItemIDs = itemGroup.ref.getSetItemsByItemID(itemID); this.selectItems(setItemIDs); } } else { // If this was a child item and the next item at this // position is a top-level item, move selection one row // up to select a sibling or parent if (ids.length == 1 && previousRow > 0) { var previousItem = Zotero.Items.get(ids[0]); if (previousItem && previousItem.getSource()) { if (this._dataItems[previousRow] && this.getLevel(previousRow) == 0) { previousRow--; } } } if (this._dataItems[previousRow]) { this.selection.select(previousRow); } // If no item at previous position, select last item in list else if (this._dataItems[this._dataItems.length - 1]) { this.selection.select(this._dataItems.length - 1); } } } else { this.rememberSelection(savedSelection); } } this._treebox.invalidate(); } // For special case in which an item needs to be selected without changes // necessarily having been made // ('collection-item' add with tag selector open) else if (selectItem) { this.selectItem(selectItem); } if (Zotero.suppressUIUpdates) { this.rememberSelection(savedSelection); } this._treebox.endUpdateBatch(); this.selection.selectEventsSuppressed = false; } /* * Unregisters view from Zotero.Notifier (called on window close) */ Zotero.ItemTreeView.prototype.unregister = function() { Zotero.Notifier.unregisterObserver(this._unregisterID); } //////////////////////////////////////////////////////////////////////////////// /// /// nsITreeView functions /// //////////////////////////////////////////////////////////////////////////////// Zotero.ItemTreeView.prototype.getCellText = function(row, column) { var obj = this._getItemAtRow(row); var val; // Image only if (column.id === "zotero-items-column-hasAttachment") { return; } else if(column.id == "zotero-items-column-type") { val = Zotero.ItemTypes.getLocalizedString(obj.ref.itemTypeID); } // Year column is just date field truncated else if (column.id == "zotero-items-column-year") { val = obj.getField('date', true).substr(0, 4) } else if (column.id === "zotero-items-column-numNotes") { val = obj.numNotes(); } else { var col = column.id.substring(20); if (col == 'title') { val = obj.ref.getDisplayTitle(); } else { val = obj.getField(col); } } switch (column.id) { // Format dates as short dates in proper locale order and locale time // (e.g. "4/4/07 14:27:23") case 'zotero-items-column-dateAdded': case 'zotero-items-column-dateModified': case 'zotero-items-column-accessDate': if (val) { var order = Zotero.Date.getLocaleDateOrder(); if (order == 'mdy') { order = 'mdy'; var join = '/'; } else if (order == 'dmy') { order = 'dmy'; var join = '.'; } else if (order == 'ymd') { order = 'YMD'; var join = '-'; } var date = Zotero.Date.sqlToDate(val, true); var parts = []; for (var i=0; i<3; i++) { switch (order[i]) { case 'y': parts.push(date.getFullYear().toString().substr(2)); break; case 'Y': parts.push(date.getFullYear()); break; case 'm': parts.push((date.getMonth() + 1)); break; case 'M': parts.push(Zotero.Utilities.lpad((date.getMonth() + 1).toString(), '0', 2)); break; case 'd': parts.push(date.getDate()); break; case 'D': parts.push(Zotero.Utilities.lpad(date.getDate().toString(), '0', 2)); break; } val = parts.join(join); val += ' ' + date.toLocaleTimeString(); } } } return val; } Zotero.ItemTreeView.prototype.getImageSrc = function(row, col) { if(col.id == 'zotero-items-column-title') { // Get item type icon and tag swatches var item = this._getItemAtRow(row).ref; var itemID = item.id; if (this._itemImages[itemID]) { return this._itemImages[itemID]; } var uri = item.getImageSrc(); var tags = item.getTags(); if (!tags.length) { this._itemImages[itemID] = uri; return uri; } //Zotero.debug("Generating tree image for item " + itemID); var colorData = []; for (let i=0, len=tags.length; i<len; i++) { let libraryIDInt = item.libraryIDInt; // TEMP colorData.push(Zotero.Tags.getColor(libraryIDInt, tags[i].name)); } var self = this; Q.all(colorData) .then(function (colorData) { colorData = colorData.filter(function (val) val !== false); if (!colorData.length) { return false; } colorData.sort(function (a, b) { return a.position - b.position; }); var colors = colorData.map(function (val) val.color); return Zotero.Tags.generateItemsListImage(colors, uri); }) // When the promise is fulfilled, the data URL is ready, so invalidate // the cell to force requesting it again .then(function (dataURL) { self._itemImages[itemID] = dataURL ? dataURL : uri; if (dataURL) { self._treebox.invalidateCell(row, col); } }) .done(); this._itemImages[itemID] = uri; return uri; } else if (col.id == 'zotero-items-column-hasAttachment') { if (this._itemGroup.isTrash()) return false; var treerow = this._getItemAtRow(row); if ((!this.isContainer(row) || !this.isContainerOpen(row)) && Zotero.Sync.Storage.getItemDownloadImageNumber(treerow.ref)) { return ''; } if (treerow.level === 0) { if (treerow.ref.isRegularItem()) { switch (treerow.ref.getBestAttachmentState()) { case 1: return "chrome://zotero/skin/bullet_blue.png"; case -1: return "chrome://zotero/skin/bullet_blue_empty.png"; default: return ""; } } } if (treerow.ref.isFileAttachment()) { if (treerow.ref.fileExists) { return "chrome://zotero/skin/bullet_blue.png"; } else { return "chrome://zotero/skin/bullet_blue_empty.png"; } } } } Zotero.ItemTreeView.prototype.isContainer = function(row) { return this._getItemAtRow(row).ref.isRegularItem(); } Zotero.ItemTreeView.prototype.isContainerOpen = function(row) { return this._dataItems[row].isOpen; } Zotero.ItemTreeView.prototype.isContainerEmpty = function(row) { if (this._sourcesOnly) { return true; } var item = this._getItemAtRow(row).ref; if (!item.isRegularItem()) { return false; } var includeTrashed = this._itemGroup.isTrash(); return item.numNotes(includeTrashed) === 0 && item.numAttachments(includeTrashed) == 0; } Zotero.ItemTreeView.prototype.getLevel = function(row) { return this._getItemAtRow(row).level; } // Gets the index of the row's container, or -1 if none (top-level) Zotero.ItemTreeView.prototype.getParentIndex = function(row) { if (row==-1) { return -1; } var thisLevel = this.getLevel(row); if(thisLevel == 0) return -1; for(var i = row - 1; i >= 0; i--) if(this.getLevel(i) < thisLevel) return i; return -1; } Zotero.ItemTreeView.prototype.hasNextSibling = function(row,afterIndex) { var thisLevel = this.getLevel(row); for(var i = afterIndex + 1; i < this.rowCount; i++) { var nextLevel = this.getLevel(i); if(nextLevel == thisLevel) return true; else if(nextLevel < thisLevel) return false; } } Zotero.ItemTreeView.prototype.toggleOpenState = function(row, skipItemMapRefresh) { // Shouldn't happen but does if an item is dragged over a closed // container until it opens and then released, since the container // is no longer in the same place when the spring-load closes if (!this.isContainer(row)) { return; } var count = 0; //used to tell the tree how many rows were added/removed var thisLevel = this.getLevel(row); // Close if (this.isContainerOpen(row)) { while((row + 1 < this._dataItems.length) && (this.getLevel(row + 1) > thisLevel)) { this._hideItem(row+1); count--; //count is negative when closing a container because we are removing rows } } // Open else { var item = this._getItemAtRow(row).ref; //Get children var includeTrashed = this._itemGroup.isTrash(); var attachments = item.getAttachments(includeTrashed); var notes = item.getNotes(includeTrashed); var newRows; if(attachments && notes) newRows = notes.concat(attachments); else if(attachments) newRows = attachments; else if(notes) newRows = notes; if (newRows) { newRows = Zotero.Items.get(newRows); for(var i = 0; i < newRows.length; i++) { count++; this._showItem(new Zotero.ItemTreeView.TreeRow(newRows[i], thisLevel + 1, false), row + i + 1); // item ref, before row } } } this._dataItems[row].isOpen = !this._dataItems[row].isOpen; if (!count) { return; } this._treebox.rowCountChanged(row+1, count); //tell treebox to repaint these this._treebox.invalidateRow(row); if (!skipItemMapRefresh) { Zotero.debug('Refreshing hash map'); this._refreshHashMap(); } } Zotero.ItemTreeView.prototype.isSorted = function() { // We sort by the first column if none selected, so return true return true; } Zotero.ItemTreeView.prototype.cycleHeader = function(column) { for(var i=0, len=this._treebox.columns.count; i<len; i++) { col = this._treebox.columns.getColumnAt(i); if(column != col) { col.element.removeAttribute('sortActive'); col.element.removeAttribute('sortDirection'); } else { // If not yet selected, start with ascending if (!col.element.getAttribute('sortActive')) { col.element.setAttribute('sortDirection', 'ascending'); } else { col.element.setAttribute('sortDirection', col.element.getAttribute('sortDirection') == 'descending' ? 'ascending' : 'descending'); } col.element.setAttribute('sortActive', true); } } this.selection.selectEventsSuppressed = true; var savedSelection = this.saveSelection(); if (savedSelection.length == 1) { var pos = this._itemRowMap[savedSelection[0]] - this._treebox.getFirstVisibleRow(); } this.sort(); this.rememberSelection(savedSelection); // If single row was selected, try to keep it in the same place if (savedSelection.length == 1) { var newRow = this._itemRowMap[savedSelection[0]]; // Calculate the last row that would give us a full view var fullTop = Math.max(0, this._dataItems.length - this._treebox.getPageLength()); // Calculate the row that would give us the same position var consistentTop = Math.max(0, newRow - pos); this._treebox.scrollToRow(Math.min(fullTop, consistentTop)); } this._treebox.invalidate(); this.selection.selectEventsSuppressed = false; } /* * Sort the items by the currently sorted column. */ Zotero.ItemTreeView.prototype.sort = function(itemID) { // If Zotero pane is hidden, mark tree for sorting later in setTree() if (!this._treebox.columns) { this._needsSort = true; return; } else { this._needsSort = false; } // Single child item sort -- just toggle parent open and closed if (itemID && this._itemRowMap[itemID] && this._getItemAtRow(this._itemRowMap[itemID]).ref.getSource()) { var parentIndex = this.getParentIndex(this._itemRowMap[itemID]); this.toggleOpenState(parentIndex); this.toggleOpenState(parentIndex); return; } var columnField = this.getSortField(); var order = this.getSortDirection() == 'descending'; var collation = Zotero.getLocaleCollation(); // Year is really the date field truncated var originalColumnField = columnField; if (columnField == 'year') { columnField = 'date'; } // Some fields (e.g. dates) need to be retrieved unformatted for sorting switch (columnField) { case 'date': var unformatted = true; break; default: var unformatted = false; } // Hash table of fields for which rows with empty values should be displayed last var emptyFirst = { title: true }; // Cache primary values while sorting, since base-field-mapped getField() // calls are relatively expensive var cache = {}; // Get the display field for a row (which might be a placeholder title) var getField; switch (originalColumnField) { case 'title': getField = function (row) { var field; var type = row.ref.itemTypeID; switch (type) { case 8: // letter case 10: // interview case 17: // case field = row.ref.getDisplayTitle(); break; default: field = row.getField(columnField, unformatted); } // Ignore some leading and trailing characters when sorting return Zotero.Items.getSortTitle(field); }; break; case 'hasAttachment': getField = function (row) { if (row.ref.isAttachment()) { var state = row.ref.fileExists ? 1 : -1; } else if (row.ref.isRegularItem()) { var state = row.ref.getBestAttachmentState(); } else { return 0; } // Make sort order present, missing, empty when ascending if (state === -1) { state = 2; } return state * -1; }; break; case 'numNotes': getField = function (row) { // Sort descending by default order = !order; return row.numNotes(false, true) || 0; }; break; case 'year': getField = function (row) { var val = row.getField(columnField, unformatted); if (val) { val = val.substr(0, 4); if (val == '0000') { val = ""; } } return val; }; break; default: getField = function (row) row.getField(columnField, unformatted); } var includeTrashed = this._itemGroup.isTrash(); var me = this, isEmptyFirst = emptyFirst[columnField]; function rowSort(a, b) { var cmp, aItemID = a.id, bItemID = b.id, fieldA = cache[aItemID], fieldB = cache[bItemID]; switch (columnField) { case 'date': fieldA = getField(a).substr(0, 10); fieldB = getField(b).substr(0, 10); cmp = strcmp(fieldA, fieldB); if (cmp !== 0) { return cmp; } break; case 'firstCreator': cmp = creatorSort(a, b); if (cmp !== 0) { return cmp; } break; case 'type': var typeA = Zotero.ItemTypes.getLocalizedString(a.ref.itemTypeID); var typeB = Zotero.ItemTypes.getLocalizedString(b.ref.itemTypeID); cmp = (typeA > typeB) ? -1 : (typeA < typeB) ? 1 : 0; if (cmp !== 0) { return cmp; } break; default: if (fieldA === undefined) { cache[aItemID] = fieldA = getField(a); } if (fieldB === undefined) { cache[bItemID] = fieldB = getField(b); } // Display rows with empty values last if (!isEmptyFirst) { if(fieldA === '' && fieldB !== '') return -1; if(fieldA !== '' && fieldB === '') return 1; } cmp = collation.compareString(1, fieldB, fieldA); if (cmp !== 0) { return cmp; } } if (columnField !== 'firstCreator') { cmp = creatorSort(a, b); if (cmp !== 0) { return cmp; } } if (columnField !== 'date') { fieldA = a.getField('date', true).substr(0, 10); fieldB = b.getField('date', true).substr(0, 10); cmp = strcmp(fieldA, fieldB); if (cmp !== 0) { return cmp; } } if (columnField !== 'title') { cmp = collation.compareString(1, b.getField('title', true), a.getField('title', true)); if (cmp !== 0) { return cmp; } } fieldA = a.getField('dateModified'); fieldB = b.getField('dateModified'); return (fieldA > fieldB) ? -1 : (fieldA < fieldB) ? 1 : 0; } var firstCreatorSortCache = {}; function creatorSort(a, b) { // // Try sorting by first word in firstCreator field, since we already have it // var aItemID = a.id, bItemID = b.id, fieldA = firstCreatorSortCache[aItemID], fieldB = firstCreatorSortCache[bItemID]; if (fieldA === undefined) { var matches = Zotero.Items.getSortTitle(a.getField('firstCreator')).match(/^[^\s]+/); var fieldA = matches ? matches[0] : ''; firstCreatorSortCache[aItemID] = fieldA; } if (fieldB === undefined) { var matches = Zotero.Items.getSortTitle(b.getField('firstCreator')).match(/^[^\s]+/); var fieldB = matches ? matches[0] : ''; firstCreatorSortCache[bItemID] = fieldB; } if (fieldA === "" && fieldB === "") { return 0; } var cmp = strcmp(fieldA, fieldB, true); if (cmp !== 0) { return cmp; } // // If first word is the same, compare actual creators // var aRef = a.ref, bRef = b.ref, aCreators = aRef.getCreators(), bCreators = bRef.getCreators(), aNumCreators = aCreators.length, bNumCreators = bCreators.length, aPrimary = Zotero.CreatorTypes.getPrimaryIDForType(aRef.itemTypeID), bPrimary = Zotero.CreatorTypes.getPrimaryIDForType(bRef.itemTypeID); const editorTypeID = 3, contributorTypeID = 2; // Find the first position of each possible creator type var aPrimaryFoundAt = false; var aEditorFoundAt = false; var aContributorFoundAt = false; loop: for (var orderIndex in aCreators) { switch (aCreators[orderIndex].creatorTypeID) { case aPrimary: aPrimaryFoundAt = orderIndex; // If we find a primary, no need to continue looking break loop; case editorTypeID: if (aEditorFoundAt === false) { aEditorFoundAt = orderIndex; } break; case contributorTypeID: if (aContributorFoundAt === false) { aContributorFoundAt = orderIndex; } break; } } if (aPrimaryFoundAt !== false) { var aFirstCreatorTypeID = aPrimary; var aPos = aPrimaryFoundAt; } else if (aEditorFoundAt !== false) { var aFirstCreatorTypeID = editorTypeID; var aPos = aEditorFoundAt; } else { var aFirstCreatorTypeID = contributorTypeID; var aPos = aContributorFoundAt; } // Same for b var bPrimaryFoundAt = false; var bEditorFoundAt = false; var bContributorFoundAt = false; loop: for (var orderIndex in bCreators) { switch (bCreators[orderIndex].creatorTypeID) { case bPrimary: bPrimaryFoundAt = orderIndex; break loop; case 3: if (bEditorFoundAt === false) { bEditorFoundAt = orderIndex; } break; case 2: if (bContributorFoundAt === false) { bContributorFoundAt = orderIndex; } break; } } if (bPrimaryFoundAt !== false) { var bFirstCreatorTypeID = bPrimary; var bPos = bPrimaryFoundAt; } else if (bEditorFoundAt !== false) { var bFirstCreatorTypeID = editorTypeID; var bPos = bEditorFoundAt; } else { var bFirstCreatorTypeID = contributorTypeID; var bPos = bContributorFoundAt; } while (true) { // Compare names fieldA = Zotero.Items.getSortTitle(aCreators[aPos].ref.lastName); fieldB = Zotero.Items.getSortTitle(bCreators[bPos].ref.lastName); cmp = strcmp(fieldA, fieldB, true); if (cmp) { return cmp; } fieldA = Zotero.Items.getSortTitle(aCreators[aPos].ref.firstName); fieldB = Zotero.Items.getSortTitle(bCreators[bPos].ref.firstName); cmp = strcmp(fieldA, fieldB, true); if (cmp) { return cmp; } // If names match, find next creator of the relevant type aPos++; var aFound = false; while (aPos < aNumCreators) { // Don't die if there's no creator at an index if (!aCreators[aPos]) { Components.utils.reportError( "Creator is missing at position " + aPos + " for item " + aRef.libraryID + "/" + aRef.key ); return -1; } if (aCreators[aPos].creatorTypeID == aFirstCreatorTypeID) { aFound = true; break; } aPos++; } bPos++; var bFound = false; while (bPos < bNumCreators) { // Don't die if there's no creator at an index if (!bCreators[bPos]) { Components.utils.reportError( "Creator is missing at position " + bPos + " for item " + bRef.libraryID + "/" + bRef.key ); return -1; } if (bCreators[bPos].creatorTypeID == bFirstCreatorTypeID) { bFound = true; break; } bPos++; } if (aFound && !bFound) { return -1; } if (bFound && !aFound) { return 1; } if (!aFound && !bFound) { return 0; } } } function strcmp(a, b, collationSort) { // Display rows with empty values last if(a === '' && b !== '') return -1; if(a !== '' && b === '') return 1; if (collationSort) { return collation.compareString(1, b, a); } return (a > b) ? -1 : (a < b) ? 1 : 0; } // Need to close all containers before sorting if (!this.selection.selectEventsSuppressed) { var unsuppress = this.selection.selectEventsSuppressed = true; this._treebox.beginUpdateBatch(); } var savedSelection = this.saveSelection(); var openItemIDs = this.saveOpenState(true); // Single-row sort if (itemID) { var row = this._itemRowMap[itemID]; for (var i=0, len=this._dataItems.length; i<len; i++) { if (i === row) { continue; } if (order) { var cmp = -1*rowSort(this._dataItems[i], this._dataItems[row]); } else { var cmp = rowSort(this._dataItems[i], this._dataItems[row]); } // As soon as we find a value greater (or smaller if reverse sort), // insert row at that position if (cmp < 0) { var rowItem = this._dataItems.splice(row, 1); this._dataItems.splice(row < i ? i-1 : i, 0, rowItem[0]); this._treebox.invalidate(); break; } // If greater than last row, move to end if (i == len-1) { var rowItem = this._dataItems.splice(row, 1); this._dataItems.splice(i, 0, rowItem[0]); this._treebox.invalidate(); } } } // Full sort else { this._dataItems.sort(rowSort); if(!order) this._dataItems.reverse(); } this._refreshHashMap(); this.rememberOpenState(openItemIDs); this.rememberSelection(savedSelection); if (unsuppress) { this.selection.selectEventsSuppressed = false; this._treebox.endUpdateBatch(); } } //////////////////////////////////////////////////////////////////////////////// /// /// Additional functions for managing data in the tree /// //////////////////////////////////////////////////////////////////////////////// /* * Select an item */ Zotero.ItemTreeView.prototype.selectItem = function(id, expand, noRecurse) { // Don't change selection if UI updates are disabled (e.g., during sync) if (Zotero.suppressUIUpdates) { Zotero.debug("Sync is running; not selecting item"); return; } // If no row map, we're probably in the process of switching collections, // so store the item to select on the item group for later if (!this._itemRowMap) { if (this._itemGroup) { this._itemGroup.itemToSelect = { id: id, expand: expand }; Zotero.debug("_itemRowMap not yet set; not selecting item"); return false; } Zotero.debug('Item group not found and no row map in ItemTreeView.selectItem() -- discarding select', 2); return false; } var row = this._itemRowMap[id]; // Get the row of the parent, if there is one var parentRow = null; var item = Zotero.Items.get(id); var parent = item.getSource(); if (parent && this._itemRowMap[parent] != undefined) { parentRow = this._itemRowMap[parent]; } // If row with id not visible, check to see if it's hidden under a parent if(row == undefined) { if (!parent || parentRow === null) { // No parent -- it's not here // Clear the quicksearch and tag selection and try again (once) if (!noRecurse) { if (this._ownerDocument.defaultView.ZoteroPane_Local) { this._ownerDocument.defaultView.ZoteroPane_Local.clearQuicksearch(); this._ownerDocument.defaultView.ZoteroPane_Local.clearTagSelection(); } return this.selectItem(id, expand, true); } Zotero.debug("Could not find row for item; not selecting item"); return false; } // If parent is already open and we haven't found the item, the child // hasn't yet been added to the view, so close parent to allow refresh if (this.isContainerOpen(parentRow)) { this.toggleOpenState(parentRow); } // Open the parent this.toggleOpenState(parentRow); row = this._itemRowMap[id]; } this.selection.select(row); // If |expand|, open row if container if (expand && this.isContainer(row) && !this.isContainerOpen(row)) { this.toggleOpenState(row); } this.selection.select(row); // We aim for a row 5 below the target row, since ensureRowIsVisible() does // the bare minimum to get the row in view for (var v = row + 5; v>=row; v--) { if (this._dataItems[v]) { this._treebox.ensureRowIsVisible(v); if (this._treebox.getFirstVisibleRow() <= row) { break; } } } // If the parent row isn't in view and we have enough room, make parent visible if (parentRow !== null && this._treebox.getFirstVisibleRow() > parentRow) { if ((row - parentRow) < this._treebox.getPageLength()) { this._treebox.ensureRowIsVisible(parentRow); } } return true; } /** * Select multiple top-level items * * @param {Integer[]} ids An array of itemIDs */ Zotero.ItemTreeView.prototype.selectItems = function(ids) { if (ids.length == 0) { return; } var rows = []; for each(var id in ids) { rows.push(this._itemRowMap[id]); } rows.sort(function (a, b) { return a - b; }); this.selection.clearSelection(); this.selection.selectEventsSuppressed = true; var lastStart = 0; for (var i = 0, len = rows.length; i < len; i++) { if (i == len - 1 || rows[i + 1] != rows[i] + 1) { this.selection.rangedSelect(rows[lastStart], rows[i], true); lastStart = i + 1; } } this.selection.selectEventsSuppressed = false; } /* * Return an array of Item objects for selected items * * If asIDs is true, return an array of itemIDs instead */ Zotero.ItemTreeView.prototype.getSelectedItems = function(asIDs) { var items = [], start = {}, end = {}; for (var i=0, len = this.selection.getRangeCount(); i<len; i++) { this.selection.getRangeAt(i,start,end); for (var j=start.value; j<=end.value; j++) { if (asIDs) { items.push(this._getItemAtRow(j).id); } else { items.push(this._getItemAtRow(j).ref); } } } return items; } /** * Delete the selection * * @param {Boolean} [force=false] Delete item even if removing from a collection */ Zotero.ItemTreeView.prototype.deleteSelection = function (force) { if (arguments.length > 1) { throw ("deleteSelection() no longer takes two parameters"); } if (this.selection.count == 0) { return; } this._treebox.beginUpdateBatch(); // Collapse open items for (var i=0; i<this.rowCount; i++) { if (this.selection.isSelected(i) && this.isContainer(i) && this.isContainerOpen(i)) { this.toggleOpenState(i, true); } } this._refreshHashMap(); // Create an array of selected items var ids = []; var start = {}; var end = {}; for (var i=0, len=this.selection.getRangeCount(); i<len; i++) { this.selection.getRangeAt(i,start,end); for (var j=start.value; j<=end.value; j++) ids.push(this._getItemAtRow(j).id); } Zotero.ItemGroupCache.clear(); var itemGroup = this._itemGroup; if (itemGroup.isBucket()) { itemGroup.ref.deleteItems(ids); } else if (itemGroup.isTrash()) { Zotero.Items.erase(ids); } else if (itemGroup.isLibrary(true) || force) { Zotero.Items.trash(ids); } else if (itemGroup.isCollection()) { itemGroup.ref.removeItems(ids); } this._treebox.endUpdateBatch(); } /* * Set the search/tags filter on the view */ Zotero.ItemTreeView.prototype.setFilter = function(type, data) { if (!this._treebox || !this._treebox.treeBody) { Components.utils.reportError("Treebox didn't exist in itemTreeView.setFilter()"); return; } this.selection.selectEventsSuppressed = true; this._treebox.beginUpdateBatch(); switch (type) { case 'search': this._itemGroup.setSearch(data); break; case 'tags': this._itemGroup.setTags(data); break; default: throw ('Invalid filter type in setFilter'); } var oldCount = this.rowCount; this.refresh(); this.sort(); this._treebox.endUpdateBatch(); this.selection.selectEventsSuppressed = false; //Zotero.debug('Running callbacks in itemTreeView.setFilter()', 4); this._runCallbacks(); } /* * Called by various view functions to show a row * * item: reference to the Item * beforeRow: row index to insert new row before */ Zotero.ItemTreeView.prototype._showItem = function(item, beforeRow) { this._dataItems.splice(beforeRow, 0, item); this.rowCount++; } /* * Called by view to hide specified row */ Zotero.ItemTreeView.prototype._hideItem = function(row) { this._dataItems.splice(row,1); this.rowCount--; } /* * Returns a reference to the item at row (see Zotero.Item in data_access.js) */ Zotero.ItemTreeView.prototype._getItemAtRow = function(row) { return this._dataItems[row]; } /* * Create hash map of item ids to row indexes */ Zotero.ItemTreeView.prototype._refreshHashMap = function() { var rowMap = {}; for (var i=0, len=this.rowCount; i<len; i++) { var row = this._getItemAtRow(i); rowMap[row.ref.id] = i; } this._itemRowMap = rowMap; } /* * Saves the ids of currently selected items for later */ Zotero.ItemTreeView.prototype.saveSelection = function() { var savedSelection = new Array(); var start = new Object(); var end = new Object(); for (var i=0, len=this.selection.getRangeCount(); i<len; i++) { this.selection.getRangeAt(i,start,end); for (var j=start.value; j<=end.value; j++) { var item = this._getItemAtRow(j); if (!item) { continue; } savedSelection.push(item.ref.id); } } return savedSelection; } /* * Sets the selection based on saved selection ids (see above) */ Zotero.ItemTreeView.prototype.rememberSelection = function(selection) { this.selection.clearSelection(); if (!this.selection.selectEventsSuppressed) { var unsuppress = this.selection.selectEventsSuppressed = true; this._treebox.beginUpdateBatch(); } for(var i=0; i < selection.length; i++) { if (this._itemRowMap[selection[i]] != null) { this.selection.toggleSelect(this._itemRowMap[selection[i]]); } // Try the parent else { var item = Zotero.Items.get(selection[i]); if (!item) { continue; } var parent = item.getSource(); if (!parent) { continue; } if (this._itemRowMap[parent] != null) { if (this.isContainerOpen(this._itemRowMap[parent])) { this.toggleOpenState(this._itemRowMap[parent]); } this.toggleOpenState(this._itemRowMap[parent]); this.selection.toggleSelect(this._itemRowMap[selection[i]]); } } } if (unsuppress) { this._treebox.endUpdateBatch(); this.selection.selectEventsSuppressed = false; } } Zotero.ItemTreeView.prototype.selectSearchMatches = function () { if (this._searchMode) { var ids = []; for (var id in this._searchItemIDs) { ids.push(id); } this.rememberSelection(ids); } else { this.selection.clearSelection(); } } Zotero.ItemTreeView.prototype.saveOpenState = function(close) { var itemIDs = []; if (close) { if (!this.selection.selectEventsSuppressed) { var unsuppress = this.selection.selectEventsSuppressed = true; this._treebox.beginUpdateBatch(); } } for (var i=0; i<this._dataItems.length; i++) { if (this.isContainer(i) && this.isContainerOpen(i)) { itemIDs.push(this._getItemAtRow(i).ref.id); if (close) { this.toggleOpenState(i, true); } } } if (close) { this._refreshHashMap(); if (unsuppress) { this._treebox.endUpdateBatch(); this.selection.selectEventsSuppressed = false; } } return itemIDs; } Zotero.ItemTreeView.prototype.rememberOpenState = function(itemIDs) { var rowsToOpen = []; for each(var id in itemIDs) { var row = this._itemRowMap[id]; // Item may not still exist if (row == undefined) { continue; } rowsToOpen.push(row); } rowsToOpen.sort(function (a, b) { return a - b; }); if (!this.selection.selectEventsSuppressed) { var unsuppress = this.selection.selectEventsSuppressed = true; this._treebox.beginUpdateBatch(); } // Reopen from bottom up for (var i=rowsToOpen.length-1; i>=0; i--) { this.toggleOpenState(rowsToOpen[i], true); } this._refreshHashMap(); if (unsuppress) { this._treebox.endUpdateBatch(); this.selection.selectEventsSuppressed = false; } } Zotero.ItemTreeView.prototype.expandMatchParents = function () { // Expand parents of child matches if (!this._searchMode) { return; } var hash = {}; for (var id in this._searchParentIDs) { hash[id] = true; } if (!this.selection.selectEventsSuppressed) { var unsuppress = this.selection.selectEventsSuppressed = true; this._treebox.beginUpdateBatch(); } for (var i=0; i<this.rowCount; i++) { var id = this._getItemAtRow(i).ref.id; if (hash[id] && this.isContainer(i) && !this.isContainerOpen(i)) { this.toggleOpenState(i, true); } } this._refreshHashMap(); if (unsuppress) { this._treebox.endUpdateBatch(); this.selection.selectEventsSuppressed = false; } } Zotero.ItemTreeView.prototype.saveFirstRow = function() { var row = this._treebox.getFirstVisibleRow(); if (row) { return this._getItemAtRow(row).ref.id; } return false; } Zotero.ItemTreeView.prototype.rememberFirstRow = function(firstRow) { if (firstRow && this._itemRowMap[firstRow]) { this._treebox.scrollToRow(this._itemRowMap[firstRow]); } } Zotero.ItemTreeView.prototype.expandAllRows = function() { var unsuppress = this.selection.selectEventsSuppressed = true; this._treebox.beginUpdateBatch(); for (var i=0; i<this.rowCount; i++) { if (this.isContainer(i) && !this.isContainerOpen(i)) { this.toggleOpenState(i, true); } } this._refreshHashMap(); this._treebox.endUpdateBatch(); this.selection.selectEventsSuppressed = false; } Zotero.ItemTreeView.prototype.collapseAllRows = function() { var unsuppress = this.selection.selectEventsSuppressed = true; this._treebox.beginUpdateBatch(); for (var i=0; i<this.rowCount; i++) { if (this.isContainer(i) && this.isContainerOpen(i)) { this.toggleOpenState(i, true); } } this._refreshHashMap(); this._treebox.endUpdateBatch(); this.selection.selectEventsSuppressed = false; } Zotero.ItemTreeView.prototype.expandSelectedRows = function() { var start = {}, end = {}; this.selection.selectEventsSuppressed = true; this._treebox.beginUpdateBatch(); for (var i = 0, len = this.selection.getRangeCount(); i<len; i++) { this.selection.getRangeAt(i, start, end); for (var j = start.value; j <= end.value; j++) { if (this.isContainer(j) && !this.isContainerOpen(j)) { this.toggleOpenState(j, true); } } } this._refreshHashMap(); this._treebox.endUpdateBatch(); this.selection.selectEventsSuppressed = false; } Zotero.ItemTreeView.prototype.collapseSelectedRows = function() { var start = {}, end = {}; this.selection.selectEventsSuppressed = true; this._treebox.beginUpdateBatch(); for (var i = 0, len = this.selection.getRangeCount(); i<len; i++) { this.selection.getRangeAt(i, start, end); for (var j = start.value; j <= end.value; j++) { if (this.isContainer(j) && this.isContainerOpen(j)) { this.toggleOpenState(j, true); } } } this._refreshHashMap(); this._treebox.endUpdateBatch(); this.selection.selectEventsSuppressed = false; } Zotero.ItemTreeView.prototype.getVisibleFields = function() { var columns = []; for (var i=0, len=this._treebox.columns.count; i<len; i++) { var col = this._treebox.columns.getColumnAt(i); if (col.element.getAttribute('hidden') != 'true') { columns.push(col.id.substring(20)); } } return columns; } /** * Returns an array of items of visible items in current sort order * * @param bool asIDs Return itemIDs * @return array An array of Zotero.Item objects or itemIDs */ Zotero.ItemTreeView.prototype.getSortedItems = function(asIDs) { var items = []; for each(var item in this._dataItems) { if (asIDs) { items.push(item.ref.id); } else { items.push(item.ref); } } return items; } Zotero.ItemTreeView.prototype.getSortField = function() { var column = this._treebox.columns.getSortedColumn() if (!column) { column = this._treebox.columns.getFirstColumn() } // zotero-items-column-_________ return column.id.substring(20); } /* * Returns 'ascending' or 'descending' */ Zotero.ItemTreeView.prototype.getSortDirection = function() { var column = this._treebox.columns.getSortedColumn(); if (!column) { return 'ascending'; } return column.element.getAttribute('sortDirection'); } //////////////////////////////////////////////////////////////////////////////// /// /// Command Controller: /// for Select All, etc. /// //////////////////////////////////////////////////////////////////////////////// Zotero.ItemTreeCommandController = function(tree) { this.tree = tree; } Zotero.ItemTreeCommandController.prototype.supportsCommand = function(cmd) { return (cmd == 'cmd_selectAll'); } Zotero.ItemTreeCommandController.prototype.isCommandEnabled = function(cmd) { return (cmd == 'cmd_selectAll'); } Zotero.ItemTreeCommandController.prototype.doCommand = function(cmd) { if (cmd == 'cmd_selectAll') { if (this.tree.view.wrappedJSObject._itemGroup.isSearchMode()) { this.tree.view.wrappedJSObject.selectSearchMatches(); } else { this.tree.view.selection.selectAll(); } } } Zotero.ItemTreeCommandController.prototype.onEvent = function(evt) { } //////////////////////////////////////////////////////////////////////////////// /// /// Drag-and-drop functions /// //////////////////////////////////////////////////////////////////////////////// /** * Start a drag using HTML 5 Drag and Drop */ Zotero.ItemTreeView.prototype.onDragStart = function (event) { var itemIDs = this.saveSelection(); var items = Zotero.Items.get(itemIDs); event.dataTransfer.setData("zotero/item", itemIDs.join()); // Multi-file drag // - Doesn't work on Windows if (!Zotero.isWin) { // If at least one file is a non-web-link attachment and can be found, // enable dragging to file system for (var i=0; i<items.length; i++) { if (items[i].isAttachment() && items[i].attachmentLinkMode != Zotero.Attachments.LINK_MODE_LINKED_URL && items[i].getFile()) { Zotero.debug("Adding file via x-moz-file-promise"); event.dataTransfer.mozSetDataAt( "application/x-moz-file-promise", new Zotero.ItemTreeView.fileDragDataProvider(), 0 ); break; } } } // Copy first file on Windows else { var index = 0; for (var i=0; i<items.length; i++) { if (items[i].isAttachment() && items[i].getAttachmentLinkMode() != Zotero.Attachments.LINK_MODE_LINKED_URL) { var file = items[i].getFile(); if (!file) { continue; } var fph = Components.classes["@mozilla.org/network/protocol;1?name=file"] .createInstance(Components.interfaces.nsIFileProtocolHandler); var uri = fph.getURLSpecFromFile(file); event.dataTransfer.mozSetDataAt("text/x-moz-url", uri + "\n" + file.leafName, index); event.dataTransfer.mozSetDataAt("application/x-moz-file", file, index); event.dataTransfer.mozSetDataAt("application/x-moz-file-promise-url", uri, index); // DEBUG: possible to drag multiple files without x-moz-file-promise? break; index++ } } } // Get Quick Copy format for current URL var url = this._ownerDocument.defaultView.content && this._ownerDocument.defaultView.content.location ? this._ownerDocument.defaultView.content.location.href : null; var format = Zotero.QuickCopy.getFormatFromURL(url); Zotero.debug("Dragging with format " + Zotero.QuickCopy.getFormattedNameFromSetting(format)); var exportCallback = function(obj, worked) { if (!worked) { Zotero.log(Zotero.getString("fileInterface.exportError"), 'warning'); return; } var text = obj.string.replace(/\r\n/g, "\n"); event.dataTransfer.setData("text/plain", text); } try { var [mode, ] = format.split('='); if (mode == 'export') { Zotero.QuickCopy.getContentFromItems(items, format, exportCallback); } else if (mode.indexOf('bibliography') == 0) { var content = Zotero.QuickCopy.getContentFromItems(items, format, null, event.shiftKey); if (content) { if (content.html) { event.dataTransfer.setData("text/html", content.html); } event.dataTransfer.setData("text/plain", content.text); } } else { Components.utils.reportError("Invalid Quick Copy mode '" + mode + "'"); } } catch (e) { Components.utils.reportError(e + " with format '" + format + "'"); } } // Implements nsIFlavorDataProvider for dragging attachment files to OS // // Not used on Windows in Firefox 3 or higher Zotero.ItemTreeView.fileDragDataProvider = function() { }; Zotero.ItemTreeView.fileDragDataProvider.prototype = { QueryInterface : function(iid) { if (iid.equals(Components.interfaces.nsIFlavorDataProvider) || iid.equals(Components.interfaces.nsISupports)) { return this; } throw Components.results.NS_NOINTERFACE; }, getFlavorData : function(transferable, flavor, data, dataLen) { if (flavor == "application/x-moz-file-promise") { // On platforms other than OS X, the only directory we know of here // is the system temp directory, and we pass the nsIFile of the file // copied there in data.value below var useTemp = !Zotero.isMac; // Get the destination directory var dirPrimitive = {}; var dataSize = {}; transferable.getTransferData("application/x-moz-file-promise-dir", dirPrimitive, dataSize); var destDir = dirPrimitive.value.QueryInterface(Components.interfaces.nsILocalFile); // Get the items we're dragging var items = {}; transferable.getTransferData("zotero/item", items, dataSize); items.value.QueryInterface(Components.interfaces.nsISupportsString); var draggedItems = Zotero.Items.get(items.value.data.split(',')); var items = []; // Make sure files exist var notFoundNames = []; for (var i=0; i<draggedItems.length; i++) { // TODO create URL? if (!draggedItems[i].isAttachment() || draggedItems[i].getAttachmentLinkMode() == Zotero.Attachments.LINK_MODE_LINKED_URL) { continue; } if (draggedItems[i].getFile()) { items.push(draggedItems[i]); } else { notFoundNames.push(draggedItems[i].getField('title')); } } // If using the temp directory, create a directory to store multiple // files, since we can (it seems) only pass one nsIFile in data.value if (useTemp && items.length > 1) { var tmpDirName = 'Zotero Dragged Files'; destDir.append(tmpDirName); if (destDir.exists()) { destDir.remove(true); } destDir.create(Components.interfaces.nsIFile.DIRECTORY_TYPE, 0755); } var copiedFiles = []; var existingItems = []; var existingFileNames = []; for (var i=0; i<items.length; i++) { // TODO create URL? if (!items[i].isAttachment() || items[i].attachmentLinkMode == Zotero.Attachments.LINK_MODE_LINKED_URL) { continue; } var file = items[i].getFile(); // Determine if we need to copy multiple files for this item // (web page snapshots) if (items[i].attachmentLinkMode != Zotero.Attachments.LINK_MODE_LINKED_FILE) { var parentDir = file.parent; var files = parentDir.directoryEntries; var numFiles = 0; while (files.hasMoreElements()) { var f = files.getNext(); f.QueryInterface(Components.interfaces.nsILocalFile); if (f.leafName.indexOf('.') != 0) { numFiles++; } } } // Create folder if multiple files if (numFiles > 1) { var dirName = Zotero.Attachments.getFileBaseNameFromItem(items[i].id); try { if (useTemp) { var copiedFile = destDir.clone(); copiedFile.append(dirName); if (copiedFile.exists()) { // If item directory already exists in the temp dir, // delete it if (items.length == 1) { copiedFile.remove(true); } // If item directory exists in the container // directory, it's a duplicate, so give this one // a different name else { copiedFile.createUnique(Components.interfaces.nsIFile.NORMAL_FILE_TYPE, 0644); var newName = copiedFile.leafName; copiedFile.remove(null); } } } parentDir.copyTo(destDir, newName ? newName : dirName); // Store nsIFile if (useTemp) { copiedFiles.push(copiedFile); } } catch (e) { if (e.name == 'NS_ERROR_FILE_ALREADY_EXISTS') { // Keep track of items that already existed existingItems.push(items[i].id); existingFileNames.push(dirName); } else { throw (e); } } } // Otherwise just copy else { try { if (useTemp) { var copiedFile = destDir.clone(); copiedFile.append(file.leafName); if (copiedFile.exists()) { // If file exists in the temp directory, // delete it if (items.length == 1) { copiedFile.remove(true); } // If file exists in the container directory, // it's a duplicate, so give this one a different // name else { copiedFile.createUnique(Components.interfaces.nsIFile.NORMAL_FILE_TYPE, 0644); var newName = copiedFile.leafName; copiedFile.remove(null); } } } file.copyTo(destDir, newName ? newName : null); // Store nsIFile if (useTemp) { copiedFiles.push(copiedFile); } } catch (e) { if (e.name == 'NS_ERROR_FILE_ALREADY_EXISTS') { existingItems.push(items[i].id); existingFileNames.push(items[i].getFile().leafName); } else { throw (e); } } } } // Files passed via data.value will be automatically moved // from the temp directory to the destination directory if (useTemp && copiedFiles.length) { if (items.length > 1) { data.value = destDir.QueryInterface(Components.interfaces.nsISupports); } else { data.value = copiedFiles[0].QueryInterface(Components.interfaces.nsISupports); } dataLen.value = 4; } if (notFoundNames.length || existingItems.length) { var promptService = Components.classes["@mozilla.org/embedcomp/prompt-service;1"] .getService(Components.interfaces.nsIPromptService); } // Display alert if files were not found if (notFoundNames.length > 0) { // On platforms that use a temporary directory, an alert here // would interrupt the dragging process, so we just log a // warning to the console if (useTemp) { for each(var name in notFoundNames) { var msg = "Attachment file for dragged item '" + name + "' not found"; Zotero.log(msg, 'warning', 'chrome://zotero/content/xpcom/itemTreeView.js'); } } else { promptService.alert(null, Zotero.getString('general.warning'), Zotero.getString('dragAndDrop.filesNotFound') + "\n\n" + notFoundNames.join("\n")); } } // Display alert if existing files were skipped if (existingItems.length > 0) { promptService.alert(null, Zotero.getString('general.warning'), Zotero.getString('dragAndDrop.existingFiles') + "\n\n" + existingFileNames.join("\n")); } } } } Zotero.ItemTreeView.prototype.canDrop = function(row, orient, dragData) { Zotero.debug("Row is " + row + "; orient is " + orient); if (row == -1 && orient == -1) { //return true; } if (!dragData || !dragData.data) { var dragData = Zotero.DragDrop.getDragData(this); } if (!dragData) { Zotero.debug("No drag data"); return false; } var dataType = dragData.dataType; var data = dragData.data; if (dataType == 'zotero/item') { var ids = data; } var itemGroup = this._itemGroup; if (orient == 0) { var rowItem = this._getItemAtRow(row).ref; // the item we are dragging over } if (dataType == 'zotero/item') { var items = Zotero.Items.get(ids); // Directly on a row if (orient == 0) { var canDrop = false; for each(var item in items) { // If any regular items, disallow drop if (item.isRegularItem()) { return false; } // Disallow cross-library child drag if (item.libraryID != itemGroup.ref.libraryID) { return false; } // Only allow dragging of notes and attachments // that aren't already children of the item if (item.getSource() != rowItem.id) { canDrop = true; } } return canDrop; } // In library, allow children to be dragged out of parent else if (itemGroup.isLibrary(true) || itemGroup.isCollection()) { for each(var item in items) { // Don't allow drag if any top-level items if (item.isTopLevelItem()) { return false; } // Don't allow web attachments to be dragged out of parents, // but do allow PDFs for now so they can be recognized if (item.isWebAttachment() && item.attachmentMIMEType != 'application/pdf') { return false; } // Don't allow children to be dragged within their own parents var parentItemID = item.getSource(); var parentIndex = this._itemRowMap[parentItemID]; if (this.getLevel(row) > 0) { if (this._getItemAtRow(this.getParentIndex(row)).ref.id == parentItemID) { return false; } } // Including immediately after the parent if (orient == 1) { if (row == parentIndex) { return false; } } // And immediately before the next parent if (orient == -1) { var nextParentIndex = null; for (var i = parentIndex + 1; i < this.rowCount; i++) { if (this.getLevel(i) == 0) { nextParentIndex = i; break; } } if (row === nextParentIndex) { return false; } } // Disallow cross-library child drag if (item.libraryID != itemGroup.ref.libraryID) { return false; } } return true; } return false; } else if (dataType == "text/x-moz-url" || dataType == 'application/x-moz-file') { // Disallow direct drop on a non-regular item (e.g. note) if (orient == 0) { if (!rowItem.isRegularItem()) { return false; } } // Don't allow drop into searches else if (itemGroup.isSearch()) { return false; } return true; } return false; } /* * Called when something's been dropped on or next to a row */ Zotero.ItemTreeView.prototype.drop = function(row, orient) { var dragData = Zotero.DragDrop.getDragData(this); if (!this.canDrop(row, orient, dragData)) { return false; } var dataType = dragData.dataType; var data = dragData.data; var itemGroup = this._itemGroup; if (dataType == 'zotero/item') { var ids = data; var items = Zotero.Items.get(ids); if (items.length < 1) { return; } // Dropped directly on a row if (orient == 0) { // Set drop target as the parent item for dragged items // // canDrop() limits this to child items var rowItem = this._getItemAtRow(row).ref; // the item we are dragging over for each(var item in items) { item.setSource(rowItem.id); item.save(); } } // Dropped outside of a row else { // Remove from parent and make top-level if (itemGroup.isLibrary(true)) { for each(var item in items) { if (!item.isRegularItem()) { item.setSource(); item.save() } } } // Add to collection else { for each(var item in items) { var source = item.isRegularItem() ? false : item.getSource(); // Top-level item if (source) { item.setSource(); item.save() } itemGroup.ref.addItem(item.id); } } } } else if (dataType == 'text/x-moz-url' || dataType == 'application/x-moz-file') { // Disallow drop into read-only libraries if (!itemGroup.editable) { var wm = Components.classes["@mozilla.org/appshell/window-mediator;1"] .getService(Components.interfaces.nsIWindowMediator); var win = wm.getMostRecentWindow("navigator:browser"); win.ZoteroPane.displayCannotEditLibraryMessage(); return; } if (itemGroup.isWithinGroup()) { var targetLibraryID = itemGroup.ref.libraryID; } else { var targetLibraryID = null; } var sourceItemID = false; var parentCollectionID = false; var treerow = this._getItemAtRow(row); if (orient == 0) { sourceItemID = treerow.ref.id } else if (itemGroup.isCollection()) { var parentCollectionID = itemGroup.ref.id; } var unlock = Zotero.Notifier.begin(true); try { for (var i=0; i<data.length; i++) { var file = data[i]; if (dataType == 'text/x-moz-url') { var url = data[i]; if (url.indexOf('file:///') == 0) { var wm = Components.classes["@mozilla.org/appshell/window-mediator;1"] .getService(Components.interfaces.nsIWindowMediator); var win = wm.getMostRecentWindow("navigator:browser"); // If dragging currently loaded page, only convert to // file if not an HTML document if (win.content.location.href != url || win.content.document.contentType != 'text/html') { var nsIFPH = Components.classes["@mozilla.org/network/protocol;1?name=file"] .getService(Components.interfaces.nsIFileProtocolHandler); try { var file = nsIFPH.getFileFromURLSpec(url); } catch (e) { Zotero.debug(e); } } } // Still string, so remote URL if (typeof file == 'string') { if (sourceItemID) { if (!itemGroup.filesEditable) { var wm = Components.classes["@mozilla.org/appshell/window-mediator;1"] .getService(Components.interfaces.nsIWindowMediator); var win = wm.getMostRecentWindow("navigator:browser"); win.ZoteroPane.displayCannotEditLibraryFilesMessage(); return; } Zotero.Attachments.importFromURL(url, sourceItemID, false, false, null, null, targetLibraryID); } else { var wm = Components.classes["@mozilla.org/appshell/window-mediator;1"] .getService(Components.interfaces.nsIWindowMediator); var win = wm.getMostRecentWindow("navigator:browser"); win.ZoteroPane.addItemFromURL(url, 'temporaryPDFHack'); // TODO: don't do this } continue; } // Otherwise file, so fall through } try { Zotero.DB.beginTransaction(); var itemID = Zotero.Attachments.importFromFile(file, sourceItemID, targetLibraryID); if (parentCollectionID) { var col = Zotero.Collections.get(parentCollectionID); if (col) { col.addItem(itemID); } } Zotero.DB.commitTransaction(); } catch (e) { Zotero.DB.rollbackTransaction(); throw (e); } } } finally { Zotero.Notifier.commit(unlock); } } } Zotero.ItemTreeView.prototype.onDragEnter = function (event) { //Zotero.debug("Storing current drag data"); Zotero.DragDrop.currentDataTransfer = event.dataTransfer; } /* * Called by HTML 5 Drag and Drop when dragging over the tree */ Zotero.ItemTreeView.prototype.onDragOver = function (event, dropdata, session) { return false; } /* * Called by HTML 5 Drag and Drop when dropping onto the tree */ Zotero.ItemTreeView.prototype.onDrop = function (event, dropdata, session) { return false; } Zotero.ItemTreeView.prototype.onDragExit = function (event) { //Zotero.debug("Clearing drag data"); Zotero.DragDrop.currentDataTransfer = null; } //////////////////////////////////////////////////////////////////////////////// /// /// Functions for nsITreeView that we have to stub out. /// //////////////////////////////////////////////////////////////////////////////// Zotero.ItemTreeView.prototype.isSeparator = function(row) { return false; } Zotero.ItemTreeView.prototype.getRowProperties = function(row, prop) {} Zotero.ItemTreeView.prototype.getColumnProperties = function(col, prop) {} Zotero.ItemTreeView.prototype.getCellProperties = function(row, col, prop) { var treeRow = this._getItemAtRow(row); var itemID = treeRow.ref.id; var props = []; // Mark items not matching search as context rows, displayed in gray if (this._searchMode && !this._searchItemIDs[itemID]) { // <=Fx21 if (prop) { var aServ = Components.classes["@mozilla.org/atom-service;1"]. getService(Components.interfaces.nsIAtomService); prop.AppendElement(aServ.getAtom("contextRow")); } // Fx22+ else { props.push("contextRow"); } } // Mark hasAttachment column, which needs special image handling if (col.id == 'zotero-items-column-hasAttachment') { // <=Fx21 if (prop) { var aServ = Components.classes["@mozilla.org/atom-service;1"]. getService(Components.interfaces.nsIAtomService); prop.AppendElement(aServ.getAtom("hasAttachment")); } // Fx22+ else { props.push("hasAttachment"); } // Don't show pie for open parent items, since we show it for the // child item if (this.isContainer(row) && this.isContainerOpen(row)) { return props.join(" "); } var num = Zotero.Sync.Storage.getItemDownloadImageNumber(treeRow.ref); //var num = Math.round(new Date().getTime() % 10000 / 10000 * 64); if (num !== false) { // <=Fx21 if (prop) { if (!aServ) { var aServ = Components.classes["@mozilla.org/atom-service;1"]. getService(Components.interfaces.nsIAtomService); } prop.AppendElement(aServ.getAtom("pie")); prop.AppendElement(aServ.getAtom("pie" + num)); } // Fx22+ else { props.push("pie", "pie" + num); } } } return props.join(" "); } Zotero.ItemTreeView.TreeRow = function(ref, level, isOpen) { this.ref = ref; //the item associated with this this.level = level; this.isOpen = isOpen; this.id = ref.id; } Zotero.ItemTreeView.TreeRow.prototype.getField = function(field, unformatted) { return this.ref.getField(field, unformatted, true); } Zotero.ItemTreeView.TreeRow.prototype.numNotes = function() { if (this.ref.isNote()) { return ''; } return this.ref.numNotes(false, true) || ''; }
chrome/content/zotero/xpcom/itemTreeView.js
/* ***** BEGIN LICENSE BLOCK ***** Copyright © 2009 Center for History and New Media George Mason University, Fairfax, Virginia, USA http://zotero.org This file is part of Zotero. Zotero is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Zotero is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with Zotero. If not, see <http://www.gnu.org/licenses/>. ***** END LICENSE BLOCK ***** */ //////////////////////////////////////////////////////////////////////////////// /// /// ItemTreeView /// -- handles the link between an individual tree and the data layer /// -- displays only items (no collections, no hierarchy) /// //////////////////////////////////////////////////////////////////////////////// /* * Constructor for the ItemTreeView object */ Zotero.ItemTreeView = function(itemGroup, sourcesOnly) { this.wrappedJSObject = this; this.rowCount = 0; this._initialized = false; this._skipKeypress = false; this._itemGroup = itemGroup; this._sourcesOnly = sourcesOnly; this._callbacks = []; this._treebox = null; this._ownerDocument = null; this._needsSort = false; this._dataItems = []; this._itemImages = {}; this._unregisterID = Zotero.Notifier.registerObserver(this, ['item', 'collection-item', 'share-items', 'bucket']); } Zotero.ItemTreeView.prototype.addCallback = function(callback) { this._callbacks.push(callback); } Zotero.ItemTreeView.prototype._runCallbacks = function() { for each(var cb in this._callbacks) { cb(); } } /** * Called by the tree itself */ Zotero.ItemTreeView.prototype.setTree = function(treebox) { var generator = this._setTreeGenerator(treebox); if(generator.next()) { Zotero.pumpGenerator(generator); } } /** * Generator used internally for setting the tree */ Zotero.ItemTreeView.prototype._setTreeGenerator = function(treebox) { try { //Zotero.debug("Calling setTree()"); var start = Date.now(); // Try to set the window document if not yet set if (treebox && !this._ownerDocument) { try { this._ownerDocument = treebox.treeBody.ownerDocument; } catch (e) {} } if (this._treebox) { if (this._needsSort) { this.sort(); } yield false; } if (!treebox) { Components.utils.reportError("Passed treebox empty in setTree()"); } this._treebox = treebox; if (this._ownerDocument.defaultView.ZoteroPane_Local) { this._ownerDocument.defaultView.ZoteroPane_Local.setItemsPaneMessage(Zotero.getString('pane.items.loading')); this._waitAfter = start + 100; } if (Zotero.locked) { var msg = "Zotero is locked -- not loading items tree"; Zotero.debug(msg, 2); if (this._ownerDocument.defaultView.ZoteroPane_Local) { this._ownerDocument.defaultView.ZoteroPane_Local.clearItemsPaneMessage(); } yield false; } // If a DB transaction is open, display error message and bail if (!Zotero.stateCheck()) { if (this._ownerDocument.defaultView.ZoteroPane_Local) { this._ownerDocument.defaultView.ZoteroPane_Local.displayErrorMessage(); } yield false; } var generator = this._refreshGenerator(); while(generator.next()) yield true; // Add a keypress listener for expand/collapse var tree = this._treebox.treeBody.parentNode; var self = this; var coloredTagsRE = new RegExp("^[1-" + Zotero.Tags.MAX_COLORED_TAGS + "]{1}$"); var listener = function(event) { if (self._skipKeyPress) { self._skipKeyPress = false; return; } // Handle arrow keys specially on multiple selection, since // otherwise the tree just applies it to the last-selected row if (event.keyCode == 39 || event.keyCode == 37) { if (self._treebox.view.selection.count > 1) { switch (event.keyCode) { case 39: self.expandSelectedRows(); break; case 37: self.collapseSelectedRows(); break; } event.preventDefault(); } return; } // Ignore other non-character keypresses if (!event.charCode) { return; } event.preventDefault(); Q.fcall(function () { var key = String.fromCharCode(event.which); if (key == '+' && !(event.ctrlKey || event.altKey || event.metaKey)) { self.expandAllRows(); return false; } else if (key == '-' && !(event.shiftKey || event.ctrlKey || event.altKey || event.metaKey)) { self.collapseAllRows(); return false; } else if (coloredTagsRE.test(key)) { let libraryID = self._itemGroup.libraryID; libraryID = libraryID ? parseInt(libraryID) : 0; let position = parseInt(key) - 1; return Zotero.Tags.getColorByPosition(libraryID, position) .then(function (colorData) { // If a color isn't assigned to this number or any // other numbers, allow key navigation if (!colorData) { return Zotero.Tags.getColors(libraryID) .then(function (colors) { return !Object.keys(colors).length; }); } var items = self.getSelectedItems(); return Zotero.Tags.toggleItemsListTags(libraryID, items, colorData.name) .then(function () { return false; }); }); } return true; }) // We have to disable key navigation on the tree in order to // keep it from acting on the 1-6 keys used for colored tags. // To allow navigation with other keys, we temporarily enable // key navigation and recreate the keyboard event. Since // that will trigger this listener again, we set a flag to // ignore the event, and then clear the flag above when the // event comes in. I see no way this could go wrong... .then(function (resend) { if (!resend) { return; } tree.disableKeyNavigation = false; self._skipKeyPress = true; var nsIDWU = Components.interfaces.nsIDOMWindowUtils; var domWindowUtils = event.originalTarget.ownerDocument.defaultView .QueryInterface(Components.interfaces.nsIInterfaceRequestor) .getInterface(nsIDWU); var modifiers = 0; if (event.altKey) { modifiers |= nsIDWU.MODIFIER_ALT; } if (event.ctrlKey) { modifiers |= nsIDWU.MODIFIER_CONTROL; } if (event.shiftKey) { modifiers |= nsIDWU.MODIFIER_SHIFT; } if (event.metaKey) { modifiers |= nsIDWU.MODIFIER_META; } domWindowUtils.sendKeyEvent( 'keypress', event.keyCode, event.charCode, modifiers ); tree.disableKeyNavigation = true; }) .catch(function (e) { Zotero.debug(e, 1); Components.utils.reportError(e); }) .done(); }; // Store listener so we can call removeEventListener() // in overlay.js::onCollectionSelected() this.listener = listener; tree.addEventListener('keypress', listener); // This seems to be the only way to prevent Enter/Return // from toggle row open/close. The event is handled by // handleKeyPress() in zoteroPane.js. tree._handleEnter = function () {}; this.sort(); // Only yield if there are callbacks; otherwise, we're almost done if(this._callbacks.length && this._waitAfter && Date.now() > this._waitAfter) yield true; this.expandMatchParents(); //Zotero.debug('Running callbacks in itemTreeView.setTree()', 4); this._runCallbacks(); if (this._ownerDocument.defaultView.ZoteroPane_Local) { this._ownerDocument.defaultView.ZoteroPane_Local.clearItemsPaneMessage(); } // Select a queued item from selectItem() if (this._itemGroup && this._itemGroup.itemToSelect) { var item = this._itemGroup.itemToSelect; this.selectItem(item['id'], item['expand']); this._itemGroup.itemToSelect = null; } delete this._waitAfter; Zotero.debug("Set tree in "+(Date.now()-start)+" ms"); } catch(e) { Zotero.logError(e); } yield false; } /** * Reload the rows from the data access methods * (doesn't call the tree.invalidate methods, etc.) */ Zotero.ItemTreeView.prototype.refresh = function() { var generator = this._refreshGenerator(); while(generator.next()) {}; } /** * Generator used internally for refresh */ Zotero.ItemTreeView._haveCachedFields = false; Zotero.ItemTreeView.prototype._refreshGenerator = function() { Zotero.debug('Refreshing items list'); if(!Zotero.ItemTreeView._haveCachedFields) yield true; var usiDisabled = Zotero.UnresponsiveScriptIndicator.disable(); this._searchMode = this._itemGroup.isSearchMode(); if (!this.selection.selectEventsSuppressed) { var unsuppress = this.selection.selectEventsSuppressed = true; //this._treebox.beginUpdateBatch(); } var savedSelection = this.saveSelection(); var savedOpenState = this.saveOpenState(); var oldRows = this.rowCount; this._dataItems = []; this._searchItemIDs = {}; // items matching the search this._searchParentIDs = {}; this.rowCount = 0; var cacheFields = ['title', 'date']; // Cache the visible fields so they don't load individually try { var visibleFields = this.getVisibleFields(); } // If treebox isn't ready, skip refresh catch (e) { yield false; } for (var i=0; i<visibleFields.length; i++) { var field = visibleFields[i]; switch (field) { case 'hasAttachment': case 'numNotes': continue; case 'year': field = 'date'; break; } if (cacheFields.indexOf(field) == -1) { cacheFields = cacheFields.concat(field); } } Zotero.DB.beginTransaction(); Zotero.Items.cacheFields(cacheFields); Zotero.ItemTreeView._haveCachedFields = true; var newRows = this._itemGroup.getItems(); var added = 0; for (var i=0, len=newRows.length; i < len; i++) { // Only add regular items if sourcesOnly is set if (this._sourcesOnly && !newRows[i].isRegularItem()) { continue; } // Don't add child items directly (instead mark their parents for // inclusion below) var sourceItemID = newRows[i].getSource(); if (sourceItemID) { this._searchParentIDs[sourceItemID] = true; } // Add top-level items else { this._showItem(new Zotero.ItemTreeView.TreeRow(newRows[i], 0, false), added + 1); //item ref, before row added++; } this._searchItemIDs[newRows[i].id] = true; } // Add parents of matches if not matches themselves for (var id in this._searchParentIDs) { if (!this._searchItemIDs[id]) { var item = Zotero.Items.get(id); this._showItem(new Zotero.ItemTreeView.TreeRow(item, 0, false), added + 1); //item ref, before row added++; } } Zotero.DB.commitTransaction(); if(this._waitAfter && Date.now() > this._waitAfter) yield true; this._refreshHashMap(); // Update the treebox's row count // this.rowCount isn't always up-to-date, so use the view's count var diff = this._treebox.view.rowCount - oldRows; if (diff != 0) { this._treebox.rowCountChanged(0, diff); } if (usiDisabled) { Zotero.UnresponsiveScriptIndicator.enable(); } this.rememberOpenState(savedOpenState); this.rememberSelection(savedSelection); this.expandMatchParents(); if (unsuppress) { // This causes a problem with the row count being wrong between views //this._treebox.endUpdateBatch(); this.selection.selectEventsSuppressed = false; } yield false; } /* * Called by Zotero.Notifier on any changes to items in the data layer */ Zotero.ItemTreeView.prototype.notify = function(action, type, ids, extraData) { if (!this._treebox || !this._treebox.treeBody) { Components.utils.reportError("Treebox didn't exist in itemTreeView.notify()"); return; } if (!this._itemRowMap) { Zotero.debug("Item row map didn't exist in itemTreeView.notify()"); return; } var itemGroup = this._itemGroup; var madeChanges = false; var sort = false; var savedSelection = this.saveSelection(); var previousRow = false; // Redraw the tree (for tag color and progress changes) if (action == 'redraw') { // Redraw specific rows if (type == 'item' && ids.length) { // Redraw specific cells if (extraData && extraData.column) { var col = this._treebox.columns.getNamedColumn( 'zotero-items-column-' + extraData.column ); for each(var id in ids) { if (extraData.column == 'title') { delete this._itemImages[id]; } this._treebox.invalidateCell(this._itemRowMap[id], col); } } else { for each(var id in ids) { delete this._itemImages[id]; this._treebox.invalidateRow(this._itemRowMap[id]); } } } // Redraw the whole tree else { this._itemImages = {}; this._treebox.invalidate(); } return; } // If refreshing a single item, just unselect and reselect it if (action == 'refresh') { if (type == 'share-items') { if (itemGroup.isShare()) { this.refresh(); } } else if (type == 'bucket') { if (itemGroup.isBucket()) { this.refresh(); } } else if (savedSelection.length == 1 && savedSelection[0] == ids[0]) { this.selection.clearSelection(); this.rememberSelection(savedSelection); } return; } if (itemGroup.isShare()) { return; } // See if we're in the active window var zp = Zotero.getActiveZoteroPane(); var activeWindow = zp && zp.itemsView == this; var quicksearch = this._ownerDocument.getElementById('zotero-tb-search'); // 'collection-item' ids are in the form collectionID-itemID if (type == 'collection-item') { if (!itemGroup.isCollection()) { return; } var splitIDs = []; for each(var id in ids) { var split = id.split('-'); // Skip if not an item in this collection if (split[0] != itemGroup.ref.id) { continue; } splitIDs.push(split[1]); } ids = splitIDs; // Select the last item even if there are no changes (e.g. if the tag // selector is open and already refreshed the pane) if (splitIDs.length > 0 && (action == 'add' || action == 'modify')) { var selectItem = splitIDs[splitIDs.length - 1]; } } this.selection.selectEventsSuppressed = true; this._treebox.beginUpdateBatch(); if ((action == 'remove' && !itemGroup.isLibrary(true)) || action == 'delete' || action == 'trash') { // On a delete in duplicates mode, just refresh rather than figuring // out what to remove if (itemGroup.isDuplicates()) { previousRow = this._itemRowMap[ids[0]]; this.refresh(); madeChanges = true; sort = true; } else { // Since a remove involves shifting of rows, we have to do it in order, // so sort the ids by row var rows = []; for (var i=0, len=ids.length; i<len; i++) { if (action == 'delete' || action == 'trash' || !itemGroup.ref.hasItem(ids[i])) { // Row might already be gone (e.g. if this is a child and // 'modify' was sent to parent) if (this._itemRowMap[ids[i]] != undefined) { rows.push(this._itemRowMap[ids[i]]); } } } if (rows.length > 0) { rows.sort(function(a,b) { return a-b }); for(var i=0, len=rows.length; i<len; i++) { var row = rows[i]; if(row != null) { this._hideItem(row-i); this._treebox.rowCountChanged(row-i,-1); } } madeChanges = true; sort = true; } } } else if (action == 'modify') { // If trash or saved search, just re-run search if (itemGroup.isTrash() || itemGroup.isSearch()) { Zotero.ItemGroupCache.clear(); this.refresh(); madeChanges = true; sort = true; } // If no quicksearch, process modifications manually else if (!quicksearch || quicksearch.value == '') { var items = Zotero.Items.get(ids); for each(var item in items) { var id = item.id; // Make sure row map is up to date // if we made changes in a previous loop if (madeChanges) { this._refreshHashMap(); } var row = this._itemRowMap[id]; // Clear item type icon and tag colors delete this._itemImages[id]; // Deleted items get a modify that we have to ignore when // not viewing the trash if (item.deleted) { continue; } // Item already exists in this view if( row != null) { var sourceItemID = this._getItemAtRow(row).ref.getSource(); var parentIndex = this.getParentIndex(row); if (this.isContainer(row) && this.isContainerOpen(row)) { this.toggleOpenState(row); this.toggleOpenState(row); sort = id; } // If item moved from top-level to under another item, // remove the old row -- the container refresh above // takes care of adding the new row else if (!this.isContainer(row) && parentIndex == -1 && sourceItemID) { this._hideItem(row); this._treebox.rowCountChanged(row+1, -1) } // If moved from under another item to top level, add row else if (!this.isContainer(row) && parentIndex != -1 && !sourceItemID) { this._showItem(new Zotero.ItemTreeView.TreeRow(item, 0, false), this.rowCount); this._treebox.rowCountChanged(this.rowCount-1, 1); sort = id; } // If not moved from under one item to another, resort the row else if (!(sourceItemID && parentIndex != -1 && this._itemRowMap[sourceItemID] != parentIndex)) { sort = id; } madeChanges = true; } else if (((itemGroup.isLibrary() || itemGroup.isGroup()) && itemGroup.ref.libraryID == item.libraryID) || (itemGroup.isCollection() && item.inCollection(itemGroup.ref.id))) { // Otherwise the item has to be added if(item.isRegularItem() || !item.getSource()) { //most likely, the note or attachment's parent was removed. this._showItem(new Zotero.ItemTreeView.TreeRow(item,0,false),this.rowCount); this._treebox.rowCountChanged(this.rowCount-1,1); madeChanges = true; sort = true; } } } if (sort && ids.length != 1) { sort = true; } } // If quicksearch, re-run it, since the results may have changed else { // If not viewing trash and all items were deleted, ignore modify var allDeleted = true; if (!itemGroup.isTrash()) { var items = Zotero.Items.get(ids); for each(var item in items) { if (!item.deleted) { allDeleted = false; break; } } } if (!allDeleted) { quicksearch.doCommand(); madeChanges = true; sort = true; } } } else if(action == 'add') { // If saved search or trash, just re-run search if (itemGroup.isSearch() || itemGroup.isTrash()) { this.refresh(); madeChanges = true; sort = true; } // If not a quicksearch and not background window saved search, // process new items manually else if (quicksearch && quicksearch.value == '') { var items = Zotero.Items.get(ids); for each(var item in items) { // if the item belongs in this collection if ((((itemGroup.isLibrary() || itemGroup.isGroup()) && itemGroup.ref.libraryID == item.libraryID) || (itemGroup.isCollection() && item.inCollection(itemGroup.ref.id))) // if we haven't already added it to our hash map && this._itemRowMap[item.id] == null // Regular item or standalone note/attachment && (item.isRegularItem() || !item.getSource())) { this._showItem(new Zotero.ItemTreeView.TreeRow(item, 0, false), this.rowCount); this._treebox.rowCountChanged(this.rowCount-1,1); madeChanges = true; } } if (madeChanges) { sort = (items.length == 1) ? items[0].id : true; } } // Otherwise re-run the search, which refreshes the item list else { // For item adds, clear the quicksearch, unless all the new items // are child items if (activeWindow && type == 'item') { var clear = false; var items = Zotero.Items.get(ids); for each(var item in items) { if (!item.getSource()) { clear = true; break; } } if (clear) { quicksearch.value = ''; } } quicksearch.doCommand(); madeChanges = true; sort = true; } } if(madeChanges) { var singleSelect = false; // If adding a single top-level item and this is the active window, select it if (action == 'add' && activeWindow) { if (ids.length == 1) { singleSelect = ids[0]; } // If there's only one parent item in the set of added items, // mark that for selection in the UI // // Only bother checking for single parent item if 1-5 total items, // since a translator is unlikely to save more than 4 child items else if (ids.length <= 5) { var items = Zotero.Items.get(ids); if (items) { var found = false; for each(var item in items) { // Check for note and attachment type, since it's quicker // than checking for parent item if (item.itemTypeID == 1 || item.itemTypeID == 14) { continue; } // We already found a top-level item, so cancel the // single selection if (found) { singleSelect = false; break; } found = true; singleSelect = item.id; } } } } if (singleSelect) { if (sort) { this.sort(typeof sort == 'number' ? sort : false); } else { this._refreshHashMap(); } // Reset to Info tab this._ownerDocument.getElementById('zotero-view-tabbox').selectedIndex = 0; this.selectItem(singleSelect); } // If single item is selected and was modified else if (action == 'modify' && ids.length == 1 && savedSelection.length == 1 && savedSelection[0] == ids[0]) { // If the item no longer matches the search term, clear the search if (quicksearch && this._itemRowMap[ids[0]] == undefined) { Zotero.debug('Selected item no longer matches quicksearch -- clearing'); quicksearch.value = ''; quicksearch.doCommand(); } if (sort) { this.sort(typeof sort == 'number' ? sort : false); } else { this._refreshHashMap(); } if (activeWindow) { this.selectItem(ids[0]); } else { this.rememberSelection(savedSelection); } } else { if (previousRow === false) { previousRow = this._itemRowMap[ids[0]]; } if (sort) { this.sort(typeof sort == 'number' ? sort : false); } else { this._refreshHashMap(); } // On removal of a row, select item at previous position if (action == 'remove' || action == 'trash' || action == 'delete') { // In duplicates view, select the next set on delete if (itemGroup.isDuplicates()) { if (this._dataItems[previousRow]) { // Mirror ZoteroPane.onTreeMouseDown behavior var itemID = this._dataItems[previousRow].ref.id; var setItemIDs = itemGroup.ref.getSetItemsByItemID(itemID); this.selectItems(setItemIDs); } } else { // If this was a child item and the next item at this // position is a top-level item, move selection one row // up to select a sibling or parent if (ids.length == 1 && previousRow > 0) { var previousItem = Zotero.Items.get(ids[0]); if (previousItem && previousItem.getSource()) { if (this._dataItems[previousRow] && this.getLevel(previousRow) == 0) { previousRow--; } } } if (this._dataItems[previousRow]) { this.selection.select(previousRow); } // If no item at previous position, select last item in list else if (this._dataItems[this._dataItems.length - 1]) { this.selection.select(this._dataItems.length - 1); } } } else { this.rememberSelection(savedSelection); } } this._treebox.invalidate(); } // For special case in which an item needs to be selected without changes // necessarily having been made // ('collection-item' add with tag selector open) else if (selectItem) { this.selectItem(selectItem); } if (Zotero.suppressUIUpdates) { this.rememberSelection(savedSelection); } this._treebox.endUpdateBatch(); this.selection.selectEventsSuppressed = false; } /* * Unregisters view from Zotero.Notifier (called on window close) */ Zotero.ItemTreeView.prototype.unregister = function() { Zotero.Notifier.unregisterObserver(this._unregisterID); } //////////////////////////////////////////////////////////////////////////////// /// /// nsITreeView functions /// //////////////////////////////////////////////////////////////////////////////// Zotero.ItemTreeView.prototype.getCellText = function(row, column) { var obj = this._getItemAtRow(row); var val; // Image only if (column.id === "zotero-items-column-hasAttachment") { return; } else if(column.id == "zotero-items-column-type") { val = Zotero.ItemTypes.getLocalizedString(obj.ref.itemTypeID); } // Year column is just date field truncated else if (column.id == "zotero-items-column-year") { val = obj.getField('date', true).substr(0, 4) } else if (column.id === "zotero-items-column-numNotes") { val = obj.numNotes(); } else { var col = column.id.substring(20); if (col == 'title') { val = obj.ref.getDisplayTitle(); } else { val = obj.getField(col); } } switch (column.id) { // Format dates as short dates in proper locale order and locale time // (e.g. "4/4/07 14:27:23") case 'zotero-items-column-dateAdded': case 'zotero-items-column-dateModified': case 'zotero-items-column-accessDate': if (val) { var order = Zotero.Date.getLocaleDateOrder(); if (order == 'mdy') { order = 'mdy'; var join = '/'; } else if (order == 'dmy') { order = 'dmy'; var join = '.'; } else if (order == 'ymd') { order = 'YMD'; var join = '-'; } var date = Zotero.Date.sqlToDate(val, true); var parts = []; for (var i=0; i<3; i++) { switch (order[i]) { case 'y': parts.push(date.getFullYear().toString().substr(2)); break; case 'Y': parts.push(date.getFullYear()); break; case 'm': parts.push((date.getMonth() + 1)); break; case 'M': parts.push(Zotero.Utilities.lpad((date.getMonth() + 1).toString(), '0', 2)); break; case 'd': parts.push(date.getDate()); break; case 'D': parts.push(Zotero.Utilities.lpad(date.getDate().toString(), '0', 2)); break; } val = parts.join(join); val += ' ' + date.toLocaleTimeString(); } } } return val; } Zotero.ItemTreeView.prototype.getImageSrc = function(row, col) { if(col.id == 'zotero-items-column-title') { // Get item type icon and tag swatches var item = this._getItemAtRow(row).ref; var itemID = item.id; if (this._itemImages[itemID]) { return this._itemImages[itemID]; } var uri = item.getImageSrc(); var tags = item.getTags(); if (!tags.length) { this._itemImages[itemID] = uri; return uri; } //Zotero.debug("Generating tree image for item " + itemID); var colorData = []; for (let i=0, len=tags.length; i<len; i++) { let libraryIDInt = item.libraryIDInt; // TEMP colorData.push(Zotero.Tags.getColor(libraryIDInt, tags[i].name)); } var self = this; Q.all(colorData) .then(function (colorData) { colorData = colorData.filter(function (val) val !== false); if (!colorData.length) { return false; } colorData.sort(function (a, b) { return a.position - b.position; }); var colors = colorData.map(function (val) val.color); return Zotero.Tags.generateItemsListImage(colors, uri); }) // When the promise is fulfilled, the data URL is ready, so invalidate // the cell to force requesting it again .then(function (dataURL) { self._itemImages[itemID] = dataURL ? dataURL : uri; if (dataURL) { self._treebox.invalidateCell(row, col); } }) .done(); this._itemImages[itemID] = uri; return uri; } else if (col.id == 'zotero-items-column-hasAttachment') { if (this._itemGroup.isTrash()) return false; var treerow = this._getItemAtRow(row); if ((!this.isContainer(row) || !this.isContainerOpen(row)) && Zotero.Sync.Storage.getItemDownloadImageNumber(treerow.ref)) { return ''; } if (treerow.level === 0) { if (treerow.ref.isRegularItem()) { switch (treerow.ref.getBestAttachmentState()) { case 1: return "chrome://zotero/skin/bullet_blue.png"; case -1: return "chrome://zotero/skin/bullet_blue_empty.png"; default: return ""; } } } if (treerow.ref.isFileAttachment()) { if (treerow.ref.fileExists) { return "chrome://zotero/skin/bullet_blue.png"; } else { return "chrome://zotero/skin/bullet_blue_empty.png"; } } } } Zotero.ItemTreeView.prototype.isContainer = function(row) { return this._getItemAtRow(row).ref.isRegularItem(); } Zotero.ItemTreeView.prototype.isContainerOpen = function(row) { return this._dataItems[row].isOpen; } Zotero.ItemTreeView.prototype.isContainerEmpty = function(row) { if (this._sourcesOnly) { return true; } var item = this._getItemAtRow(row).ref; if (!item.isRegularItem()) { return false; } var includeTrashed = this._itemGroup.isTrash(); return item.numNotes(includeTrashed) === 0 && item.numAttachments(includeTrashed) == 0; } Zotero.ItemTreeView.prototype.getLevel = function(row) { return this._getItemAtRow(row).level; } // Gets the index of the row's container, or -1 if none (top-level) Zotero.ItemTreeView.prototype.getParentIndex = function(row) { if (row==-1) { return -1; } var thisLevel = this.getLevel(row); if(thisLevel == 0) return -1; for(var i = row - 1; i >= 0; i--) if(this.getLevel(i) < thisLevel) return i; return -1; } Zotero.ItemTreeView.prototype.hasNextSibling = function(row,afterIndex) { var thisLevel = this.getLevel(row); for(var i = afterIndex + 1; i < this.rowCount; i++) { var nextLevel = this.getLevel(i); if(nextLevel == thisLevel) return true; else if(nextLevel < thisLevel) return false; } } Zotero.ItemTreeView.prototype.toggleOpenState = function(row, skipItemMapRefresh) { // Shouldn't happen but does if an item is dragged over a closed // container until it opens and then released, since the container // is no longer in the same place when the spring-load closes if (!this.isContainer(row)) { return; } var count = 0; //used to tell the tree how many rows were added/removed var thisLevel = this.getLevel(row); // Close if (this.isContainerOpen(row)) { while((row + 1 < this._dataItems.length) && (this.getLevel(row + 1) > thisLevel)) { this._hideItem(row+1); count--; //count is negative when closing a container because we are removing rows } } // Open else { var item = this._getItemAtRow(row).ref; //Get children var includeTrashed = this._itemGroup.isTrash(); var attachments = item.getAttachments(includeTrashed); var notes = item.getNotes(includeTrashed); var newRows; if(attachments && notes) newRows = notes.concat(attachments); else if(attachments) newRows = attachments; else if(notes) newRows = notes; if (newRows) { newRows = Zotero.Items.get(newRows); for(var i = 0; i < newRows.length; i++) { count++; this._showItem(new Zotero.ItemTreeView.TreeRow(newRows[i], thisLevel + 1, false), row + i + 1); // item ref, before row } } } this._dataItems[row].isOpen = !this._dataItems[row].isOpen; if (!count) { return; } this._treebox.rowCountChanged(row+1, count); //tell treebox to repaint these this._treebox.invalidateRow(row); if (!skipItemMapRefresh) { Zotero.debug('Refreshing hash map'); this._refreshHashMap(); } } Zotero.ItemTreeView.prototype.isSorted = function() { // We sort by the first column if none selected, so return true return true; } Zotero.ItemTreeView.prototype.cycleHeader = function(column) { for(var i=0, len=this._treebox.columns.count; i<len; i++) { col = this._treebox.columns.getColumnAt(i); if(column != col) { col.element.removeAttribute('sortActive'); col.element.removeAttribute('sortDirection'); } else { // If not yet selected, start with ascending if (!col.element.getAttribute('sortActive')) { col.element.setAttribute('sortDirection', 'ascending'); } else { col.element.setAttribute('sortDirection', col.element.getAttribute('sortDirection') == 'descending' ? 'ascending' : 'descending'); } col.element.setAttribute('sortActive', true); } } this.selection.selectEventsSuppressed = true; var savedSelection = this.saveSelection(); if (savedSelection.length == 1) { var pos = this._itemRowMap[savedSelection[0]] - this._treebox.getFirstVisibleRow(); } this.sort(); this.rememberSelection(savedSelection); // If single row was selected, try to keep it in the same place if (savedSelection.length == 1) { var newRow = this._itemRowMap[savedSelection[0]]; // Calculate the last row that would give us a full view var fullTop = Math.max(0, this._dataItems.length - this._treebox.getPageLength()); // Calculate the row that would give us the same position var consistentTop = Math.max(0, newRow - pos); this._treebox.scrollToRow(Math.min(fullTop, consistentTop)); } this._treebox.invalidate(); this.selection.selectEventsSuppressed = false; } /* * Sort the items by the currently sorted column. */ Zotero.ItemTreeView.prototype.sort = function(itemID) { // If Zotero pane is hidden, mark tree for sorting later in setTree() if (!this._treebox.columns) { this._needsSort = true; return; } else { this._needsSort = false; } // Single child item sort -- just toggle parent open and closed if (itemID && this._itemRowMap[itemID] && this._getItemAtRow(this._itemRowMap[itemID]).ref.getSource()) { var parentIndex = this.getParentIndex(this._itemRowMap[itemID]); this.toggleOpenState(parentIndex); this.toggleOpenState(parentIndex); return; } var columnField = this.getSortField(); var order = this.getSortDirection() == 'descending'; var collation = Zotero.getLocaleCollation(); // Year is really the date field truncated var originalColumnField = columnField; if (columnField == 'year') { columnField = 'date'; } // Some fields (e.g. dates) need to be retrieved unformatted for sorting switch (columnField) { case 'date': var unformatted = true; break; default: var unformatted = false; } // Hash table of fields for which rows with empty values should be displayed last var emptyFirst = { title: true }; // Cache primary values while sorting, since base-field-mapped getField() // calls are relatively expensive var cache = {}; // Get the display field for a row (which might be a placeholder title) var getField; switch (originalColumnField) { case 'title': getField = function (row) { var field; var type = row.ref.itemTypeID; switch (type) { case 8: // letter case 10: // interview case 17: // case field = row.ref.getDisplayTitle(); break; default: field = row.getField(columnField, unformatted); } // Ignore some leading and trailing characters when sorting return Zotero.Items.getSortTitle(field); }; break; case 'hasAttachment': getField = function (row) { if (row.ref.isAttachment()) { var state = row.ref.fileExists ? 1 : -1; } else if (row.ref.isRegularItem()) { var state = row.ref.getBestAttachmentState(); } else { return 0; } // Make sort order present, missing, empty when ascending if (state === -1) { state = 2; } return state * -1; }; break; case 'numNotes': getField = function (row) { // Sort descending by default order = !order; return row.numNotes(false, true) || 0; }; break; case 'year': getField = function (row) { var val = row.getField(columnField, unformatted); if (val) { val = val.substr(0, 4); if (val == '0000') { val = ""; } } return val; }; break; default: getField = function (row) row.getField(columnField, unformatted); } var includeTrashed = this._itemGroup.isTrash(); var me = this, isEmptyFirst = emptyFirst[columnField]; function rowSort(a, b) { var cmp, aItemID = a.id, bItemID = b.id, fieldA = cache[aItemID], fieldB = cache[bItemID]; switch (columnField) { case 'date': fieldA = getField(a).substr(0, 10); fieldB = getField(b).substr(0, 10); cmp = strcmp(fieldA, fieldB); if (cmp !== 0) { return cmp; } break; case 'firstCreator': cmp = creatorSort(a, b); if (cmp !== 0) { return cmp; } break; case 'type': var typeA = Zotero.ItemTypes.getLocalizedString(a.ref.itemTypeID); var typeB = Zotero.ItemTypes.getLocalizedString(b.ref.itemTypeID); cmp = (typeA > typeB) ? -1 : (typeA < typeB) ? 1 : 0; if (cmp !== 0) { return cmp; } break; default: if (fieldA === undefined) { cache[aItemID] = fieldA = getField(a); } if (fieldB === undefined) { cache[bItemID] = fieldB = getField(b); } // Display rows with empty values last if (!isEmptyFirst) { if(fieldA === '' && fieldB !== '') return -1; if(fieldA !== '' && fieldB === '') return 1; } cmp = collation.compareString(1, fieldB, fieldA); if (cmp !== 0) { return cmp; } } if (columnField !== 'firstCreator') { cmp = creatorSort(a, b); if (cmp !== 0) { return cmp; } } if (columnField !== 'date') { fieldA = a.getField('date', true).substr(0, 10); fieldB = b.getField('date', true).substr(0, 10); cmp = strcmp(fieldA, fieldB); if (cmp !== 0) { return cmp; } } fieldA = a.getField('dateModified'); fieldB = b.getField('dateModified'); return (fieldA > fieldB) ? -1 : (fieldA < fieldB) ? 1 : 0; } var firstCreatorSortCache = {}; function creatorSort(a, b) { // // Try sorting by first word in firstCreator field, since we already have it // var aItemID = a.id, bItemID = b.id, fieldA = firstCreatorSortCache[aItemID], fieldB = firstCreatorSortCache[bItemID]; if (fieldA === undefined) { var matches = Zotero.Items.getSortTitle(a.getField('firstCreator')).match(/^[^\s]+/); var fieldA = matches ? matches[0] : ''; firstCreatorSortCache[aItemID] = fieldA; } if (fieldB === undefined) { var matches = Zotero.Items.getSortTitle(b.getField('firstCreator')).match(/^[^\s]+/); var fieldB = matches ? matches[0] : ''; firstCreatorSortCache[bItemID] = fieldB; } if (fieldA === "" && fieldB === "") { return 0; } var cmp = strcmp(fieldA, fieldB, true); if (cmp !== 0) { return cmp; } // // If first word is the same, compare actual creators // var aRef = a.ref, bRef = b.ref, aCreators = aRef.getCreators(), bCreators = bRef.getCreators(), aNumCreators = aCreators.length, bNumCreators = bCreators.length, aPrimary = Zotero.CreatorTypes.getPrimaryIDForType(aRef.itemTypeID), bPrimary = Zotero.CreatorTypes.getPrimaryIDForType(bRef.itemTypeID); const editorTypeID = 3, contributorTypeID = 2; // Find the first position of each possible creator type var aPrimaryFoundAt = false; var aEditorFoundAt = false; var aContributorFoundAt = false; loop: for (var orderIndex in aCreators) { switch (aCreators[orderIndex].creatorTypeID) { case aPrimary: aPrimaryFoundAt = orderIndex; // If we find a primary, no need to continue looking break loop; case editorTypeID: if (aEditorFoundAt === false) { aEditorFoundAt = orderIndex; } break; case contributorTypeID: if (aContributorFoundAt === false) { aContributorFoundAt = orderIndex; } break; } } if (aPrimaryFoundAt !== false) { var aFirstCreatorTypeID = aPrimary; var aPos = aPrimaryFoundAt; } else if (aEditorFoundAt !== false) { var aFirstCreatorTypeID = editorTypeID; var aPos = aEditorFoundAt; } else { var aFirstCreatorTypeID = contributorTypeID; var aPos = aContributorFoundAt; } // Same for b var bPrimaryFoundAt = false; var bEditorFoundAt = false; var bContributorFoundAt = false; loop: for (var orderIndex in bCreators) { switch (bCreators[orderIndex].creatorTypeID) { case bPrimary: bPrimaryFoundAt = orderIndex; break loop; case 3: if (bEditorFoundAt === false) { bEditorFoundAt = orderIndex; } break; case 2: if (bContributorFoundAt === false) { bContributorFoundAt = orderIndex; } break; } } if (bPrimaryFoundAt !== false) { var bFirstCreatorTypeID = bPrimary; var bPos = bPrimaryFoundAt; } else if (bEditorFoundAt !== false) { var bFirstCreatorTypeID = editorTypeID; var bPos = bEditorFoundAt; } else { var bFirstCreatorTypeID = contributorTypeID; var bPos = bContributorFoundAt; } while (true) { // Compare names fieldA = Zotero.Items.getSortTitle(aCreators[aPos].ref.lastName); fieldB = Zotero.Items.getSortTitle(bCreators[bPos].ref.lastName); cmp = strcmp(fieldA, fieldB, true); if (cmp) { return cmp; } fieldA = Zotero.Items.getSortTitle(aCreators[aPos].ref.firstName); fieldB = Zotero.Items.getSortTitle(bCreators[bPos].ref.firstName); cmp = strcmp(fieldA, fieldB, true); if (cmp) { return cmp; } // If names match, find next creator of the relevant type aPos++; var aFound = false; while (aPos < aNumCreators) { // Don't die if there's no creator at an index if (!aCreators[aPos]) { Components.utils.reportError( "Creator is missing at position " + aPos + " for item " + aRef.libraryID + "/" + aRef.key ); return -1; } if (aCreators[aPos].creatorTypeID == aFirstCreatorTypeID) { aFound = true; break; } aPos++; } bPos++; var bFound = false; while (bPos < bNumCreators) { // Don't die if there's no creator at an index if (!bCreators[bPos]) { Components.utils.reportError( "Creator is missing at position " + bPos + " for item " + bRef.libraryID + "/" + bRef.key ); return -1; } if (bCreators[bPos].creatorTypeID == bFirstCreatorTypeID) { bFound = true; break; } bPos++; } if (aFound && !bFound) { return -1; } if (bFound && !aFound) { return 1; } if (!aFound && !bFound) { return 0; } } } function strcmp(a, b, collationSort) { // Display rows with empty values last if(a === '' && b !== '') return -1; if(a !== '' && b === '') return 1; if (collationSort) { return collation.compareString(1, b, a); } return (a > b) ? -1 : (a < b) ? 1 : 0; } // Need to close all containers before sorting if (!this.selection.selectEventsSuppressed) { var unsuppress = this.selection.selectEventsSuppressed = true; this._treebox.beginUpdateBatch(); } var savedSelection = this.saveSelection(); var openItemIDs = this.saveOpenState(true); // Single-row sort if (itemID) { var row = this._itemRowMap[itemID]; for (var i=0, len=this._dataItems.length; i<len; i++) { if (i === row) { continue; } if (order) { var cmp = -1*rowSort(this._dataItems[i], this._dataItems[row]); } else { var cmp = rowSort(this._dataItems[i], this._dataItems[row]); } // As soon as we find a value greater (or smaller if reverse sort), // insert row at that position if (cmp < 0) { var rowItem = this._dataItems.splice(row, 1); this._dataItems.splice(row < i ? i-1 : i, 0, rowItem[0]); this._treebox.invalidate(); break; } // If greater than last row, move to end if (i == len-1) { var rowItem = this._dataItems.splice(row, 1); this._dataItems.splice(i, 0, rowItem[0]); this._treebox.invalidate(); } } } // Full sort else { this._dataItems.sort(rowSort); if(!order) this._dataItems.reverse(); } this._refreshHashMap(); this.rememberOpenState(openItemIDs); this.rememberSelection(savedSelection); if (unsuppress) { this.selection.selectEventsSuppressed = false; this._treebox.endUpdateBatch(); } } //////////////////////////////////////////////////////////////////////////////// /// /// Additional functions for managing data in the tree /// //////////////////////////////////////////////////////////////////////////////// /* * Select an item */ Zotero.ItemTreeView.prototype.selectItem = function(id, expand, noRecurse) { // Don't change selection if UI updates are disabled (e.g., during sync) if (Zotero.suppressUIUpdates) { Zotero.debug("Sync is running; not selecting item"); return; } // If no row map, we're probably in the process of switching collections, // so store the item to select on the item group for later if (!this._itemRowMap) { if (this._itemGroup) { this._itemGroup.itemToSelect = { id: id, expand: expand }; Zotero.debug("_itemRowMap not yet set; not selecting item"); return false; } Zotero.debug('Item group not found and no row map in ItemTreeView.selectItem() -- discarding select', 2); return false; } var row = this._itemRowMap[id]; // Get the row of the parent, if there is one var parentRow = null; var item = Zotero.Items.get(id); var parent = item.getSource(); if (parent && this._itemRowMap[parent] != undefined) { parentRow = this._itemRowMap[parent]; } // If row with id not visible, check to see if it's hidden under a parent if(row == undefined) { if (!parent || parentRow === null) { // No parent -- it's not here // Clear the quicksearch and tag selection and try again (once) if (!noRecurse) { if (this._ownerDocument.defaultView.ZoteroPane_Local) { this._ownerDocument.defaultView.ZoteroPane_Local.clearQuicksearch(); this._ownerDocument.defaultView.ZoteroPane_Local.clearTagSelection(); } return this.selectItem(id, expand, true); } Zotero.debug("Could not find row for item; not selecting item"); return false; } // If parent is already open and we haven't found the item, the child // hasn't yet been added to the view, so close parent to allow refresh if (this.isContainerOpen(parentRow)) { this.toggleOpenState(parentRow); } // Open the parent this.toggleOpenState(parentRow); row = this._itemRowMap[id]; } this.selection.select(row); // If |expand|, open row if container if (expand && this.isContainer(row) && !this.isContainerOpen(row)) { this.toggleOpenState(row); } this.selection.select(row); // We aim for a row 5 below the target row, since ensureRowIsVisible() does // the bare minimum to get the row in view for (var v = row + 5; v>=row; v--) { if (this._dataItems[v]) { this._treebox.ensureRowIsVisible(v); if (this._treebox.getFirstVisibleRow() <= row) { break; } } } // If the parent row isn't in view and we have enough room, make parent visible if (parentRow !== null && this._treebox.getFirstVisibleRow() > parentRow) { if ((row - parentRow) < this._treebox.getPageLength()) { this._treebox.ensureRowIsVisible(parentRow); } } return true; } /** * Select multiple top-level items * * @param {Integer[]} ids An array of itemIDs */ Zotero.ItemTreeView.prototype.selectItems = function(ids) { if (ids.length == 0) { return; } var rows = []; for each(var id in ids) { rows.push(this._itemRowMap[id]); } rows.sort(function (a, b) { return a - b; }); this.selection.clearSelection(); this.selection.selectEventsSuppressed = true; var lastStart = 0; for (var i = 0, len = rows.length; i < len; i++) { if (i == len - 1 || rows[i + 1] != rows[i] + 1) { this.selection.rangedSelect(rows[lastStart], rows[i], true); lastStart = i + 1; } } this.selection.selectEventsSuppressed = false; } /* * Return an array of Item objects for selected items * * If asIDs is true, return an array of itemIDs instead */ Zotero.ItemTreeView.prototype.getSelectedItems = function(asIDs) { var items = [], start = {}, end = {}; for (var i=0, len = this.selection.getRangeCount(); i<len; i++) { this.selection.getRangeAt(i,start,end); for (var j=start.value; j<=end.value; j++) { if (asIDs) { items.push(this._getItemAtRow(j).id); } else { items.push(this._getItemAtRow(j).ref); } } } return items; } /** * Delete the selection * * @param {Boolean} [force=false] Delete item even if removing from a collection */ Zotero.ItemTreeView.prototype.deleteSelection = function (force) { if (arguments.length > 1) { throw ("deleteSelection() no longer takes two parameters"); } if (this.selection.count == 0) { return; } this._treebox.beginUpdateBatch(); // Collapse open items for (var i=0; i<this.rowCount; i++) { if (this.selection.isSelected(i) && this.isContainer(i) && this.isContainerOpen(i)) { this.toggleOpenState(i, true); } } this._refreshHashMap(); // Create an array of selected items var ids = []; var start = {}; var end = {}; for (var i=0, len=this.selection.getRangeCount(); i<len; i++) { this.selection.getRangeAt(i,start,end); for (var j=start.value; j<=end.value; j++) ids.push(this._getItemAtRow(j).id); } Zotero.ItemGroupCache.clear(); var itemGroup = this._itemGroup; if (itemGroup.isBucket()) { itemGroup.ref.deleteItems(ids); } else if (itemGroup.isTrash()) { Zotero.Items.erase(ids); } else if (itemGroup.isLibrary(true) || force) { Zotero.Items.trash(ids); } else if (itemGroup.isCollection()) { itemGroup.ref.removeItems(ids); } this._treebox.endUpdateBatch(); } /* * Set the search/tags filter on the view */ Zotero.ItemTreeView.prototype.setFilter = function(type, data) { if (!this._treebox || !this._treebox.treeBody) { Components.utils.reportError("Treebox didn't exist in itemTreeView.setFilter()"); return; } this.selection.selectEventsSuppressed = true; this._treebox.beginUpdateBatch(); switch (type) { case 'search': this._itemGroup.setSearch(data); break; case 'tags': this._itemGroup.setTags(data); break; default: throw ('Invalid filter type in setFilter'); } var oldCount = this.rowCount; this.refresh(); this.sort(); this._treebox.endUpdateBatch(); this.selection.selectEventsSuppressed = false; //Zotero.debug('Running callbacks in itemTreeView.setFilter()', 4); this._runCallbacks(); } /* * Called by various view functions to show a row * * item: reference to the Item * beforeRow: row index to insert new row before */ Zotero.ItemTreeView.prototype._showItem = function(item, beforeRow) { this._dataItems.splice(beforeRow, 0, item); this.rowCount++; } /* * Called by view to hide specified row */ Zotero.ItemTreeView.prototype._hideItem = function(row) { this._dataItems.splice(row,1); this.rowCount--; } /* * Returns a reference to the item at row (see Zotero.Item in data_access.js) */ Zotero.ItemTreeView.prototype._getItemAtRow = function(row) { return this._dataItems[row]; } /* * Create hash map of item ids to row indexes */ Zotero.ItemTreeView.prototype._refreshHashMap = function() { var rowMap = {}; for (var i=0, len=this.rowCount; i<len; i++) { var row = this._getItemAtRow(i); rowMap[row.ref.id] = i; } this._itemRowMap = rowMap; } /* * Saves the ids of currently selected items for later */ Zotero.ItemTreeView.prototype.saveSelection = function() { var savedSelection = new Array(); var start = new Object(); var end = new Object(); for (var i=0, len=this.selection.getRangeCount(); i<len; i++) { this.selection.getRangeAt(i,start,end); for (var j=start.value; j<=end.value; j++) { var item = this._getItemAtRow(j); if (!item) { continue; } savedSelection.push(item.ref.id); } } return savedSelection; } /* * Sets the selection based on saved selection ids (see above) */ Zotero.ItemTreeView.prototype.rememberSelection = function(selection) { this.selection.clearSelection(); if (!this.selection.selectEventsSuppressed) { var unsuppress = this.selection.selectEventsSuppressed = true; this._treebox.beginUpdateBatch(); } for(var i=0; i < selection.length; i++) { if (this._itemRowMap[selection[i]] != null) { this.selection.toggleSelect(this._itemRowMap[selection[i]]); } // Try the parent else { var item = Zotero.Items.get(selection[i]); if (!item) { continue; } var parent = item.getSource(); if (!parent) { continue; } if (this._itemRowMap[parent] != null) { if (this.isContainerOpen(this._itemRowMap[parent])) { this.toggleOpenState(this._itemRowMap[parent]); } this.toggleOpenState(this._itemRowMap[parent]); this.selection.toggleSelect(this._itemRowMap[selection[i]]); } } } if (unsuppress) { this._treebox.endUpdateBatch(); this.selection.selectEventsSuppressed = false; } } Zotero.ItemTreeView.prototype.selectSearchMatches = function () { if (this._searchMode) { var ids = []; for (var id in this._searchItemIDs) { ids.push(id); } this.rememberSelection(ids); } else { this.selection.clearSelection(); } } Zotero.ItemTreeView.prototype.saveOpenState = function(close) { var itemIDs = []; if (close) { if (!this.selection.selectEventsSuppressed) { var unsuppress = this.selection.selectEventsSuppressed = true; this._treebox.beginUpdateBatch(); } } for (var i=0; i<this._dataItems.length; i++) { if (this.isContainer(i) && this.isContainerOpen(i)) { itemIDs.push(this._getItemAtRow(i).ref.id); if (close) { this.toggleOpenState(i, true); } } } if (close) { this._refreshHashMap(); if (unsuppress) { this._treebox.endUpdateBatch(); this.selection.selectEventsSuppressed = false; } } return itemIDs; } Zotero.ItemTreeView.prototype.rememberOpenState = function(itemIDs) { var rowsToOpen = []; for each(var id in itemIDs) { var row = this._itemRowMap[id]; // Item may not still exist if (row == undefined) { continue; } rowsToOpen.push(row); } rowsToOpen.sort(function (a, b) { return a - b; }); if (!this.selection.selectEventsSuppressed) { var unsuppress = this.selection.selectEventsSuppressed = true; this._treebox.beginUpdateBatch(); } // Reopen from bottom up for (var i=rowsToOpen.length-1; i>=0; i--) { this.toggleOpenState(rowsToOpen[i], true); } this._refreshHashMap(); if (unsuppress) { this._treebox.endUpdateBatch(); this.selection.selectEventsSuppressed = false; } } Zotero.ItemTreeView.prototype.expandMatchParents = function () { // Expand parents of child matches if (!this._searchMode) { return; } var hash = {}; for (var id in this._searchParentIDs) { hash[id] = true; } if (!this.selection.selectEventsSuppressed) { var unsuppress = this.selection.selectEventsSuppressed = true; this._treebox.beginUpdateBatch(); } for (var i=0; i<this.rowCount; i++) { var id = this._getItemAtRow(i).ref.id; if (hash[id] && this.isContainer(i) && !this.isContainerOpen(i)) { this.toggleOpenState(i, true); } } this._refreshHashMap(); if (unsuppress) { this._treebox.endUpdateBatch(); this.selection.selectEventsSuppressed = false; } } Zotero.ItemTreeView.prototype.saveFirstRow = function() { var row = this._treebox.getFirstVisibleRow(); if (row) { return this._getItemAtRow(row).ref.id; } return false; } Zotero.ItemTreeView.prototype.rememberFirstRow = function(firstRow) { if (firstRow && this._itemRowMap[firstRow]) { this._treebox.scrollToRow(this._itemRowMap[firstRow]); } } Zotero.ItemTreeView.prototype.expandAllRows = function() { var unsuppress = this.selection.selectEventsSuppressed = true; this._treebox.beginUpdateBatch(); for (var i=0; i<this.rowCount; i++) { if (this.isContainer(i) && !this.isContainerOpen(i)) { this.toggleOpenState(i, true); } } this._refreshHashMap(); this._treebox.endUpdateBatch(); this.selection.selectEventsSuppressed = false; } Zotero.ItemTreeView.prototype.collapseAllRows = function() { var unsuppress = this.selection.selectEventsSuppressed = true; this._treebox.beginUpdateBatch(); for (var i=0; i<this.rowCount; i++) { if (this.isContainer(i) && this.isContainerOpen(i)) { this.toggleOpenState(i, true); } } this._refreshHashMap(); this._treebox.endUpdateBatch(); this.selection.selectEventsSuppressed = false; } Zotero.ItemTreeView.prototype.expandSelectedRows = function() { var start = {}, end = {}; this.selection.selectEventsSuppressed = true; this._treebox.beginUpdateBatch(); for (var i = 0, len = this.selection.getRangeCount(); i<len; i++) { this.selection.getRangeAt(i, start, end); for (var j = start.value; j <= end.value; j++) { if (this.isContainer(j) && !this.isContainerOpen(j)) { this.toggleOpenState(j, true); } } } this._refreshHashMap(); this._treebox.endUpdateBatch(); this.selection.selectEventsSuppressed = false; } Zotero.ItemTreeView.prototype.collapseSelectedRows = function() { var start = {}, end = {}; this.selection.selectEventsSuppressed = true; this._treebox.beginUpdateBatch(); for (var i = 0, len = this.selection.getRangeCount(); i<len; i++) { this.selection.getRangeAt(i, start, end); for (var j = start.value; j <= end.value; j++) { if (this.isContainer(j) && this.isContainerOpen(j)) { this.toggleOpenState(j, true); } } } this._refreshHashMap(); this._treebox.endUpdateBatch(); this.selection.selectEventsSuppressed = false; } Zotero.ItemTreeView.prototype.getVisibleFields = function() { var columns = []; for (var i=0, len=this._treebox.columns.count; i<len; i++) { var col = this._treebox.columns.getColumnAt(i); if (col.element.getAttribute('hidden') != 'true') { columns.push(col.id.substring(20)); } } return columns; } /** * Returns an array of items of visible items in current sort order * * @param bool asIDs Return itemIDs * @return array An array of Zotero.Item objects or itemIDs */ Zotero.ItemTreeView.prototype.getSortedItems = function(asIDs) { var items = []; for each(var item in this._dataItems) { if (asIDs) { items.push(item.ref.id); } else { items.push(item.ref); } } return items; } Zotero.ItemTreeView.prototype.getSortField = function() { var column = this._treebox.columns.getSortedColumn() if (!column) { column = this._treebox.columns.getFirstColumn() } // zotero-items-column-_________ return column.id.substring(20); } /* * Returns 'ascending' or 'descending' */ Zotero.ItemTreeView.prototype.getSortDirection = function() { var column = this._treebox.columns.getSortedColumn(); if (!column) { return 'ascending'; } return column.element.getAttribute('sortDirection'); } //////////////////////////////////////////////////////////////////////////////// /// /// Command Controller: /// for Select All, etc. /// //////////////////////////////////////////////////////////////////////////////// Zotero.ItemTreeCommandController = function(tree) { this.tree = tree; } Zotero.ItemTreeCommandController.prototype.supportsCommand = function(cmd) { return (cmd == 'cmd_selectAll'); } Zotero.ItemTreeCommandController.prototype.isCommandEnabled = function(cmd) { return (cmd == 'cmd_selectAll'); } Zotero.ItemTreeCommandController.prototype.doCommand = function(cmd) { if (cmd == 'cmd_selectAll') { if (this.tree.view.wrappedJSObject._itemGroup.isSearchMode()) { this.tree.view.wrappedJSObject.selectSearchMatches(); } else { this.tree.view.selection.selectAll(); } } } Zotero.ItemTreeCommandController.prototype.onEvent = function(evt) { } //////////////////////////////////////////////////////////////////////////////// /// /// Drag-and-drop functions /// //////////////////////////////////////////////////////////////////////////////// /** * Start a drag using HTML 5 Drag and Drop */ Zotero.ItemTreeView.prototype.onDragStart = function (event) { var itemIDs = this.saveSelection(); var items = Zotero.Items.get(itemIDs); event.dataTransfer.setData("zotero/item", itemIDs.join()); // Multi-file drag // - Doesn't work on Windows if (!Zotero.isWin) { // If at least one file is a non-web-link attachment and can be found, // enable dragging to file system for (var i=0; i<items.length; i++) { if (items[i].isAttachment() && items[i].attachmentLinkMode != Zotero.Attachments.LINK_MODE_LINKED_URL && items[i].getFile()) { Zotero.debug("Adding file via x-moz-file-promise"); event.dataTransfer.mozSetDataAt( "application/x-moz-file-promise", new Zotero.ItemTreeView.fileDragDataProvider(), 0 ); break; } } } // Copy first file on Windows else { var index = 0; for (var i=0; i<items.length; i++) { if (items[i].isAttachment() && items[i].getAttachmentLinkMode() != Zotero.Attachments.LINK_MODE_LINKED_URL) { var file = items[i].getFile(); if (!file) { continue; } var fph = Components.classes["@mozilla.org/network/protocol;1?name=file"] .createInstance(Components.interfaces.nsIFileProtocolHandler); var uri = fph.getURLSpecFromFile(file); event.dataTransfer.mozSetDataAt("text/x-moz-url", uri + "\n" + file.leafName, index); event.dataTransfer.mozSetDataAt("application/x-moz-file", file, index); event.dataTransfer.mozSetDataAt("application/x-moz-file-promise-url", uri, index); // DEBUG: possible to drag multiple files without x-moz-file-promise? break; index++ } } } // Get Quick Copy format for current URL var url = this._ownerDocument.defaultView.content && this._ownerDocument.defaultView.content.location ? this._ownerDocument.defaultView.content.location.href : null; var format = Zotero.QuickCopy.getFormatFromURL(url); Zotero.debug("Dragging with format " + Zotero.QuickCopy.getFormattedNameFromSetting(format)); var exportCallback = function(obj, worked) { if (!worked) { Zotero.log(Zotero.getString("fileInterface.exportError"), 'warning'); return; } var text = obj.string.replace(/\r\n/g, "\n"); event.dataTransfer.setData("text/plain", text); } try { var [mode, ] = format.split('='); if (mode == 'export') { Zotero.QuickCopy.getContentFromItems(items, format, exportCallback); } else if (mode.indexOf('bibliography') == 0) { var content = Zotero.QuickCopy.getContentFromItems(items, format, null, event.shiftKey); if (content) { if (content.html) { event.dataTransfer.setData("text/html", content.html); } event.dataTransfer.setData("text/plain", content.text); } } else { Components.utils.reportError("Invalid Quick Copy mode '" + mode + "'"); } } catch (e) { Components.utils.reportError(e + " with format '" + format + "'"); } } // Implements nsIFlavorDataProvider for dragging attachment files to OS // // Not used on Windows in Firefox 3 or higher Zotero.ItemTreeView.fileDragDataProvider = function() { }; Zotero.ItemTreeView.fileDragDataProvider.prototype = { QueryInterface : function(iid) { if (iid.equals(Components.interfaces.nsIFlavorDataProvider) || iid.equals(Components.interfaces.nsISupports)) { return this; } throw Components.results.NS_NOINTERFACE; }, getFlavorData : function(transferable, flavor, data, dataLen) { if (flavor == "application/x-moz-file-promise") { // On platforms other than OS X, the only directory we know of here // is the system temp directory, and we pass the nsIFile of the file // copied there in data.value below var useTemp = !Zotero.isMac; // Get the destination directory var dirPrimitive = {}; var dataSize = {}; transferable.getTransferData("application/x-moz-file-promise-dir", dirPrimitive, dataSize); var destDir = dirPrimitive.value.QueryInterface(Components.interfaces.nsILocalFile); // Get the items we're dragging var items = {}; transferable.getTransferData("zotero/item", items, dataSize); items.value.QueryInterface(Components.interfaces.nsISupportsString); var draggedItems = Zotero.Items.get(items.value.data.split(',')); var items = []; // Make sure files exist var notFoundNames = []; for (var i=0; i<draggedItems.length; i++) { // TODO create URL? if (!draggedItems[i].isAttachment() || draggedItems[i].getAttachmentLinkMode() == Zotero.Attachments.LINK_MODE_LINKED_URL) { continue; } if (draggedItems[i].getFile()) { items.push(draggedItems[i]); } else { notFoundNames.push(draggedItems[i].getField('title')); } } // If using the temp directory, create a directory to store multiple // files, since we can (it seems) only pass one nsIFile in data.value if (useTemp && items.length > 1) { var tmpDirName = 'Zotero Dragged Files'; destDir.append(tmpDirName); if (destDir.exists()) { destDir.remove(true); } destDir.create(Components.interfaces.nsIFile.DIRECTORY_TYPE, 0755); } var copiedFiles = []; var existingItems = []; var existingFileNames = []; for (var i=0; i<items.length; i++) { // TODO create URL? if (!items[i].isAttachment() || items[i].attachmentLinkMode == Zotero.Attachments.LINK_MODE_LINKED_URL) { continue; } var file = items[i].getFile(); // Determine if we need to copy multiple files for this item // (web page snapshots) if (items[i].attachmentLinkMode != Zotero.Attachments.LINK_MODE_LINKED_FILE) { var parentDir = file.parent; var files = parentDir.directoryEntries; var numFiles = 0; while (files.hasMoreElements()) { var f = files.getNext(); f.QueryInterface(Components.interfaces.nsILocalFile); if (f.leafName.indexOf('.') != 0) { numFiles++; } } } // Create folder if multiple files if (numFiles > 1) { var dirName = Zotero.Attachments.getFileBaseNameFromItem(items[i].id); try { if (useTemp) { var copiedFile = destDir.clone(); copiedFile.append(dirName); if (copiedFile.exists()) { // If item directory already exists in the temp dir, // delete it if (items.length == 1) { copiedFile.remove(true); } // If item directory exists in the container // directory, it's a duplicate, so give this one // a different name else { copiedFile.createUnique(Components.interfaces.nsIFile.NORMAL_FILE_TYPE, 0644); var newName = copiedFile.leafName; copiedFile.remove(null); } } } parentDir.copyTo(destDir, newName ? newName : dirName); // Store nsIFile if (useTemp) { copiedFiles.push(copiedFile); } } catch (e) { if (e.name == 'NS_ERROR_FILE_ALREADY_EXISTS') { // Keep track of items that already existed existingItems.push(items[i].id); existingFileNames.push(dirName); } else { throw (e); } } } // Otherwise just copy else { try { if (useTemp) { var copiedFile = destDir.clone(); copiedFile.append(file.leafName); if (copiedFile.exists()) { // If file exists in the temp directory, // delete it if (items.length == 1) { copiedFile.remove(true); } // If file exists in the container directory, // it's a duplicate, so give this one a different // name else { copiedFile.createUnique(Components.interfaces.nsIFile.NORMAL_FILE_TYPE, 0644); var newName = copiedFile.leafName; copiedFile.remove(null); } } } file.copyTo(destDir, newName ? newName : null); // Store nsIFile if (useTemp) { copiedFiles.push(copiedFile); } } catch (e) { if (e.name == 'NS_ERROR_FILE_ALREADY_EXISTS') { existingItems.push(items[i].id); existingFileNames.push(items[i].getFile().leafName); } else { throw (e); } } } } // Files passed via data.value will be automatically moved // from the temp directory to the destination directory if (useTemp && copiedFiles.length) { if (items.length > 1) { data.value = destDir.QueryInterface(Components.interfaces.nsISupports); } else { data.value = copiedFiles[0].QueryInterface(Components.interfaces.nsISupports); } dataLen.value = 4; } if (notFoundNames.length || existingItems.length) { var promptService = Components.classes["@mozilla.org/embedcomp/prompt-service;1"] .getService(Components.interfaces.nsIPromptService); } // Display alert if files were not found if (notFoundNames.length > 0) { // On platforms that use a temporary directory, an alert here // would interrupt the dragging process, so we just log a // warning to the console if (useTemp) { for each(var name in notFoundNames) { var msg = "Attachment file for dragged item '" + name + "' not found"; Zotero.log(msg, 'warning', 'chrome://zotero/content/xpcom/itemTreeView.js'); } } else { promptService.alert(null, Zotero.getString('general.warning'), Zotero.getString('dragAndDrop.filesNotFound') + "\n\n" + notFoundNames.join("\n")); } } // Display alert if existing files were skipped if (existingItems.length > 0) { promptService.alert(null, Zotero.getString('general.warning'), Zotero.getString('dragAndDrop.existingFiles') + "\n\n" + existingFileNames.join("\n")); } } } } Zotero.ItemTreeView.prototype.canDrop = function(row, orient, dragData) { Zotero.debug("Row is " + row + "; orient is " + orient); if (row == -1 && orient == -1) { //return true; } if (!dragData || !dragData.data) { var dragData = Zotero.DragDrop.getDragData(this); } if (!dragData) { Zotero.debug("No drag data"); return false; } var dataType = dragData.dataType; var data = dragData.data; if (dataType == 'zotero/item') { var ids = data; } var itemGroup = this._itemGroup; if (orient == 0) { var rowItem = this._getItemAtRow(row).ref; // the item we are dragging over } if (dataType == 'zotero/item') { var items = Zotero.Items.get(ids); // Directly on a row if (orient == 0) { var canDrop = false; for each(var item in items) { // If any regular items, disallow drop if (item.isRegularItem()) { return false; } // Disallow cross-library child drag if (item.libraryID != itemGroup.ref.libraryID) { return false; } // Only allow dragging of notes and attachments // that aren't already children of the item if (item.getSource() != rowItem.id) { canDrop = true; } } return canDrop; } // In library, allow children to be dragged out of parent else if (itemGroup.isLibrary(true) || itemGroup.isCollection()) { for each(var item in items) { // Don't allow drag if any top-level items if (item.isTopLevelItem()) { return false; } // Don't allow web attachments to be dragged out of parents, // but do allow PDFs for now so they can be recognized if (item.isWebAttachment() && item.attachmentMIMEType != 'application/pdf') { return false; } // Don't allow children to be dragged within their own parents var parentItemID = item.getSource(); var parentIndex = this._itemRowMap[parentItemID]; if (this.getLevel(row) > 0) { if (this._getItemAtRow(this.getParentIndex(row)).ref.id == parentItemID) { return false; } } // Including immediately after the parent if (orient == 1) { if (row == parentIndex) { return false; } } // And immediately before the next parent if (orient == -1) { var nextParentIndex = null; for (var i = parentIndex + 1; i < this.rowCount; i++) { if (this.getLevel(i) == 0) { nextParentIndex = i; break; } } if (row === nextParentIndex) { return false; } } // Disallow cross-library child drag if (item.libraryID != itemGroup.ref.libraryID) { return false; } } return true; } return false; } else if (dataType == "text/x-moz-url" || dataType == 'application/x-moz-file') { // Disallow direct drop on a non-regular item (e.g. note) if (orient == 0) { if (!rowItem.isRegularItem()) { return false; } } // Don't allow drop into searches else if (itemGroup.isSearch()) { return false; } return true; } return false; } /* * Called when something's been dropped on or next to a row */ Zotero.ItemTreeView.prototype.drop = function(row, orient) { var dragData = Zotero.DragDrop.getDragData(this); if (!this.canDrop(row, orient, dragData)) { return false; } var dataType = dragData.dataType; var data = dragData.data; var itemGroup = this._itemGroup; if (dataType == 'zotero/item') { var ids = data; var items = Zotero.Items.get(ids); if (items.length < 1) { return; } // Dropped directly on a row if (orient == 0) { // Set drop target as the parent item for dragged items // // canDrop() limits this to child items var rowItem = this._getItemAtRow(row).ref; // the item we are dragging over for each(var item in items) { item.setSource(rowItem.id); item.save(); } } // Dropped outside of a row else { // Remove from parent and make top-level if (itemGroup.isLibrary(true)) { for each(var item in items) { if (!item.isRegularItem()) { item.setSource(); item.save() } } } // Add to collection else { for each(var item in items) { var source = item.isRegularItem() ? false : item.getSource(); // Top-level item if (source) { item.setSource(); item.save() } itemGroup.ref.addItem(item.id); } } } } else if (dataType == 'text/x-moz-url' || dataType == 'application/x-moz-file') { // Disallow drop into read-only libraries if (!itemGroup.editable) { var wm = Components.classes["@mozilla.org/appshell/window-mediator;1"] .getService(Components.interfaces.nsIWindowMediator); var win = wm.getMostRecentWindow("navigator:browser"); win.ZoteroPane.displayCannotEditLibraryMessage(); return; } if (itemGroup.isWithinGroup()) { var targetLibraryID = itemGroup.ref.libraryID; } else { var targetLibraryID = null; } var sourceItemID = false; var parentCollectionID = false; var treerow = this._getItemAtRow(row); if (orient == 0) { sourceItemID = treerow.ref.id } else if (itemGroup.isCollection()) { var parentCollectionID = itemGroup.ref.id; } var unlock = Zotero.Notifier.begin(true); try { for (var i=0; i<data.length; i++) { var file = data[i]; if (dataType == 'text/x-moz-url') { var url = data[i]; if (url.indexOf('file:///') == 0) { var wm = Components.classes["@mozilla.org/appshell/window-mediator;1"] .getService(Components.interfaces.nsIWindowMediator); var win = wm.getMostRecentWindow("navigator:browser"); // If dragging currently loaded page, only convert to // file if not an HTML document if (win.content.location.href != url || win.content.document.contentType != 'text/html') { var nsIFPH = Components.classes["@mozilla.org/network/protocol;1?name=file"] .getService(Components.interfaces.nsIFileProtocolHandler); try { var file = nsIFPH.getFileFromURLSpec(url); } catch (e) { Zotero.debug(e); } } } // Still string, so remote URL if (typeof file == 'string') { if (sourceItemID) { if (!itemGroup.filesEditable) { var wm = Components.classes["@mozilla.org/appshell/window-mediator;1"] .getService(Components.interfaces.nsIWindowMediator); var win = wm.getMostRecentWindow("navigator:browser"); win.ZoteroPane.displayCannotEditLibraryFilesMessage(); return; } Zotero.Attachments.importFromURL(url, sourceItemID, false, false, null, null, targetLibraryID); } else { var wm = Components.classes["@mozilla.org/appshell/window-mediator;1"] .getService(Components.interfaces.nsIWindowMediator); var win = wm.getMostRecentWindow("navigator:browser"); win.ZoteroPane.addItemFromURL(url, 'temporaryPDFHack'); // TODO: don't do this } continue; } // Otherwise file, so fall through } try { Zotero.DB.beginTransaction(); var itemID = Zotero.Attachments.importFromFile(file, sourceItemID, targetLibraryID); if (parentCollectionID) { var col = Zotero.Collections.get(parentCollectionID); if (col) { col.addItem(itemID); } } Zotero.DB.commitTransaction(); } catch (e) { Zotero.DB.rollbackTransaction(); throw (e); } } } finally { Zotero.Notifier.commit(unlock); } } } Zotero.ItemTreeView.prototype.onDragEnter = function (event) { //Zotero.debug("Storing current drag data"); Zotero.DragDrop.currentDataTransfer = event.dataTransfer; } /* * Called by HTML 5 Drag and Drop when dragging over the tree */ Zotero.ItemTreeView.prototype.onDragOver = function (event, dropdata, session) { return false; } /* * Called by HTML 5 Drag and Drop when dropping onto the tree */ Zotero.ItemTreeView.prototype.onDrop = function (event, dropdata, session) { return false; } Zotero.ItemTreeView.prototype.onDragExit = function (event) { //Zotero.debug("Clearing drag data"); Zotero.DragDrop.currentDataTransfer = null; } //////////////////////////////////////////////////////////////////////////////// /// /// Functions for nsITreeView that we have to stub out. /// //////////////////////////////////////////////////////////////////////////////// Zotero.ItemTreeView.prototype.isSeparator = function(row) { return false; } Zotero.ItemTreeView.prototype.getRowProperties = function(row, prop) {} Zotero.ItemTreeView.prototype.getColumnProperties = function(col, prop) {} Zotero.ItemTreeView.prototype.getCellProperties = function(row, col, prop) { var treeRow = this._getItemAtRow(row); var itemID = treeRow.ref.id; var props = []; // Mark items not matching search as context rows, displayed in gray if (this._searchMode && !this._searchItemIDs[itemID]) { // <=Fx21 if (prop) { var aServ = Components.classes["@mozilla.org/atom-service;1"]. getService(Components.interfaces.nsIAtomService); prop.AppendElement(aServ.getAtom("contextRow")); } // Fx22+ else { props.push("contextRow"); } } // Mark hasAttachment column, which needs special image handling if (col.id == 'zotero-items-column-hasAttachment') { // <=Fx21 if (prop) { var aServ = Components.classes["@mozilla.org/atom-service;1"]. getService(Components.interfaces.nsIAtomService); prop.AppendElement(aServ.getAtom("hasAttachment")); } // Fx22+ else { props.push("hasAttachment"); } // Don't show pie for open parent items, since we show it for the // child item if (this.isContainer(row) && this.isContainerOpen(row)) { return props.join(" "); } var num = Zotero.Sync.Storage.getItemDownloadImageNumber(treeRow.ref); //var num = Math.round(new Date().getTime() % 10000 / 10000 * 64); if (num !== false) { // <=Fx21 if (prop) { if (!aServ) { var aServ = Components.classes["@mozilla.org/atom-service;1"]. getService(Components.interfaces.nsIAtomService); } prop.AppendElement(aServ.getAtom("pie")); prop.AppendElement(aServ.getAtom("pie" + num)); } // Fx22+ else { props.push("pie", "pie" + num); } } } return props.join(" "); } Zotero.ItemTreeView.TreeRow = function(ref, level, isOpen) { this.ref = ref; //the item associated with this this.level = level; this.isOpen = isOpen; this.id = ref.id; } Zotero.ItemTreeView.TreeRow.prototype.getField = function(field, unformatted) { return this.ref.getField(field, unformatted, true); } Zotero.ItemTreeView.TreeRow.prototype.numNotes = function() { if (this.ref.isNote()) { return ''; } return this.ref.numNotes(false, true) || ''; }
Sort by title after creator and date, if not primary sort Addresses #275
chrome/content/zotero/xpcom/itemTreeView.js
Sort by title after creator and date, if not primary sort
<ide><path>hrome/content/zotero/xpcom/itemTreeView.js <ide> fieldB = b.getField('date', true).substr(0, 10); <ide> <ide> cmp = strcmp(fieldA, fieldB); <add> if (cmp !== 0) { <add> return cmp; <add> } <add> } <add> <add> if (columnField !== 'title') { <add> cmp = collation.compareString(1, b.getField('title', true), a.getField('title', true)); <ide> if (cmp !== 0) { <ide> return cmp; <ide> }
JavaScript
mit
f38b670b39b0408e542ec5b073426252fb66829b
0
h2non/domlight,h2non/domlight
/*! domlight - v.0.1.0 - MIT License - https://github.com/h2non/domlight */ (function (root, factory) { if (typeof define === 'function' && define.amd) { define(['exports'], factory) } else if (typeof exports === 'object') { factory(exports) if (typeof module === 'object' && module !== null) { module.exports = exports = exports.Domlight } } else { factory(root) } }(this, function (exports) { 'use strict' var VERSION = '0.1.0' var NODE_ID = 'focusable-overlay' var slice = Array.prototype.slice var hasOwn = Object.prototype.hasOwnProperty var defaults = { fadeDuration: 700, hideOnClick: false, hideOnESC: true, findOnResize: true } var elements = [] var columnWrapper = null var overlay = null var isSetup = false var isVisible = false var body = document.body var columnSelector = '#' + NODE_ID + ' .column' function Domlight(element, options) { if (element && element.length) { element = element[0] } else if (!(element instanceof HTMLElement)) { throw new TypeError('First argument should be a Node or jQuery/Zepto selector') } options = merge(merge({}, defaults), options) spotlightElement(element, options) return { element: element, options: options, isVisible: getVisibility, hide: function () { hide(element) } } } function getVisibility() { return isVisible } function setup(options) { var newDiv = document.createElement('div') newDiv.id = NODE_ID body.insertBefore(newDiv, body.firstChild) overlay = newDiv isSetup = true addEvents(options) addStylesheet(options) } function addEvents(options) { if (options.hideOnESC) { window.addEventListener('keyup', keyupHandler) } if (options.hideOnClick) { overlay.addEventListener('click', hideAll) } } function keyupHandler(event) { if (event.keyCode === 27 && isVisible) { hideAll() window.removeEventListener('keyup', keyupHandler) } } function onBodyReady(fn, args) { document.onreadystatechange = function () { if (document.readyState === 'complete') { body = document.body fn.apply(null, args) } } } function spotlightElement(element, options) { if (document.readyState !== 'complete') { return onBodyReady(spotlightElement, arguments) } else if (body == null) { body = document.body } if (isSetup === false) { setup(options) } setFocus(element, options) } function setFocus(element, options) { var styleEl = window.getComputedStyle(element) var position = styleEl.getPropertyValue('position') var zIndex = +styleEl.getPropertyValue('z-index') elements.push({ zIndex: zIndex, position: position, element: element }) body.style.overflow = 'hidden' if (position === 'static') { element.style.position = 'relative' } if (zIndex < 10000) { element.style.zIndex = 10000 } if (isVisible === false) { createColumns(element) } overlay.style.display = 'block' // the transition won't happen at the same time as display: block; create a short delay setTimeout(function() { overlay.style.opacity = '1' }, 50) } function hide(element) { var index = findElement(element) if (index) { restoreElementStyle(elements[index]) elements.splice(index, 1) } if (elements.length) { clearColumns() createColumns(elements[0].element) } else { hideAll() } } function findElement(element) { var index = -1 for (var i = 0, l = elements.length; i < l; i += 1) { if (elements[i].element === element) { index = i break } } return index } function hideAll() { isVisible = false body.style.overflow = '' overlay.style.display = 'none' clearColumns() elements.splice(0).forEach(restoreElementStyle) } function restoreElementStyle(node) { node.element.style.zIndex = node.zIndex node.element.style.position = node.position } function createColumns(element) { var createdColumns = 0 isVisible = true clearColumns() while (createdColumns < 4) { createColumn(element, createdColumns) createdColumns += 1 } } function createColumn(element, index) { var offset = element.getBoundingClientRect() var top = 0, left = 0, width = px(element.clientWidth), height = '100%' switch (index) { case 0: width = px(offset.left) break case 1: left = px(offset.left) height = px(offset.top) break case 2: left = px(offset.left) top = px(element.clientHeight + offset.top) break case 3: width = '100%' left = px(element.clientWidth + offset.left) break } var styles = 'top:' + top + ';left:' + left + ';width:' + width + ';height:' + height var column = createColumnDivisor(styles) overlay.appendChild(column) } function createColumnDivisor(styles) { var column = document.createElement('div') column.className = 'column' column.setAttribute('style', styles) return column } function clearColumns() { var columns = overlay.querySelectorAll('#' + NODE_ID + ' .column') for (var i = 0, l = columns.length; i < l; i += 1) { columns[i].parentNode.removeChild(columns[i]) } } function px(value) { return value + 'px' } function addStylesheet(options) { var sheet = appendStylesheet() sheet.insertRule('#' + NODE_ID + '{' + + 'display:none;' + 'opacity:0;' + 'transition: opacity ' + options.fadeDuration + 'ms;' + 'position: absolute;' + 'top: 0;' + 'left: 0;' + 'width: 100%;' + 'height: 100%;' + 'z-index: 9999;' + 'overflow: hidden;' + 'pointer-events: none;' + '}', 0) sheet.insertRule('#' + NODE_ID + ' .column' + '{' + 'position: absolute;' + 'background: rgba(0,0,0,0.8);' + 'pointer-events: all;' + '}', 1) } function appendStylesheet() { var style = document.createElement('style') style.appendChild(document.createTextNode('')) document.head.appendChild(style) return style.sheet } function getActiveElements() { return elements.map(function (node) { return node.element }) } function merge(target, source) { for (var key in source) if (hasOwn.call(source, key)) { target[key] = source[key] } return target } exports.Domlight = Domlight Domlight.defaults = defaults Domlight.hideAll = hideAll Domlight.isVisible = getVisibility Domlight.getActiveElements = getActiveElements Domlight.VERSION = VERSION }))
domlight.js
/*! domlight - v.0.1.0 - MIT License - https://github.com/h2non/domlight */ (function (root, factory) { if (typeof define === 'function' && define.amd) { define(['exports'], factory) } else if (typeof exports === 'object') { factory(exports) if (typeof module === 'object' && module !== null) { module.exports = exports = exports.Domlight } } else { factory(root) } }(this, function (exports) { 'use strict' var VERSION = '0.1.0' var NODE_ID = 'focusable-overlay' var slice = Array.prototype.slice var hasOwn = Object.prototype.hasOwnProperty var defaults = { fadeDuration: 700, hideOnClick: false, hideOnESC: true, findOnResize: true } var elements = [] var columnWrapper = null var overlay = null var isSetup = false var isVisible = false var body = document.body var columnSelector = '#' + NODE_ID + ' .column' function Domlight(element, options) { if (element && element.length) { element = element[0] } else if (!(element instanceof HTMLElement)) { throw new TypeError('First argument should be a Node or jQuery/Zepto selector') } options = merge(merge({}, defaults), options) spotlightElement(element, options) return { element: element, options: options, isVisible: getVisibility, hide: function () { hide(element) } } } function getVisibility() { return isVisible } function setup(options) { var newDiv = document.createElement('div') newDiv.id = NODE_ID body.insertBefore(newDiv, body.firstChild) overlay = newDiv isSetup = true addEvents(options) addStylesheet(options) } function addEvents(options) { if (options.hideOnESC) { window.addEventListener('keyup', keyupHandler) } if (options.hideOnClick) { overlay.addEventListener('click', hideAll) } } function keyupHandler(event) { if (event.keyCode === 27 && isVisible) { hideAll() window.removeEventListener('keyup', keyupHandler) } } function onBodyReady(fn, args) { document.onreadystatechange = function () { if (document.readyState === 'complete') { body = document.body fn.apply(null, args) } } } function spotlightElement(element, options) { if (document.readyState !== 'complete') { return onBodyReady(spotlightElement, arguments) } else if (body == null) { body = document.body } if (isSetup === false) { setup(options) } setFocus(element, options) } function setFocus(element, options) { var styleEl = window.getComputedStyle(element) elements.push({ zIndex: styleEl.getPropertyValue('z-index'), position: styleEl.getPropertyValue('z-index'), element: element }) body.style.overflow = 'hidden' element.style.position = 'relative' element.style.zIndex = 10000 if (isVisible === false) { createColumns(element) } overlay.style.display = 'block' // the transition won't happen at the same time as display: block; create a short delay setTimeout(function() { overlay.style.opacity = '1' }, 50) } function hide(element) { var index = findElement(element) if (index) { restoreElementStyle(elements[index]) elements.splice(index, 1) } if (elements.length) { clearColumns() createColumns(elements[0].element) } else { hideAll() } } function findElement(element) { var index = -1 for (var i = 0, l = elements.length; i < l; i += 1) { if (elements[i].element === element) { index = i break } } return index } function hideAll() { isVisible = false body.style.overflow = '' overlay.style.display = 'none' clearColumns() elements.splice(0).forEach(restoreElementStyle) } function restoreElementStyle(node) { node.element.style.zIndex = node.zIndex node.element.style.position = node.position } function createColumns(element) { var createdColumns = 0 isVisible = true clearColumns() while (createdColumns < 4) { createColumn(element, createdColumns) createdColumns += 1 } } function createColumn(element, index) { var offset = element.getBoundingClientRect() var top = 0, left = 0, width = px(element.clientWidth), height = '100%' switch (index) { case 0: width = px(offset.left) break case 1: left = px(offset.left) height = px(offset.top) break case 2: left = px(offset.left) top = px(element.clientHeight + offset.top) break case 3: width = '100%' left = px(element.clientWidth + offset.left) break } var styles = 'top:' + top + ';left:' + left + ';width:' + width + ';height:' + height var column = createColumnDivisor(styles) overlay.appendChild(column) } function createColumnDivisor(styles) { var column = document.createElement('div') column.className = 'column' column.setAttribute('style', styles) return column } function clearColumns() { var columns = overlay.querySelectorAll('#' + NODE_ID + ' .column') for (var i = 0, l = columns.length; i < l; i += 1) { columns[i].parentNode.removeChild(columns[i]) } } function px(value) { return value + 'px' } function addStylesheet(options) { var sheet = appendStylesheet() sheet.insertRule('#' + NODE_ID + '{' + + 'display:none;' + 'opacity:0;' + 'transition: opacity ' + options.fadeDuration + 'ms;' + 'position: absolute;' + 'top: 0;' + 'left: 0;' + 'width: 100%;' + 'height: 100%;' + 'z-index: 9999;' + 'overflow: hidden;' + 'pointer-events: none;' + '}', 0) sheet.insertRule('#' + NODE_ID + ' .column' + '{' + 'position: absolute;' + 'background: rgba(0,0,0,0.8);' + 'pointer-events: all;' + '}', 1) } function appendStylesheet() { var style = document.createElement('style') style.appendChild(document.createTextNode('')) document.head.appendChild(style) return style.sheet } function getActiveElements() { return elements.map(function (node) { return node.element }) } function merge(target, source) { for (var key in source) if (hasOwn.call(source, key)) { target[key] = source[key] } return target } exports.Domlight = Domlight Domlight.defaults = defaults Domlight.hideAll = hideAll Domlight.isVisible = getVisibility Domlight.getActiveElements = getActiveElements Domlight.VERSION = VERSION }))
fix(style): multiple elements style
domlight.js
fix(style): multiple elements style
<ide><path>omlight.js <ide> <ide> function setFocus(element, options) { <ide> var styleEl = window.getComputedStyle(element) <add> var position = styleEl.getPropertyValue('position') <add> var zIndex = +styleEl.getPropertyValue('z-index') <ide> <ide> elements.push({ <del> zIndex: styleEl.getPropertyValue('z-index'), <del> position: styleEl.getPropertyValue('z-index'), <add> zIndex: zIndex, <add> position: position, <ide> element: element <ide> }) <ide> <ide> body.style.overflow = 'hidden' <del> element.style.position = 'relative' <del> element.style.zIndex = 10000 <add> if (position === 'static') { <add> element.style.position = 'relative' <add> } <add> if (zIndex < 10000) { <add> element.style.zIndex = 10000 <add> } <ide> <ide> if (isVisible === false) { <ide> createColumns(element)
JavaScript
bsd-3-clause
10bb0c7a58f55803ac95ae456f38a7cfbc1331da
0
maier49/dgrid,dylans/dgrid,maier49/dgrid,kfranqueiro/dgrid,dylans/dgrid,kfranqueiro/dgrid,dylans/dgrid,kfranqueiro/dgrid,maier49/dgrid
define([ 'dojo/_base/declare', 'dojo/_base/lang', 'dojo/Deferred', 'dstore/Memory', 'dstore/Trackable', 'dstore/QueryResults' ], function (declare, lang, Deferred, Memory, Trackable, QueryResults) { // summary: // Creates a store that wraps the delegate store's query results and total in Deferred // instances. If delay is set, the Deferreds will be resolved asynchronously after delay +/-50% // milliseconds to simulate network requests that may come back out of order. var AsyncStore = declare(Memory, { delay: 200, randomizeDelay: false, fetch: function () { var actualData = this.fetchSync(); var actualTotal = actualData.totalLength; var resultsDeferred = new Deferred(); var totalDeferred = new Deferred(); function resolveResults() { resultsDeferred.resolve(actualData); } function resolveTotal() { totalDeferred.resolve(actualTotal); } setTimeout(resolveTotal, this.delay * (this.randomizeDelay ? Math.random() + 0.5 : 1)); setTimeout(resolveResults, this.delay * (this.randomizeDelay ? Math.random() + 0.5 : 1)); return new QueryResults(resultsDeferred, { totalLength: totalDeferred }); }, fetchRange: function (kwArgs) { // dstore/Memory#fetchRange always uses fetchSync, which we aren't extending, // so we need to extend this as well. var results = this.fetch(); return new QueryResults(results.then(function (data) { return data.slice(kwArgs.start, kwArgs.end); }), { totalLength: results.then(function (data) { return data.length; }) }); } }); var TrackableAsyncStore = declare([ AsyncStore, Trackable ]); return function (kwArgs, Mixin) { kwArgs = kwArgs || {}; if (kwArgs.data) { kwArgs = lang.mixin({}, kwArgs, { data: lang.clone(kwArgs.data) }); } var Ctor = Mixin ? declare([TrackableAsyncStore, Mixin]) : TrackableAsyncStore; return new Ctor(kwArgs); }; });
test/data/createAsyncStore.js
define([ 'dojo/_base/declare', 'dojo/_base/lang', 'dojo/Deferred', 'dstore/Memory', 'dstore/Trackable', 'dstore/QueryResults' ], function (declare, lang, Deferred, Memory, Trackable, QueryResults) { // summary: // Creates a store that wraps the delegate store's query results and total in Deferred // instances. If delay is set, the Deferreds will be resolved asynchronously after delay +/-50% // milliseconds to simulate network requests that may come back out of order. var AsyncStore = declare(Memory, { delay: 200, randomizeDelay: false, fetch: function () { var actualData = this.fetchSync(); var actualTotal = actualData.totalLength; var resultsDeferred = new Deferred(); var totalDeferred = new Deferred(); function resolveResults() { resultsDeferred.resolve(actualData); } function resolveTotal() { totalDeferred.resolve(actualTotal); } setTimeout(resolveTotal, this.delay * (this.randomizeDelay ? Math.random() + 0.5 : 1)); setTimeout(resolveResults, this.delay * (this.randomizeDelay ? Math.random() + 0.5 : 1)); return new QueryResults(resultsDeferred, { totalLength: totalDeferred }); }, fetchRange: function (kwArgs) { // dstore/Memory currently handles the data as potentially async // but not the length. // TODO: Revisit/remove when dstore is always-promise. var results = this.fetch(); return new QueryResults(results.then(function (data) { return data.slice(kwArgs.start, kwArgs.end); }), { totalLength: results.then(function (data) { return data.length; }) }); } }); var TrackableAsyncStore = declare([ AsyncStore, Trackable ]); return function (kwArgs, Mixin) { kwArgs = kwArgs || {}; if (kwArgs.data) { kwArgs = lang.mixin({}, kwArgs, { data: lang.clone(kwArgs.data) }); } var Ctor = Mixin ? declare([TrackableAsyncStore, Mixin]) : TrackableAsyncStore; return new Ctor(kwArgs); }; });
createAsyncStore: Remove obsolete TODO
test/data/createAsyncStore.js
createAsyncStore: Remove obsolete TODO
<ide><path>est/data/createAsyncStore.js <ide> }, <ide> <ide> fetchRange: function (kwArgs) { <del> // dstore/Memory currently handles the data as potentially async <del> // but not the length. <del> // TODO: Revisit/remove when dstore is always-promise. <add> // dstore/Memory#fetchRange always uses fetchSync, which we aren't extending, <add> // so we need to extend this as well. <add> <ide> var results = this.fetch(); <ide> return new QueryResults(results.then(function (data) { <ide> return data.slice(kwArgs.start, kwArgs.end); <ide> }); <ide> <ide> var TrackableAsyncStore = declare([ AsyncStore, Trackable ]); <del> <add> <ide> return function (kwArgs, Mixin) { <ide> kwArgs = kwArgs || {}; <ide>
Java
mpl-2.0
abf9cc12a2b8b34485910a9e6617d9535a82cacd
0
mozilla-mobile/focus-android,Achintya999/focus-android,pocmo/focus-android,codebu5ter/focus-android,jonalmeida/focus-android,pocmo/focus-android,Benestar/focus-android,ekager/focus-android,mozilla-mobile/focus-android,Benestar/focus-android,Achintya999/focus-android,liuche/focus-android,Benestar/focus-android,codebu5ter/focus-android,liuche/focus-android,ekager/focus-android,layely/focus-android,pocmo/focus-android,jonalmeida/focus-android,Benestar/focus-android,layely/focus-android,pocmo/focus-android,layely/focus-android,mozilla-mobile/focus-android,pocmo/focus-android,layely/focus-android,mozilla-mobile/focus-android,layely/focus-android,liuche/focus-android,liuche/focus-android,pocmo/focus-android,codebu5ter/focus-android,jonalmeida/focus-android,mastizada/focus-android,ekager/focus-android,codebu5ter/focus-android,liuche/focus-android,ekager/focus-android,ekager/focus-android,Achintya999/focus-android,mastizada/focus-android,mastizada/focus-android,liuche/focus-android,jonalmeida/focus-android,jonalmeida/focus-android,mozilla-mobile/focus-android,Benestar/focus-android,ekager/focus-android,mozilla-mobile/focus-android,mastizada/focus-android,mastizada/focus-android,jonalmeida/focus-android,Achintya999/focus-android
/* -*- Mode: Java; c-basic-offset: 4; tab-width: 20; indent-tabs-mode: nil; -*- * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package org.mozilla.focus.utils; import android.content.Context; import android.content.SharedPreferences; import android.content.res.Resources; import android.preference.PreferenceManager; import android.support.annotation.Nullable; import org.mozilla.focus.BuildConfig; import org.mozilla.focus.R; import org.mozilla.focus.fragment.FirstrunFragment; import org.mozilla.focus.search.SearchEngine; /** * A simple wrapper for SharedPreferences that makes reading preference a little bit easier. */ public class Settings { private final SharedPreferences preferences; private final Resources resources; public Settings(Context context) { preferences = PreferenceManager.getDefaultSharedPreferences(context); resources = context.getResources(); } public boolean shouldBlockImages() { return preferences.getBoolean( resources.getString(R.string.pref_key_performance_block_images), false); } public boolean shouldShowFirstrun() { return !preferences.getBoolean(FirstrunFragment.FIRSTRUN_PREF, false); } public boolean shouldUseSecureMode() { // Always allow screenshots in debug builds - it's really hard to get UX feedback // without screenshots. if (BuildConfig.BUILD_TYPE.equals("debug")) { return false; } return preferences.getBoolean( resources.getString(R.string.pref_key_secure), true); } @Nullable public String getDefaultSearchEngineName() { return preferences.getString( resources.getString(R.string.pref_key_search_engine), null); } public void setDefaultSearchEngine(SearchEngine searchEngine) { preferences.edit() .putString(resources.getString(R.string.pref_key_search_engine), searchEngine.getName()) .apply(); } }
app/src/main/java/org/mozilla/focus/utils/Settings.java
/* -*- Mode: Java; c-basic-offset: 4; tab-width: 20; indent-tabs-mode: nil; -*- * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package org.mozilla.focus.utils; import android.content.Context; import android.content.SharedPreferences; import android.content.res.Resources; import android.preference.PreferenceManager; import android.support.annotation.Nullable; import org.mozilla.focus.R; import org.mozilla.focus.fragment.FirstrunFragment; import org.mozilla.focus.search.SearchEngine; /** * A simple wrapper for SharedPreferences that makes reading preference a little bit easier. */ public class Settings { private final SharedPreferences preferences; private final Resources resources; public Settings(Context context) { preferences = PreferenceManager.getDefaultSharedPreferences(context); resources = context.getResources(); } public boolean shouldBlockImages() { return preferences.getBoolean( resources.getString(R.string.pref_key_performance_block_images), false); } public boolean shouldShowFirstrun() { return !preferences.getBoolean(FirstrunFragment.FIRSTRUN_PREF, false); } public boolean shouldUseSecureMode() { return preferences.getBoolean( resources.getString(R.string.pref_key_secure), true); } @Nullable public String getDefaultSearchEngineName() { return preferences.getString( resources.getString(R.string.pref_key_search_engine), null); } public void setDefaultSearchEngine(SearchEngine searchEngine) { preferences.edit() .putString(resources.getString(R.string.pref_key_search_engine), searchEngine.getName()) .apply(); } }
Disable SECURE mode in debug builds
app/src/main/java/org/mozilla/focus/utils/Settings.java
Disable SECURE mode in debug builds
<ide><path>pp/src/main/java/org/mozilla/focus/utils/Settings.java <ide> import android.preference.PreferenceManager; <ide> import android.support.annotation.Nullable; <ide> <add>import org.mozilla.focus.BuildConfig; <ide> import org.mozilla.focus.R; <ide> import org.mozilla.focus.fragment.FirstrunFragment; <ide> import org.mozilla.focus.search.SearchEngine; <ide> } <ide> <ide> public boolean shouldUseSecureMode() { <add> // Always allow screenshots in debug builds - it's really hard to get UX feedback <add> // without screenshots. <add> if (BuildConfig.BUILD_TYPE.equals("debug")) { <add> return false; <add> } <add> <ide> return preferences.getBoolean( <ide> resources.getString(R.string.pref_key_secure), <ide> true);
Java
apache-2.0
3ba9c7723e5724047fb52af1d49bfb0a689ae593
0
Distrotech/intellij-community,ernestp/consulo,ahb0327/intellij-community,akosyakov/intellij-community,allotria/intellij-community,salguarnieri/intellij-community,ibinti/intellij-community,ThiagoGarciaAlves/intellij-community,gnuhub/intellij-community,apixandru/intellij-community,vladmm/intellij-community,fitermay/intellij-community,apixandru/intellij-community,adedayo/intellij-community,kdwink/intellij-community,ahb0327/intellij-community,izonder/intellij-community,FHannes/intellij-community,xfournet/intellij-community,fitermay/intellij-community,ThiagoGarciaAlves/intellij-community,semonte/intellij-community,ahb0327/intellij-community,fitermay/intellij-community,da1z/intellij-community,ThiagoGarciaAlves/intellij-community,youdonghai/intellij-community,caot/intellij-community,vladmm/intellij-community,robovm/robovm-studio,caot/intellij-community,da1z/intellij-community,semonte/intellij-community,youdonghai/intellij-community,retomerz/intellij-community,robovm/robovm-studio,ol-loginov/intellij-community,Lekanich/intellij-community,kdwink/intellij-community,ThiagoGarciaAlves/intellij-community,TangHao1987/intellij-community,tmpgit/intellij-community,nicolargo/intellij-community,idea4bsd/idea4bsd,samthor/intellij-community,ftomassetti/intellij-community,ol-loginov/intellij-community,da1z/intellij-community,MichaelNedzelsky/intellij-community,ahb0327/intellij-community,semonte/intellij-community,adedayo/intellij-community,izonder/intellij-community,allotria/intellij-community,fitermay/intellij-community,hurricup/intellij-community,jagguli/intellij-community,Distrotech/intellij-community,Distrotech/intellij-community,retomerz/intellij-community,hurricup/intellij-community,idea4bsd/idea4bsd,akosyakov/intellij-community,apixandru/intellij-community,allotria/intellij-community,idea4bsd/idea4bsd,hurricup/intellij-community,caot/intellij-community,kool79/intellij-community,alphafoobar/intellij-community,tmpgit/intellij-community,apixandru/intellij-community,vvv1559/intellij-community,ftomassetti/intellij-community,kdwink/intellij-community,supersven/intellij-community,xfournet/intellij-community,gnuhub/intellij-community,ftomassetti/intellij-community,suncycheng/intellij-community,fnouama/intellij-community,vvv1559/intellij-community,muntasirsyed/intellij-community,fnouama/intellij-community,caot/intellij-community,blademainer/intellij-community,ahb0327/intellij-community,muntasirsyed/intellij-community,vladmm/intellij-community,michaelgallacher/intellij-community,MER-GROUP/intellij-community,muntasirsyed/intellij-community,slisson/intellij-community,retomerz/intellij-community,FHannes/intellij-community,dslomov/intellij-community,asedunov/intellij-community,amith01994/intellij-community,wreckJ/intellij-community,gnuhub/intellij-community,youdonghai/intellij-community,adedayo/intellij-community,ftomassetti/intellij-community,caot/intellij-community,fengbaicanhe/intellij-community,slisson/intellij-community,Lekanich/intellij-community,blademainer/intellij-community,fnouama/intellij-community,diorcety/intellij-community,tmpgit/intellij-community,asedunov/intellij-community,pwoodworth/intellij-community,pwoodworth/intellij-community,TangHao1987/intellij-community,semonte/intellij-community,FHannes/intellij-community,idea4bsd/idea4bsd,akosyakov/intellij-community,ol-loginov/intellij-community,lucafavatella/intellij-community,salguarnieri/intellij-community,Lekanich/intellij-community,akosyakov/intellij-community,jagguli/intellij-community,adedayo/intellij-community,kool79/intellij-community,amith01994/intellij-community,nicolargo/intellij-community,ftomassetti/intellij-community,wreckJ/intellij-community,clumsy/intellij-community,michaelgallacher/intellij-community,supersven/intellij-community,tmpgit/intellij-community,dslomov/intellij-community,diorcety/intellij-community,ibinti/intellij-community,gnuhub/intellij-community,ThiagoGarciaAlves/intellij-community,kdwink/intellij-community,allotria/intellij-community,ThiagoGarciaAlves/intellij-community,fengbaicanhe/intellij-community,salguarnieri/intellij-community,amith01994/intellij-community,ol-loginov/intellij-community,vladmm/intellij-community,supersven/intellij-community,ryano144/intellij-community,MER-GROUP/intellij-community,slisson/intellij-community,supersven/intellij-community,vvv1559/intellij-community,da1z/intellij-community,vladmm/intellij-community,kdwink/intellij-community,MichaelNedzelsky/intellij-community,orekyuu/intellij-community,fnouama/intellij-community,clumsy/intellij-community,TangHao1987/intellij-community,ivan-fedorov/intellij-community,dslomov/intellij-community,FHannes/intellij-community,alphafoobar/intellij-community,MichaelNedzelsky/intellij-community,amith01994/intellij-community,kool79/intellij-community,mglukhikh/intellij-community,vladmm/intellij-community,da1z/intellij-community,SerCeMan/intellij-community,suncycheng/intellij-community,ahb0327/intellij-community,akosyakov/intellij-community,ahb0327/intellij-community,TangHao1987/intellij-community,ernestp/consulo,da1z/intellij-community,TangHao1987/intellij-community,ryano144/intellij-community,suncycheng/intellij-community,clumsy/intellij-community,SerCeMan/intellij-community,apixandru/intellij-community,lucafavatella/intellij-community,Distrotech/intellij-community,caot/intellij-community,SerCeMan/intellij-community,diorcety/intellij-community,orekyuu/intellij-community,orekyuu/intellij-community,salguarnieri/intellij-community,izonder/intellij-community,ol-loginov/intellij-community,TangHao1987/intellij-community,amith01994/intellij-community,asedunov/intellij-community,nicolargo/intellij-community,samthor/intellij-community,ibinti/intellij-community,alphafoobar/intellij-community,wreckJ/intellij-community,FHannes/intellij-community,idea4bsd/idea4bsd,blademainer/intellij-community,lucafavatella/intellij-community,Lekanich/intellij-community,salguarnieri/intellij-community,diorcety/intellij-community,gnuhub/intellij-community,kool79/intellij-community,amith01994/intellij-community,signed/intellij-community,vladmm/intellij-community,kool79/intellij-community,FHannes/intellij-community,suncycheng/intellij-community,lucafavatella/intellij-community,allotria/intellij-community,fnouama/intellij-community,MER-GROUP/intellij-community,pwoodworth/intellij-community,xfournet/intellij-community,ivan-fedorov/intellij-community,slisson/intellij-community,gnuhub/intellij-community,mglukhikh/intellij-community,adedayo/intellij-community,xfournet/intellij-community,pwoodworth/intellij-community,kool79/intellij-community,caot/intellij-community,holmes/intellij-community,suncycheng/intellij-community,ThiagoGarciaAlves/intellij-community,ThiagoGarciaAlves/intellij-community,dslomov/intellij-community,FHannes/intellij-community,retomerz/intellij-community,kdwink/intellij-community,muntasirsyed/intellij-community,caot/intellij-community,wreckJ/intellij-community,youdonghai/intellij-community,orekyuu/intellij-community,idea4bsd/idea4bsd,idea4bsd/idea4bsd,fitermay/intellij-community,TangHao1987/intellij-community,apixandru/intellij-community,amith01994/intellij-community,fitermay/intellij-community,petteyg/intellij-community,ivan-fedorov/intellij-community,michaelgallacher/intellij-community,michaelgallacher/intellij-community,slisson/intellij-community,MichaelNedzelsky/intellij-community,MichaelNedzelsky/intellij-community,allotria/intellij-community,supersven/intellij-community,ivan-fedorov/intellij-community,kool79/intellij-community,xfournet/intellij-community,Lekanich/intellij-community,petteyg/intellij-community,lucafavatella/intellij-community,ftomassetti/intellij-community,ftomassetti/intellij-community,salguarnieri/intellij-community,kool79/intellij-community,clumsy/intellij-community,ivan-fedorov/intellij-community,muntasirsyed/intellij-community,ThiagoGarciaAlves/intellij-community,semonte/intellij-community,Distrotech/intellij-community,robovm/robovm-studio,mglukhikh/intellij-community,michaelgallacher/intellij-community,samthor/intellij-community,pwoodworth/intellij-community,blademainer/intellij-community,jagguli/intellij-community,mglukhikh/intellij-community,apixandru/intellij-community,semonte/intellij-community,ivan-fedorov/intellij-community,asedunov/intellij-community,mglukhikh/intellij-community,fengbaicanhe/intellij-community,nicolargo/intellij-community,vladmm/intellij-community,pwoodworth/intellij-community,idea4bsd/idea4bsd,xfournet/intellij-community,dslomov/intellij-community,orekyuu/intellij-community,dslomov/intellij-community,semonte/intellij-community,fnouama/intellij-community,MER-GROUP/intellij-community,tmpgit/intellij-community,asedunov/intellij-community,samthor/intellij-community,izonder/intellij-community,tmpgit/intellij-community,asedunov/intellij-community,muntasirsyed/intellij-community,nicolargo/intellij-community,salguarnieri/intellij-community,ryano144/intellij-community,robovm/robovm-studio,samthor/intellij-community,ibinti/intellij-community,ThiagoGarciaAlves/intellij-community,fitermay/intellij-community,ibinti/intellij-community,dslomov/intellij-community,kool79/intellij-community,samthor/intellij-community,fitermay/intellij-community,slisson/intellij-community,ftomassetti/intellij-community,clumsy/intellij-community,mglukhikh/intellij-community,hurricup/intellij-community,youdonghai/intellij-community,fnouama/intellij-community,MER-GROUP/intellij-community,vvv1559/intellij-community,SerCeMan/intellij-community,kdwink/intellij-community,da1z/intellij-community,samthor/intellij-community,SerCeMan/intellij-community,FHannes/intellij-community,hurricup/intellij-community,hurricup/intellij-community,gnuhub/intellij-community,alphafoobar/intellij-community,xfournet/intellij-community,da1z/intellij-community,lucafavatella/intellij-community,supersven/intellij-community,blademainer/intellij-community,asedunov/intellij-community,idea4bsd/idea4bsd,orekyuu/intellij-community,xfournet/intellij-community,kool79/intellij-community,caot/intellij-community,petteyg/intellij-community,jagguli/intellij-community,consulo/consulo,wreckJ/intellij-community,ol-loginov/intellij-community,vvv1559/intellij-community,dslomov/intellij-community,ol-loginov/intellij-community,izonder/intellij-community,fengbaicanhe/intellij-community,semonte/intellij-community,MER-GROUP/intellij-community,retomerz/intellij-community,wreckJ/intellij-community,allotria/intellij-community,Lekanich/intellij-community,signed/intellij-community,alphafoobar/intellij-community,diorcety/intellij-community,fengbaicanhe/intellij-community,amith01994/intellij-community,vvv1559/intellij-community,ibinti/intellij-community,amith01994/intellij-community,ryano144/intellij-community,ftomassetti/intellij-community,blademainer/intellij-community,samthor/intellij-community,apixandru/intellij-community,suncycheng/intellij-community,slisson/intellij-community,fnouama/intellij-community,MER-GROUP/intellij-community,adedayo/intellij-community,izonder/intellij-community,robovm/robovm-studio,TangHao1987/intellij-community,lucafavatella/intellij-community,Lekanich/intellij-community,blademainer/intellij-community,retomerz/intellij-community,holmes/intellij-community,akosyakov/intellij-community,fengbaicanhe/intellij-community,Distrotech/intellij-community,youdonghai/intellij-community,michaelgallacher/intellij-community,lucafavatella/intellij-community,tmpgit/intellij-community,wreckJ/intellij-community,asedunov/intellij-community,holmes/intellij-community,apixandru/intellij-community,signed/intellij-community,ol-loginov/intellij-community,SerCeMan/intellij-community,ahb0327/intellij-community,pwoodworth/intellij-community,robovm/robovm-studio,kool79/intellij-community,petteyg/intellij-community,nicolargo/intellij-community,ahb0327/intellij-community,hurricup/intellij-community,diorcety/intellij-community,xfournet/intellij-community,SerCeMan/intellij-community,vladmm/intellij-community,slisson/intellij-community,blademainer/intellij-community,fengbaicanhe/intellij-community,dslomov/intellij-community,caot/intellij-community,jagguli/intellij-community,MER-GROUP/intellij-community,orekyuu/intellij-community,MichaelNedzelsky/intellij-community,orekyuu/intellij-community,blademainer/intellij-community,clumsy/intellij-community,fitermay/intellij-community,orekyuu/intellij-community,mglukhikh/intellij-community,FHannes/intellij-community,ol-loginov/intellij-community,signed/intellij-community,dslomov/intellij-community,michaelgallacher/intellij-community,robovm/robovm-studio,allotria/intellij-community,alphafoobar/intellij-community,ryano144/intellij-community,blademainer/intellij-community,pwoodworth/intellij-community,orekyuu/intellij-community,gnuhub/intellij-community,da1z/intellij-community,ahb0327/intellij-community,muntasirsyed/intellij-community,asedunov/intellij-community,diorcety/intellij-community,muntasirsyed/intellij-community,izonder/intellij-community,wreckJ/intellij-community,lucafavatella/intellij-community,clumsy/intellij-community,signed/intellij-community,MichaelNedzelsky/intellij-community,petteyg/intellij-community,jagguli/intellij-community,apixandru/intellij-community,ernestp/consulo,wreckJ/intellij-community,jagguli/intellij-community,slisson/intellij-community,slisson/intellij-community,xfournet/intellij-community,petteyg/intellij-community,petteyg/intellij-community,kdwink/intellij-community,fnouama/intellij-community,ivan-fedorov/intellij-community,fnouama/intellij-community,robovm/robovm-studio,petteyg/intellij-community,slisson/intellij-community,consulo/consulo,SerCeMan/intellij-community,vladmm/intellij-community,youdonghai/intellij-community,wreckJ/intellij-community,izonder/intellij-community,jagguli/intellij-community,orekyuu/intellij-community,holmes/intellij-community,da1z/intellij-community,xfournet/intellij-community,ol-loginov/intellij-community,mglukhikh/intellij-community,ol-loginov/intellij-community,izonder/intellij-community,holmes/intellij-community,holmes/intellij-community,orekyuu/intellij-community,Lekanich/intellij-community,akosyakov/intellij-community,pwoodworth/intellij-community,hurricup/intellij-community,muntasirsyed/intellij-community,michaelgallacher/intellij-community,nicolargo/intellij-community,hurricup/intellij-community,akosyakov/intellij-community,tmpgit/intellij-community,diorcety/intellij-community,amith01994/intellij-community,akosyakov/intellij-community,izonder/intellij-community,amith01994/intellij-community,supersven/intellij-community,michaelgallacher/intellij-community,ryano144/intellij-community,ftomassetti/intellij-community,suncycheng/intellij-community,MichaelNedzelsky/intellij-community,FHannes/intellij-community,alphafoobar/intellij-community,retomerz/intellij-community,ernestp/consulo,gnuhub/intellij-community,consulo/consulo,ftomassetti/intellij-community,wreckJ/intellij-community,fengbaicanhe/intellij-community,idea4bsd/idea4bsd,salguarnieri/intellij-community,lucafavatella/intellij-community,consulo/consulo,ThiagoGarciaAlves/intellij-community,vladmm/intellij-community,semonte/intellij-community,MichaelNedzelsky/intellij-community,youdonghai/intellij-community,gnuhub/intellij-community,muntasirsyed/intellij-community,supersven/intellij-community,salguarnieri/intellij-community,muntasirsyed/intellij-community,Lekanich/intellij-community,Distrotech/intellij-community,asedunov/intellij-community,hurricup/intellij-community,SerCeMan/intellij-community,mglukhikh/intellij-community,samthor/intellij-community,Distrotech/intellij-community,MichaelNedzelsky/intellij-community,jagguli/intellij-community,nicolargo/intellij-community,jagguli/intellij-community,ibinti/intellij-community,alphafoobar/intellij-community,SerCeMan/intellij-community,retomerz/intellij-community,consulo/consulo,Lekanich/intellij-community,supersven/intellij-community,SerCeMan/intellij-community,mglukhikh/intellij-community,ftomassetti/intellij-community,retomerz/intellij-community,ahb0327/intellij-community,petteyg/intellij-community,kdwink/intellij-community,adedayo/intellij-community,SerCeMan/intellij-community,allotria/intellij-community,TangHao1987/intellij-community,alphafoobar/intellij-community,ivan-fedorov/intellij-community,MER-GROUP/intellij-community,apixandru/intellij-community,izonder/intellij-community,ernestp/consulo,MichaelNedzelsky/intellij-community,apixandru/intellij-community,da1z/intellij-community,Distrotech/intellij-community,nicolargo/intellij-community,diorcety/intellij-community,ryano144/intellij-community,ryano144/intellij-community,retomerz/intellij-community,tmpgit/intellij-community,holmes/intellij-community,alphafoobar/intellij-community,da1z/intellij-community,ivan-fedorov/intellij-community,asedunov/intellij-community,diorcety/intellij-community,blademainer/intellij-community,signed/intellij-community,lucafavatella/intellij-community,amith01994/intellij-community,akosyakov/intellij-community,holmes/intellij-community,ibinti/intellij-community,robovm/robovm-studio,TangHao1987/intellij-community,dslomov/intellij-community,supersven/intellij-community,FHannes/intellij-community,adedayo/intellij-community,petteyg/intellij-community,retomerz/intellij-community,vvv1559/intellij-community,youdonghai/intellij-community,suncycheng/intellij-community,suncycheng/intellij-community,youdonghai/intellij-community,fnouama/intellij-community,petteyg/intellij-community,signed/intellij-community,ThiagoGarciaAlves/intellij-community,apixandru/intellij-community,fitermay/intellij-community,idea4bsd/idea4bsd,da1z/intellij-community,mglukhikh/intellij-community,apixandru/intellij-community,retomerz/intellij-community,ibinti/intellij-community,fengbaicanhe/intellij-community,hurricup/intellij-community,robovm/robovm-studio,fengbaicanhe/intellij-community,nicolargo/intellij-community,semonte/intellij-community,adedayo/intellij-community,vladmm/intellij-community,ivan-fedorov/intellij-community,tmpgit/intellij-community,jagguli/intellij-community,MER-GROUP/intellij-community,ryano144/intellij-community,akosyakov/intellij-community,pwoodworth/intellij-community,mglukhikh/intellij-community,signed/intellij-community,salguarnieri/intellij-community,consulo/consulo,nicolargo/intellij-community,MER-GROUP/intellij-community,ol-loginov/intellij-community,MichaelNedzelsky/intellij-community,kdwink/intellij-community,vvv1559/intellij-community,muntasirsyed/intellij-community,fengbaicanhe/intellij-community,samthor/intellij-community,robovm/robovm-studio,blademainer/intellij-community,holmes/intellij-community,hurricup/intellij-community,alphafoobar/intellij-community,clumsy/intellij-community,michaelgallacher/intellij-community,Lekanich/intellij-community,salguarnieri/intellij-community,supersven/intellij-community,xfournet/intellij-community,signed/intellij-community,idea4bsd/idea4bsd,xfournet/intellij-community,vvv1559/intellij-community,michaelgallacher/intellij-community,hurricup/intellij-community,clumsy/intellij-community,FHannes/intellij-community,kdwink/intellij-community,diorcety/intellij-community,wreckJ/intellij-community,alphafoobar/intellij-community,ibinti/intellij-community,fitermay/intellij-community,ryano144/intellij-community,suncycheng/intellij-community,ivan-fedorov/intellij-community,holmes/intellij-community,adedayo/intellij-community,idea4bsd/idea4bsd,adedayo/intellij-community,allotria/intellij-community,semonte/intellij-community,fitermay/intellij-community,ryano144/intellij-community,MER-GROUP/intellij-community,caot/intellij-community,ivan-fedorov/intellij-community,ahb0327/intellij-community,allotria/intellij-community,asedunov/intellij-community,gnuhub/intellij-community,fnouama/intellij-community,signed/intellij-community,pwoodworth/intellij-community,ernestp/consulo,izonder/intellij-community,pwoodworth/intellij-community,samthor/intellij-community,fengbaicanhe/intellij-community,akosyakov/intellij-community,ibinti/intellij-community,vvv1559/intellij-community,jagguli/intellij-community,holmes/intellij-community,suncycheng/intellij-community,signed/intellij-community,youdonghai/intellij-community,Distrotech/intellij-community,clumsy/intellij-community,michaelgallacher/intellij-community,robovm/robovm-studio,allotria/intellij-community,supersven/intellij-community,ibinti/intellij-community,youdonghai/intellij-community,salguarnieri/intellij-community,dslomov/intellij-community,lucafavatella/intellij-community,Distrotech/intellij-community,Lekanich/intellij-community,retomerz/intellij-community,lucafavatella/intellij-community,kool79/intellij-community,tmpgit/intellij-community,nicolargo/intellij-community,ibinti/intellij-community,adedayo/intellij-community,allotria/intellij-community,TangHao1987/intellij-community,tmpgit/intellij-community,vvv1559/intellij-community,youdonghai/intellij-community,holmes/intellij-community,FHannes/intellij-community,fitermay/intellij-community,caot/intellij-community,semonte/intellij-community,kdwink/intellij-community,mglukhikh/intellij-community,TangHao1987/intellij-community,clumsy/intellij-community,suncycheng/intellij-community,vvv1559/intellij-community,samthor/intellij-community,ryano144/intellij-community,asedunov/intellij-community,slisson/intellij-community,clumsy/intellij-community,signed/intellij-community,diorcety/intellij-community,petteyg/intellij-community,semonte/intellij-community,signed/intellij-community,vvv1559/intellij-community,gnuhub/intellij-community,Distrotech/intellij-community
/* * Copyright 2000-2012 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.packageDependencies.ui; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.Iconable; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vcs.FileStatusManager; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiFile; import com.intellij.psi.PsiManager; import com.intellij.util.IconUtil; import org.jetbrains.annotations.Nullable; import javax.swing.*; import java.awt.*; import java.util.Map; import java.util.Set; public class FileNode extends PackageDependenciesNode implements Comparable<FileNode>{ private final VirtualFile myVFile; private final boolean myMarked; public FileNode(VirtualFile file, Project project, boolean marked) { super(project); myVFile = file; myMarked = marked; } public void fillFiles(Set<PsiFile> set, boolean recursively) { super.fillFiles(set, recursively); final PsiFile file = getFile(); if (file != null && file.isValid()) { set.add(file); } } public boolean hasUnmarked() { return !myMarked; } public boolean hasMarked() { return myMarked; } public String toString() { return myVFile.getName(); } public Icon getOpenIcon() { return getIcon(); } public Icon getClosedIcon() { return getIcon(); } private Icon getIcon() { return IconUtil.getIcon(myVFile, Iconable.ICON_FLAG_VISIBILITY | Iconable.ICON_FLAG_READ_STATUS, myProject); } public int getWeight() { return 5; } public int getContainingFiles() { return 1; } public PsiElement getPsiElement() { return getFile(); } public Color getColor() { if (myColor == null) { myColor = FileStatusManager.getInstance(myProject).getStatus(myVFile).getColor(); if (myColor == null) { myColor = NOT_CHANGED; } } return myColor == NOT_CHANGED ? null : myColor; } public boolean equals(Object o) { if (isEquals()){ return super.equals(o); } if (this == o) return true; if (!(o instanceof FileNode)) return false; final FileNode fileNode = (FileNode)o; if (!myVFile.equals(fileNode.myVFile)) return false; return true; } public int hashCode() { return myVFile.hashCode(); } public boolean isValid() { return myVFile != null && myVFile.isValid(); } @Override public boolean canSelectInLeftTree(final Map<PsiFile, Set<PsiFile>> deps) { return deps.containsKey(getFile()); } @Nullable private PsiFile getFile() { return myVFile.isValid() && !myProject.isDisposed() ? PsiManager.getInstance(myProject).findFile(myVFile) : null; } @Override public int compareTo(FileNode o) { final int compare = StringUtil.compare(myVFile != null ? myVFile.getFileType().getDefaultExtension() : null, o.myVFile != null ? o.myVFile.getFileType().getDefaultExtension() : null, true); if (compare != 0) return compare; return StringUtil.compare(toString(), o.toString(), true); } }
platform/lang-impl/src/com/intellij/packageDependencies/ui/FileNode.java
/* * Copyright 2000-2012 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.packageDependencies.ui; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.Iconable; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vcs.FileStatusManager; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiFile; import com.intellij.psi.PsiManager; import com.intellij.util.IconUtil; import org.jetbrains.annotations.Nullable; import javax.swing.*; import java.awt.*; import java.util.Map; import java.util.Set; public class FileNode extends PackageDependenciesNode implements Comparable<FileNode>{ private final VirtualFile myVFile; private final boolean myMarked; public FileNode(VirtualFile file, Project project, boolean marked) { super(project); myVFile = file; myMarked = marked; } public void fillFiles(Set<PsiFile> set, boolean recursively) { super.fillFiles(set, recursively); set.add(getFile()); } public boolean hasUnmarked() { return !myMarked; } public boolean hasMarked() { return myMarked; } public String toString() { return myVFile.getName(); } public Icon getOpenIcon() { return getIcon(); } public Icon getClosedIcon() { return getIcon(); } private Icon getIcon() { return IconUtil.getIcon(myVFile, Iconable.ICON_FLAG_VISIBILITY | Iconable.ICON_FLAG_READ_STATUS, myProject); } public int getWeight() { return 5; } public int getContainingFiles() { return 1; } public PsiElement getPsiElement() { return getFile(); } public Color getColor() { if (myColor == null) { myColor = FileStatusManager.getInstance(myProject).getStatus(myVFile).getColor(); if (myColor == null) { myColor = NOT_CHANGED; } } return myColor == NOT_CHANGED ? null : myColor; } public boolean equals(Object o) { if (isEquals()){ return super.equals(o); } if (this == o) return true; if (!(o instanceof FileNode)) return false; final FileNode fileNode = (FileNode)o; if (!myVFile.equals(fileNode.myVFile)) return false; return true; } public int hashCode() { return myVFile.hashCode(); } public boolean isValid() { return myVFile != null && myVFile.isValid(); } @Override public boolean canSelectInLeftTree(final Map<PsiFile, Set<PsiFile>> deps) { return deps.containsKey(getFile()); } @Nullable private PsiFile getFile() { return myVFile.isValid() && !myProject.isDisposed() ? PsiManager.getInstance(myProject).findFile(myVFile) : null; } @Override public int compareTo(FileNode o) { final int compare = StringUtil.compare(myVFile != null ? myVFile.getFileType().getDefaultExtension() : null, o.myVFile != null ? o.myVFile.getFileType().getDefaultExtension() : null, true); if (compare != 0) return compare; return StringUtil.compare(toString(), o.toString(), true); } }
EA-35337 - NPE: FindDependencyUtil.updateIndicator
platform/lang-impl/src/com/intellij/packageDependencies/ui/FileNode.java
EA-35337 - NPE: FindDependencyUtil.updateIndicator
<ide><path>latform/lang-impl/src/com/intellij/packageDependencies/ui/FileNode.java <ide> <ide> public void fillFiles(Set<PsiFile> set, boolean recursively) { <ide> super.fillFiles(set, recursively); <del> set.add(getFile()); <add> final PsiFile file = getFile(); <add> if (file != null && file.isValid()) { <add> set.add(file); <add> } <ide> } <ide> <ide> public boolean hasUnmarked() {
Java
lgpl-2.1
5b485f71e97ea250007a5e3eaf13f4bd4f230cf7
0
CreativeMD/LittleTiles
package com.creativemd.littletiles.common.structure; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map.Entry; import javax.annotation.Nullable; import com.creativemd.creativecore.common.utils.math.Rotation; import com.creativemd.creativecore.common.utils.mc.WorldUtils; import com.creativemd.creativecore.common.utils.type.HashMapList; import com.creativemd.creativecore.common.world.SubWorld; import com.creativemd.littletiles.LittleTiles; import com.creativemd.littletiles.common.action.LittleActionException; import com.creativemd.littletiles.common.action.block.LittleActionActivated; import com.creativemd.littletiles.common.entity.EntityAnimation; import com.creativemd.littletiles.common.structure.attribute.LittleStructureAttribute; import com.creativemd.littletiles.common.structure.connection.IStructureChildConnector; import com.creativemd.littletiles.common.structure.connection.StructureLink; import com.creativemd.littletiles.common.structure.connection.StructureLinkFromSubWorld; import com.creativemd.littletiles.common.structure.connection.StructureLinkTile; import com.creativemd.littletiles.common.structure.connection.StructureLinkToSubWorld; import com.creativemd.littletiles.common.structure.connection.StructureMainTile; import com.creativemd.littletiles.common.structure.exception.MissingTileEntity; import com.creativemd.littletiles.common.structure.registry.LittleStructureRegistry; import com.creativemd.littletiles.common.structure.registry.LittleStructureType; import com.creativemd.littletiles.common.structure.registry.LittleStructureType.StructureTypeRelative; import com.creativemd.littletiles.common.structure.relative.StructureRelative; import com.creativemd.littletiles.common.tileentity.TileEntityLittleTiles; import com.creativemd.littletiles.common.tiles.LittleTile; import com.creativemd.littletiles.common.tiles.LittleTile.LittleTilePosition; import com.creativemd.littletiles.common.tiles.place.PlacePreviewTile; import com.creativemd.littletiles.common.tiles.preview.LittleAbsolutePreviewsStructure; import com.creativemd.littletiles.common.tiles.preview.LittlePreviews; import com.creativemd.littletiles.common.tiles.preview.LittlePreviewsStructure; import com.creativemd.littletiles.common.tiles.preview.LittleTilePreview; import com.creativemd.littletiles.common.tiles.vec.LittleTileIdentifierRelative; import com.creativemd.littletiles.common.tiles.vec.LittleTileIdentifierStructureAbsolute; import com.creativemd.littletiles.common.tiles.vec.LittleTileIdentifierStructureRelative; import com.creativemd.littletiles.common.tiles.vec.LittleTilePos; import com.creativemd.littletiles.common.tiles.vec.LittleTileVec; import com.creativemd.littletiles.common.tiles.vec.LittleTileVecContext; import com.creativemd.littletiles.common.tiles.vec.RelativeBlockPos; import com.creativemd.littletiles.common.utils.grid.LittleGridContext; import com.creativemd.littletiles.common.utils.ingredients.LittleIngredients; import com.creativemd.littletiles.common.utils.vec.LittleTransformation; import com.creativemd.littletiles.common.utils.vec.SurroundingBox; import net.minecraft.block.state.IBlockState; import net.minecraft.entity.Entity; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.nbt.NBTTagIntArray; import net.minecraft.nbt.NBTTagList; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.EnumFacing; import net.minecraft.util.EnumFacing.Axis; import net.minecraft.util.EnumHand; import net.minecraft.util.math.AxisAlignedBB; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.BlockPos.MutableBlockPos; import net.minecraft.util.math.Vec3d; import net.minecraft.world.IBlockAccess; import net.minecraft.world.World; import net.minecraft.world.chunk.Chunk; public abstract class LittleStructure { private static final Iterator<LittleTile> EMPTY_ITERATOR = new Iterator<LittleTile>() { @Override public boolean hasNext() { return false; } @Override public LittleTile next() { return null; } }; private static final HashMapList<BlockPos, LittleTile> EMPTY_HASHMAPLIST = new HashMapList<>(); public static LittleStructure createAndLoadStructure(NBTTagCompound nbt, @Nullable LittleTile mainTile) { if (nbt == null) return null; String id = nbt.getString("id"); LittleStructureType type = LittleStructureRegistry.getStructureType(id); if (type != null) { LittleStructure structure = type.createStructure(); structure.mainTile = mainTile; structure.loadFromNBT(nbt); return structure; } else System.out.println("Could not find structureID=" + id); return null; } public final LittleStructureType type; public String name; /** The core of the structure. Handles saving & loading of the structures. * All tiles inside the structure connect to it in relative block positions and absolute identifier **/ private LittleTile mainTile; protected LittleTilePos lastMainTileVec = null; protected HashMapList<BlockPos, LittleTile> tiles = null; public LinkedHashMap<BlockPos, Integer> tilesToLoad = null; public IStructureChildConnector parent; public List<IStructureChildConnector> children; /** Used for placing and structures in item form */ private List<LittleStructure> tempChildren; public LittleStructure(LittleStructureType type) { this.type = type; } // ================Basics================ public World getWorld() { return mainTile.te.getWorld(); } public LittleStructureAttribute getAttribute() { return type.attribute; } // ================MainTile================ /** The core of the structure. Handles saving & loading of the structures. * All tiles inside the structure connect to it in relative block positions and absolute identifier **/ public LittleTile getMainTile() { return mainTile; } public LittleTileIdentifierStructureAbsolute getAbsoluteIdentifier() { return new LittleTileIdentifierStructureAbsolute(mainTile, getAttribute()); } public boolean hasMainTile() { return mainTile != null; } public boolean isStructurePlaced() { return hasMainTile(); } public boolean selectMainTile() { if (load()) { LittleTile first = tiles.getFirst(); if (first != null) { setMainTile(first); return true; } } return false; } public void setMainTile(LittleTile tile) { if (isStructurePlaced()) checkLoaded(); this.mainTile = tile; this.mainTile.connection = new StructureMainTile(mainTile, this); World world = getWorld(); if (parent != null) { LittleStructure parentStructure = parent.getStructure(world); parentStructure.updateChildConnection(parent.getChildID(), this); this.updateParentConnection(parent.getChildID(), parentStructure); } for (IStructureChildConnector child : children) { LittleStructure childStructure = child.getStructure(world); childStructure.updateParentConnection(child.getChildID(), this); this.updateChildConnection(child.getChildID(), childStructure); } if (tiles == null) { tiles = new HashMapList<>(); tiles.add(mainTile.getBlockPos(), mainTile); } else if (!contains(tile)) add(tile); for (Entry<BlockPos, ArrayList<LittleTile>> entry : tiles.entrySet()) { try { TileEntityLittleTiles te = loadTE(entry.getKey()); world.markChunkDirty(entry.getKey(), te); for (LittleTile stTile : entry.getValue()) { if (stTile != mainTile) { stTile.connection = getStructureLink(stTile); stTile.connection.setLoadedStructure(this); } } } catch (MissingTileEntity e) { markToBeLoaded(entry.getKey()); e.printStackTrace(); } } LittleTilePos absolute = tile.getAbsolutePos(); if (lastMainTileVec != null) { LittleTileVecContext vec = lastMainTileVec.getRelative(absolute); if (!lastMainTileVec.equals(absolute)) { for (StructureTypeRelative relative : type.relatives) { StructureRelative relativeST = relative.getRelative(this); if (relativeST != null) relativeST.onMove(this, vec.context, vec.vec); } } } lastMainTileVec = absolute; updateStructure(); } public boolean doesLinkToMainTile(LittleTile tile) { try { return tile == getMainTile() || (tile.connection.isLink() && tile.connection.getStructurePosition().equals(mainTile.getBlockPos()) && tile.connection.is(mainTile)); } catch (Exception e) { e.printStackTrace(); } return false; } // ================Tiles================ public boolean loaded() { return mainTile != null && tiles != null && (tilesToLoad == null || tilesToLoad.size() == 0) && !isRelationToParentBroken() && !isRelationToChildrenBroken(); } protected void checkLoaded() { if (!loaded()) throw new RuntimeException("Structure is not loaded cannot add tile!"); } protected boolean checkForTiles(World world, BlockPos pos, Integer expectedCount) { Chunk chunk = world.getChunkFromBlockCoords(pos); if (WorldUtils.checkIfChunkExists(chunk)) { // chunk.isChunkLoaded TileEntity tileEntity = world.getTileEntity(pos); if (tileEntity instanceof TileEntityLittleTiles) { if (!((TileEntityLittleTiles) tileEntity).hasLoaded()) return false; int found = 0; if (tiles.keySet().contains(pos)) tiles.removeKey(pos); for (LittleTile tile : (TileEntityLittleTiles) tileEntity) { if (tile.isChildOfStructure() && (tile.connection.getStructureWithoutLoading() == this || doesLinkToMainTile(tile))) { tiles.add(pos, tile); if (tile.connection.isLink()) tile.connection.setLoadedStructure(this); found++; } } if (found == expectedCount) return true; } } return false; } public boolean load() { if (mainTile != null) { if (tiles == null) { tiles = new HashMapList<>(); add(mainTile); } if (tilesToLoad == null) return !isRelationToParentBroken() && !isRelationToChildrenBroken(); for (Iterator<Entry<BlockPos, Integer>> iterator = tilesToLoad.entrySet().iterator(); iterator.hasNext();) { Entry<BlockPos, Integer> entry = iterator.next(); if (checkForTiles(mainTile.te.getWorld(), entry.getKey(), entry.getValue())) iterator.remove(); } if (!tiles.contains(mainTile)) add(mainTile); if (tilesToLoad.size() == 0) tilesToLoad = null; return loaded(); } return false; } @Deprecated public void removeTileList() { this.tiles = null; } public void createTilesList() { if (isStructurePlaced()) throw new RuntimeException("Cannot create list, structure is placed already"); this.tiles = new HashMapList<>(); } public List<TileEntityLittleTiles> collectBlocks() { if (!load()) return Collections.EMPTY_LIST; World world = getWorld(); List<TileEntityLittleTiles> blocks = new ArrayList<>(tiles.size()); for (BlockPos pos : tiles.keySet()) blocks.add((TileEntityLittleTiles) world.getTileEntity(pos)); return blocks; } public HashMapList<BlockPos, LittleTile> copyOfTiles() { if (!load()) return EMPTY_HASHMAPLIST; return new HashMapList<>(tiles); } public Iterator<LittleTile> getTiles() { if (!load()) return EMPTY_ITERATOR; return tiles.iterator(); } public TileEntityLittleTiles loadTE(BlockPos pos) throws MissingTileEntity { TileEntity te = getWorld().getTileEntity(pos); if (te == null || !(te instanceof TileEntityLittleTiles)) throw new MissingTileEntity(pos); return (TileEntityLittleTiles) te; } /*public HashMapList<TileEntityLittleTiles, LittleTile> loadTE(HashMapList<BlockPos, LittleTile> map) { HashMapList<TileEntityLittleTiles, LittleTile> blocks = new HashMapList<>(); for (Entry<BlockPos, ArrayList<LittleTile>> entry : map.entrySet()) blocks.add(loadTE(entry.getKey()), entry.getValue()); return blocks; }*/ public HashMapList<BlockPos, LittleTile> blockTiles() { if (!load()) return EMPTY_HASHMAPLIST; return tiles; } public HashMapList<BlockPos, LittleTile> collectBlockTilesChildren(HashMapList<BlockPos, LittleTile> tiles, boolean onlySameWorld) { if (!load() || !loadChildren()) return tiles; tiles.addAll(this.tiles); for (IStructureChildConnector child : children) if (!onlySameWorld || !child.isLinkToAnotherWorld()) child.getStructure(getWorld()).collectBlockTilesChildren(tiles, onlySameWorld); return tiles; } public boolean contains(LittleTile tile) { return tiles.contains(tile.getBlockPos(), tile); } public void remove(LittleTile tile) { checkLoaded(); tiles.removeValue(tile.getBlockPos(), tile); //if (tile == mainTile) //selectMainTile(); } public void add(LittleTile tile) { tiles.add(tile.getBlockPos(), tile); } public void combineTiles() { if (load()) { for (TileEntityLittleTiles te : collectBlocks()) te.combineTiles(this); } } protected void markToBeLoaded(BlockPos pos) { List<LittleTile> tiles = this.tiles.getValues(pos); this.tiles.removeKey(pos); if (tiles != null && !tiles.isEmpty()) { if (tilesToLoad == null) tilesToLoad = new LinkedHashMap<>(); tilesToLoad.put(pos, tiles.size()); } } public int count() { int count = 0; if (tilesToLoad != null) for (Integer tiles : tilesToLoad.values()) count += tiles; if (tiles != null) { for (Entry<BlockPos, ArrayList<LittleTile>> entry : tiles.entrySet()) if (tilesToLoad == null || !tilesToLoad.containsKey(entry.getKey())) count += entry.getValue().size(); } return count; } public boolean isChildOf(LittleStructure structure) { if (parent != null && parent.isConnected(getWorld())) return structure == parent.getStructureWithoutLoading() || parent.getStructureWithoutLoading().isChildOf(structure); return false; } // ================Connections================ public LittleTileIdentifierStructureRelative getMainTileCoord(BlockPos pos) { return new LittleTileIdentifierStructureRelative(pos, mainTile.getBlockPos(), mainTile.getContext(), mainTile.getIdentifier(), getAttribute()); } public StructureLinkTile getStructureLink(LittleTile tile) { return new StructureLinkTile(tile.te, mainTile.getBlockPos(), mainTile.getContext(), mainTile.getIdentifier(), getAttribute(), tile); } public boolean isRelationToParentBroken() { return parent != null && !parent.isConnected(getWorld()); } public boolean isRelationToChildrenBroken() { for (IStructureChildConnector child : children) { if (!child.isConnected(getWorld())) return true; } return false; } public void updateChildConnection(int i, LittleStructure child) { World world = getWorld(); World childWorld = child.getWorld(); IStructureChildConnector<LittleStructure> connector; if (childWorld == world) connector = new StructureLink(this.mainTile.te, child.getMainTile().getBlockPos(), child.getMainTile().getContext(), child.getMainTile().getIdentifier(), child.getAttribute(), this, i, false); else if (childWorld instanceof SubWorld && ((SubWorld) childWorld).parent != null) connector = new StructureLinkToSubWorld(child.getMainTile(), child.getAttribute(), this, i, ((SubWorld) childWorld).parent.getUniqueID()); else throw new RuntimeException("Invalid connection between to structures!"); connector.setLoadedStructure(child); if (children.size() > i) children.set(i, connector); else if (children.size() == i) children.add(connector); else throw new RuntimeException("Invalid childId " + children.size() + "."); } public void updateParentConnection(int i, LittleStructure parent) { World world = getWorld(); World parentWorld = parent.getWorld(); IStructureChildConnector<LittleStructure> connector; if (parentWorld == world) connector = new StructureLink(this.mainTile.te, parent.getMainTile().getBlockPos(), parent.getMainTile().getContext(), parent.getMainTile().getIdentifier(), parent.getAttribute(), this, i, true); else if (world instanceof SubWorld && ((SubWorld) world).parent != null) connector = new StructureLinkFromSubWorld(parent.getMainTile(), parent.getAttribute(), this, i); else throw new RuntimeException("Invalid connection between to structures!"); connector.setLoadedStructure(parent); this.parent = connector; } public boolean loadParent() { if (parent != null) return parent.isConnected(getWorld()); return true; } public boolean loadChildren() { if (children == null) children = new ArrayList<>(); if (children.isEmpty()) return true; for (IStructureChildConnector child : children) if (!child.isConnected(mainTile.te.getWorld()) || !child.getStructureWithoutLoading().load() || !child.getStructureWithoutLoading().loadChildren()) return false; return true; } // ================Placing================ public void createTempChildList() { this.tempChildren = new ArrayList<>(); } public void addTempChild(LittleStructure child) { this.tempChildren.add(child); } /** takes name of stack and connects the structure to its children (does so recursively) * * @param stack */ public void placedStructure(@Nullable ItemStack stack) { NBTTagCompound nbt; if (name == null && stack != null && (nbt = stack.getSubCompound("display")) != null && nbt.hasKey("Name", 8)) name = nbt.getString("Name"); combineTiles(); if (tempChildren != null) { children = new ArrayList<>(); for (int i = 0; i < tempChildren.size(); i++) { LittleStructure child = tempChildren.get(i); child.updateParentConnection(i, this); this.updateChildConnection(i, child); child.placedStructure(null); } tempChildren = null; } } // ================Synchronization================ /** This will notify every client that the structure has changed */ public void updateStructure() { mainTile.te.updateBlock(); } // ================Save and loading================ public void loadStructure(LittleTile mainTile) { this.mainTile = mainTile; this.mainTile.connection = new StructureMainTile(mainTile, this); if (tiles != null && !contains(mainTile)) add(mainTile); } public void loadFromNBT(NBTTagCompound nbt) { if (tiles != null) tiles = null; tilesToLoad = new LinkedHashMap<>(); // LoadTiles if (nbt.hasKey("count")) // Old way { int count = nbt.getInteger("count"); for (int i = 0; i < count; i++) { LittleTileIdentifierRelative coord = null; if (nbt.hasKey("i" + i + "coX")) { LittleTilePosition pos = new LittleTilePosition("i" + i, nbt); coord = new LittleTileIdentifierRelative(mainTile.te, pos.coord, LittleGridContext.get(), new int[] { pos.position.x, pos.position.y, pos.position.z }); } else { coord = LittleTileIdentifierRelative.loadIdentifierOld("i" + i, nbt); } BlockPos pos = coord.getAbsolutePosition(mainTile.te); Integer insideBlock = tilesToLoad.get(pos); if (insideBlock == null) insideBlock = new Integer(1); else insideBlock = insideBlock + 1; tilesToLoad.put(pos, insideBlock); } tiles = new HashMapList<>(); } else if (nbt.hasKey("tiles")) { // new way NBTTagList list = nbt.getTagList("tiles", 11); for (int i = 0; i < list.tagCount(); i++) { int[] array = list.getIntArrayAt(i); if (array.length == 4) { RelativeBlockPos pos = new RelativeBlockPos(array); tilesToLoad.put(pos.getAbsolutePos(mainTile.te), array[3]); } else System.out.println("Found invalid array! " + nbt); } tiles = new HashMapList<>(); } if (nbt.hasKey("name")) name = nbt.getString("name"); else name = null; // Load family (parent and children) if (nbt.hasKey("parent")) parent = StructureLink.loadFromNBT(this, nbt.getCompoundTag("parent"), true); else parent = null; if (nbt.hasKey("children")) { children = new ArrayList<>(); NBTTagList list = nbt.getTagList("children", 10); for (int i = 0; i < list.tagCount(); i++) { children.add(StructureLink.loadFromNBT(this, list.getCompoundTagAt(i), false)); } if (this instanceof IAnimatedStructure && ((IAnimatedStructure) this).isAnimated()) { for (IStructureChildConnector child : children) { if (child instanceof StructureLinkToSubWorld && ((StructureLinkToSubWorld) child).entityUUID.equals(((IAnimatedStructure) this).getAnimation().getUniqueID())) throw new RuntimeException("Something went wrong during loading!"); } } } else children = new ArrayList<>(); for (StructureTypeRelative relative : type.relatives) { if (nbt.hasKey(relative.saveKey)) relative.createAndSetRelative(this, nbt); else failedLoadingRelative(nbt, relative); } loadFromNBTExtra(nbt); } protected void failedLoadingRelative(NBTTagCompound nbt, StructureTypeRelative relative) { relative.setRelative(this, null); } protected abstract void loadFromNBTExtra(NBTTagCompound nbt); public NBTTagCompound writeToNBTPreview(NBTTagCompound nbt, BlockPos newCenter) { nbt.setString("id", type.id); if (name != null) nbt.setString("name", name); else nbt.removeTag("name"); LittleTileVecContext vec = getMainTile().getAbsolutePos().getRelative(new LittleTilePos(newCenter, getMainTile().getContext())); LittleTileVec inverted = vec.vec.copy(); inverted.invert(); for (StructureTypeRelative relative : type.relatives) { StructureRelative relativeST = relative.getRelative(this); if (relativeST == null) continue; relativeST.onMove(this, vec.context, vec.vec); relativeST.writeToNBT(relative.saveKey, nbt); relativeST.onMove(this, vec.context, inverted); } writeToNBTExtra(nbt); return nbt; } public void writeToNBT(NBTTagCompound nbt) { nbt.setString("id", type.id); if (name != null) nbt.setString("name", name); else nbt.removeTag("name"); // Save family (parent and children) if (parent != null) nbt.setTag("parent", parent.writeToNBT(new NBTTagCompound())); if (children != null && !children.isEmpty()) { NBTTagList list = new NBTTagList(); for (IStructureChildConnector child : children) { list.appendTag(child.writeToNBT(new NBTTagCompound())); } nbt.setTag("children", list); } // SaveTiles HashMap<BlockPos, Integer> positions = new HashMap<>(); if (tiles != null) for (Entry<BlockPos, ArrayList<LittleTile>> entry : tiles.entrySet()) if (entry.getValue().size() > 0) positions.put(entry.getKey(), entry.getValue().size()); if (tilesToLoad != null) positions.putAll(tilesToLoad); if (positions.size() > 0) { NBTTagList list = new NBTTagList(); for (Iterator<Entry<BlockPos, Integer>> iterator = positions.entrySet().iterator(); iterator.hasNext();) { Entry<BlockPos, Integer> entry = iterator.next(); RelativeBlockPos pos = new RelativeBlockPos(mainTile.te, entry.getKey()); list.appendTag(new NBTTagIntArray(new int[] { pos.getRelativePos().getX(), pos.getRelativePos().getY(), pos.getRelativePos().getZ(), entry.getValue() })); } nbt.setTag("tiles", list); } for (StructureTypeRelative relative : type.relatives) { StructureRelative relativeST = relative.getRelative(this); if (relativeST == null) continue; relativeST.writeToNBT(relative.saveKey, nbt); } writeToNBTExtra(nbt); } protected abstract void writeToNBTExtra(NBTTagCompound nbt); // ================Item Form================ public void addIngredients(LittleIngredients ingredients) { } public void finializePreview(LittlePreviews previews) { } // ====================Destroy==================== public void onLittleTileDestroy() { if (parent != null) { if (parent.isConnected(getWorld())) parent.getStructure(getWorld()).onLittleTileDestroy(); return; } if (load() && loadChildren()) removeStructure(); } public void removeStructure() { checkLoaded(); onStructureDestroyed(); for (IStructureChildConnector child : children) child.destroyStructure(); if (this instanceof IAnimatedStructure && ((IAnimatedStructure) this).isAnimated()) ((IAnimatedStructure) this).destroyAnimation(); else if (mainTile.te.contains(mainTile)) for (Entry<BlockPos, ArrayList<LittleTile>> entry : tiles.entrySet()) try { loadTE(entry.getKey()).updateTiles((x) -> x.removeAll(entry.getValue())); } catch (MissingTileEntity e) { //e.printStackTrace(); } } /** Is called before the structure is removed */ public void onStructureDestroyed() { } // ====================Previews==================== public LittleGridContext getMinContext() { LittleGridContext context = LittleGridContext.getMin(); for (IStructureChildConnector child : children) context = LittleGridContext.max(context, child.getStructure(getWorld()).getMinContext()); for (StructureTypeRelative relative : type.relatives) { StructureRelative relativeST = relative.getRelative(this); if (relativeST == null) continue; relativeST.convertToSmallest(); context = LittleGridContext.max(context, relativeST.getContext()); } return context; } public LittleAbsolutePreviewsStructure getAbsolutePreviews(BlockPos pos) { NBTTagCompound structureNBT = new NBTTagCompound(); this.writeToNBTPreview(structureNBT, pos); LittleAbsolutePreviewsStructure previews = new LittleAbsolutePreviewsStructure(structureNBT, pos, getMinContext()); for (Iterator<LittleTile> iterator = getTiles(); iterator.hasNext();) { previews.addTile(iterator.next()); } for (IStructureChildConnector child : children) previews.addChild(child.getStructure(getWorld()).getPreviews(pos)); previews.convertToSmallest(); previews.ensureContext(getMinContext()); return previews; } public LittlePreviewsStructure getPreviews(BlockPos pos) { NBTTagCompound structureNBT = new NBTTagCompound(); this.writeToNBTPreview(structureNBT, pos); LittlePreviewsStructure previews = new LittlePreviewsStructure(structureNBT, getMinContext()); for (Iterator<LittleTile> iterator = getTiles(); iterator.hasNext();) { LittleTile tile = iterator.next(); LittleTilePreview preview = previews.addTile(tile); preview.box.add(new LittleTileVec(previews.context, tile.getBlockPos().subtract(pos))); } for (IStructureChildConnector child : children) previews.addChild(child.getStructure(getWorld()).getPreviews(pos)); previews.convertToSmallest(); previews.ensureContext(getMinContext()); return previews; } public LittleAbsolutePreviewsStructure getAbsolutePreviewsSameWorldOnly(BlockPos pos) { NBTTagCompound structureNBT = new NBTTagCompound(); this.writeToNBTPreview(structureNBT, pos); LittleAbsolutePreviewsStructure previews = new LittleAbsolutePreviewsStructure(structureNBT, pos, getMinContext()); for (Iterator<LittleTile> iterator = getTiles(); iterator.hasNext();) previews.addTile(iterator.next()); for (IStructureChildConnector child : children) if (!child.isLinkToAnotherWorld()) previews.addChild(child.getStructure(getWorld()).getPreviewsSameWorldOnly(pos)); else previews.getStructure().addTempChild(child.getStructure(getWorld())); previews.convertToSmallest(); previews.ensureContext(getMinContext()); return previews; } public LittlePreviewsStructure getPreviewsSameWorldOnly(BlockPos pos) { NBTTagCompound structureNBT = new NBTTagCompound(); this.writeToNBTPreview(structureNBT, pos); LittlePreviewsStructure previews = new LittlePreviewsStructure(structureNBT, getMinContext()); for (Iterator<LittleTile> iterator = getTiles(); iterator.hasNext();) { LittleTile tile = iterator.next(); LittleTilePreview preview = previews.addTile(tile); preview.box.add(new LittleTileVec(previews.context, tile.getBlockPos().subtract(pos))); } for (IStructureChildConnector child : children) if (!child.isLinkToAnotherWorld()) previews.addChild(child.getStructure(getWorld()).getPreviews(pos)); else previews.getStructure().addTempChild(child.getStructure(getWorld())); previews.convertToSmallest(); previews.ensureContext(getMinContext()); return previews; } public MutableBlockPos getMinPos(MutableBlockPos pos) { for (BlockPos tePos : tiles.keySet()) pos.setPos(Math.min(pos.getX(), tePos.getX()), Math.min(pos.getY(), tePos.getY()), Math.min(pos.getZ(), tePos.getZ())); for (IStructureChildConnector child : children) child.getStructure(getWorld()).getMinPos(pos); return pos; } public List<PlacePreviewTile> getSpecialTiles(LittlePreviews previews) { if (type.relatives.isEmpty()) return Collections.EMPTY_LIST; List<PlacePreviewTile> placePreviews = new ArrayList<>(); for (StructureTypeRelative relative : type.relatives) { StructureRelative relativeST = relative.getRelative(this); if (relativeST == null) continue; PlacePreviewTile tile = getPlacePreview(relativeST, relative, previews); if (relativeST.getContext().size < previews.context.size) tile.convertTo(relativeST.getContext(), previews.context); placePreviews.add(tile); } return placePreviews; } protected PlacePreviewTile getPlacePreview(StructureRelative relative, StructureTypeRelative type, LittlePreviews previews) { return relative.getPlacePreview(previews, type); } // ====================Transform & Transfer==================== public void transferChildrenToAnimation(EntityAnimation animation) { for (IStructureChildConnector child : children) { LittleStructure childStructure = child.getStructure(getWorld()); if (child.isLinkToAnotherWorld()) { EntityAnimation subAnimation = ((IAnimatedStructure) childStructure).getAnimation(); int l1 = subAnimation.chunkCoordX; int i2 = subAnimation.chunkCoordZ; World world = getWorld(); if (subAnimation.addedToChunk) { Chunk chunk = world.getChunkFromChunkCoords(l1, i2); if (chunk != null) chunk.removeEntity(subAnimation); subAnimation.addedToChunk = false; } world.loadedEntityList.remove(subAnimation); subAnimation.setParentWorld(animation.fakeWorld); animation.fakeWorld.spawnEntity(subAnimation); subAnimation.updateTickState(); } else childStructure.transferChildrenToAnimation(animation); } } public void transferChildrenFromAnimation(EntityAnimation animation) { World parentWorld = animation.fakeWorld.getParent(); for (IStructureChildConnector child : children) { LittleStructure childStructure = child.getStructure(getWorld()); if (child.isLinkToAnotherWorld()) { EntityAnimation subAnimation = ((IAnimatedStructure) childStructure).getAnimation(); int l1 = subAnimation.chunkCoordX; int i2 = subAnimation.chunkCoordZ; if (subAnimation.addedToChunk) { Chunk chunk = animation.fakeWorld.getChunkFromChunkCoords(l1, i2); if (chunk != null) chunk.removeEntity(subAnimation); subAnimation.addedToChunk = false; } animation.fakeWorld.loadedEntityList.remove(subAnimation); subAnimation.setParentWorld(parentWorld); parentWorld.spawnEntity(subAnimation); subAnimation.updateTickState(); } else childStructure.transferChildrenFromAnimation(animation); } } public void transformAnimation(LittleTransformation transformation) { for (IStructureChildConnector child : children) { LittleStructure childStructure = child.getStructure(getWorld()); if (child.isLinkToAnotherWorld()) ((IAnimatedStructure) childStructure).getAnimation().transformWorld(transformation); else childStructure.transformAnimation(transformation); } } // ====================Relatives==================== public void onMove(LittleGridContext context, LittleTileVec offset) { for (StructureTypeRelative relative : type.relatives) { StructureRelative relativeST = relative.getRelative(this); if (relativeST == null) continue; relativeST.onMove(this, context, offset); } } public void onFlip(LittleGridContext context, Axis axis, LittleTileVec doubledCenter) { for (StructureTypeRelative relative : type.relatives) { StructureRelative relativeST = relative.getRelative(this); if (relativeST == null) continue; relativeST.onFlip(this, context, axis, doubledCenter); } } public void onRotate(LittleGridContext context, Rotation rotation, LittleTileVec doubledCenter) { for (StructureTypeRelative relative : type.relatives) { StructureRelative relativeST = relative.getRelative(this); if (relativeST == null) continue; relativeST.onRotate(this, context, rotation, doubledCenter); } } // ====================Helpers==================== public AxisAlignedBB getSurroundingBox() { if (load()) return new SurroundingBox(true).add(tiles.entrySet()).getSurroundingBox(); return null; } public Vec3d getHighestCenterVec() { if (load()) return new SurroundingBox(true).add(tiles.entrySet()).getHighestCenterVec(); return null; } public LittleTilePos getHighestCenterPoint() { if (load()) return new SurroundingBox(true).add(tiles.entrySet()).getHighestCenterPoint(); return null; } // ====================Extra==================== public ItemStack getStructureDrop() { if (parent != null) { if (parent.isConnected(getWorld())) return parent.getStructure(getWorld()).getStructureDrop(); return ItemStack.EMPTY; } if (load() && loadChildren()) { BlockPos pos = getMinPos(new MutableBlockPos(getMainTile().getBlockPos())); ItemStack stack = new ItemStack(LittleTiles.multiTiles); LittlePreviews previews = getPreviews(pos); LittleTilePreview.savePreview(previews, stack); if (name != null) { NBTTagCompound display = new NBTTagCompound(); display.setString("Name", name); stack.getTagCompound().setTag("display", display); } return stack; } return ItemStack.EMPTY; } public boolean onBlockActivated(World worldIn, LittleTile tile, BlockPos pos, IBlockState state, EntityPlayer playerIn, EnumHand hand, @Nullable ItemStack heldItem, EnumFacing side, float hitX, float hitY, float hitZ, LittleActionActivated action) throws LittleActionException { return false; } public boolean isBed(IBlockAccess world, BlockPos pos, EntityLivingBase player) { return false; } public void onEntityCollidedWithBlock(World worldIn, BlockPos pos, IBlockState state, Entity entityIn) { } public void onUpdatePacketReceived() { } // ====================Premade==================== public boolean canOnlyBePlacedByItemStack() { return false; } /** Only important for structures which require to be placed by the given * itemstack * * @return */ public String getStructureDropIdentifier() { return null; } }
src/main/java/com/creativemd/littletiles/common/structure/LittleStructure.java
package com.creativemd.littletiles.common.structure; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map.Entry; import javax.annotation.Nullable; import com.creativemd.creativecore.common.utils.math.Rotation; import com.creativemd.creativecore.common.utils.mc.WorldUtils; import com.creativemd.creativecore.common.utils.type.HashMapList; import com.creativemd.creativecore.common.world.SubWorld; import com.creativemd.littletiles.LittleTiles; import com.creativemd.littletiles.common.action.LittleActionException; import com.creativemd.littletiles.common.action.block.LittleActionActivated; import com.creativemd.littletiles.common.entity.EntityAnimation; import com.creativemd.littletiles.common.structure.attribute.LittleStructureAttribute; import com.creativemd.littletiles.common.structure.connection.IStructureChildConnector; import com.creativemd.littletiles.common.structure.connection.StructureLink; import com.creativemd.littletiles.common.structure.connection.StructureLinkFromSubWorld; import com.creativemd.littletiles.common.structure.connection.StructureLinkTile; import com.creativemd.littletiles.common.structure.connection.StructureLinkToSubWorld; import com.creativemd.littletiles.common.structure.connection.StructureMainTile; import com.creativemd.littletiles.common.structure.exception.MissingTileEntity; import com.creativemd.littletiles.common.structure.registry.LittleStructureRegistry; import com.creativemd.littletiles.common.structure.registry.LittleStructureType; import com.creativemd.littletiles.common.structure.registry.LittleStructureType.StructureTypeRelative; import com.creativemd.littletiles.common.structure.relative.StructureRelative; import com.creativemd.littletiles.common.tileentity.TileEntityLittleTiles; import com.creativemd.littletiles.common.tiles.LittleTile; import com.creativemd.littletiles.common.tiles.LittleTile.LittleTilePosition; import com.creativemd.littletiles.common.tiles.place.PlacePreviewTile; import com.creativemd.littletiles.common.tiles.preview.LittleAbsolutePreviewsStructure; import com.creativemd.littletiles.common.tiles.preview.LittlePreviews; import com.creativemd.littletiles.common.tiles.preview.LittlePreviewsStructure; import com.creativemd.littletiles.common.tiles.preview.LittleTilePreview; import com.creativemd.littletiles.common.tiles.vec.LittleTileIdentifierRelative; import com.creativemd.littletiles.common.tiles.vec.LittleTileIdentifierStructureAbsolute; import com.creativemd.littletiles.common.tiles.vec.LittleTileIdentifierStructureRelative; import com.creativemd.littletiles.common.tiles.vec.LittleTilePos; import com.creativemd.littletiles.common.tiles.vec.LittleTileVec; import com.creativemd.littletiles.common.tiles.vec.LittleTileVecContext; import com.creativemd.littletiles.common.tiles.vec.RelativeBlockPos; import com.creativemd.littletiles.common.utils.grid.LittleGridContext; import com.creativemd.littletiles.common.utils.ingredients.LittleIngredients; import com.creativemd.littletiles.common.utils.vec.LittleTransformation; import com.creativemd.littletiles.common.utils.vec.SurroundingBox; import net.minecraft.block.state.IBlockState; import net.minecraft.entity.Entity; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.nbt.NBTTagIntArray; import net.minecraft.nbt.NBTTagList; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.EnumFacing; import net.minecraft.util.EnumFacing.Axis; import net.minecraft.util.EnumHand; import net.minecraft.util.math.AxisAlignedBB; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.BlockPos.MutableBlockPos; import net.minecraft.util.math.Vec3d; import net.minecraft.world.IBlockAccess; import net.minecraft.world.World; import net.minecraft.world.chunk.Chunk; public abstract class LittleStructure { private static final Iterator<LittleTile> EMPTY_ITERATOR = new Iterator<LittleTile>() { @Override public boolean hasNext() { return false; } @Override public LittleTile next() { return null; } }; private static final HashMapList<BlockPos, LittleTile> EMPTY_HASHMAPLIST = new HashMapList<>(); public static LittleStructure createAndLoadStructure(NBTTagCompound nbt, @Nullable LittleTile mainTile) { if (nbt == null) return null; String id = nbt.getString("id"); LittleStructureType type = LittleStructureRegistry.getStructureType(id); if (type != null) { LittleStructure structure = type.createStructure(); structure.mainTile = mainTile; structure.loadFromNBT(nbt); return structure; } else System.out.println("Could not find structureID=" + id); return null; } public final LittleStructureType type; public String name; /** The core of the structure. Handles saving & loading of the structures. * All tiles inside the structure connect to it in relative block positions and absolute identifier **/ private LittleTile mainTile; protected LittleTilePos lastMainTileVec = null; protected HashMapList<BlockPos, LittleTile> tiles = null; public LinkedHashMap<BlockPos, Integer> tilesToLoad = null; public IStructureChildConnector parent; public List<IStructureChildConnector> children; /** Used for placing and structures in item form */ private List<LittleStructure> tempChildren; public LittleStructure(LittleStructureType type) { this.type = type; } // ================Basics================ public World getWorld() { return mainTile.te.getWorld(); } public LittleStructureAttribute getAttribute() { return type.attribute; } // ================MainTile================ /** The core of the structure. Handles saving & loading of the structures. * All tiles inside the structure connect to it in relative block positions and absolute identifier **/ public LittleTile getMainTile() { return mainTile; } public LittleTileIdentifierStructureAbsolute getAbsoluteIdentifier() { return new LittleTileIdentifierStructureAbsolute(mainTile, getAttribute()); } public boolean hasMainTile() { return mainTile != null; } public boolean isStructurePlaced() { return hasMainTile(); } public boolean selectMainTile() { if (load()) { LittleTile first = tiles.getFirst(); if (first != null) { setMainTile(first); return true; } } return false; } public void setMainTile(LittleTile tile) { if (isStructurePlaced()) checkLoaded(); this.mainTile = tile; this.mainTile.connection = new StructureMainTile(mainTile, this); World world = getWorld(); if (parent != null) { LittleStructure parentStructure = parent.getStructure(world); parentStructure.updateChildConnection(parent.getChildID(), this); this.updateParentConnection(parent.getChildID(), parentStructure); } for (IStructureChildConnector child : children) { LittleStructure childStructure = child.getStructure(world); childStructure.updateParentConnection(child.getChildID(), this); this.updateChildConnection(child.getChildID(), childStructure); } if (tiles == null) { tiles = new HashMapList<>(); tiles.add(mainTile.getBlockPos(), mainTile); } else if (!contains(tile)) add(tile); for (Entry<BlockPos, ArrayList<LittleTile>> entry : tiles.entrySet()) { try { TileEntityLittleTiles te = loadTE(entry.getKey()); world.markChunkDirty(entry.getKey(), te); for (LittleTile stTile : entry.getValue()) { if (stTile != mainTile) { stTile.connection = getStructureLink(stTile); stTile.connection.setLoadedStructure(this); } } } catch (MissingTileEntity e) { markToBeLoaded(entry.getKey()); e.printStackTrace(); } } LittleTilePos absolute = tile.getAbsolutePos(); if (lastMainTileVec != null) { LittleTileVecContext vec = lastMainTileVec.getRelative(absolute); if (!lastMainTileVec.equals(absolute)) { for (StructureTypeRelative relative : type.relatives) { StructureRelative relativeST = relative.getRelative(this); if (relativeST != null) relativeST.onMove(this, vec.context, vec.vec); } } } lastMainTileVec = absolute; updateStructure(); } public boolean doesLinkToMainTile(LittleTile tile) { try { return tile == getMainTile() || (tile.connection.isLink() && tile.connection.getStructurePosition().equals(mainTile.getBlockPos()) && tile.connection.is(mainTile)); } catch (Exception e) { e.printStackTrace(); } return false; } // ================Tiles================ public boolean loaded() { return mainTile != null && tiles != null && (tilesToLoad == null || tilesToLoad.size() == 0) && !isRelationToParentBroken() && !isRelationToChildrenBroken(); } protected void checkLoaded() { if (!loaded()) throw new RuntimeException("Structure is not loaded cannot add tile!"); } protected boolean checkForTiles(World world, BlockPos pos, Integer expectedCount) { Chunk chunk = world.getChunkFromBlockCoords(pos); if (WorldUtils.checkIfChunkExists(chunk)) { // chunk.isChunkLoaded TileEntity tileEntity = world.getTileEntity(pos); if (tileEntity instanceof TileEntityLittleTiles) { if (!((TileEntityLittleTiles) tileEntity).hasLoaded()) return false; int found = 0; if (tiles.keySet().contains(pos)) tiles.removeKey(pos); for (LittleTile tile : (TileEntityLittleTiles) tileEntity) { if (tile.isChildOfStructure() && (tile.connection.getStructureWithoutLoading() == this || doesLinkToMainTile(tile))) { tiles.add(pos, tile); if (tile.connection.isLink()) tile.connection.setLoadedStructure(this); found++; } } if (found == expectedCount) return true; } } return false; } public boolean load() { if (mainTile != null) { if (tiles == null) { tiles = new HashMapList<>(); add(mainTile); } if (tilesToLoad == null) return !isRelationToParentBroken() && !isRelationToChildrenBroken(); for (Iterator<Entry<BlockPos, Integer>> iterator = tilesToLoad.entrySet().iterator(); iterator.hasNext();) { Entry<BlockPos, Integer> entry = iterator.next(); if (checkForTiles(mainTile.te.getWorld(), entry.getKey(), entry.getValue())) iterator.remove(); } if (!tiles.contains(mainTile)) add(mainTile); if (tilesToLoad.size() == 0) tilesToLoad = null; return loaded(); } return false; } @Deprecated public void removeTileList() { this.tiles = null; } public void createTilesList() { if (isStructurePlaced()) throw new RuntimeException("Cannot create list, structure is placed already"); this.tiles = new HashMapList<>(); } public List<TileEntityLittleTiles> collectBlocks() { if (!load()) return Collections.EMPTY_LIST; World world = getWorld(); List<TileEntityLittleTiles> blocks = new ArrayList<>(tiles.size()); for (BlockPos pos : tiles.keySet()) blocks.add((TileEntityLittleTiles) world.getTileEntity(pos)); return blocks; } public HashMapList<BlockPos, LittleTile> copyOfTiles() { if (!load()) return EMPTY_HASHMAPLIST; return new HashMapList<>(tiles); } public Iterator<LittleTile> getTiles() { if (!load()) return EMPTY_ITERATOR; return tiles.iterator(); } public TileEntityLittleTiles loadTE(BlockPos pos) throws MissingTileEntity { TileEntity te = getWorld().getTileEntity(pos); if (te == null || !(te instanceof TileEntityLittleTiles)) throw new MissingTileEntity(pos); return (TileEntityLittleTiles) te; } /*public HashMapList<TileEntityLittleTiles, LittleTile> loadTE(HashMapList<BlockPos, LittleTile> map) { HashMapList<TileEntityLittleTiles, LittleTile> blocks = new HashMapList<>(); for (Entry<BlockPos, ArrayList<LittleTile>> entry : map.entrySet()) blocks.add(loadTE(entry.getKey()), entry.getValue()); return blocks; }*/ public HashMapList<BlockPos, LittleTile> blockTiles() { if (!load()) return EMPTY_HASHMAPLIST; return tiles; } public HashMapList<BlockPos, LittleTile> collectBlockTilesChildren(HashMapList<BlockPos, LittleTile> tiles, boolean onlySameWorld) { if (!load() || !loadChildren()) return tiles; tiles.addAll(this.tiles); for (IStructureChildConnector child : children) if (!onlySameWorld || !child.isLinkToAnotherWorld()) child.getStructure(getWorld()).collectBlockTilesChildren(tiles, onlySameWorld); return tiles; } public boolean contains(LittleTile tile) { return tiles.contains(tile.getBlockPos(), tile); } public void remove(LittleTile tile) { checkLoaded(); tiles.removeValue(tile.getBlockPos(), tile); //if (tile == mainTile) //selectMainTile(); } public void add(LittleTile tile) { tiles.add(tile.getBlockPos(), tile); } public void combineTiles() { if (load()) { for (TileEntityLittleTiles te : collectBlocks()) te.combineTiles(this); } } protected void markToBeLoaded(BlockPos pos) { List<LittleTile> tiles = this.tiles.getValues(pos); this.tiles.removeKey(pos); if (tiles != null && !tiles.isEmpty()) { if (tilesToLoad == null) tilesToLoad = new LinkedHashMap<>(); tilesToLoad.put(pos, tiles.size()); } } public int count() { int count = 0; if (tilesToLoad != null) for (Integer tiles : tilesToLoad.values()) count += tiles; if (tiles != null) { for (Entry<BlockPos, ArrayList<LittleTile>> entry : tiles.entrySet()) if (tilesToLoad == null || !tilesToLoad.containsKey(entry.getKey())) count += entry.getValue().size(); } return count; } public boolean isChildOf(LittleStructure structure) { if (parent != null && parent.isConnected(getWorld())) return structure == parent.getStructureWithoutLoading() || parent.getStructureWithoutLoading().isChildOf(structure); return false; } // ================Connections================ public LittleTileIdentifierStructureRelative getMainTileCoord(BlockPos pos) { return new LittleTileIdentifierStructureRelative(pos, mainTile.getBlockPos(), mainTile.getContext(), mainTile.getIdentifier(), getAttribute()); } public StructureLinkTile getStructureLink(LittleTile tile) { return new StructureLinkTile(tile.te, mainTile.getBlockPos(), mainTile.getContext(), mainTile.getIdentifier(), getAttribute(), tile); } public boolean isRelationToParentBroken() { return parent != null && !parent.isConnected(getWorld()); } public boolean isRelationToChildrenBroken() { for (IStructureChildConnector child : children) { if (!child.isConnected(getWorld())) return true; } return false; } public void updateChildConnection(int i, LittleStructure child) { World world = getWorld(); World childWorld = child.getWorld(); IStructureChildConnector<LittleStructure> connector; if (childWorld == world) connector = new StructureLink(this.mainTile.te, child.getMainTile().getBlockPos(), child.getMainTile().getContext(), child.getMainTile().getIdentifier(), child.getAttribute(), this, i, false); else if (childWorld instanceof SubWorld && ((SubWorld) childWorld).parent != null) connector = new StructureLinkToSubWorld(child.getMainTile(), child.getAttribute(), this, i, ((SubWorld) childWorld).parent.getUniqueID()); else throw new RuntimeException("Invalid connection between to structures!"); connector.setLoadedStructure(child); if (children.size() > i) children.set(i, connector); else if (children.size() == i) children.add(connector); else throw new RuntimeException("Invalid childId " + children.size() + "."); } public void updateParentConnection(int i, LittleStructure parent) { World world = getWorld(); World parentWorld = parent.getWorld(); IStructureChildConnector<LittleStructure> connector; if (parentWorld == world) connector = new StructureLink(this.mainTile.te, parent.getMainTile().getBlockPos(), parent.getMainTile().getContext(), parent.getMainTile().getIdentifier(), parent.getAttribute(), this, i, true); else if (world instanceof SubWorld && ((SubWorld) world).parent != null) connector = new StructureLinkFromSubWorld(parent.getMainTile(), parent.getAttribute(), this, i); else throw new RuntimeException("Invalid connection between to structures!"); connector.setLoadedStructure(parent); this.parent = connector; } public boolean loadParent() { if (parent != null) return parent.isConnected(getWorld()); return true; } public boolean loadChildren() { if (children == null) children = new ArrayList<>(); if (children.isEmpty()) return true; for (IStructureChildConnector child : children) if (!child.isConnected(mainTile.te.getWorld()) || !child.getStructureWithoutLoading().load() || !child.getStructureWithoutLoading().loadChildren()) return false; return true; } // ================Placing================ public void createTempChildList() { this.tempChildren = new ArrayList<>(); } public void addTempChild(LittleStructure child) { this.tempChildren.add(child); } /** takes name of stack and connects the structure to its children (does so recursively) * * @param stack */ public void placedStructure(@Nullable ItemStack stack) { NBTTagCompound nbt; if (name == null && stack != null && (nbt = stack.getSubCompound("display")) != null && nbt.hasKey("Name", 8)) name = nbt.getString("Name"); combineTiles(); if (tempChildren != null) { children = new ArrayList<>(); for (int i = 0; i < tempChildren.size(); i++) { LittleStructure child = tempChildren.get(i); child.updateParentConnection(i, this); this.updateChildConnection(i, child); child.placedStructure(null); } tempChildren = null; } } // ================Synchronization================ /** This will notify every client that the structure has changed */ public void updateStructure() { mainTile.te.updateBlock(); } // ================Save and loading================ public void loadStructure(LittleTile mainTile) { this.mainTile = mainTile; this.mainTile.connection = new StructureMainTile(mainTile, this); if (tiles != null && !contains(mainTile)) add(mainTile); } public void loadFromNBT(NBTTagCompound nbt) { if (tiles != null) tiles = null; tilesToLoad = new LinkedHashMap<>(); // LoadTiles if (nbt.hasKey("count")) // Old way { int count = nbt.getInteger("count"); for (int i = 0; i < count; i++) { LittleTileIdentifierRelative coord = null; if (nbt.hasKey("i" + i + "coX")) { LittleTilePosition pos = new LittleTilePosition("i" + i, nbt); coord = new LittleTileIdentifierRelative(mainTile.te, pos.coord, LittleGridContext.get(), new int[] { pos.position.x, pos.position.y, pos.position.z }); } else { coord = LittleTileIdentifierRelative.loadIdentifierOld("i" + i, nbt); } BlockPos pos = coord.getAbsolutePosition(mainTile.te); Integer insideBlock = tilesToLoad.get(pos); if (insideBlock == null) insideBlock = new Integer(1); else insideBlock = insideBlock + 1; tilesToLoad.put(pos, insideBlock); } tiles = new HashMapList<>(); } else if (nbt.hasKey("tiles")) { // new way NBTTagList list = nbt.getTagList("tiles", 11); for (int i = 0; i < list.tagCount(); i++) { int[] array = list.getIntArrayAt(i); if (array.length == 4) { RelativeBlockPos pos = new RelativeBlockPos(array); tilesToLoad.put(pos.getAbsolutePos(mainTile.te), array[3]); } else System.out.println("Found invalid array! " + nbt); } tiles = new HashMapList<>(); } if (nbt.hasKey("name")) name = nbt.getString("name"); else name = null; // Load family (parent and children) if (nbt.hasKey("parent")) parent = StructureLink.loadFromNBT(this, nbt.getCompoundTag("parent"), true); else parent = null; if (nbt.hasKey("children")) { children = new ArrayList<>(); NBTTagList list = nbt.getTagList("children", 10); for (int i = 0; i < list.tagCount(); i++) { children.add(StructureLink.loadFromNBT(this, list.getCompoundTagAt(i), false)); } if (this instanceof IAnimatedStructure && ((IAnimatedStructure) this).isAnimated()) { for (IStructureChildConnector child : children) { if (child instanceof StructureLinkToSubWorld && ((StructureLinkToSubWorld) child).entityUUID.equals(((IAnimatedStructure) this).getAnimation().getUniqueID())) throw new RuntimeException("Something went wrong during loading!"); } } } else children = new ArrayList<>(); for (StructureTypeRelative relative : type.relatives) { if (nbt.hasKey(relative.saveKey)) relative.createAndSetRelative(this, nbt); else failedLoadingRelative(nbt, relative); } loadFromNBTExtra(nbt); } protected void failedLoadingRelative(NBTTagCompound nbt, StructureTypeRelative relative) { relative.setRelative(this, null); } protected abstract void loadFromNBTExtra(NBTTagCompound nbt); public NBTTagCompound writeToNBTPreview(NBTTagCompound nbt, BlockPos newCenter) { nbt.setString("id", type.id); if (name != null) nbt.setString("name", name); else nbt.removeTag("name"); LittleTileVecContext vec = getMainTile().getAbsolutePos().getRelative(new LittleTilePos(newCenter, getMainTile().getContext())); LittleTileVec inverted = vec.vec.copy(); inverted.invert(); for (StructureTypeRelative relative : type.relatives) { StructureRelative relativeST = relative.getRelative(this); if (relativeST == null) continue; relativeST.onMove(this, vec.context, vec.vec); relativeST.writeToNBT(relative.saveKey, nbt); relativeST.onMove(this, vec.context, inverted); } writeToNBTExtra(nbt); return nbt; } public void writeToNBT(NBTTagCompound nbt) { nbt.setString("id", type.id); if (name != null) nbt.setString("name", name); else nbt.removeTag("name"); // Save family (parent and children) if (parent != null) nbt.setTag("parent", parent.writeToNBT(new NBTTagCompound())); if (children != null && !children.isEmpty()) { NBTTagList list = new NBTTagList(); for (IStructureChildConnector child : children) { list.appendTag(child.writeToNBT(new NBTTagCompound())); } nbt.setTag("children", list); } // SaveTiles HashMap<BlockPos, Integer> positions = new HashMap<>(); if (tiles != null) for (Entry<BlockPos, ArrayList<LittleTile>> entry : tiles.entrySet()) if (entry.getValue().size() > 0) positions.put(entry.getKey(), entry.getValue().size()); if (tilesToLoad != null) positions.putAll(tilesToLoad); if (positions.size() > 0) { NBTTagList list = new NBTTagList(); for (Iterator<Entry<BlockPos, Integer>> iterator = positions.entrySet().iterator(); iterator.hasNext();) { Entry<BlockPos, Integer> entry = iterator.next(); RelativeBlockPos pos = new RelativeBlockPos(mainTile.te, entry.getKey()); list.appendTag(new NBTTagIntArray(new int[] { pos.getRelativePos().getX(), pos.getRelativePos().getY(), pos.getRelativePos().getZ(), entry.getValue() })); } nbt.setTag("tiles", list); } for (StructureTypeRelative relative : type.relatives) { StructureRelative relativeST = relative.getRelative(this); if (relativeST == null) continue; relativeST.writeToNBT(relative.saveKey, nbt); } writeToNBTExtra(nbt); } protected abstract void writeToNBTExtra(NBTTagCompound nbt); // ================Item Form================ public void addIngredients(LittleIngredients ingredients) { } public void finializePreview(LittlePreviews previews) { } // ====================Destroy==================== public void onLittleTileDestroy() { if (parent != null) { if (parent.isConnected(getWorld())) parent.getStructure(getWorld()).onLittleTileDestroy(); return; } mainTile = null; if (load() && loadChildren()) removeStructure(); } public void removeStructure() { checkLoaded(); onStructureDestroyed(); if (this instanceof IAnimatedStructure && ((IAnimatedStructure) this).isAnimated()) ((IAnimatedStructure) this).destroyAnimation(); else for (Entry<BlockPos, ArrayList<LittleTile>> entry : tiles.entrySet()) try { loadTE(entry.getKey()).updateTiles((x) -> x.removeAll(entry.getValue())); } catch (MissingTileEntity e) { //e.printStackTrace(); } for (IStructureChildConnector child : children) child.destroyStructure(); } /** Is called before the structure is removed */ public void onStructureDestroyed() { } // ====================Previews==================== public LittleGridContext getMinContext() { LittleGridContext context = LittleGridContext.getMin(); for (IStructureChildConnector child : children) context = LittleGridContext.max(context, child.getStructure(getWorld()).getMinContext()); for (StructureTypeRelative relative : type.relatives) { StructureRelative relativeST = relative.getRelative(this); if (relativeST == null) continue; relativeST.convertToSmallest(); context = LittleGridContext.max(context, relativeST.getContext()); } return context; } public LittleAbsolutePreviewsStructure getAbsolutePreviews(BlockPos pos) { NBTTagCompound structureNBT = new NBTTagCompound(); this.writeToNBTPreview(structureNBT, pos); LittleAbsolutePreviewsStructure previews = new LittleAbsolutePreviewsStructure(structureNBT, pos, getMinContext()); for (Iterator<LittleTile> iterator = getTiles(); iterator.hasNext();) { previews.addTile(iterator.next()); } for (IStructureChildConnector child : children) previews.addChild(child.getStructure(getWorld()).getPreviews(pos)); previews.convertToSmallest(); previews.ensureContext(getMinContext()); return previews; } public LittlePreviewsStructure getPreviews(BlockPos pos) { NBTTagCompound structureNBT = new NBTTagCompound(); this.writeToNBTPreview(structureNBT, pos); LittlePreviewsStructure previews = new LittlePreviewsStructure(structureNBT, getMinContext()); for (Iterator<LittleTile> iterator = getTiles(); iterator.hasNext();) { LittleTile tile = iterator.next(); LittleTilePreview preview = previews.addTile(tile); preview.box.add(new LittleTileVec(previews.context, tile.getBlockPos().subtract(pos))); } for (IStructureChildConnector child : children) previews.addChild(child.getStructure(getWorld()).getPreviews(pos)); previews.convertToSmallest(); previews.ensureContext(getMinContext()); return previews; } public LittleAbsolutePreviewsStructure getAbsolutePreviewsSameWorldOnly(BlockPos pos) { NBTTagCompound structureNBT = new NBTTagCompound(); this.writeToNBTPreview(structureNBT, pos); LittleAbsolutePreviewsStructure previews = new LittleAbsolutePreviewsStructure(structureNBT, pos, getMinContext()); for (Iterator<LittleTile> iterator = getTiles(); iterator.hasNext();) previews.addTile(iterator.next()); for (IStructureChildConnector child : children) if (!child.isLinkToAnotherWorld()) previews.addChild(child.getStructure(getWorld()).getPreviewsSameWorldOnly(pos)); else previews.getStructure().addTempChild(child.getStructure(getWorld())); previews.convertToSmallest(); previews.ensureContext(getMinContext()); return previews; } public LittlePreviewsStructure getPreviewsSameWorldOnly(BlockPos pos) { NBTTagCompound structureNBT = new NBTTagCompound(); this.writeToNBTPreview(structureNBT, pos); LittlePreviewsStructure previews = new LittlePreviewsStructure(structureNBT, getMinContext()); for (Iterator<LittleTile> iterator = getTiles(); iterator.hasNext();) { LittleTile tile = iterator.next(); LittleTilePreview preview = previews.addTile(tile); preview.box.add(new LittleTileVec(previews.context, tile.getBlockPos().subtract(pos))); } for (IStructureChildConnector child : children) if (!child.isLinkToAnotherWorld()) previews.addChild(child.getStructure(getWorld()).getPreviews(pos)); else previews.getStructure().addTempChild(child.getStructure(getWorld())); previews.convertToSmallest(); previews.ensureContext(getMinContext()); return previews; } public MutableBlockPos getMinPos(MutableBlockPos pos) { for (BlockPos tePos : tiles.keySet()) pos.setPos(Math.min(pos.getX(), tePos.getX()), Math.min(pos.getY(), tePos.getY()), Math.min(pos.getZ(), tePos.getZ())); for (IStructureChildConnector child : children) child.getStructure(getWorld()).getMinPos(pos); return pos; } public List<PlacePreviewTile> getSpecialTiles(LittlePreviews previews) { if (type.relatives.isEmpty()) return Collections.EMPTY_LIST; List<PlacePreviewTile> placePreviews = new ArrayList<>(); for (StructureTypeRelative relative : type.relatives) { StructureRelative relativeST = relative.getRelative(this); if (relativeST == null) continue; PlacePreviewTile tile = getPlacePreview(relativeST, relative, previews); if (relativeST.getContext().size < previews.context.size) tile.convertTo(relativeST.getContext(), previews.context); placePreviews.add(tile); } return placePreviews; } protected PlacePreviewTile getPlacePreview(StructureRelative relative, StructureTypeRelative type, LittlePreviews previews) { return relative.getPlacePreview(previews, type); } // ====================Transform & Transfer==================== public void transferChildrenToAnimation(EntityAnimation animation) { for (IStructureChildConnector child : children) { LittleStructure childStructure = child.getStructure(getWorld()); if (child.isLinkToAnotherWorld()) { EntityAnimation subAnimation = ((IAnimatedStructure) childStructure).getAnimation(); int l1 = subAnimation.chunkCoordX; int i2 = subAnimation.chunkCoordZ; World world = getWorld(); if (subAnimation.addedToChunk) { Chunk chunk = world.getChunkFromChunkCoords(l1, i2); if (chunk != null) chunk.removeEntity(subAnimation); subAnimation.addedToChunk = false; } world.loadedEntityList.remove(subAnimation); subAnimation.setParentWorld(animation.fakeWorld); animation.fakeWorld.spawnEntity(subAnimation); subAnimation.updateTickState(); } else childStructure.transferChildrenToAnimation(animation); } } public void transferChildrenFromAnimation(EntityAnimation animation) { World parentWorld = animation.fakeWorld.getParent(); for (IStructureChildConnector child : children) { LittleStructure childStructure = child.getStructure(getWorld()); if (child.isLinkToAnotherWorld()) { EntityAnimation subAnimation = ((IAnimatedStructure) childStructure).getAnimation(); int l1 = subAnimation.chunkCoordX; int i2 = subAnimation.chunkCoordZ; if (subAnimation.addedToChunk) { Chunk chunk = animation.fakeWorld.getChunkFromChunkCoords(l1, i2); if (chunk != null) chunk.removeEntity(subAnimation); subAnimation.addedToChunk = false; } animation.fakeWorld.loadedEntityList.remove(subAnimation); subAnimation.setParentWorld(parentWorld); parentWorld.spawnEntity(subAnimation); subAnimation.updateTickState(); } else childStructure.transferChildrenFromAnimation(animation); } } public void transformAnimation(LittleTransformation transformation) { for (IStructureChildConnector child : children) { LittleStructure childStructure = child.getStructure(getWorld()); if (child.isLinkToAnotherWorld()) ((IAnimatedStructure) childStructure).getAnimation().transformWorld(transformation); else childStructure.transformAnimation(transformation); } } // ====================Relatives==================== public void onMove(LittleGridContext context, LittleTileVec offset) { for (StructureTypeRelative relative : type.relatives) { StructureRelative relativeST = relative.getRelative(this); if (relativeST == null) continue; relativeST.onMove(this, context, offset); } } public void onFlip(LittleGridContext context, Axis axis, LittleTileVec doubledCenter) { for (StructureTypeRelative relative : type.relatives) { StructureRelative relativeST = relative.getRelative(this); if (relativeST == null) continue; relativeST.onFlip(this, context, axis, doubledCenter); } } public void onRotate(LittleGridContext context, Rotation rotation, LittleTileVec doubledCenter) { for (StructureTypeRelative relative : type.relatives) { StructureRelative relativeST = relative.getRelative(this); if (relativeST == null) continue; relativeST.onRotate(this, context, rotation, doubledCenter); } } // ====================Helpers==================== public AxisAlignedBB getSurroundingBox() { if (load()) return new SurroundingBox(true).add(tiles.entrySet()).getSurroundingBox(); return null; } public Vec3d getHighestCenterVec() { if (load()) return new SurroundingBox(true).add(tiles.entrySet()).getHighestCenterVec(); return null; } public LittleTilePos getHighestCenterPoint() { if (load()) return new SurroundingBox(true).add(tiles.entrySet()).getHighestCenterPoint(); return null; } // ====================Extra==================== public ItemStack getStructureDrop() { if (parent != null) { if (parent.isConnected(getWorld())) return parent.getStructure(getWorld()).getStructureDrop(); return ItemStack.EMPTY; } if (load() && loadChildren()) { BlockPos pos = getMinPos(new MutableBlockPos(getMainTile().getBlockPos())); ItemStack stack = new ItemStack(LittleTiles.multiTiles); LittlePreviews previews = getPreviews(pos); LittleTilePreview.savePreview(previews, stack); if (name != null) { NBTTagCompound display = new NBTTagCompound(); display.setString("Name", name); stack.getTagCompound().setTag("display", display); } return stack; } return ItemStack.EMPTY; } public boolean onBlockActivated(World worldIn, LittleTile tile, BlockPos pos, IBlockState state, EntityPlayer playerIn, EnumHand hand, @Nullable ItemStack heldItem, EnumFacing side, float hitX, float hitY, float hitZ, LittleActionActivated action) throws LittleActionException { return false; } public boolean isBed(IBlockAccess world, BlockPos pos, EntityLivingBase player) { return false; } public void onEntityCollidedWithBlock(World worldIn, BlockPos pos, IBlockState state, Entity entityIn) { } public void onUpdatePacketReceived() { } // ====================Premade==================== public boolean canOnlyBePlacedByItemStack() { return false; } /** Only important for structures which require to be placed by the given * itemstack * * @return */ public String getStructureDropIdentifier() { return null; } }
Fixed crash when removing structure
src/main/java/com/creativemd/littletiles/common/structure/LittleStructure.java
Fixed crash when removing structure
<ide><path>rc/main/java/com/creativemd/littletiles/common/structure/LittleStructure.java <ide> return; <ide> } <ide> <del> mainTile = null; <del> <ide> if (load() && loadChildren()) <ide> removeStructure(); <ide> } <ide> <ide> onStructureDestroyed(); <ide> <add> for (IStructureChildConnector child : children) <add> child.destroyStructure(); <add> <ide> if (this instanceof IAnimatedStructure && ((IAnimatedStructure) this).isAnimated()) <ide> ((IAnimatedStructure) this).destroyAnimation(); <del> else <add> else if (mainTile.te.contains(mainTile)) <ide> for (Entry<BlockPos, ArrayList<LittleTile>> entry : tiles.entrySet()) <ide> try { <ide> loadTE(entry.getKey()).updateTiles((x) -> x.removeAll(entry.getValue())); <ide> //e.printStackTrace(); <ide> } <ide> <del> for (IStructureChildConnector child : children) <del> child.destroyStructure(); <ide> } <ide> <ide> /** Is called before the structure is removed */
Java
apache-2.0
21543194b1049efa7f42c55d66d412c0b8cc0f9a
0
googleapis/java-core,googleapis/java-core,googleapis/java-core
/* * Copyright 2017 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.cloud; import static java.nio.charset.StandardCharsets.UTF_8; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; /** * Retrieves Google Cloud project-id and a limited set of instance attributes from Metadata server. * @see <a href="https://cloud.google.com/compute/docs/storing-retrieving-metadata"> * https://cloud.google.com/compute/docs/storing-retrieving-metadata</a> */ public class MetadataConfig { private static final String METADATA_URL = "http://metadata/computeMetadata/v1/"; private MetadataConfig() { } public static String getProjectId() { return getAttribute("project/project-id"); } public static String getZone() { String zoneId = getAttribute("instance/zone"); if (zoneId.contains("/")) { return zoneId.substring(zoneId.lastIndexOf('/') + 1); } return zoneId; } public static String getInstanceId() { return getAttribute("instance/id"); } public static String getClusterName() { return getAttribute("instance/attributes/cluster-name"); } public static String getContainerName(){ return getAttribute("instance/attributes/container-name"); } public static String getNamespaceId(){ return getAttribute("instance/attributes/namespace-id"); } public static String getAttribute(String attributeName) { try { URL url = new URL(METADATA_URL + attributeName); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestProperty("Metadata-Flavor", "Google"); InputStream input = connection.getInputStream(); if (connection.getResponseCode() == 200) { try (BufferedReader reader = new BufferedReader(new InputStreamReader(input, UTF_8))) { return reader.readLine(); } } } catch (IOException ignore) { // ignore } return null; } }
google-cloud-core/src/main/java/com/google/cloud/MetadataConfig.java
/* * Copyright 2017 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.cloud; import static java.nio.charset.StandardCharsets.UTF_8; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; /** * Retrieves Google Cloud project-id and a limited set of instance attributes from Metadata server. * @see <a href="https://cloud.google.com/compute/docs/storing-retrieving-metadata"> * https://cloud.google.com/compute/docs/storing-retrieving-metadata</a> */ public class MetadataConfig { private static final String METADATA_URL = "http://metadata/computeMetadata/v1/"; private MetadataConfig() { } public static String getProjectId() { return getAttribute("project/project-id"); } public static String getZone() { String zoneId = getAttribute("instance/zone"); if (zoneId.contains("/")) { return zoneId.substring(zoneId.lastIndexOf('/') + 1); } return zoneId; } public static String getInstanceId() { return getAttribute("instance/id"); } public static String getClusterName() { return getAttribute("instance/attributes/cluster-name"); } public static String getAttribute(String attributeName) { try { URL url = new URL(METADATA_URL + attributeName); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestProperty("Metadata-Flavor", "Google"); InputStream input = connection.getInputStream(); if (connection.getResponseCode() == 200) { try (BufferedReader reader = new BufferedReader(new InputStreamReader(input, UTF_8))) { return reader.readLine(); } } } catch (IOException ignore) { // ignore } return null; } }
Add missing fields on MonitoredResourceUtil (#3887) * added missing fields #3559 * Fix indentation
google-cloud-core/src/main/java/com/google/cloud/MetadataConfig.java
Add missing fields on MonitoredResourceUtil (#3887)
<ide><path>oogle-cloud-core/src/main/java/com/google/cloud/MetadataConfig.java <ide> return getAttribute("instance/attributes/cluster-name"); <ide> } <ide> <add> public static String getContainerName(){ <add> return getAttribute("instance/attributes/container-name"); <add> } <add> <add> public static String getNamespaceId(){ <add> return getAttribute("instance/attributes/namespace-id"); <add> } <add> <ide> public static String getAttribute(String attributeName) { <ide> try { <ide> URL url = new URL(METADATA_URL + attributeName);
Java
bsd-3-clause
47c444d1ca3691328b18080cd81ff76197836e7b
0
shankari/cordova-unified-logger,e-mission/cordova-unified-logger,shankari/cordova-unified-logger,e-mission/cordova-unified-logger
package edu.berkeley.eecs.emission.cordova.unifiedlogger; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.support.v4.app.NotificationCompat; import org.apache.cordova.CordovaActivity; import edu.berkeley.eecs.emission.MainActivity; import edu.berkeley.eecs.emission.R; public class NotificationHelper { private static String TAG = "NotificationHelper"; public static void createNotification(Context context, int id, String message) { NotificationCompat.Builder builder = new NotificationCompat.Builder(context); Bitmap appIcon = BitmapFactory.decodeResource(context.getResources(), R.mipmap.icon); builder.setLargeIcon(appIcon); builder.setSmallIcon(R.drawable.ic_visibility_black); builder.setContentTitle(context.getString(R.string.app_name)); builder.setContentText(message); /* * This is a bit of magic voodoo. The tutorial on launching the activity actually uses a stackbuilder * to create a fake stack for the new activity. However, it looks like the stackbuilder * is only available in more recent versions of the API. So I use the version for a special activity PendingIntent * (since our app currently has only one activity) which resolves that issue. * This also appears to work, at least in the emulator. * * TODO: Decide what level API we want to support, and whether we want a more comprehensive activity. */ Intent activityIntent = new Intent(context, MainActivity.class); activityIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); PendingIntent activityPendingIntent = PendingIntent.getActivity(context, 0, activityIntent, PendingIntent.FLAG_UPDATE_CURRENT); builder.setContentIntent(activityPendingIntent); NotificationManager nMgr = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE); Log.d(context, TAG, "Generating notify with id " + id + " and message " + message); nMgr.notify(id, builder.build()); } /* * Used to show a pending intent - e.g. to turn on location services */ public static void createNotification(Context context, int id, String message, PendingIntent intent) { NotificationCompat.Builder builder = new NotificationCompat.Builder(context); Bitmap appIcon = BitmapFactory.decodeResource(context.getResources(), R.mipmap.icon); builder.setLargeIcon(appIcon); builder.setSmallIcon(R.drawable.ic_visibility_black); builder.setContentTitle(context.getString(R.string.app_name)); builder.setContentText(message); /* * This is a bit of magic voodoo. The tutorial on launching the activity actually uses a stackbuilder * to create a fake stack for the new activity. However, it looks like the stackbuilder * is only available in more recent versions of the API. So I use the version for a special activity PendingIntent * (since our app currently has only one activity) which resolves that issue. * This also appears to work, at least in the emulator. * * TODO: Decide what level API we want to support, and whether we want a more comprehensive activity. */ builder.setContentIntent(intent); builder.setAutoCancel(true); NotificationManager nMgr = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE); Log.d(context, TAG, "Generating notify with id " + id + " and message " + message); nMgr.notify(id, builder.build()); } }
src/android/NotificationHelper.java
package edu.berkeley.eecs.emission.cordova.unifiedlogger; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.support.v4.app.NotificationCompat; import org.apache.cordova.CordovaActivity; import edu.berkeley.eecs.emission.MainActivity; import edu.berkeley.eecs.emission.R; public class NotificationHelper { private static String TAG = "NotificationHelper"; public static void createNotification(Context context, int id, String message) { NotificationCompat.Builder builder = new NotificationCompat.Builder(context); Bitmap appIcon = BitmapFactory.decodeResource(context.getResources(), R.drawable.icon); builder.setLargeIcon(appIcon); builder.setSmallIcon(R.drawable.ic_visibility_black); builder.setContentTitle(context.getString(R.string.app_name)); builder.setContentText(message); /* * This is a bit of magic voodoo. The tutorial on launching the activity actually uses a stackbuilder * to create a fake stack for the new activity. However, it looks like the stackbuilder * is only available in more recent versions of the API. So I use the version for a special activity PendingIntent * (since our app currently has only one activity) which resolves that issue. * This also appears to work, at least in the emulator. * * TODO: Decide what level API we want to support, and whether we want a more comprehensive activity. */ Intent activityIntent = new Intent(context, MainActivity.class); activityIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); PendingIntent activityPendingIntent = PendingIntent.getActivity(context, 0, activityIntent, PendingIntent.FLAG_UPDATE_CURRENT); builder.setContentIntent(activityPendingIntent); NotificationManager nMgr = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE); Log.d(context, TAG, "Generating notify with id " + id + " and message " + message); nMgr.notify(id, builder.build()); } /* * Used to show a pending intent - e.g. to turn on location services */ public static void createNotification(Context context, int id, String message, PendingIntent intent) { NotificationCompat.Builder builder = new NotificationCompat.Builder(context); Bitmap appIcon = BitmapFactory.decodeResource(context.getResources(), R.drawable.icon); builder.setLargeIcon(appIcon); builder.setSmallIcon(R.drawable.ic_visibility_black); builder.setContentTitle(context.getString(R.string.app_name)); builder.setContentText(message); /* * This is a bit of magic voodoo. The tutorial on launching the activity actually uses a stackbuilder * to create a fake stack for the new activity. However, it looks like the stackbuilder * is only available in more recent versions of the API. So I use the version for a special activity PendingIntent * (since our app currently has only one activity) which resolves that issue. * This also appears to work, at least in the emulator. * * TODO: Decide what level API we want to support, and whether we want a more comprehensive activity. */ builder.setContentIntent(intent); builder.setAutoCancel(true); NotificationManager nMgr = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE); Log.d(context, TAG, "Generating notify with id " + id + " and message " + message); nMgr.notify(id, builder.build()); } }
Change the icons in the notification helper to match the new locations Icons are now in mipmap instead of drawable https://android-developers.googleblog.com/2014/10/getting-your-apps-ready-for-nexus-6-and.html
src/android/NotificationHelper.java
Change the icons in the notification helper to match the new locations
<ide><path>rc/android/NotificationHelper.java <ide> <ide> public static void createNotification(Context context, int id, String message) { <ide> NotificationCompat.Builder builder = new NotificationCompat.Builder(context); <del> Bitmap appIcon = BitmapFactory.decodeResource(context.getResources(), R.drawable.icon); <add> Bitmap appIcon = BitmapFactory.decodeResource(context.getResources(), R.mipmap.icon); <ide> builder.setLargeIcon(appIcon); <ide> builder.setSmallIcon(R.drawable.ic_visibility_black); <ide> builder.setContentTitle(context.getString(R.string.app_name)); <ide> */ <ide> public static void createNotification(Context context, int id, String message, PendingIntent intent) { <ide> NotificationCompat.Builder builder = new NotificationCompat.Builder(context); <del> Bitmap appIcon = BitmapFactory.decodeResource(context.getResources(), R.drawable.icon); <add> Bitmap appIcon = BitmapFactory.decodeResource(context.getResources(), R.mipmap.icon); <ide> builder.setLargeIcon(appIcon); <ide> builder.setSmallIcon(R.drawable.ic_visibility_black); <ide> builder.setContentTitle(context.getString(R.string.app_name));
Java
bsd-3-clause
55623abde427d144c88b74c6f86304210d45aabb
0
Biomatters/barcode-validator,Biomatters/barcode-validator
package com.biomatters.plugins.barcoding.validator.research.report; import com.biomatters.geneious.publicapi.components.Dialogs; import com.biomatters.geneious.publicapi.components.GPanel; import com.biomatters.geneious.publicapi.components.GTable; import com.biomatters.geneious.publicapi.components.GTextPane; import com.biomatters.geneious.publicapi.documents.URN; import com.biomatters.geneious.publicapi.plugin.ActionProvider; import com.biomatters.geneious.publicapi.plugin.DocumentViewer; import com.biomatters.geneious.publicapi.plugin.GeneiousAction; import com.biomatters.geneious.publicapi.plugin.Options; import com.biomatters.geneious.publicapi.utilities.GeneralUtilities; import com.biomatters.geneious.publicapi.utilities.IconUtilities; import com.biomatters.geneious.publicapi.utilities.StringUtilities; import com.biomatters.plugins.barcoding.validator.output.RecordOfValidationResult; import com.biomatters.plugins.barcoding.validator.output.ValidationOutputRecord; import com.biomatters.plugins.barcoding.validator.output.ValidationReportDocument; import com.biomatters.plugins.barcoding.validator.research.report.table.ColumnGroup; import com.biomatters.plugins.barcoding.validator.research.report.table.GroupableTableHeader; import com.biomatters.plugins.barcoding.validator.research.report.table.GroupableTableHeaderUI; import com.biomatters.plugins.barcoding.validator.validation.ValidationOptions; import com.biomatters.plugins.barcoding.validator.validation.results.LinkResultColumn; import com.biomatters.plugins.barcoding.validator.validation.results.ResultColumn; import com.biomatters.plugins.barcoding.validator.validation.results.ResultFact; import javax.swing.*; import javax.swing.event.HyperlinkListener; import javax.swing.plaf.basic.BasicTableHeaderUI; import javax.swing.table.*; import java.awt.*; import java.awt.event.*; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.*; import java.util.List; import java.util.regex.Pattern; /** * Displays a {@link com.biomatters.plugins.barcoding.validator.output.ValidationReportDocument} in a user * friendly manner using Java's HTML viewer. * <br/> * The view is sortable and includes links to input and output * {@link com.biomatters.geneious.publicapi.documents.AnnotatedPluginDocument} in Geneious. * * @author Matthew Cheung * Created on 2/10/14 10:04 AM */ public class ValidationReportViewer extends DocumentViewer { ValidationReportDocument reportDocument; JTable table = null; public ValidationReportViewer(ValidationReportDocument reportDocument) { this.reportDocument = reportDocument; } public String getHtml() { return generateHtml(reportDocument); } public static final String OPTION_PREFIX = "option:"; public HyperlinkListener getHyperlinkListener() { final Map<String, ValidationOptions> optionsMap = getOptionMap(reportDocument); return new DocumentOpeningHyperlinkListener("ReportDocumentFactory", Collections.<String, DocumentOpeningHyperlinkListener.UrlProcessor>singletonMap(OPTION_PREFIX, new DocumentOpeningHyperlinkListener.UrlProcessor() { @Override void process(String url) { final String optionLable = url.substring(OPTION_PREFIX.length()); final ValidationOptions options = optionsMap.get(optionLable); SwingUtilities.invokeLater(new Runnable() { public void run() { options.setEnabled(false); Dialogs.DialogOptions dialogOptions = new Dialogs.DialogOptions(Dialogs.OK_ONLY, "Options"); Dialogs.showMoreOptionsDialog(dialogOptions, options.getPanel(), options.getAdvancedPanel()); } }); } })); } private static Map<String, ValidationOptions> getOptionMap(ValidationReportDocument reportDocument) { Map<String, ValidationOptions> ret = new HashMap<String, ValidationOptions>(); if (reportDocument == null || reportDocument.getRecords() == null) return ret; List<ValidationOutputRecord> records = reportDocument.getRecords(); for (ValidationOutputRecord record : records) { for (RecordOfValidationResult result : record.getValidationResults()) { ValidationOptions options = result.getOptions(); ret.put(options.getLabel(), options); } } return ret; } private static String generateHtml(ValidationReportDocument reportDocument) { List<ValidationOutputRecord> records = reportDocument.getRecords(); return getHeaderOfReport(records, reportDocument.getDescriptionOfOptions()); } private static String getHeaderOfReport(List<ValidationOutputRecord> records, String descriptionOfOptionUsed) { List<ValidationOutputRecord> recordsThatPassedAll = new ArrayList<ValidationOutputRecord>(); List<ValidationOutputRecord> recordsThatFailedAtLeastOnce = new ArrayList<ValidationOutputRecord>(); for (ValidationOutputRecord record : records) { if(record.isAllPassed()) { recordsThatPassedAll.add(record); } else { recordsThatFailedAtLeastOnce.add(record); } } boolean allPassed = recordsThatPassedAll.size() == records.size(); boolean allFailed = recordsThatFailedAtLeastOnce.size() == records.size(); StringBuilder headerBuilder = new StringBuilder("<h1>Validation Report</h1>"); headerBuilder.append(descriptionOfOptionUsed); headerBuilder.append("<br><br>").append( "Ran validations on <strong>").append(records.size()).append("</strong> sets of barcode data:"); headerBuilder.append("<ul>"); if(!allFailed) { appendHeaderLineItem(headerBuilder, "green", allPassed, recordsThatPassedAll, "passed all validations"); } if(!allPassed) { appendHeaderLineItem(headerBuilder, "red", allFailed, recordsThatFailedAtLeastOnce, "failed at least one validations"); } headerBuilder.append("</ul>"); return headerBuilder.toString(); } private static void appendHeaderLineItem(StringBuilder headerBuilder, String colour, boolean isAll, List<ValidationOutputRecord> records, String whatHappened) { List<URN> barcodeUrns = new ArrayList<URN>(); for (ValidationOutputRecord record : records) { barcodeUrns.add(record.getBarcodeSequenceUrn()); } String countString = (isAll ? "All " : "") + records.size(); headerBuilder.append( "<li><font color=\"").append(colour).append("\"><strong>").append( countString).append("</strong></font> sets ").append(whatHappened).append(". ").append( getLinkForSelectingDocuments("Select all", barcodeUrns)); } private static String getLinkForSelectingDocuments(String label, List<URN> documentUrns) { List<String> urnStrings = new ArrayList<String>(); for (URN inputUrn : documentUrns) { urnStrings.add(inputUrn.toString()); } return "<a href=\"" + StringUtilities.join(",", urnStrings) + "\">" + label + "</a>"; } private JTextPane getTextPane() { String html = getHtml(); if(html == null || html.isEmpty()) { return null; } final JTextPane textPane = new GTextPane(); textPane.setContentType("text/html"); textPane.setEditable(false); HyperlinkListener hyperlinkListener = getHyperlinkListener(); if(hyperlinkListener != null) { textPane.addHyperlinkListener(hyperlinkListener); } textPane.setText(html); return textPane; } @Override public JComponent getComponent() { JComponent textPane = getTextPane(); GPanel rootPanel = new GPanel(new BorderLayout()); final JScrollPane scroll = new JScrollPane(rootPanel); scroll.getViewport().setOpaque(false); scroll.setOpaque(false); scroll.setBorder(null); rootPanel.add(textPane, BorderLayout.NORTH); if (table == null) { table = getTable(); } if (table != null) { JScrollPane tableScrollPane = new JScrollPane(table, ScrollPaneConstants.VERTICAL_SCROLLBAR_NEVER, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER); // Set the scroll pane's preferred size to the same as the table so scroll bars are never needed tableScrollPane.getViewport().setPreferredSize(table.getPreferredSize()); // Delegate our mouse wheel events on the table's scroll pane to the root one tableScrollPane.addMouseWheelListener(new MouseWheelListener() { @Override public void mouseWheelMoved(MouseWheelEvent e) { for (MouseWheelListener mouseWheelListener : scroll.getMouseWheelListeners()) { mouseWheelListener.mouseWheelMoved(e); } } }); rootPanel.add(tableScrollPane, BorderLayout.CENTER); } Dimension oldPrefSize = rootPanel.getPreferredSize(); // Add 500 px to the preferred height so users can scroll past the table rootPanel.setPreferredSize(new Dimension(oldPrefSize.width, oldPrefSize.height + 500)); return scroll; } public JTable getTable() { List<ValidationOutputRecord> records = reportDocument.getRecords(); final ValidationReportTableModel tableModel = new ValidationReportTableModel(records); final JTable table = new GTable(tableModel); table.setDefaultRenderer(ResultColumn.class, new DefaultTableCellRenderer() { @Override public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { return super.getTableCellRendererComponent(table, ((ResultColumn) value).getDisplayValue(), isSelected, hasFocus, row, column); } }); TableRowSorter<ValidationReportTableModel> sorter = new TableRowSorter<ValidationReportTableModel>(tableModel); for (int i = 0; i < table.getColumnCount(); i++) { Class<?> columnClass = table.getColumnClass(i); if(CellValue.class.isAssignableFrom(columnClass)) { sorter.setComparator(i, getCellValueComparator(CellValue.class)); } } table.setRowSorter(sorter); GroupableTableHeader head = new GroupableTableHeader(table.getTableHeader()); table.setTableHeader(head); TableCellRenderer headerRenderer = head.getDefaultRenderer(); if(headerRenderer instanceof DefaultTableCellRenderer) { ((DefaultTableCellRenderer) headerRenderer).setHorizontalAlignment(SwingConstants.CENTER); } table.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { if (e.getButton() != MouseEvent.BUTTON1) { return; } Object source = e.getSource(); if (source instanceof JTable) { JTable table = (JTable) source; Object cell = table.getValueAt(table.getSelectedRow(), table.getSelectedColumn()); if (cell instanceof CellValue) { ResultColumn value = ((CellValue) cell).value; if(value instanceof LinkResultColumn) { ((LinkResultColumn)value).getData().openLink(); } } } } }); mergeHeaer(table, records.get(0)); final GroupableTableHeaderUI groupableTableHeaderUI = new GroupableTableHeaderUI(); table.getTableHeader().setUI(groupableTableHeaderUI); table.setAutoCreateRowSorter(false); MouseListener[] mouseListeners = head.getMouseListeners(); MouseListener originalHeaderMouseListener = null; for (final MouseListener mouseListener : mouseListeners) { if(mouseListener instanceof BasicTableHeaderUI.MouseInputHandler) { originalHeaderMouseListener = mouseListener; } } if(originalHeaderMouseListener != null) { head.removeMouseListener(originalHeaderMouseListener); MouseAdapter wrapper = wrapMouseListenerForHeader(tableModel, table, groupableTableHeaderUI, originalHeaderMouseListener); head.addMouseListener(wrapper); } return table; } private MouseAdapter wrapMouseListenerForHeader(final ValidationReportTableModel tableModel, final JTable table, final GroupableTableHeaderUI groupableTableHeaderUI, final MouseListener originalHeaderMouseListener) { return new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { int column = table.columnAtPoint(e.getPoint()); if (column >= tableModel.getFixedColumnLength() && e.getY() <= groupableTableHeaderUI.getHeaderHeight() / 2) { tableModel.displayOptions(column); } else { originalHeaderMouseListener.mouseClicked(e); } } }; } private static <T extends Comparable<T>> Comparator getCellValueComparator( // There is a warning that we don't use the class. But we need this parameter at compile time to type the generic @SuppressWarnings("UnusedParameters") Class<T> columnClass) { return new Comparator<CellValue<T>>() { @Override public int compare(CellValue<T> o1, CellValue<T> o2) { return o1.compareTo(o2); } }; } private void mergeHeaer(JTable table, ValidationOutputRecord record) { TableColumnModel cm = table.getColumnModel(); GroupableTableHeader head = (GroupableTableHeader) table.getTableHeader(); TableCellRenderer headerRenderer = head.getDefaultRenderer(); int colIndex = record.getFixedColumns(record.getTraceDocumentUrns().get(0)).size(); Map<Class, Map<URN, RecordOfValidationResult>> validationResultsMap = record.getValidationResultsMap(); for (Map<URN, RecordOfValidationResult> entry : validationResultsMap.values()) { if (entry.size() > 0) { ResultFact fact = entry.values().iterator().next().getFact(); ColumnGroup factGroup = new ColumnGroup(fact.getFactName(), headerRenderer); for (int i = 0; i < fact.getColumns().size(); i++) { factGroup.add(cm.getColumn(colIndex++)); } head.addColumnGroup(factGroup); } } } @Override public ActionProvider getActionProvider() { return new ActionProvider() { @Override public List<GeneiousAction> getOtherActions() { List<GeneiousAction> ret = new ArrayList<GeneiousAction>(); ret.add(new ExportReportAction("Export report table to csv file", table)); return ret; } }; } protected static class ExportReportAction extends GeneiousAction { private JTable table = null; public ExportReportAction(String name, JTable table) { super(name, null, IconUtilities.getIcons("export16.png")); this.table = table; } public void actionPerformed(ActionEvent e) { if (table == null) { Dialogs.showMessageDialog("Can not find table"); return; } SwingUtilities.invokeLater(new Runnable() { public void run() { Options options = new Options(ValidationReportViewer.class); Options.FileSelectionOption selectionOption = options.addFileSelectionOption("targetFolder", "Export Folder:", "", new String[0], "Browse..."); selectionOption.setSelectionType(JFileChooser.DIRECTORIES_ONLY); Options.StringOption filenameOption = options.addStringOption("filename", "Filename:", "report.csv", "Name of CSV file"); options.setEnabled(true); if (!Dialogs.showOptionsDialog(options, "Export report table to csv file", false)) { return; } File outFile = new File(selectionOption.getValue(), filenameOption.getValue()); if(outFile.exists()) { if (!Dialogs.showYesNoDialog(outFile.getName() + " already exists, do you want to replace it?", "Replace File?", null, Dialogs.DialogIcon.QUESTION)) { return; } } BufferedWriter writer = null; try { writer = new BufferedWriter(new FileWriter(outFile)); int columnCount = table.getColumnModel().getColumnCount(); List<String> values = getHeader(); writeRow(writer, values); int rowCount = table.getRowCount(); for (int row = 0; row < rowCount; row++) { values.clear(); for (int column=0; column < columnCount; column++) { Object value = table.getValueAt(row, column); if(value instanceof CellValue) { value = ((CellValue)value).value.getDisplayValue(); } if (value == null) { values.add(""); } else { values.add(stripHtmlTags(value.toString(), true)); } } writeRow(writer, values); } Dialogs.showMessageDialog("Table exported to " + outFile.getAbsolutePath() + " successfully."); } catch (IOException e1) { Dialogs.showMessageDialog("Failed to export table: " + e1.getMessage()); } finally { GeneralUtilities.attemptClose(writer); } } }); } protected List<String> getHeader(){ int columnCount = table.getColumnModel().getColumnCount(); GroupableTableHeader header = (GroupableTableHeader) table.getTableHeader(); List<String> values = new LinkedList<String>(); for (int column = 0; column < columnCount; column++) { StringBuilder sb = new StringBuilder(); Enumeration columnGroups = header.getColumnGroups(table.getColumnModel().getColumn(column)); while (columnGroups != null && columnGroups.hasMoreElements()) { sb.append(((ColumnGroup) columnGroups.nextElement()).getText()).append(" - "); } sb.append(table.getColumnModel().getColumn(column).getHeaderValue().toString()); values.add(sb.toString()); } return values; } private void writeRow(BufferedWriter writer, List<String> values) throws IOException { boolean first = true; for (String value : values) { if (first) { first = false; } else { writer.write(","); } writer.write(escapeValueForCsv(value)); } writer.newLine(); } private String escapeValueForCsv(String value) { value = value.replaceAll("\"", "\"\""); if (value.contains("\"") || value.contains(",") || value.contains("\n")) { value = "\"" + value + "\""; } return value; } private String stripHtmlTags(String string, boolean onlyIfStartsWithHtmlTag) { if ((string == null) || "".equals(string) || (onlyIfStartsWithHtmlTag && !string.regionMatches(true, 0, "<html>", 0, 6))) { return string; } string = Pattern.compile("</?[a-zA-Z0-9][^>]*>").matcher(string).replaceAll(""); string = string.replace("&gt;",">"); string = string.replace("&lt;","<"); return string; } } /** * A value in the table model that is aware of it's index and the value associated with the consensus * @param <T> Type of the data contained in a cell. Corresponds to the {@link com.biomatters.plugins.barcoding.validator.validation.results.ResultColumn} type. */ private static class CellValue<T extends Comparable<T>> implements Comparable<CellValue<T>> { private ResultColumn<T> consensusValue; private Integer index; private ResultColumn<T> value; public CellValue(ResultColumn<T> consensusValue, ResultColumn<T> value, Integer index) { this.consensusValue = consensusValue; this.value = value; this.index = index; } @Override public String toString() { return value.getDisplayValue().toString(); } @Override public int compareTo(CellValue<T> o) { int consensusCompareResult = consensusValue.getData().compareTo(o.consensusValue.getData()); if(consensusCompareResult == 0) { return index.compareTo(o.index); } else { return consensusCompareResult; } } } public static class ValidationReportTableModel extends AbstractTableModel { private List<ValidationOutputRecord> records; private List<List<CellValue<?>>> data = new ArrayList<List<CellValue<?>>>(); public ValidationReportTableModel(List<ValidationOutputRecord> records) { this.records = new ArrayList<ValidationOutputRecord>(); for (ValidationOutputRecord record : records) { this.records.add(record); } updateTable(); } @Override public Class<?> getColumnClass(int columnIndex) { return CellValue.class; } public void updateTable() { data = new ArrayList<List<CellValue<?>>>(); for (ValidationOutputRecord record : records) { List<ResultColumn> firstRow = null; for (List<ResultColumn> resultColumns : record.exportTable()) { if(firstRow == null) { firstRow = resultColumns; } List<CellValue<?>> values = new ArrayList<CellValue<?>>(); for(int columnIndex=0; columnIndex<resultColumns.size(); columnIndex++) { CellValue<?> cellValue = getCellValue(firstRow.get(columnIndex), resultColumns.get(columnIndex), columnIndex); values.add(cellValue); } data.add(values); } } } private <T extends Comparable<T>> CellValue getCellValue(ResultColumn<T> firstRowValue, ResultColumn currentRowValue, int columnIndex) { // Have to cast because getClass() actually returns Class<? extends ResultColumn> due to type erasure :( //noinspection unchecked Class<ResultColumn<T>> firstRowClass = (Class<ResultColumn<T>>) firstRowValue.getClass(); return new CellValue<T>(firstRowClass.cast(firstRowValue), firstRowClass.cast(currentRowValue), columnIndex); } @Override public int getRowCount() { return data.size(); } @Override public int getColumnCount() { if (data.size() == 0) { return 0; } return data.get(0).size(); } @Override public CellValue getValueAt(int rowIndex, int columnIndex) { return data.get(rowIndex).get(columnIndex); } @Override public String getColumnName(int column) { if (data.size() == 0) { return super.getColumnName(column); } return data.get(0).get(column).value.getName(); } public void displayOptions(int columnIndex) { final ValidationOptions options = getOptionAt(columnIndex); if (options == null) { return; } SwingUtilities.invokeLater(new Runnable() { public void run() { options.setEnabled(false); Dialogs.DialogOptions dialogOptions = new Dialogs.DialogOptions(Dialogs.OK_ONLY, "Options"); Dialogs.showMoreOptionsDialog(dialogOptions, options.getPanel(), options.getAdvancedPanel()); } }); } public ValidationOptions getOptionAt(int columnIndex) { assert records != null && records.size() > 0; Map<Integer, ValidationOptions> colunmOptionsMap = records.get(0).getColunmOptionsMap(false); assert colunmOptionsMap != null; return colunmOptionsMap.get(columnIndex); } public int getFixedColumnLength() { assert records != null && records.size() > 0; ValidationOutputRecord record = records.get(0); return record.getFixedColumns(record.getOneURN()).size(); } } }
researchTool/src/com/biomatters/plugins/barcoding/validator/research/report/ValidationReportViewer.java
package com.biomatters.plugins.barcoding.validator.research.report; import com.biomatters.geneious.publicapi.components.Dialogs; import com.biomatters.geneious.publicapi.components.GPanel; import com.biomatters.geneious.publicapi.components.GTable; import com.biomatters.geneious.publicapi.components.GTextPane; import com.biomatters.geneious.publicapi.documents.URN; import com.biomatters.geneious.publicapi.plugin.ActionProvider; import com.biomatters.geneious.publicapi.plugin.DocumentViewer; import com.biomatters.geneious.publicapi.plugin.GeneiousAction; import com.biomatters.geneious.publicapi.plugin.Options; import com.biomatters.geneious.publicapi.utilities.GeneralUtilities; import com.biomatters.geneious.publicapi.utilities.IconUtilities; import com.biomatters.geneious.publicapi.utilities.StringUtilities; import com.biomatters.plugins.barcoding.validator.output.RecordOfValidationResult; import com.biomatters.plugins.barcoding.validator.output.ValidationOutputRecord; import com.biomatters.plugins.barcoding.validator.output.ValidationReportDocument; import com.biomatters.plugins.barcoding.validator.research.report.table.ColumnGroup; import com.biomatters.plugins.barcoding.validator.research.report.table.GroupableTableHeader; import com.biomatters.plugins.barcoding.validator.research.report.table.GroupableTableHeaderUI; import com.biomatters.plugins.barcoding.validator.validation.ValidationOptions; import com.biomatters.plugins.barcoding.validator.validation.results.LinkResultColumn; import com.biomatters.plugins.barcoding.validator.validation.results.ResultColumn; import com.biomatters.plugins.barcoding.validator.validation.results.ResultFact; import javax.swing.*; import javax.swing.event.HyperlinkListener; import javax.swing.plaf.basic.BasicTableHeaderUI; import javax.swing.table.*; import java.awt.*; import java.awt.event.*; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.*; import java.util.List; import java.util.regex.Pattern; /** * Displays a {@link com.biomatters.plugins.barcoding.validator.output.ValidationReportDocument} in a user * friendly manner using Java's HTML viewer. * <br/> * The view is sortable and includes links to input and output * {@link com.biomatters.geneious.publicapi.documents.AnnotatedPluginDocument} in Geneious. * * @author Matthew Cheung * Created on 2/10/14 10:04 AM */ public class ValidationReportViewer extends DocumentViewer { ValidationReportDocument reportDocument; JTable table = null; public ValidationReportViewer(ValidationReportDocument reportDocument) { this.reportDocument = reportDocument; } public String getHtml() { return generateHtml(reportDocument); } public static final String OPTION_PREFIX = "option:"; public HyperlinkListener getHyperlinkListener() { final Map<String, ValidationOptions> optionsMap = getOptionMap(reportDocument); return new DocumentOpeningHyperlinkListener("ReportDocumentFactory", Collections.<String, DocumentOpeningHyperlinkListener.UrlProcessor>singletonMap(OPTION_PREFIX, new DocumentOpeningHyperlinkListener.UrlProcessor() { @Override void process(String url) { final String optionLable = url.substring(OPTION_PREFIX.length()); final ValidationOptions options = optionsMap.get(optionLable); SwingUtilities.invokeLater(new Runnable() { public void run() { options.setEnabled(false); Dialogs.DialogOptions dialogOptions = new Dialogs.DialogOptions(Dialogs.OK_ONLY, "Options"); Dialogs.showMoreOptionsDialog(dialogOptions, options.getPanel(), options.getAdvancedPanel()); } }); } })); } private static Map<String, ValidationOptions> getOptionMap(ValidationReportDocument reportDocument) { Map<String, ValidationOptions> ret = new HashMap<String, ValidationOptions>(); if (reportDocument == null || reportDocument.getRecords() == null) return ret; List<ValidationOutputRecord> records = reportDocument.getRecords(); for (ValidationOutputRecord record : records) { for (RecordOfValidationResult result : record.getValidationResults()) { ValidationOptions options = result.getOptions(); ret.put(options.getLabel(), options); } } return ret; } private static String generateHtml(ValidationReportDocument reportDocument) { List<ValidationOutputRecord> records = reportDocument.getRecords(); return getHeaderOfReport(records, reportDocument.getDescriptionOfOptions()); } private static String getHeaderOfReport(List<ValidationOutputRecord> records, String descriptionOfOptionUsed) { List<ValidationOutputRecord> recordsThatPassedAll = new ArrayList<ValidationOutputRecord>(); List<ValidationOutputRecord> recordsThatFailedAtLeastOnce = new ArrayList<ValidationOutputRecord>(); for (ValidationOutputRecord record : records) { if(record.isAllPassed()) { recordsThatPassedAll.add(record); } else { recordsThatFailedAtLeastOnce.add(record); } } boolean allPassed = recordsThatPassedAll.size() == records.size(); boolean allFailed = recordsThatFailedAtLeastOnce.size() == records.size(); StringBuilder headerBuilder = new StringBuilder("<h1>Validation Report</h1>"); headerBuilder.append(descriptionOfOptionUsed); headerBuilder.append("<br><br>").append( "Ran validations on <strong>").append(records.size()).append("</strong> sets of barcode data:"); headerBuilder.append("<ul>"); if(!allFailed) { appendHeaderLineItem(headerBuilder, "green", allPassed, recordsThatPassedAll, "passed all validations"); } if(!allPassed) { appendHeaderLineItem(headerBuilder, "red", allFailed, recordsThatFailedAtLeastOnce, "failed at least one validations"); } headerBuilder.append("</ul>"); return headerBuilder.toString(); } private static void appendHeaderLineItem(StringBuilder headerBuilder, String colour, boolean isAll, List<ValidationOutputRecord> records, String whatHappened) { List<URN> barcodeUrns = new ArrayList<URN>(); for (ValidationOutputRecord record : records) { barcodeUrns.add(record.getBarcodeSequenceUrn()); } String countString = (isAll ? "All " : "") + records.size(); headerBuilder.append( "<li><font color=\"").append(colour).append("\"><strong>").append( countString).append("</strong></font> sets ").append(whatHappened).append(". ").append( getLinkForSelectingDocuments("Select all", barcodeUrns)); } private static String getLinkForSelectingDocuments(String label, List<URN> documentUrns) { List<String> urnStrings = new ArrayList<String>(); for (URN inputUrn : documentUrns) { urnStrings.add(inputUrn.toString()); } return "<a href=\"" + StringUtilities.join(",", urnStrings) + "\">" + label + "</a>"; } private JTextPane getTextPane() { String html = getHtml(); if(html == null || html.isEmpty()) { return null; } final JTextPane textPane = new GTextPane(); textPane.setContentType("text/html"); textPane.setEditable(false); HyperlinkListener hyperlinkListener = getHyperlinkListener(); if(hyperlinkListener != null) { textPane.addHyperlinkListener(hyperlinkListener); } textPane.setText(html); return textPane; } @Override public JComponent getComponent() { JComponent textPane = getTextPane(); GPanel rootPanel = new GPanel(new BorderLayout()); final JScrollPane scroll = new JScrollPane(rootPanel); scroll.getViewport().setOpaque(false); scroll.setOpaque(false); scroll.setBorder(null); rootPanel.add(textPane, BorderLayout.NORTH); if (table == null) { table = getTable(); } if (table != null) { JScrollPane tableScrollPane = new JScrollPane(table, ScrollPaneConstants.VERTICAL_SCROLLBAR_NEVER, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER); // Set the scroll pane's preferred size to the same as the table so scroll bars are never needed tableScrollPane.getViewport().setPreferredSize(table.getPreferredSize()); // Delegate our mouse wheel events on the table's scroll pane to the root one tableScrollPane.addMouseWheelListener(new MouseWheelListener() { @Override public void mouseWheelMoved(MouseWheelEvent e) { for (MouseWheelListener mouseWheelListener : scroll.getMouseWheelListeners()) { mouseWheelListener.mouseWheelMoved(e); } } }); rootPanel.add(tableScrollPane, BorderLayout.CENTER); } Dimension oldPrefSize = rootPanel.getPreferredSize(); // Add 500 px to the preferred height so users can scroll past the table rootPanel.setPreferredSize(new Dimension(oldPrefSize.width, oldPrefSize.height + 500)); return scroll; } public JTable getTable() { List<ValidationOutputRecord> records = reportDocument.getRecords(); final ValidationReportTableModel tableModel = new ValidationReportTableModel(records); final JTable table = new GTable(tableModel); table.setDefaultRenderer(ResultColumn.class, new DefaultTableCellRenderer() { @Override public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { return super.getTableCellRendererComponent(table, ((ResultColumn) value).getDisplayValue(), isSelected, hasFocus, row, column); } }); TableRowSorter<ValidationReportTableModel> sorter = new TableRowSorter<ValidationReportTableModel>(tableModel); for (int i = 0; i < table.getColumnCount(); i++) { Class<?> columnClass = table.getColumnClass(i); if(CellValue.class.isAssignableFrom(columnClass)) { sorter.setComparator(i, getCellValueComparator(CellValue.class)); } } table.setRowSorter(sorter); GroupableTableHeader head = new GroupableTableHeader(table.getTableHeader()); table.setTableHeader(head); TableCellRenderer headerRenderer = head.getDefaultRenderer(); if(headerRenderer instanceof DefaultTableCellRenderer) { ((DefaultTableCellRenderer) headerRenderer).setHorizontalAlignment(SwingConstants.CENTER); } table.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { if (e.getButton() != MouseEvent.BUTTON1) { return; } Object source = e.getSource(); if (source instanceof JTable) { JTable table = (JTable) source; Object cell = table.getValueAt(table.getSelectedRow(), table.getSelectedColumn()); if (cell instanceof LinkResultColumn.LinkBox) { ((LinkResultColumn.LinkBox) cell).openLink(); } } } }); mergeHeaer(table, records.get(0)); final GroupableTableHeaderUI groupableTableHeaderUI = new GroupableTableHeaderUI(); table.getTableHeader().setUI(groupableTableHeaderUI); table.setAutoCreateRowSorter(false); MouseListener[] mouseListeners = head.getMouseListeners(); MouseListener originalHeaderMouseListener = null; for (final MouseListener mouseListener : mouseListeners) { if(mouseListener instanceof BasicTableHeaderUI.MouseInputHandler) { originalHeaderMouseListener = mouseListener; } } if(originalHeaderMouseListener != null) { head.removeMouseListener(originalHeaderMouseListener); MouseAdapter wrapper = wrapMouseListenerForHeader(tableModel, table, groupableTableHeaderUI, originalHeaderMouseListener); head.addMouseListener(wrapper); } return table; } private MouseAdapter wrapMouseListenerForHeader(final ValidationReportTableModel tableModel, final JTable table, final GroupableTableHeaderUI groupableTableHeaderUI, final MouseListener originalHeaderMouseListener) { return new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { int column = table.columnAtPoint(e.getPoint()); if (column >= tableModel.getFixedColumnLength() && e.getY() <= groupableTableHeaderUI.getHeaderHeight() / 2) { tableModel.displayOptions(column); } else { originalHeaderMouseListener.mouseClicked(e); } } }; } private static <T extends Comparable<T>> Comparator getCellValueComparator( // There is a warning that we don't use the class. But we need this parameter at compile time to type the generic @SuppressWarnings("UnusedParameters") Class<T> columnClass) { return new Comparator<CellValue<T>>() { @Override public int compare(CellValue<T> o1, CellValue<T> o2) { return o1.compareTo(o2); } }; } private void mergeHeaer(JTable table, ValidationOutputRecord record) { TableColumnModel cm = table.getColumnModel(); GroupableTableHeader head = (GroupableTableHeader) table.getTableHeader(); TableCellRenderer headerRenderer = head.getDefaultRenderer(); int colIndex = record.getFixedColumns(record.getTraceDocumentUrns().get(0)).size(); Map<Class, Map<URN, RecordOfValidationResult>> validationResultsMap = record.getValidationResultsMap(); for (Map<URN, RecordOfValidationResult> entry : validationResultsMap.values()) { if (entry.size() > 0) { ResultFact fact = entry.values().iterator().next().getFact(); ColumnGroup factGroup = new ColumnGroup(fact.getFactName(), headerRenderer); for (int i = 0; i < fact.getColumns().size(); i++) { factGroup.add(cm.getColumn(colIndex++)); } head.addColumnGroup(factGroup); } } } @Override public ActionProvider getActionProvider() { return new ActionProvider() { @Override public List<GeneiousAction> getOtherActions() { List<GeneiousAction> ret = new ArrayList<GeneiousAction>(); ret.add(new ExportReportAction("Export report table to csv file", table)); return ret; } }; } protected static class ExportReportAction extends GeneiousAction { private JTable table = null; public ExportReportAction(String name, JTable table) { super(name, null, IconUtilities.getIcons("export16.png")); this.table = table; } public void actionPerformed(ActionEvent e) { if (table == null) { Dialogs.showMessageDialog("Can not find table"); return; } SwingUtilities.invokeLater(new Runnable() { public void run() { Options options = new Options(ValidationReportViewer.class); Options.FileSelectionOption selectionOption = options.addFileSelectionOption("targetFolder", "Export Folder:", "", new String[0], "Browse..."); selectionOption.setSelectionType(JFileChooser.DIRECTORIES_ONLY); Options.StringOption filenameOption = options.addStringOption("filename", "Filename:", "report.csv", "Name of CSV file"); options.setEnabled(true); if (!Dialogs.showOptionsDialog(options, "Export report table to csv file", false)) { return; } File outFile = new File(selectionOption.getValue(), filenameOption.getValue()); if(outFile.exists()) { if (!Dialogs.showYesNoDialog(outFile.getName() + " already exists, do you want to replace it?", "Replace File?", null, Dialogs.DialogIcon.QUESTION)) { return; } } BufferedWriter writer = null; try { writer = new BufferedWriter(new FileWriter(outFile)); int columnCount = table.getColumnModel().getColumnCount(); List<String> values = getHeader(); writeRow(writer, values); int rowCount = table.getRowCount(); for (int row = 0; row < rowCount; row++) { values.clear(); for (int column=0; column < columnCount; column++) { Object value = table.getValueAt(row, column); if(value instanceof ResultColumn) { value = ((ResultColumn)value).getDisplayValue(); } if (value == null) { values.add(""); } else { values.add(stripHtmlTags(value.toString(), true)); } } writeRow(writer, values); } Dialogs.showMessageDialog("Table exported to " + outFile.getAbsolutePath() + " successfully."); } catch (IOException e1) { Dialogs.showMessageDialog("Failed to export table: " + e1.getMessage()); } finally { GeneralUtilities.attemptClose(writer); } } }); } protected List<String> getHeader(){ int columnCount = table.getColumnModel().getColumnCount(); GroupableTableHeader header = (GroupableTableHeader) table.getTableHeader(); List<String> values = new LinkedList<String>(); for (int column = 0; column < columnCount; column++) { StringBuilder sb = new StringBuilder(); Enumeration columnGroups = header.getColumnGroups(table.getColumnModel().getColumn(column)); while (columnGroups != null && columnGroups.hasMoreElements()) { sb.append(((ColumnGroup) columnGroups.nextElement()).getText()).append(" - "); } sb.append(table.getColumnModel().getColumn(column).getHeaderValue().toString()); values.add(sb.toString()); } return values; } private void writeRow(BufferedWriter writer, List<String> values) throws IOException { boolean first = true; for (String value : values) { if (first) { first = false; } else { writer.write(","); } writer.write(escapeValueForCsv(value)); } writer.newLine(); } private String escapeValueForCsv(String value) { value = value.replaceAll("\"", "\"\""); if (value.contains("\"") || value.contains(",") || value.contains("\n")) { value = "\"" + value + "\""; } return value; } private String stripHtmlTags(String string, boolean onlyIfStartsWithHtmlTag) { if ((string == null) || "".equals(string) || (onlyIfStartsWithHtmlTag && !string.regionMatches(true, 0, "<html>", 0, 6))) { return string; } string = Pattern.compile("</?[a-zA-Z0-9][^>]*>").matcher(string).replaceAll(""); string = string.replace("&gt;",">"); string = string.replace("&lt;","<"); return string; } } /** * A value in the table model that is aware of it's index and the value associated with the consensus * @param <T> Type of the data contained in a cell. Corresponds to the {@link com.biomatters.plugins.barcoding.validator.validation.results.ResultColumn} type. */ private static class CellValue<T extends Comparable<T>> implements Comparable<CellValue<T>> { private ResultColumn<T> consensusValue; private Integer index; private ResultColumn<T> value; public CellValue(ResultColumn<T> consensusValue, ResultColumn<T> value, Integer index) { this.consensusValue = consensusValue; this.value = value; this.index = index; } @Override public String toString() { return value.getDisplayValue().toString(); } @Override public int compareTo(CellValue<T> o) { int consensusCompareResult = consensusValue.getData().compareTo(o.consensusValue.getData()); if(consensusCompareResult == 0) { return index.compareTo(o.index); } else { return consensusCompareResult; } } } public static class ValidationReportTableModel extends AbstractTableModel { private List<ValidationOutputRecord> records; private List<List<CellValue<?>>> data = new ArrayList<List<CellValue<?>>>(); public ValidationReportTableModel(List<ValidationOutputRecord> records) { this.records = new ArrayList<ValidationOutputRecord>(); for (ValidationOutputRecord record : records) { this.records.add(record); } updateTable(); } @Override public Class<?> getColumnClass(int columnIndex) { return CellValue.class; } public void updateTable() { data = new ArrayList<List<CellValue<?>>>(); for (ValidationOutputRecord record : records) { List<ResultColumn> firstRow = null; for (List<ResultColumn> resultColumns : record.exportTable()) { if(firstRow == null) { firstRow = resultColumns; } List<CellValue<?>> values = new ArrayList<CellValue<?>>(); for(int columnIndex=0; columnIndex<resultColumns.size(); columnIndex++) { CellValue<?> cellValue = getCellValue(firstRow.get(columnIndex), resultColumns.get(columnIndex), columnIndex); values.add(cellValue); } data.add(values); } } } private <T extends Comparable<T>> CellValue getCellValue(ResultColumn<T> firstRowValue, ResultColumn currentRowValue, int columnIndex) { // Have to cast because getClass() actually returns Class<? extends ResultColumn> due to type erasure :( //noinspection unchecked Class<ResultColumn<T>> firstRowClass = (Class<ResultColumn<T>>) firstRowValue.getClass(); return new CellValue<T>(firstRowClass.cast(firstRowValue), firstRowClass.cast(currentRowValue), columnIndex); } @Override public int getRowCount() { return data.size(); } @Override public int getColumnCount() { if (data.size() == 0) { return 0; } return data.get(0).size(); } @Override public CellValue getValueAt(int rowIndex, int columnIndex) { return data.get(rowIndex).get(columnIndex); } @Override public String getColumnName(int column) { if (data.size() == 0) { return super.getColumnName(column); } return data.get(0).get(column).value.getName(); } public void displayOptions(int columnIndex) { final ValidationOptions options = getOptionAt(columnIndex); if (options == null) { return; } SwingUtilities.invokeLater(new Runnable() { public void run() { options.setEnabled(false); Dialogs.DialogOptions dialogOptions = new Dialogs.DialogOptions(Dialogs.OK_ONLY, "Options"); Dialogs.showMoreOptionsDialog(dialogOptions, options.getPanel(), options.getAdvancedPanel()); } }); } public ValidationOptions getOptionAt(int columnIndex) { assert records != null && records.size() > 0; Map<Integer, ValidationOptions> colunmOptionsMap = records.get(0).getColunmOptionsMap(false); assert colunmOptionsMap != null; return colunmOptionsMap.get(columnIndex); } public int getFixedColumnLength() { assert records != null && records.size() > 0; ValidationOutputRecord record = records.get(0); return record.getFixedColumns(record.getOneURN()).size(); } } }
BV-69 - The table in the validation report should be sortable - Fix bugs that occurred due to changing of TableModel
researchTool/src/com/biomatters/plugins/barcoding/validator/research/report/ValidationReportViewer.java
BV-69 - The table in the validation report should be sortable - Fix bugs that occurred due to changing of TableModel
<ide><path>esearchTool/src/com/biomatters/plugins/barcoding/validator/research/report/ValidationReportViewer.java <ide> if (source instanceof JTable) { <ide> JTable table = (JTable) source; <ide> Object cell = table.getValueAt(table.getSelectedRow(), table.getSelectedColumn()); <del> if (cell instanceof LinkResultColumn.LinkBox) { <del> ((LinkResultColumn.LinkBox) cell).openLink(); <add> if (cell instanceof CellValue) { <add> ResultColumn value = ((CellValue) cell).value; <add> if(value instanceof LinkResultColumn) { <add> ((LinkResultColumn)value).getData().openLink(); <add> } <ide> } <ide> } <ide> } <ide> values.clear(); <ide> for (int column=0; column < columnCount; column++) { <ide> Object value = table.getValueAt(row, column); <del> if(value instanceof ResultColumn) { <del> value = ((ResultColumn)value).getDisplayValue(); <add> if(value instanceof CellValue) { <add> value = ((CellValue)value).value.getDisplayValue(); <ide> } <ide> if (value == null) { <ide> values.add("");
Java
mit
94e10c308d279bfb3c93a10b1bf6dd13985c86ae
0
seqcode/seqcode-core,seqcode/seqcode-core,seqcode/seqcode-core,seqcode/seqcode-core
package edu.psu.compbio.seqcode.projects.akshay.utils; import java.io.FileWriter; import java.io.IOException; import java.text.ParseException; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.Iterator; import java.util.List; import edu.psu.compbio.seqcode.genome.GenomeConfig; import edu.psu.compbio.seqcode.genome.location.Point; import edu.psu.compbio.seqcode.genome.location.Region; import edu.psu.compbio.seqcode.genome.location.RepeatMaskedRegion; import edu.psu.compbio.seqcode.gse.datasets.motifs.WeightMatrix; import edu.psu.compbio.seqcode.gse.gsebricks.verbs.sequence.SequenceGenerator; import edu.psu.compbio.seqcode.gse.utils.ArgParser; import edu.psu.compbio.seqcode.gse.utils.io.RegionFileUtilities; import edu.psu.compbio.seqcode.gse.utils.sequence.SequenceUtils; import edu.psu.compbio.seqcode.gse.gsebricks.verbs.location.RepeatMaskedGenerator; import edu.psu.compbio.seqcode.projects.shaun.MotifAnalysisSandbox; public class MotifToKmers { private GenomeConfig gcon; private List<Region> posSet; private List<Point> posPeaks=null; private List<Region> negSet; private List<Point> negPeaks = null; private int Kmin; private int Kmax; private WeightMatrix motif; //private double[] threshholds; private int threshlevel; private String posOutFile; private String negOutFile; public MotifToKmers (GenomeConfig gconf) { gcon = gcon; } //Mutators public void setPosSet(List<Region> pos){posSet = pos;} public void setNegSet(List<Region> neg){negSet = neg;} public void setKmin(int kmin){Kmin=kmin;} public void setKmax(int kmax){Kmax = kmax;} public void setMontif(WeightMatrix matrix){motif = matrix;} public void setThreslevel(int t){threshlevel = t;} public void setPosOut(String po){posOutFile = po;} public void setNegOut(String no){negOutFile = no;} public static void main(String[] args) throws IOException, ParseException{ ArgParser ap = new ArgParser(args); GenomeConfig gcon = new GenomeConfig(args); MotifToKmers runner = new MotifToKmers(gcon); boolean cache = ap.hasKey("seq"); String seqpath=""; if(cache){ seqpath = ap.getKeyValue("seq"); } int win = ap.hasKey("win") ? new Integer(ap.getKeyValue("win")).intValue():-1; String peaksFile = ap.getKeyValue("peaks"); List<Point> peaksP = RegionFileUtilities.loadPeaksFromPeakFile(gcon.getGenome(), ap.getKeyValue("peaksP"), win); List<Region> regsP = new ArrayList<Region>(); for(Point p : peaksP){ regsP.add(p.expand(win/2)); } List<Point> peaksN = RegionFileUtilities.loadPeaksFromPeakFile(gcon.getGenome(), ap.getKeyValue("peaksN"), win); List<Region> regsN = new ArrayList<Region>(); for(Point p : peaksN){ regsN.add(p.expand(win/2)); } String outname = ap.getKeyValue("out"); String posout = outname.concat("-pos.kmers"); String negout = outname.concat("-neg.kmers"); int thresLvl = ap.hasKey("threslevel") ? new Integer(ap.getKeyValue("threslevel")).intValue():10; int kmin = ap.hasKey("kmin") ? new Integer(ap.getKeyValue("kmin")).intValue():3; int kmax = ap.hasKey("kmax") ? new Integer(ap.getKeyValue("kmax")).intValue():8; String motiffile = ap.getKeyValue("motiffile"); String backfile = ap.getKeyValue("back"); List<WeightMatrix> matrixList = MotifAnalysisSandbox.loadMotifFromFile(motiffile, backfile, gcon.getGenome()); WeightMatrix matrix = matrixList.get(0); runner.setPosSet(regsP); runner.setNegSet(regsN); runner.setKmin(kmin); runner.setKmax(kmax); runner.setMontif(matrix); runner.setThreslevel(thresLvl); runner.setPosOut(posout); runner.setNegOut(negout); runner.execute(cache, seqpath); } @SuppressWarnings("unchecked") public void execute(boolean useCache, String genPath) throws IOException{ SequenceGenerator seqgen = new SequenceGenerator(); seqgen.useCache(useCache); if(useCache){ seqgen.useLocalFiles(true); seqgen.setGenomePath(genPath); } FileWriter foutP = new FileWriter(posOutFile); FileWriter foutN = new FileWriter(negOutFile); StringBuilder headerSB = new StringBuilder(); StringBuilder posSB = new StringBuilder(); StringBuilder negSB = new StringBuilder(); headerSB.append("Region"); HashMap<String, List<Integer>> kmerCountsP = new HashMap<String,List<Integer>>(); HashMap<String, List<Integer>> kmerCountsN = new HashMap<String,List<Integer>>(); List<String> kmer_order=new ArrayList<String>(); for(int k=Kmin; k<=Kmax; k++){ // iterating over different k-mer lengths int numK = (int)Math.pow(4, k); int[][] currKKmerCountsP = new int[posSet.size()][numK]; int[][] currKKmerCountsN = new int[negSet.size()][numK]; boolean[] isMotifKmer = new boolean[numK]; List<Double> scores = new ArrayList<Double>(); for(int i=0; i<numK; i++){ //iterating over k-mers of a given length and finding motifs that belong to a motif String currKmer = RegionFileUtilities.int2seq(i, k); String revCurrKmer = SequenceUtils.reverseComplement(currKmer); double scoref = scoreKmer(currKmer); double scoreR = scoreKmer(revCurrKmer); double score = scoref > scoreR ? scoref : scoreR; scores.add(score); } @SuppressWarnings("rawtypes") Comparator cmp = Collections.reverseOrder(); Collections.sort(scores,cmp); double threshold = scores.get((int)(threshlevel*scores.size()/100)); for(int i=0; i<numK; i++){ String currKmer = RegionFileUtilities.int2seq(i, k); String revCurrKmer = SequenceUtils.reverseComplement(currKmer); int revCurrKmerInd = RegionFileUtilities.seq2int(revCurrKmer); double scoref = scoreKmer(currKmer); double scoreR = scoreKmer(revCurrKmer); double score = scoref > scoreR ? scoref : scoreR; if(score >threshold && i < revCurrKmerInd ){ isMotifKmer[i] = true; } } for(int pr=0; pr<posSet.size(); pr++){ for(int i=0; i <numK; i++){ currKKmerCountsP[pr][i]=0; } } int prCounter=0; for(Region r : posSet){ // Count kmer frequencies at the positive set if(!kmerCountsP.containsKey(r.getLocationString())){ kmerCountsP.put(r.getLocationString(),new ArrayList<Integer>()); } String seq = seqgen.execute(r).toUpperCase(); if(seq.contains("N")) continue; for(int i=0; i<(seq.length()-k+1); i++){ String currK = seq.substring(i, i+k); String revCurrK = SequenceUtils.reverseComplement(currK); if(isMotifKmer[RegionFileUtilities.seq2int(currK)]){ currKKmerCountsP[prCounter][RegionFileUtilities.seq2int(currK)]++; } if(isMotifKmer[RegionFileUtilities.seq2int(revCurrK)]){ currKKmerCountsP[prCounter][RegionFileUtilities.seq2int(revCurrK)]++; } } prCounter++; } for(int nr=0; nr<negSet.size(); nr++){ for(int i=0; i <numK; i++){ currKKmerCountsN[nr][i]=0; } } int nrCounter = 0; for(Region r : negSet){ if(!kmerCountsN.containsKey(r.getLocationString())){ kmerCountsN.put(r.getLocationString(),new ArrayList<Integer>()); } String seq = seqgen.execute(r).toUpperCase(); if(seq.contains("N")) continue; for(int i=0; i<(seq.length()-k+1); i++){ String currK = seq.substring(i, i+k); String revCurrK = SequenceUtils.reverseComplement(currK); if(isMotifKmer[RegionFileUtilities.seq2int(currK)]){ currKKmerCountsN[nrCounter][RegionFileUtilities.seq2int(currK)]++; } if(isMotifKmer[RegionFileUtilities.seq2int(revCurrK)]){ currKKmerCountsN[nrCounter][RegionFileUtilities.seq2int(revCurrK)]++; } } nrCounter++; } for(int i=0; i<numK; i++){ // Adding header if(isMotifKmer[i]){ headerSB.append("\t"); headerSB.append(RegionFileUtilities.int2seq(i, k)); } } prCounter =0; for (Region r : posSet){ for(int i=0; i<numK; i++){ if(isMotifKmer[i]){ kmerCountsP.get(r.getLocationString()).add(currKKmerCountsP[prCounter][i]); kmer_order.add(RegionFileUtilities.int2seq(i, k)); } } prCounter++; } nrCounter = 0; for(Region r : negSet){ for(int i=0; i<numK; i++){ if(isMotifKmer[i]){ kmerCountsN.get(r.getLocationString()).add(currKKmerCountsN[nrCounter][i]); } } nrCounter++; } } for(String rlocation : kmerCountsP.keySet()){ posSB.append(rlocation); for(int c : kmerCountsP.get(rlocation)){ posSB.append("\t"); posSB.append(c); } posSB.append("\n"); } for(String rlocation : kmerCountsN.keySet()){ negSB.append(rlocation); for(int c : kmerCountsN.get(rlocation)){ negSB.append("\t"); negSB.append(c); } negSB.append("\n"); } foutP.write(headerSB.toString()+"\n"); foutP.write(posSB.toString()+"\n"); foutN.write(headerSB.toString()+"\n"); foutN.write(negSB.toString()+"\n"); foutP.close(); foutN.close(); } private double scoreKmer(String kmer){ double maxScore=motif.getMinScore(); char[] kmerChar = kmer.toCharArray(); if(motif.length() < kmer.length()){ maxScore = motif.getMinScore(); return maxScore; } for(int i=0; i<motif.length()-kmer.length(); i++){ float score = (float)0.0; for(int j=0; j< kmer.length(); j++){ score += motif.matrix[i][kmerChar[j]]; } if(maxScore <score){ maxScore =score; } } return maxScore; } }
src/edu/psu/compbio/seqcode/projects/akshay/utils/MotifToKmers.java
package edu.psu.compbio.seqcode.projects.akshay.utils; import java.io.FileWriter; import java.io.IOException; import java.text.ParseException; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.Iterator; import java.util.List; import edu.psu.compbio.seqcode.genome.GenomeConfig; import edu.psu.compbio.seqcode.genome.location.Point; import edu.psu.compbio.seqcode.genome.location.Region; import edu.psu.compbio.seqcode.genome.location.RepeatMaskedRegion; import edu.psu.compbio.seqcode.gse.datasets.motifs.WeightMatrix; import edu.psu.compbio.seqcode.gse.gsebricks.verbs.sequence.SequenceGenerator; import edu.psu.compbio.seqcode.gse.utils.ArgParser; import edu.psu.compbio.seqcode.gse.utils.io.RegionFileUtilities; import edu.psu.compbio.seqcode.gse.utils.sequence.SequenceUtils; import edu.psu.compbio.seqcode.gse.gsebricks.verbs.location.RepeatMaskedGenerator; import edu.psu.compbio.seqcode.projects.shaun.MotifAnalysisSandbox; public class MotifToKmers { private GenomeConfig gcon; private List<Region> posSet; private List<Point> posPeaks=null; private List<Region> negSet; private List<Point> negPeaks = null; private int Kmin; private int Kmax; private WeightMatrix motif; //private double[] threshholds; private int threshlevel; private String posOutFile; private String negOutFile; public MotifToKmers (GenomeConfig gconf) { gcon = gcon; } //Mutators public void setPosSet(List<Region> pos){posSet = pos;} public void setNegSet(List<Region> neg){negSet = neg;} public void setKmin(int kmin){Kmin=kmin;} public void setKmax(int kmax){Kmax = kmax;} public void setMontif(WeightMatrix matrix){motif = matrix;} public void setThreslevel(int t){threshlevel = t;} public void setPosOut(String po){posOutFile = po;} public void setNegOut(String no){negOutFile = no;} public static void main(String[] args) throws IOException, ParseException{ ArgParser ap = new ArgParser(args); GenomeConfig gcon = new GenomeConfig(args); MotifToKmers runner = new MotifToKmers(gcon); boolean cache = ap.hasKey("seq"); String seqpath=""; if(cache){ seqpath = ap.getKeyValue("seq"); } int win = ap.hasKey("win") ? new Integer(ap.getKeyValue("win")).intValue():-1; String peaksFile = ap.getKeyValue("peaks"); List<Point> peaksP = RegionFileUtilities.loadPeaksFromPeakFile(gcon.getGenome(), ap.getKeyValue("peaksP"), win); List<Region> regsP = new ArrayList<Region>(); for(Point p : peaksP){ regsP.add(p.expand(win/2)); } List<Point> peaksN = RegionFileUtilities.loadPeaksFromPeakFile(gcon.getGenome(), ap.getKeyValue("peaksN"), win); List<Region> regsN = new ArrayList<Region>(); for(Point p : peaksN){ regsN.add(p.expand(win/2)); } String outname = ap.getKeyValue("out"); String posout = outname.concat("-pos.kmers"); String negout = outname.concat("-neg.kmers"); int thresLvl = ap.hasKey("threslevel") ? new Integer(ap.getKeyValue("threslevel")).intValue():10; int kmin = ap.hasKey("kmin") ? new Integer(ap.getKeyValue("kmin")).intValue():3; int kmax = ap.hasKey("kmax") ? new Integer(ap.getKeyValue("kmax")).intValue():8; String motiffile = ap.getKeyValue("motiffile"); String backfile = ap.getKeyValue("back"); List<WeightMatrix> matrixList = MotifAnalysisSandbox.loadMotifFromFile(motiffile, backfile, gcon.getGenome()); WeightMatrix matrix = matrixList.get(0); runner.setPosSet(regsP); runner.setNegSet(regsN); runner.setKmin(kmin); runner.setKmax(kmax); runner.setMontif(matrix); runner.setThreslevel(thresLvl); runner.setPosOut(posout); runner.setNegOut(negout); runner.execute(cache, seqpath); } @SuppressWarnings("unchecked") public void execute(boolean useCache, String genPath) throws IOException{ SequenceGenerator seqgen = new SequenceGenerator(); seqgen.useCache(useCache); if(useCache){ seqgen.useLocalFiles(true); seqgen.setGenomePath(genPath); } FileWriter foutP = new FileWriter(posOutFile); FileWriter foutN = new FileWriter(negOutFile); StringBuilder headerSB = new StringBuilder(); StringBuilder posSB = new StringBuilder(); StringBuilder negSB = new StringBuilder(); headerSB.append("Region"); HashMap<String, List<Integer>> kmerCountsP = new HashMap<String,List<Integer>>(); HashMap<String, List<Integer>> kmerCountsN = new HashMap<String,List<Integer>>(); List<String> kmer_order=new ArrayList<String>(); for(int k=Kmin; k<=Kmax; k++){ // iterating over different k-mer lengths int numK = (int)Math.pow(4, k); int[][] currKKmerCountsP = new int[posSet.size()][numK]; int[][] currKKmerCountsN = new int[negSet.size()][numK]; boolean[] isMotifKmer = new boolean[numK]; List<Double> scores = new ArrayList<Double>(); for(int i=0; i<numK; i++){ //iterating over k-mers of a given length and finding motifs that belong to a motif String currKmer = RegionFileUtilities.int2seq(i, k); String revCurrKmer = SequenceUtils.reverseComplement(currKmer); double scoref = scoreKmer(currKmer); double scoreR = scoreKmer(revCurrKmer); double score = scoref > scoreR ? scoref : scoreR; scores.add(score); } @SuppressWarnings("rawtypes") Comparator cmp = Collections.reverseOrder(); Collections.sort(scores,cmp); double threshold = scores.get((int)(threshlevel*scores.size()/100)); for(int i=0; i<numK; i++){ String currKmer = RegionFileUtilities.int2seq(i, k); String revCurrKmer = SequenceUtils.reverseComplement(currKmer); int revCurrKmerInd = RegionFileUtilities.seq2int(revCurrKmer); double scoref = scoreKmer(currKmer); double scoreR = scoreKmer(revCurrKmer); double score = scoref > scoreR ? scoref : scoreR; if(score >threshold && i < revCurrKmerInd ){ isMotifKmer[i] = true; } } for(int pr=0; pr<posSet.size(); pr++){ for(int i=0; i <numK; i++){ currKKmerCountsP[pr][i]=0; } } int prCounter=0; for(Region r : posSet){ // Count kmer frequencies at the positive set if(!kmerCountsP.containsKey(r.getLocationString())){ kmerCountsP.put(r.getLocationString(),new ArrayList<Integer>()); } String seq = seqgen.execute(r).toUpperCase(); if(seq.contains("N")) continue; for(int i=0; i<(seq.length()-k+1); i++){ String currK = seq.substring(i, i+k); String revCurrK = SequenceUtils.reverseComplement(currK); if(isMotifKmer[RegionFileUtilities.seq2int(currK)]){ currKKmerCountsP[prCounter][RegionFileUtilities.seq2int(currK)]++; } if(isMotifKmer[RegionFileUtilities.seq2int(revCurrK)]){ currKKmerCountsP[prCounter][RegionFileUtilities.seq2int(revCurrK)]++; } } prCounter++; } for(int nr=0; nr<negSet.size(); nr++){ for(int i=0; i <numK; i++){ currKKmerCountsN[nr][i]=0; } } int nrCounter = 0; for(Region r : negSet){ if(!kmerCountsN.containsKey(r.getLocationString())){ kmerCountsN.put(r.getLocationString(),new ArrayList<Integer>()); } String seq = seqgen.execute(r).toUpperCase(); if(seq.contains("N")) continue; for(int i=0; i<(seq.length()-k+1); i++){ String currK = seq.substring(i, i+k); String revCurrK = SequenceUtils.reverseComplement(currK); if(isMotifKmer[RegionFileUtilities.seq2int(currK)]){ currKKmerCountsN[nrCounter][RegionFileUtilities.seq2int(currK)]++; } if(isMotifKmer[RegionFileUtilities.seq2int(revCurrK)]){ currKKmerCountsN[nrCounter][RegionFileUtilities.seq2int(revCurrK)]++; } } nrCounter++; } for(int i=0; i<numK; i++){ // Adding header if(isMotifKmer[i]){ headerSB.append("\t"); headerSB.append(RegionFileUtilities.int2seq(i, k)); } } prCounter =0; for (Region r : posSet){ for(int i=0; i<numK; i++){ if(isMotifKmer[i]){ kmerCountsP.get(r.getLocationString()).add(currKKmerCountsP[prCounter][i]); kmer_order.add(RegionFileUtilities.int2seq(i, k)); } } prCounter++; } nrCounter = 0; for(Region r : negSet){ for(int i=0; i<numK; i++){ if(isMotifKmer[i]){ kmerCountsN.get(r.getLocationString()).add(currKKmerCountsN[nrCounter][i]); } } nrCounter++; } for(String rlocation : kmerCountsP.keySet()){ posSB.append(rlocation); for(int c : kmerCountsP.get(rlocation)){ posSB.append("\t"); posSB.append(c); } posSB.append("\n"); } for(String rlocation : kmerCountsN.keySet()){ negSB.append(rlocation); for(int c : kmerCountsN.get(rlocation)){ negSB.append("\t"); negSB.append(c); } negSB.append("\n"); } } foutP.write(headerSB.toString()+"\n"); foutP.write(posSB.toString()+"\n"); foutN.write(headerSB.toString()+"\n"); foutN.write(negSB.toString()+"\n"); foutP.close(); foutN.close(); } private double scoreKmer(String kmer){ double maxScore=motif.getMinScore(); char[] kmerChar = kmer.toCharArray(); if(motif.length() < kmer.length()){ maxScore = motif.getMinScore(); return maxScore; } for(int i=0; i<motif.length()-kmer.length(); i++){ float score = (float)0.0; for(int j=0; j< kmer.length(); j++){ score += motif.matrix[i][kmerChar[j]]; } if(maxScore <score){ maxScore =score; } } return maxScore; } }
Minor bug fix in MotifsToKmers
src/edu/psu/compbio/seqcode/projects/akshay/utils/MotifToKmers.java
Minor bug fix in MotifsToKmers
<ide><path>rc/edu/psu/compbio/seqcode/projects/akshay/utils/MotifToKmers.java <ide> } <ide> nrCounter++; <ide> } <del> <del> for(String rlocation : kmerCountsP.keySet()){ <del> posSB.append(rlocation); <del> for(int c : kmerCountsP.get(rlocation)){ <del> posSB.append("\t"); <del> posSB.append(c); <del> } <del> posSB.append("\n"); <del> } <del> <del> for(String rlocation : kmerCountsN.keySet()){ <del> negSB.append(rlocation); <del> for(int c : kmerCountsN.get(rlocation)){ <del> negSB.append("\t"); <del> negSB.append(c); <del> } <del> negSB.append("\n"); <del> } <del> } <add> <add> } <add> <add> for(String rlocation : kmerCountsP.keySet()){ <add> posSB.append(rlocation); <add> for(int c : kmerCountsP.get(rlocation)){ <add> posSB.append("\t"); <add> posSB.append(c); <add> } <add> posSB.append("\n"); <add> } <add> <add> for(String rlocation : kmerCountsN.keySet()){ <add> negSB.append(rlocation); <add> for(int c : kmerCountsN.get(rlocation)){ <add> negSB.append("\t"); <add> negSB.append(c); <add> } <add> negSB.append("\n"); <add> } <add> <ide> foutP.write(headerSB.toString()+"\n"); <ide> foutP.write(posSB.toString()+"\n"); <ide>
Java
agpl-3.0
23cfe6ec8678cb470d3f6118c854bdaaffb8e4ab
0
c0deh4xor/jPOS,atancasis/jPOS,sebastianpacheco/jPOS,sebastianpacheco/jPOS,chhil/jPOS,fayezasar/jPOS,poynt/jPOS,jpos/jPOS,alcarraz/jPOS,jpos/jPOS,c0deh4xor/jPOS,imam-san/jPOS-1,alcarraz/jPOS,bharavi/jPOS,atancasis/jPOS,juanibdn/jPOS,fayezasar/jPOS,barspi/jPOS,sebastianpacheco/jPOS,yinheli/jPOS,barspi/jPOS,c0deh4xor/jPOS,alcarraz/jPOS,barspi/jPOS,poynt/jPOS,imam-san/jPOS-1,chhil/jPOS,yinheli/jPOS,juanibdn/jPOS,bharavi/jPOS,imam-san/jPOS-1,bharavi/jPOS,juanibdn/jPOS,atancasis/jPOS,jpos/jPOS,poynt/jPOS,yinheli/jPOS
/* * Copyright (c) 2000 jPOS.org. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the jPOS project * (http://www.jpos.org/)". Alternately, this acknowledgment may * appear in the software itself, if and wherever such third-party * acknowledgments normally appear. * * 4. The names "jPOS" and "jPOS.org" must not be used to endorse * or promote products derived from this software without prior * written permission. For written permission, please contact * [email protected]. * * 5. Products derived from this software may not be called "jPOS", * nor may "jPOS" appear in their name, without prior written * permission of the jPOS project. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE JPOS PROJECT OR ITS CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the jPOS Project. For more * information please see <http://www.jpos.org/>. */ package org.jpos.util; import java.io.*; import java.util.*; import org.jpos.core.Configurable; import org.jpos.core.Configuration; import org.jpos.core.ConfigurationException; /** * Rotates logs * @author <a href="mailto:[email protected]">Alejandro P. Revilla</a> * @version $Revision$ $Date$ * @see org.jpos.core.Configurable * @since jPOS 1.2 */ public class RotateLogListener extends SimpleLogListener implements Configurable { FileOutputStream f; String logName; int maxCopies; long sleepTime; long maxSize; int msgCount; public static final int CHECK_INTERVAL = 100; /** * @param name base log filename * @param sleepTime switch logs every t seconds * @param maxCopies number of old logs * @param maxSize in bytes */ public RotateLogListener (String logName, int sleepTime, int maxCopies, long maxSize) throws IOException { super(); this.logName = logName; this.maxCopies = maxCopies; this.sleepTime = sleepTime * 1000; this.maxSize = maxSize; f = null; openLogFile (); Timer timer = DefaultTimer.getTimer(); if (sleepTime != 0) timer.schedule (new Rotate(), sleepTime, sleepTime); } public RotateLogListener (String logName, int sleepTime, int maxCopies) throws IOException { this (logName, sleepTime, maxCopies, 100*1024*1024); // safe maxSize } public RotateLogListener () { super(); } /** * Configure this RotateLogListener<br> * Properties:<br> * <ul> * <li>file base log filename * <li>[window] in seconds (default 0 - never rotate) * <li>[count] number of copies (default 0 == single copy) * <li>[maxsize] max log size in bytes (aprox) * </ul> * @param cfg Configuration * @throws ConfigurationException */ public void setConfiguration (Configuration cfg) throws ConfigurationException { maxCopies = cfg.getInt ("copies"); sleepTime = cfg.getInt ("window") * 1000; logName = cfg.get ("file"); maxSize = cfg.getLong ("maxsize"); try { openLogFile(); } catch (IOException e) { throw new ConfigurationException (e); } Timer timer = DefaultTimer.getTimer(); if (sleepTime != 0) timer.schedule (new Rotate(), sleepTime, sleepTime); } public synchronized void log (LogEvent ev) { if (msgCount++ > CHECK_INTERVAL) { checkSize(); msgCount = 0; } super.log (ev); } private synchronized void openLogFile() throws IOException { if (f != null) f.close(); f = new FileOutputStream (logName, true); setPrintStream (new PrintStream(f)); } public synchronized void logRotate () throws IOException { setPrintStream (null); super.close(); f.close(); for (int i=maxCopies; i>0; ) { File dest = new File (logName + "." + i); File source = new File (logName + ((--i > 0) ? ("." + i) : "")); dest.delete(); source.renameTo(dest); } openLogFile(); } protected void logDebug (String msg) { if (p != null) { p.println ("<log realm=\"rotate-log-listener\" at=\""+new Date().toString() +"\">"); p.println (" "+msg); p.println ("</log-debug>"); } } private void checkSize() { File logFile = new File (logName); if (logFile.length() > maxSize) { try { logDebug ("maxSize ("+maxSize+") threshold reached"); logRotate(); } catch (IOException e) { e.printStackTrace (System.err); } } } public class Rotate extends TimerTask { public void run() { try { logDebug ("time exceeded - log rotated"); logRotate(); } catch (IOException e) { e.printStackTrace (System.err); } } } }
jpos/src/main/org/jpos/util/RotateLogListener.java
/* * Copyright (c) 2000 jPOS.org. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the jPOS project * (http://www.jpos.org/)". Alternately, this acknowledgment may * appear in the software itself, if and wherever such third-party * acknowledgments normally appear. * * 4. The names "jPOS" and "jPOS.org" must not be used to endorse * or promote products derived from this software without prior * written permission. For written permission, please contact * [email protected]. * * 5. Products derived from this software may not be called "jPOS", * nor may "jPOS" appear in their name, without prior written * permission of the jPOS project. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE JPOS PROJECT OR ITS CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the jPOS Project. For more * information please see <http://www.jpos.org/>. */ package org.jpos.util; import java.io.*; import java.util.*; import org.jpos.core.Configurable; import org.jpos.core.Configuration; import org.jpos.core.ConfigurationException; /** * Rotates logs * @author <a href="mailto:[email protected]">Alejandro P. Revilla</a> * @version $Revision$ $Date$ * @see org.jpos.core.Configurable * @since jPOS 1.2 */ public class RotateLogListener extends SimpleLogListener implements Configurable { FileOutputStream f; String logName; int maxCopies; long sleepTime; long maxSize; int msgCount; public static final int CHECK_INTERVAL = 0; /** * @param name base log filename * @param sleepTime switch logs every t seconds * @param maxCopies number of old logs * @param maxSize in bytes */ public RotateLogListener (String logName, int sleepTime, int maxCopies, long maxSize) throws IOException { super(); this.logName = logName; this.maxCopies = maxCopies; this.sleepTime = sleepTime * 1000; this.maxSize = maxSize; f = null; openLogFile (); Timer timer = DefaultTimer.getTimer(); if (sleepTime != 0) timer.schedule (new Rotate(), sleepTime, sleepTime); } public RotateLogListener (String logName, int sleepTime, int maxCopies) throws IOException { this (logName, sleepTime, maxCopies, 100*1024*1024); // safe maxSize } public RotateLogListener () { super(); } /** * Configure this RotateLogListener<br> * Properties:<br> * <ul> * <li>file base log filename * <li>[window] in seconds (default 0 - never rotate) * <li>[count] number of copies (default 0 == single copy) * <li>[maxsize] max log size in bytes (aprox) * </ul> * @param cfg Configuration * @throws ConfigurationException */ public void setConfiguration (Configuration cfg) throws ConfigurationException { maxCopies = cfg.getInt ("copies"); sleepTime = cfg.getInt ("window") * 1000; logName = cfg.get ("file"); maxSize = cfg.getLong ("maxsize"); try { openLogFile(); } catch (IOException e) { throw new ConfigurationException (e); } Timer timer = DefaultTimer.getTimer(); if (sleepTime != 0) timer.schedule (new Rotate(), sleepTime, sleepTime); } public synchronized void log (LogEvent ev) { if (msgCount++ > CHECK_INTERVAL) { checkSize(); msgCount = 0; } super.log (ev); } private synchronized void openLogFile() throws IOException { if (f != null) f.close(); f = new FileOutputStream (logName, true); setPrintStream (new PrintStream(f)); } public synchronized void logRotate () throws IOException { setPrintStream (null); super.close(); f.close(); for (int i=maxCopies; i>0; ) { File dest = new File (logName + "." + i); File source = new File (logName + ((--i > 0) ? ("." + i) : "")); dest.delete(); source.renameTo(dest); } openLogFile(); } protected void logDebug (String msg) { if (p != null) { p.println ("<log realm=\"rotate-log-listener\" at=\""+new Date().toString() +"\">"); p.println (" "+msg); p.println ("</log-debug>"); } } private void checkSize() { File logFile = new File (logName); if (logFile.length() > maxSize) { try { logDebug ("maxSize ("+maxSize+") threshold reached"); logRotate(); } catch (IOException e) { e.printStackTrace (System.err); } } } public class Rotate extends TimerTask { public void run() { try { logDebug ("time exceeded - log rotated"); logRotate(); } catch (IOException e) { e.printStackTrace (System.err); } } } }
Check size every 100 log events
jpos/src/main/org/jpos/util/RotateLogListener.java
Check size every 100 log events
<ide><path>pos/src/main/org/jpos/util/RotateLogListener.java <ide> long sleepTime; <ide> long maxSize; <ide> int msgCount; <del> public static final int CHECK_INTERVAL = 0; <add> public static final int CHECK_INTERVAL = 100; <ide> <ide> /** <ide> * @param name base log filename
Java
apache-2.0
58f6dfb9542d10971e560886cc797644b03b0826
0
calvinjia/tachyon,wwjiang007/alluxio,Alluxio/alluxio,Alluxio/alluxio,madanadit/alluxio,wwjiang007/alluxio,calvinjia/tachyon,madanadit/alluxio,maobaolong/alluxio,Alluxio/alluxio,EvilMcJerkface/alluxio,maobaolong/alluxio,calvinjia/tachyon,calvinjia/tachyon,madanadit/alluxio,Alluxio/alluxio,calvinjia/tachyon,maobaolong/alluxio,calvinjia/tachyon,madanadit/alluxio,bf8086/alluxio,bf8086/alluxio,EvilMcJerkface/alluxio,Alluxio/alluxio,wwjiang007/alluxio,bf8086/alluxio,madanadit/alluxio,maobaolong/alluxio,EvilMcJerkface/alluxio,wwjiang007/alluxio,Alluxio/alluxio,wwjiang007/alluxio,maobaolong/alluxio,madanadit/alluxio,bf8086/alluxio,bf8086/alluxio,calvinjia/tachyon,maobaolong/alluxio,maobaolong/alluxio,Alluxio/alluxio,EvilMcJerkface/alluxio,maobaolong/alluxio,EvilMcJerkface/alluxio,wwjiang007/alluxio,wwjiang007/alluxio,maobaolong/alluxio,bf8086/alluxio,madanadit/alluxio,madanadit/alluxio,bf8086/alluxio,wwjiang007/alluxio,calvinjia/tachyon,Alluxio/alluxio,EvilMcJerkface/alluxio,bf8086/alluxio,Alluxio/alluxio,maobaolong/alluxio,Alluxio/alluxio,EvilMcJerkface/alluxio,wwjiang007/alluxio,EvilMcJerkface/alluxio,wwjiang007/alluxio
/* * The Alluxio Open Foundation licenses this work under the Apache License, version 2.0 * (the "License"). You may not use this work except in compliance with the License, which is * available at www.apache.org/licenses/LICENSE-2.0 * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, * either express or implied, as more fully set forth in the License. * * See the NOTICE file distributed with this work for information regarding copyright ownership. */ package alluxio.worker.block.evictor; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertEquals; import alluxio.conf.ServerConfiguration; import alluxio.conf.PropertyKey; import alluxio.worker.block.BlockMetadataManager; import alluxio.worker.block.BlockMetadataManagerView; import alluxio.worker.block.BlockStoreEventListener; import alluxio.worker.block.BlockStoreLocation; import alluxio.worker.block.TieredBlockStoreTestUtils; import alluxio.worker.block.allocator.Allocator; import alluxio.worker.block.allocator.MaxFreeAllocator; import alluxio.worker.block.meta.StorageDir; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import java.io.File; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; /** * Unit tests for specific behavior of {@link LRFUEvictor} such as evicting/moving blocks with * minimum CRF value and cascading LRFU eviction. */ public class LRFUEvictorTest { private static final long SESSION_ID = 2; private static final long BLOCK_ID = 10; private BlockMetadataManager mMetaManager; private BlockMetadataManagerView mManagerView; private Evictor mEvictor; private double mStepFactor; private double mAttenuationFactor; /** Rule to create a new temporary folder during each test. */ @Rule public TemporaryFolder mTestFolder = new TemporaryFolder(); /** * Sets up all dependencies before a test runs. */ @Before public final void before() throws Exception { File tempFolder = mTestFolder.newFolder(); mMetaManager = TieredBlockStoreTestUtils.defaultMetadataManager(tempFolder.getAbsolutePath()); mManagerView = new BlockMetadataManagerView(mMetaManager, Collections.<Long>emptySet(), Collections.<Long>emptySet()); ServerConfiguration.set(PropertyKey.WORKER_EVICTOR_CLASS, LRFUEvictor.class.getName()); ServerConfiguration.set(PropertyKey.WORKER_ALLOCATOR_CLASS, MaxFreeAllocator.class.getName()); Allocator allocator = Allocator.Factory.create(mManagerView); mStepFactor = ServerConfiguration.getDouble(PropertyKey.WORKER_EVICTOR_LRFU_STEP_FACTOR); mAttenuationFactor = ServerConfiguration.getDouble(PropertyKey.WORKER_EVICTOR_LRFU_ATTENUATION_FACTOR); mEvictor = Evictor.Factory.create(mManagerView, allocator); } /** * Caches bytes into {@link StorageDir}. * * @param sessionId session who caches the data * @param blockId id of the cached block * @param bytes size of the block in bytes * @param tierLevel tier level * @param dirIdx index of a directory */ private void cache(long sessionId, long blockId, long bytes, int tierLevel, int dirIdx) throws Exception { StorageDir dir = mMetaManager.getTiers().get(tierLevel).getDir(dirIdx); TieredBlockStoreTestUtils.cache(sessionId, blockId, bytes, dir, mMetaManager, mEvictor); } /** * Access the block to update {@link Evictor}. */ private void access(long blockId) { ((BlockStoreEventListener) mEvictor).onAccessBlock(SESSION_ID, blockId); } private double calculateAccessWeight(long timeInterval) { return Math.pow(1.0 / mAttenuationFactor, mStepFactor * timeInterval); } /** * Sort all blocks in ascending order of CRF. * * @return the sorted CRF of all blocks */ private List<Map.Entry<Long, Double>> getSortedCRF(Map<Long, Double> crfMap) { List<Map.Entry<Long, Double>> sortedCRF = new ArrayList<>(crfMap.entrySet()); Collections.sort(sortedCRF, new Comparator<Map.Entry<Long, Double>>() { @Override public int compare(Entry<Long, Double> o1, Entry<Long, Double> o2) { double res = o1.getValue() - o2.getValue(); if (res < 0) { return -1; } else if (res > 0) { return 1; } else { return 0; } } }); return sortedCRF; } /** * Tests that the eviction in the bottom tier works. */ @Test public void evictInBottomTier() throws Exception { int bottomTierOrdinal = TieredBlockStoreTestUtils .TIER_ORDINAL[TieredBlockStoreTestUtils.TIER_ORDINAL.length - 1]; Map<Long, Double> blockIdToCRF = new HashMap<>(); // capacity increases with index long[] bottomTierDirCapacity = TieredBlockStoreTestUtils.TIER_CAPACITY_BYTES[bottomTierOrdinal]; int nDir = bottomTierDirCapacity.length; // fill in dirs from larger to smaller capacity with blockId equal to BLOCK_ID plus dir index for (int i = 0; i < nDir; i++) { cache(SESSION_ID, BLOCK_ID + i, bottomTierDirCapacity[i], bottomTierOrdinal, i); // update CRF of blocks when blocks are committed blockIdToCRF.put(BLOCK_ID + i, calculateAccessWeight(nDir - 1 - i)); } // access blocks in the order: 10, 10, 11, 10, 11, 12. Update CRF of all blocks // during each access for (int i = 0; i < nDir; i++) { for (int j = 0; j <= i; j++) { access(BLOCK_ID + j); for (int k = 0; k < nDir; k++) { if (k == j) { blockIdToCRF.put(BLOCK_ID + k, blockIdToCRF.get(BLOCK_ID + k) * calculateAccessWeight(1L) + 1.0); } else { blockIdToCRF.put(BLOCK_ID + k, blockIdToCRF.get(BLOCK_ID + k) * calculateAccessWeight(1L)); } } } } // sort blocks in ascending order of CRF List<Entry<Long, Double>> blockCRF = getSortedCRF(blockIdToCRF); BlockStoreLocation anyDirInBottomTier = BlockStoreLocation.anyDirInTier(TieredBlockStoreTestUtils.TIER_ALIAS[bottomTierOrdinal]); // request smallest capacity and update access time on the evicted block for nDir times, the dir // to evict blocks from should be in the same order as sorted blockCRF for (int i = 0; i < nDir; i++) { EvictionPlan plan = mEvictor.freeSpaceWithView(bottomTierDirCapacity[0], anyDirInBottomTier, mManagerView); assertNotNull(plan); assertTrue(plan.toMove().isEmpty()); assertEquals(1, plan.toEvict().size()); long toEvictBlockId = plan.toEvict().get(0).getFirst(); long objectBlockId = blockCRF.get(i).getKey(); assertEquals(objectBlockId + " " + toEvictBlockId, objectBlockId, toEvictBlockId); // update CRF of the chosen block in case that it is chosen again for (int j = 0; j < nDir; j++) { access(toEvictBlockId); } } } /** * Tests the cascading eviction with the first tier filled and the second tier empty resulting in * no eviction. */ @Test public void cascadingEvictionTest1() throws Exception { // Two tiers, each dir in the second tier has more space than any dir in the first tier. Fill in // the first tier, leave the second tier empty. Request space from the first tier, blocks should // be moved from the first to the second tier without eviction. int firstTierOrdinal = TieredBlockStoreTestUtils.TIER_ORDINAL[0]; long[] firstTierDirCapacity = TieredBlockStoreTestUtils.TIER_CAPACITY_BYTES[0]; int nDir = firstTierDirCapacity.length; Map<Long, Double> blockIdToCRF = new HashMap<>(); for (int i = 0; i < nDir; i++) { cache(SESSION_ID, BLOCK_ID + i, firstTierDirCapacity[i], firstTierOrdinal, i); // update CRF of blocks when blocks are committed blockIdToCRF.put(BLOCK_ID + i, calculateAccessWeight(nDir - 1 - i)); } // access blocks in the order: 10, 10, 11. Update CRF of all blocks // during each access for (int i = 0; i < nDir; i++) { for (int j = 0; j <= i; j++) { access(BLOCK_ID + j); for (int k = 0; k < nDir; k++) { if (k == j) { blockIdToCRF.put(BLOCK_ID + k, blockIdToCRF.get(BLOCK_ID + k) * calculateAccessWeight(1L) + 1.0); } else { blockIdToCRF.put(BLOCK_ID + k, blockIdToCRF.get(BLOCK_ID + k) * calculateAccessWeight(1L)); } } } } List<Map.Entry<Long, Double>> blockCRF = getSortedCRF(blockIdToCRF); BlockStoreLocation anyDirInFirstTier = BlockStoreLocation.anyDirInTier(TieredBlockStoreTestUtils.TIER_ALIAS[firstTierOrdinal]); long smallestCapacity = firstTierDirCapacity[0]; // request smallest capacity and update access time on the moved block for nDir times, the dir // to move blocks from should be in the same order as sorted blockCRF for (int i = 0; i < nDir; i++) { EvictionPlan plan = mEvictor.freeSpaceWithView(smallestCapacity, anyDirInFirstTier, mManagerView); assertTrue(EvictorTestUtils.validCascadingPlan(smallestCapacity, plan, mMetaManager)); assertEquals(0, plan.toEvict().size()); assertEquals(1, plan.toMove().size()); long blockId = plan.toMove().get(0).getBlockId(); long objectBlockId = blockCRF.get(i).getKey(); assertEquals(objectBlockId, blockId); // update CRF of the chosen block in case that it is chosen again for (int j = 0; j < nDir; j++) { access(objectBlockId); } } } /** * Tests the cascading eviction with the first and second tier filled resulting in blocks in the * second tier are evicted. */ @Test public void cascadingEvictionTest2() throws Exception { // Two tiers, the second tier has more dirs than the first tier and each dir in the second tier // has more space than any dir in the first tier. Fill in all dirs and request space from the // first tier, blocks should be moved from the first to the second tier, and some blocks in the // second tier should be evicted to hold blocks moved from the first tier. long blockId = BLOCK_ID; long totalBlocks = 0; for (int tierOrdinal : TieredBlockStoreTestUtils.TIER_ORDINAL) { totalBlocks += TieredBlockStoreTestUtils.TIER_CAPACITY_BYTES[tierOrdinal].length; } Map<Long, Double> blockIdToCRF = new HashMap<>(); for (int tierOrdinal : TieredBlockStoreTestUtils.TIER_ORDINAL) { long[] tierCapacity = TieredBlockStoreTestUtils.TIER_CAPACITY_BYTES[tierOrdinal]; for (int dirIdx = 0; dirIdx < tierCapacity.length; dirIdx++) { cache(SESSION_ID, blockId, tierCapacity[dirIdx], tierOrdinal, dirIdx); // update CRF of blocks when blocks are committed blockIdToCRF.put(blockId, calculateAccessWeight(totalBlocks - 1 - (blockId - BLOCK_ID))); blockId++; } } // access blocks in the order: 10, 10, 11, 10, 11, 12, 10, 11, 12, 13, 10, 11, 12, 13, 14 // Update CRF of all blocks during each access for (int i = 0; i < totalBlocks; i++) { for (int j = 0; j <= i; j++) { access(BLOCK_ID + j); for (int k = 0; k < totalBlocks; k++) { if (k == j) { blockIdToCRF.put(BLOCK_ID + k, blockIdToCRF.get(BLOCK_ID + k) * calculateAccessWeight(1L) + 1.0); } else { blockIdToCRF.put(BLOCK_ID + k, blockIdToCRF.get(BLOCK_ID + k) * calculateAccessWeight(1L)); } } } } List<Map.Entry<Long, Double>> blockCRF = getSortedCRF(blockIdToCRF); // sorted blocks in the first tier List<Long> blocksInFirstTier = new ArrayList<>(); // sorted blocks in the second tier List<Long> blocksInSecondTier = new ArrayList<>(); for (int i = 0; i < blockCRF.size(); i++) { long block = blockCRF.get(i).getKey(); if (block - BLOCK_ID < TieredBlockStoreTestUtils.TIER_CAPACITY_BYTES[0].length) { blocksInFirstTier.add(block); } else if (block - BLOCK_ID < TieredBlockStoreTestUtils.TIER_CAPACITY_BYTES[0].length + TieredBlockStoreTestUtils.TIER_CAPACITY_BYTES[1].length) { blocksInSecondTier.add(block); } } BlockStoreLocation anyDirInFirstTier = BlockStoreLocation.anyDirInTier(TieredBlockStoreTestUtils.TIER_ALIAS[0]); int nDirInFirstTier = TieredBlockStoreTestUtils.TIER_CAPACITY_BYTES[0].length; long smallestCapacity = TieredBlockStoreTestUtils.TIER_CAPACITY_BYTES[0][0]; for (int i = 0; i < nDirInFirstTier; i++) { EvictionPlan plan = mEvictor.freeSpaceWithView(smallestCapacity, anyDirInFirstTier, mManagerView); assertTrue(EvictorTestUtils.validCascadingPlan(smallestCapacity, plan, mMetaManager)); // block with minimum CRF in the first tier needs to be moved to the second tier assertEquals(1, plan.toMove().size()); long blockIdMovedInFirstTier = plan.toMove().get(0).getBlockId(); long objectBlockIdInFirstTier = blocksInFirstTier.get(i); assertEquals(objectBlockIdInFirstTier, blockIdMovedInFirstTier); // cached block with minimum CRF in the second tier will be evicted to hold blocks moved // from first tier assertEquals(1, plan.toEvict().size()); long blockIdEvictedInSecondTier = plan.toEvict().get(0).getFirst(); long objectBlockIdInSecondTier = blocksInSecondTier.get(i); assertEquals(objectBlockIdInSecondTier, blockIdEvictedInSecondTier); // update CRF of the chosen blocks in case that they are chosen again for (int j = 0; j < totalBlocks; j++) { access(blockIdMovedInFirstTier); } for (int j = 0; j < totalBlocks; j++) { access(blockIdEvictedInSecondTier); } } } }
core/server/worker/src/test/java/alluxio/worker/block/evictor/LRFUEvictorTest.java
/* * The Alluxio Open Foundation licenses this work under the Apache License, version 2.0 * (the "License"). You may not use this work except in compliance with the License, which is * available at www.apache.org/licenses/LICENSE-2.0 * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, * either express or implied, as more fully set forth in the License. * * See the NOTICE file distributed with this work for information regarding copyright ownership. */ package alluxio.worker.block.evictor; import alluxio.conf.ServerConfiguration; import alluxio.conf.PropertyKey; import alluxio.worker.block.BlockMetadataManager; import alluxio.worker.block.BlockMetadataManagerView; import alluxio.worker.block.BlockStoreEventListener; import alluxio.worker.block.BlockStoreLocation; import alluxio.worker.block.TieredBlockStoreTestUtils; import alluxio.worker.block.allocator.Allocator; import alluxio.worker.block.allocator.MaxFreeAllocator; import alluxio.worker.block.meta.StorageDir; import org.junit.Assert; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import java.io.File; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; /** * Unit tests for specific behavior of {@link LRFUEvictor} such as evicting/moving blocks with * minimum CRF value and cascading LRFU eviction. */ public class LRFUEvictorTest { private static final long SESSION_ID = 2; private static final long BLOCK_ID = 10; private BlockMetadataManager mMetaManager; private BlockMetadataManagerView mManagerView; private Evictor mEvictor; private double mStepFactor; private double mAttenuationFactor; /** Rule to create a new temporary folder during each test. */ @Rule public TemporaryFolder mTestFolder = new TemporaryFolder(); /** * Sets up all dependencies before a test runs. */ @Before public final void before() throws Exception { File tempFolder = mTestFolder.newFolder(); mMetaManager = TieredBlockStoreTestUtils.defaultMetadataManager(tempFolder.getAbsolutePath()); mManagerView = new BlockMetadataManagerView(mMetaManager, Collections.<Long>emptySet(), Collections.<Long>emptySet()); ServerConfiguration.set(PropertyKey.WORKER_EVICTOR_CLASS, LRFUEvictor.class.getName()); ServerConfiguration.set(PropertyKey.WORKER_ALLOCATOR_CLASS, MaxFreeAllocator.class.getName()); Allocator allocator = Allocator.Factory.create(mManagerView); mStepFactor = ServerConfiguration.getDouble(PropertyKey.WORKER_EVICTOR_LRFU_STEP_FACTOR); mAttenuationFactor = ServerConfiguration.getDouble(PropertyKey.WORKER_EVICTOR_LRFU_ATTENUATION_FACTOR); mEvictor = Evictor.Factory.create(mManagerView, allocator); } /** * Caches bytes into {@link StorageDir}. * * @param sessionId session who caches the data * @param blockId id of the cached block * @param bytes size of the block in bytes * @param tierLevel tier level * @param dirIdx index of a directory */ private void cache(long sessionId, long blockId, long bytes, int tierLevel, int dirIdx) throws Exception { StorageDir dir = mMetaManager.getTiers().get(tierLevel).getDir(dirIdx); TieredBlockStoreTestUtils.cache(sessionId, blockId, bytes, dir, mMetaManager, mEvictor); } /** * Access the block to update {@link Evictor}. */ private void access(long blockId) { ((BlockStoreEventListener) mEvictor).onAccessBlock(SESSION_ID, blockId); } private double calculateAccessWeight(long timeInterval) { return Math.pow(1.0 / mAttenuationFactor, mStepFactor * timeInterval); } /** * Sort all blocks in ascending order of CRF. * * @return the sorted CRF of all blocks */ private List<Map.Entry<Long, Double>> getSortedCRF(Map<Long, Double> crfMap) { List<Map.Entry<Long, Double>> sortedCRF = new ArrayList<>(crfMap.entrySet()); Collections.sort(sortedCRF, new Comparator<Map.Entry<Long, Double>>() { @Override public int compare(Entry<Long, Double> o1, Entry<Long, Double> o2) { double res = o1.getValue() - o2.getValue(); if (res < 0) { return -1; } else if (res > 0) { return 1; } else { return 0; } } }); return sortedCRF; } /** * Tests that the eviction in the bottom tier works. */ @Test public void evictInBottomTier() throws Exception { int bottomTierOrdinal = TieredBlockStoreTestUtils .TIER_ORDINAL[TieredBlockStoreTestUtils.TIER_ORDINAL.length - 1]; Map<Long, Double> blockIdToCRF = new HashMap<>(); // capacity increases with index long[] bottomTierDirCapacity = TieredBlockStoreTestUtils.TIER_CAPACITY_BYTES[bottomTierOrdinal]; int nDir = bottomTierDirCapacity.length; // fill in dirs from larger to smaller capacity with blockId equal to BLOCK_ID plus dir index for (int i = 0; i < nDir; i++) { cache(SESSION_ID, BLOCK_ID + i, bottomTierDirCapacity[i], bottomTierOrdinal, i); // update CRF of blocks when blocks are committed blockIdToCRF.put(BLOCK_ID + i, calculateAccessWeight(nDir - 1 - i)); } // access blocks in the order: 10, 10, 11, 10, 11, 12. Update CRF of all blocks // during each access for (int i = 0; i < nDir; i++) { for (int j = 0; j <= i; j++) { access(BLOCK_ID + j); for (int k = 0; k < nDir; k++) { if (k == j) { blockIdToCRF.put(BLOCK_ID + k, blockIdToCRF.get(BLOCK_ID + k) * calculateAccessWeight(1L) + 1.0); } else { blockIdToCRF.put(BLOCK_ID + k, blockIdToCRF.get(BLOCK_ID + k) * calculateAccessWeight(1L)); } } } } // sort blocks in ascending order of CRF List<Entry<Long, Double>> blockCRF = getSortedCRF(blockIdToCRF); BlockStoreLocation anyDirInBottomTier = BlockStoreLocation.anyDirInTier(TieredBlockStoreTestUtils.TIER_ALIAS[bottomTierOrdinal]); // request smallest capacity and update access time on the evicted block for nDir times, the dir // to evict blocks from should be in the same order as sorted blockCRF for (int i = 0; i < nDir; i++) { EvictionPlan plan = mEvictor.freeSpaceWithView(bottomTierDirCapacity[0], anyDirInBottomTier, mManagerView); Assert.assertNotNull(plan); Assert.assertTrue(plan.toMove().isEmpty()); Assert.assertEquals(1, plan.toEvict().size()); long toEvictBlockId = plan.toEvict().get(0).getFirst(); long objectBlockId = blockCRF.get(i).getKey(); Assert.assertEquals(objectBlockId + " " + toEvictBlockId, objectBlockId, toEvictBlockId); // update CRF of the chosen block in case that it is chosen again for (int j = 0; j < nDir; j++) { access(toEvictBlockId); } } } /** * Tests the cascading eviction with the first tier filled and the second tier empty resulting in * no eviction. */ @Test public void cascadingEvictionTest1() throws Exception { // Two tiers, each dir in the second tier has more space than any dir in the first tier. Fill in // the first tier, leave the second tier empty. Request space from the first tier, blocks should // be moved from the first to the second tier without eviction. int firstTierOrdinal = TieredBlockStoreTestUtils.TIER_ORDINAL[0]; long[] firstTierDirCapacity = TieredBlockStoreTestUtils.TIER_CAPACITY_BYTES[0]; int nDir = firstTierDirCapacity.length; Map<Long, Double> blockIdToCRF = new HashMap<>(); for (int i = 0; i < nDir; i++) { cache(SESSION_ID, BLOCK_ID + i, firstTierDirCapacity[i], firstTierOrdinal, i); // update CRF of blocks when blocks are committed blockIdToCRF.put(BLOCK_ID + i, calculateAccessWeight(nDir - 1 - i)); } // access blocks in the order: 10, 10, 11. Update CRF of all blocks // during each access for (int i = 0; i < nDir; i++) { for (int j = 0; j <= i; j++) { access(BLOCK_ID + j); for (int k = 0; k < nDir; k++) { if (k == j) { blockIdToCRF.put(BLOCK_ID + k, blockIdToCRF.get(BLOCK_ID + k) * calculateAccessWeight(1L) + 1.0); } else { blockIdToCRF.put(BLOCK_ID + k, blockIdToCRF.get(BLOCK_ID + k) * calculateAccessWeight(1L)); } } } } List<Map.Entry<Long, Double>> blockCRF = getSortedCRF(blockIdToCRF); BlockStoreLocation anyDirInFirstTier = BlockStoreLocation.anyDirInTier(TieredBlockStoreTestUtils.TIER_ALIAS[firstTierOrdinal]); long smallestCapacity = firstTierDirCapacity[0]; // request smallest capacity and update access time on the moved block for nDir times, the dir // to move blocks from should be in the same order as sorted blockCRF for (int i = 0; i < nDir; i++) { EvictionPlan plan = mEvictor.freeSpaceWithView(smallestCapacity, anyDirInFirstTier, mManagerView); Assert.assertTrue(EvictorTestUtils.validCascadingPlan(smallestCapacity, plan, mMetaManager)); Assert.assertEquals(0, plan.toEvict().size()); Assert.assertEquals(1, plan.toMove().size()); long blockId = plan.toMove().get(0).getBlockId(); long objectBlockId = blockCRF.get(i).getKey(); Assert.assertEquals(objectBlockId, blockId); // update CRF of the chosen block in case that it is chosen again for (int j = 0; j < nDir; j++) { access(objectBlockId); } } } /** * Tests the cascading eviction with the first and second tier filled resulting in blocks in the * second tier are evicted. */ @Test public void cascadingEvictionTest2() throws Exception { // Two tiers, the second tier has more dirs than the first tier and each dir in the second tier // has more space than any dir in the first tier. Fill in all dirs and request space from the // first tier, blocks should be moved from the first to the second tier, and some blocks in the // second tier should be evicted to hold blocks moved from the first tier. long blockId = BLOCK_ID; long totalBlocks = 0; for (int tierOrdinal : TieredBlockStoreTestUtils.TIER_ORDINAL) { totalBlocks += TieredBlockStoreTestUtils.TIER_CAPACITY_BYTES[tierOrdinal].length; } Map<Long, Double> blockIdToCRF = new HashMap<>(); for (int tierOrdinal : TieredBlockStoreTestUtils.TIER_ORDINAL) { long[] tierCapacity = TieredBlockStoreTestUtils.TIER_CAPACITY_BYTES[tierOrdinal]; for (int dirIdx = 0; dirIdx < tierCapacity.length; dirIdx++) { cache(SESSION_ID, blockId, tierCapacity[dirIdx], tierOrdinal, dirIdx); // update CRF of blocks when blocks are committed blockIdToCRF.put(blockId, calculateAccessWeight(totalBlocks - 1 - (blockId - BLOCK_ID))); blockId++; } } // access blocks in the order: 10, 10, 11, 10, 11, 12, 10, 11, 12, 13, 10, 11, 12, 13, 14 // Update CRF of all blocks during each access for (int i = 0; i < totalBlocks; i++) { for (int j = 0; j <= i; j++) { access(BLOCK_ID + j); for (int k = 0; k < totalBlocks; k++) { if (k == j) { blockIdToCRF.put(BLOCK_ID + k, blockIdToCRF.get(BLOCK_ID + k) * calculateAccessWeight(1L) + 1.0); } else { blockIdToCRF.put(BLOCK_ID + k, blockIdToCRF.get(BLOCK_ID + k) * calculateAccessWeight(1L)); } } } } List<Map.Entry<Long, Double>> blockCRF = getSortedCRF(blockIdToCRF); // sorted blocks in the first tier List<Long> blocksInFirstTier = new ArrayList<>(); // sorted blocks in the second tier List<Long> blocksInSecondTier = new ArrayList<>(); for (int i = 0; i < blockCRF.size(); i++) { long block = blockCRF.get(i).getKey(); if (block - BLOCK_ID < TieredBlockStoreTestUtils.TIER_CAPACITY_BYTES[0].length) { blocksInFirstTier.add(block); } else if (block - BLOCK_ID < TieredBlockStoreTestUtils.TIER_CAPACITY_BYTES[0].length + TieredBlockStoreTestUtils.TIER_CAPACITY_BYTES[1].length) { blocksInSecondTier.add(block); } } BlockStoreLocation anyDirInFirstTier = BlockStoreLocation.anyDirInTier(TieredBlockStoreTestUtils.TIER_ALIAS[0]); int nDirInFirstTier = TieredBlockStoreTestUtils.TIER_CAPACITY_BYTES[0].length; long smallestCapacity = TieredBlockStoreTestUtils.TIER_CAPACITY_BYTES[0][0]; for (int i = 0; i < nDirInFirstTier; i++) { EvictionPlan plan = mEvictor.freeSpaceWithView(smallestCapacity, anyDirInFirstTier, mManagerView); Assert.assertTrue(EvictorTestUtils.validCascadingPlan(smallestCapacity, plan, mMetaManager)); // block with minimum CRF in the first tier needs to be moved to the second tier Assert.assertEquals(1, plan.toMove().size()); long blockIdMovedInFirstTier = plan.toMove().get(0).getBlockId(); long objectBlockIdInFirstTier = blocksInFirstTier.get(i); Assert.assertEquals(objectBlockIdInFirstTier, blockIdMovedInFirstTier); // cached block with minimum CRF in the second tier will be evicted to hold blocks moved // from first tier Assert.assertEquals(1, plan.toEvict().size()); long blockIdEvictedInSecondTier = plan.toEvict().get(0).getFirst(); long objectBlockIdInSecondTier = blocksInSecondTier.get(i); Assert.assertEquals(objectBlockIdInSecondTier, blockIdEvictedInSecondTier); // update CRF of the chosen blocks in case that they are chosen again for (int j = 0; j < totalBlocks; j++) { access(blockIdMovedInFirstTier); } for (int j = 0; j < totalBlocks; j++) { access(blockIdEvictedInSecondTier); } } } }
[SMALLFIX] Use static imports for standard test utilities Change import org.junit.Assert; to import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertEquals; AND Update all Assert.{{ method }}* to {{ method }}* For example update Assert.assertTrue(mGraph.getRoots().isEmpty()); to assertTrue(mGraph.getRoots().isEmpty()); pr-link: Alluxio/alluxio#8706 change-id: cid-26025b08d94770c9a9a3af92efa5b4a5ddbbd1f4
core/server/worker/src/test/java/alluxio/worker/block/evictor/LRFUEvictorTest.java
[SMALLFIX] Use static imports for standard test utilities
<ide><path>ore/server/worker/src/test/java/alluxio/worker/block/evictor/LRFUEvictorTest.java <ide> <ide> package alluxio.worker.block.evictor; <ide> <add>import static org.junit.Assert.assertNotNull; <add>import static org.junit.Assert.assertTrue; <add>import static org.junit.Assert.assertEquals; <add> <ide> import alluxio.conf.ServerConfiguration; <ide> import alluxio.conf.PropertyKey; <ide> import alluxio.worker.block.BlockMetadataManager; <ide> import alluxio.worker.block.allocator.MaxFreeAllocator; <ide> import alluxio.worker.block.meta.StorageDir; <ide> <del>import org.junit.Assert; <ide> import org.junit.Before; <ide> import org.junit.Rule; <ide> import org.junit.Test; <ide> for (int i = 0; i < nDir; i++) { <ide> EvictionPlan plan = <ide> mEvictor.freeSpaceWithView(bottomTierDirCapacity[0], anyDirInBottomTier, mManagerView); <del> Assert.assertNotNull(plan); <del> Assert.assertTrue(plan.toMove().isEmpty()); <del> Assert.assertEquals(1, plan.toEvict().size()); <add> assertNotNull(plan); <add> assertTrue(plan.toMove().isEmpty()); <add> assertEquals(1, plan.toEvict().size()); <ide> long toEvictBlockId = plan.toEvict().get(0).getFirst(); <ide> long objectBlockId = blockCRF.get(i).getKey(); <del> Assert.assertEquals(objectBlockId + " " + toEvictBlockId, objectBlockId, toEvictBlockId); <add> assertEquals(objectBlockId + " " + toEvictBlockId, objectBlockId, toEvictBlockId); <ide> // update CRF of the chosen block in case that it is chosen again <ide> for (int j = 0; j < nDir; j++) { <ide> access(toEvictBlockId); <ide> for (int i = 0; i < nDir; i++) { <ide> EvictionPlan plan = <ide> mEvictor.freeSpaceWithView(smallestCapacity, anyDirInFirstTier, mManagerView); <del> Assert.assertTrue(EvictorTestUtils.validCascadingPlan(smallestCapacity, plan, mMetaManager)); <del> Assert.assertEquals(0, plan.toEvict().size()); <del> Assert.assertEquals(1, plan.toMove().size()); <add> assertTrue(EvictorTestUtils.validCascadingPlan(smallestCapacity, plan, mMetaManager)); <add> assertEquals(0, plan.toEvict().size()); <add> assertEquals(1, plan.toMove().size()); <ide> long blockId = plan.toMove().get(0).getBlockId(); <ide> long objectBlockId = blockCRF.get(i).getKey(); <del> Assert.assertEquals(objectBlockId, blockId); <add> assertEquals(objectBlockId, blockId); <ide> // update CRF of the chosen block in case that it is chosen again <ide> for (int j = 0; j < nDir; j++) { <ide> access(objectBlockId); <ide> for (int i = 0; i < nDirInFirstTier; i++) { <ide> EvictionPlan plan = <ide> mEvictor.freeSpaceWithView(smallestCapacity, anyDirInFirstTier, mManagerView); <del> Assert.assertTrue(EvictorTestUtils.validCascadingPlan(smallestCapacity, plan, mMetaManager)); <add> assertTrue(EvictorTestUtils.validCascadingPlan(smallestCapacity, plan, mMetaManager)); <ide> // block with minimum CRF in the first tier needs to be moved to the second tier <del> Assert.assertEquals(1, plan.toMove().size()); <add> assertEquals(1, plan.toMove().size()); <ide> long blockIdMovedInFirstTier = plan.toMove().get(0).getBlockId(); <ide> long objectBlockIdInFirstTier = blocksInFirstTier.get(i); <del> Assert.assertEquals(objectBlockIdInFirstTier, blockIdMovedInFirstTier); <add> assertEquals(objectBlockIdInFirstTier, blockIdMovedInFirstTier); <ide> // cached block with minimum CRF in the second tier will be evicted to hold blocks moved <ide> // from first tier <del> Assert.assertEquals(1, plan.toEvict().size()); <add> assertEquals(1, plan.toEvict().size()); <ide> long blockIdEvictedInSecondTier = plan.toEvict().get(0).getFirst(); <ide> long objectBlockIdInSecondTier = blocksInSecondTier.get(i); <del> Assert.assertEquals(objectBlockIdInSecondTier, blockIdEvictedInSecondTier); <add> assertEquals(objectBlockIdInSecondTier, blockIdEvictedInSecondTier); <ide> // update CRF of the chosen blocks in case that they are chosen again <ide> for (int j = 0; j < totalBlocks; j++) { <ide> access(blockIdMovedInFirstTier);
Java
mit
660b12ce9fdd3937ee6b69924a7d9f8c9078f19a
0
dscrobonia/appsensor,sims143/appsensor,timothy22000/appsensor,timothy22000/appsensor,mahmoodm2/appsensor,sanjaygouri/appsensor,sims143/appsensor,ProZachJ/appsensor,mahmoodm2/appsensor,ksmaheshkumar/appsensor,ProZachJ/appsensor,jtmelton/appsensor,jtmelton/appsensor,jtmelton/appsensor,timothy22000/appsensor,jtmelton/appsensor,mahmoodm2/appsensor,dscrobonia/appsensor,sanjaygouri/appsensor,ProZachJ/appsensor,mahmoodm2/appsensor,ashishmgupta/appsensor,jtmelton/appsensor,ksmaheshkumar/appsensor,timothy22000/appsensor,dscrobonia/appsensor,dscrobonia/appsensor,ProZachJ/appsensor,dscrobonia/appsensor,ashishmgupta/appsensor,ProZachJ/appsensor,ProZachJ/appsensor,ashishmgupta/appsensor,dscrobonia/appsensor,jtmelton/appsensor,mahmoodm2/appsensor
package org.owasp.appsensor.handler.impl; import java.util.ArrayList; import java.util.Collection; import java.util.GregorianCalendar; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import javax.ws.rs.core.MediaType; import org.owasp.appsensor.Attack; import org.owasp.appsensor.Event; import org.owasp.appsensor.RequestHandler; import org.owasp.appsensor.Response; import org.owasp.appsensor.ServerObjectFactory; /** * This is the restful endpoint that handles requests on the server-side. * * @author John Melton ([email protected]) http://www.jtmelton.com/ */ @Path("/api/v1.0") @Produces("application/json") public class RestRequestHandler implements RequestHandler { //TODO: add rest server-side handlers here @Override @POST @Path("/events") public void addEvent(Event event) { ServerObjectFactory.getEventStore().addEvent(event); } @Override @POST @Path("/attacks") public void addAttack(Attack attack) { ServerObjectFactory.getAttackStore().addAttack(attack); } @Override @GET @Path("/responses") @Produces(MediaType.APPLICATION_JSON) public Collection<Response> getResponses(@QueryParam("detectionSystemId") String detectionSystemId, @QueryParam("earliest") long earliest) { Collection<Response> responses = new ArrayList<Response>(); Response response1 = new Response(); response1.setAction("log"); response1.setDetectionSystemId("server1"); response1.setTimestamp(new GregorianCalendar().getTimeInMillis() - 30); responses.add(response1); Response response2 = new Response(); response2.setAction("logout"); response2.setDetectionSystemId("server2"); response2.setTimestamp(new GregorianCalendar().getTimeInMillis() - 15); responses.add(response2); Response response3 = new Response(); response3.setAction("disable"); response3.setDetectionSystemId("server2"); response3.setTimestamp(new GregorianCalendar().getTimeInMillis() + 10); responses.add(response3); return responses; // return ServerObjectFactory.getResponseStore().findResponses(detectionSystemId, earliest); } }
appsensor-ws-rest-server/src/main/java/org/owasp/appsensor/handler/impl/RestRequestHandler.java
package org.owasp.appsensor.handler.impl; import java.util.ArrayList; import java.util.Collection; import java.util.GregorianCalendar; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import javax.ws.rs.core.MediaType; import org.owasp.appsensor.Attack; import org.owasp.appsensor.Event; import org.owasp.appsensor.RequestHandler; import org.owasp.appsensor.Response; import org.owasp.appsensor.ServerObjectFactory; /** * This is the restful endpoint that handles requests on the server-side. * * @author jtmelton */ @Path("/api/v1.0") @Produces("application/json") public class RestRequestHandler implements RequestHandler { //TODO: add rest server-side handlers here @Override @POST @Path("/events") public void addEvent(Event event) { ServerObjectFactory.getEventStore().addEvent(event); } @Override @POST @Path("/attacks") public void addAttack(Attack attack) { ServerObjectFactory.getAttackStore().addAttack(attack); } @Override @GET @Path("/responses") @Produces(MediaType.APPLICATION_JSON) public Collection<Response> getResponses(@QueryParam("detectionSystemId") String detectionSystemId, @QueryParam("earliest") long earliest) { Collection<Response> responses = new ArrayList<Response>(); Response response1 = new Response(); response1.setAction("log"); response1.setDetectionSystemId("server1"); response1.setTimestamp(new GregorianCalendar().getTimeInMillis() - 30); responses.add(response1); Response response2 = new Response(); response2.setAction("logout"); response2.setDetectionSystemId("server2"); response2.setTimestamp(new GregorianCalendar().getTimeInMillis() - 15); responses.add(response2); Response response3 = new Response(); response3.setAction("disable"); response3.setDetectionSystemId("server2"); response3.setTimestamp(new GregorianCalendar().getTimeInMillis() + 10); responses.add(response3); return responses; // return ServerObjectFactory.getResponseStore().findResponses(detectionSystemId, earliest); } }
clean up javadoc
appsensor-ws-rest-server/src/main/java/org/owasp/appsensor/handler/impl/RestRequestHandler.java
clean up javadoc
<ide><path>ppsensor-ws-rest-server/src/main/java/org/owasp/appsensor/handler/impl/RestRequestHandler.java <ide> /** <ide> * This is the restful endpoint that handles requests on the server-side. <ide> * <del> * @author jtmelton <add> * @author John Melton ([email protected]) http://www.jtmelton.com/ <ide> */ <ide> @Path("/api/v1.0") <ide> @Produces("application/json")
Java
bsd-3-clause
2cf0fa68d2749b8c833970f9b4689b77c009b63a
0
NCIP/nci-term-browser,NCIP/nci-term-browser,NCIP/nci-term-browser,NCIP/nci-term-browser
package gov.nih.nci.evs.browser.properties; import java.io.File; import java.io.FileInputStream; import java.util.Iterator; import java.util.Properties; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.HashMap; import org.apache.log4j.Logger; /** * <!-- LICENSE_TEXT_START --> * Copyright 2008,2009 NGIT. This software was developed in conjunction with the National Cancer Institute, * and so to the extent government employees are co-authors, any rights in such works shall be subject to Title 17 of the United States Code, section 105. * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the disclaimer of Article 3, below. Redistributions * in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other * materials provided with the distribution. * 2. The end-user documentation included with the redistribution, if any, must include the following acknowledgment: * "This product includes software developed by NGIT and the National Cancer Institute." * If no such end-user documentation is to be included, this acknowledgment shall appear in the software itself, * wherever such third-party acknowledgments normally appear. * 3. The names "The National Cancer Institute", "NCI" and "NGIT" must not be used to endorse or promote products derived from this software. * 4. This license does not authorize the incorporation of this software into any third party proprietary programs. This license does not authorize * the recipient to use any trademarks owned by either NCI or NGIT * 5. THIS SOFTWARE IS PROVIDED "AS IS," AND ANY EXPRESSED OR IMPLIED WARRANTIES, (INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE) ARE DISCLAIMED. IN NO EVENT SHALL THE NATIONAL CANCER INSTITUTE, * NGIT, OR THEIR AFFILIATES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * <!-- LICENSE_TEXT_END --> */ /** * @author EVS Team * @version 1.0 * * Modification history * Initial implementation [email protected] * */ public class NCItBrowserProperties { private static List displayItemList; private static HashMap configurableItemMap; // KLO public static final String EVS_SERVICE_URL = "EVS_SERVICE_URL"; public static final String LG_CONFIG_FILE = "LG_CONFIG_FILE"; public static final String MAXIMUM_RETURN = "MAXIMUM_RETURN"; public static final String EHCACHE_XML_PATHNAME = "EHCACHE_XML_PATHNAME"; public static final String SORT_BY_SCORE = "SORT_BY_SCORE"; public static final String MAIL_SMTP_SERVER = "MAIL_SMTP_SERVER"; public static final String NCICB_CONTACT_URL = "NCICB_CONTACT_URL"; public static final String MAXIMUM_TREE_LEVEL = "MAXIMUM_TREE_LEVEL"; public static final String TERMINOLOGY_SUBSET_DOWNLOAD_URL= "TERMINOLOGY_SUBSET_DOWNLOAD_URL"; public static final String NCIT_BUILD_INFO = "NCIT_BUILD_INFO"; private static Logger log = Logger.getLogger(NCItBrowserProperties.class); private static NCItBrowserProperties NCItBrowserProperties = null; private static Properties properties = new Properties(); private static int maxToReturn = 1000; private static int maxTreeLevel = 1000; private static String service_url = null; private static String lg_config_file = null; private static String sort_by_score = null; private static String mail_smtp_server = null; private static String ncicb_contact_url = null; private static String terminology_subset_download_url = null; /** * Private constructor for singleton pattern. */ private NCItBrowserProperties() {} /** * Gets the single instance of NCItBrowserProperties. * * @return single instance of NCItBrowserProperties * * @throws Exception the exception */ public static NCItBrowserProperties getInstance() throws Exception{ if(NCItBrowserProperties == null) { synchronized(NCItBrowserProperties.class) { if(NCItBrowserProperties == null) { NCItBrowserProperties = new NCItBrowserProperties(); loadProperties(); String max_str = NCItBrowserProperties.getProperty(NCItBrowserProperties.MAXIMUM_RETURN); maxToReturn = Integer.parseInt(max_str); String max_tree_level_str = NCItBrowserProperties.getProperty(NCItBrowserProperties.MAXIMUM_TREE_LEVEL); maxTreeLevel = Integer.parseInt(max_tree_level_str); service_url = NCItBrowserProperties.getProperty(NCItBrowserProperties.EVS_SERVICE_URL); //System.out.println("EVS_SERVICE_URL: " + service_url); lg_config_file = NCItBrowserProperties.getProperty(NCItBrowserProperties.LG_CONFIG_FILE); //System.out.println("LG_CONFIG_FILE: " + lg_config_file); sort_by_score = NCItBrowserProperties.getProperty(NCItBrowserProperties.SORT_BY_SCORE); ncicb_contact_url = NCItBrowserProperties.getProperty(NCItBrowserProperties.NCICB_CONTACT_URL); mail_smtp_server = NCItBrowserProperties.getProperty(NCItBrowserProperties.MAIL_SMTP_SERVER); terminology_subset_download_url = NCItBrowserProperties.getProperty(NCItBrowserProperties.TERMINOLOGY_SUBSET_DOWNLOAD_URL); } } } return NCItBrowserProperties ; } //public String getProperty(String key) throws Exception{ public static String getProperty(String key) throws Exception{ //return properties.getProperty(key); String ret_str = (String) configurableItemMap.get(key); if (ret_str == null) return null; if (ret_str.compareToIgnoreCase("null") == 0) return null; return ret_str; } public List getDisplayItemList() { return this.displayItemList; } private static void loadProperties() throws Exception { String propertyFile = System.getProperty("gov.nih.nci.evs.browser.NCItBrowserProperties"); log.info("NCItBrowserProperties File Location= "+ propertyFile); PropertyFileParser parser = new PropertyFileParser(propertyFile); parser.run(); displayItemList = parser.getDisplayItemList(); configurableItemMap = parser.getConfigurableItemMap(); } }
software/ncitbrowser/src/java/gov/nih/nci/evs/browser/properties/NCItBrowserProperties.java
package gov.nih.nci.evs.browser.properties; import java.io.File; import java.io.FileInputStream; import java.util.Iterator; import java.util.Properties; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.HashMap; import org.apache.log4j.Logger; /** * <!-- LICENSE_TEXT_START --> * Copyright 2008,2009 NGIT. This software was developed in conjunction with the National Cancer Institute, * and so to the extent government employees are co-authors, any rights in such works shall be subject to Title 17 of the United States Code, section 105. * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the disclaimer of Article 3, below. Redistributions * in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other * materials provided with the distribution. * 2. The end-user documentation included with the redistribution, if any, must include the following acknowledgment: * "This product includes software developed by NGIT and the National Cancer Institute." * If no such end-user documentation is to be included, this acknowledgment shall appear in the software itself, * wherever such third-party acknowledgments normally appear. * 3. The names "The National Cancer Institute", "NCI" and "NGIT" must not be used to endorse or promote products derived from this software. * 4. This license does not authorize the incorporation of this software into any third party proprietary programs. This license does not authorize * the recipient to use any trademarks owned by either NCI or NGIT * 5. THIS SOFTWARE IS PROVIDED "AS IS," AND ANY EXPRESSED OR IMPLIED WARRANTIES, (INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE) ARE DISCLAIMED. IN NO EVENT SHALL THE NATIONAL CANCER INSTITUTE, * NGIT, OR THEIR AFFILIATES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * <!-- LICENSE_TEXT_END --> */ /** * @author EVS Team * @version 1.0 * * Modification history * Initial implementation [email protected] * */ public class NCItBrowserProperties { private static List displayItemList; private static HashMap configurableItemMap; //KLO public static final String EVS_SERVICE_URL = "EVS_SERVICE_URL"; public static final String MAXIMUM_RETURN = "MAXIMUM_RETURN"; public static final String EHCACHE_XML_PATHNAME = "EHCACHE_XML_PATHNAME"; public static final String SORT_BY_SCORE = "SORT_BY_SCORE"; public static final String MAIL_SMTP_SERVER = "MAIL_SMTP_SERVER"; public static final String NCICB_CONTACT_URL = "NCICB_CONTACT_URL"; public static final String MAXIMUM_TREE_LEVEL = "MAXIMUM_TREE_LEVEL"; public static final String TERMINOLOGY_SUBSET_DOWNLOAD_URL= "TERMINOLOGY_SUBSET_DOWNLOAD_URL"; public static final String NCIT_BUILD_INFO = "NCIT_BUILD_INFO"; private static Logger log = Logger.getLogger(NCItBrowserProperties.class); private static NCItBrowserProperties NCItBrowserProperties = null; private static Properties properties = new Properties(); private static int maxToReturn = 1000; private static int maxTreeLevel = 1000; private static String service_url = null; private static String sort_by_score = null; private static String mail_smtp_server = null; private static String ncicb_contact_url = null; private static String terminology_subset_download_url = null; /** * Private constructor for singleton pattern. */ private NCItBrowserProperties() {} /** * Gets the single instance of NCItBrowserProperties. * * @return single instance of NCItBrowserProperties * * @throws Exception the exception */ public static NCItBrowserProperties getInstance() throws Exception{ if(NCItBrowserProperties == null) { synchronized(NCItBrowserProperties.class) { if(NCItBrowserProperties == null) { NCItBrowserProperties = new NCItBrowserProperties(); loadProperties(); String max_str = NCItBrowserProperties.getProperty(NCItBrowserProperties.MAXIMUM_RETURN); maxToReturn = Integer.parseInt(max_str); String max_tree_level_str = NCItBrowserProperties.getProperty(NCItBrowserProperties.MAXIMUM_TREE_LEVEL); maxTreeLevel = Integer.parseInt(max_tree_level_str); service_url = NCItBrowserProperties.getProperty(NCItBrowserProperties.EVS_SERVICE_URL); //System.out.println("EVS_SERVICE_URL: " + service_url); sort_by_score = NCItBrowserProperties.getProperty(NCItBrowserProperties.SORT_BY_SCORE); ncicb_contact_url = NCItBrowserProperties.getProperty(NCItBrowserProperties.NCICB_CONTACT_URL); mail_smtp_server = NCItBrowserProperties.getProperty(NCItBrowserProperties.MAIL_SMTP_SERVER); terminology_subset_download_url = NCItBrowserProperties.getProperty(NCItBrowserProperties.TERMINOLOGY_SUBSET_DOWNLOAD_URL); } } } return NCItBrowserProperties ; } //public String getProperty(String key) throws Exception{ public static String getProperty(String key) throws Exception{ //return properties.getProperty(key); String ret_str = (String) configurableItemMap.get(key); if (ret_str == null) return null; if (ret_str.compareToIgnoreCase("null") == 0) return null; return ret_str; } public List getDisplayItemList() { return this.displayItemList; } private static void loadProperties() throws Exception { String propertyFile = System.getProperty("gov.nih.nci.evs.browser.NCItBrowserProperties"); log.info("NCItBrowserProperties File Location= "+ propertyFile); PropertyFileParser parser = new PropertyFileParser(propertyFile); parser.run(); displayItemList = parser.getDisplayItemList(); configurableItemMap = parser.getConfigurableItemMap(); } }
Adding code to move LG_CONFIG_FILE from properties-service.xml to NCItBrowserProperties.xml. git-svn-id: 8a910031c78bbe8a754298bb28800c1494820db3@422 0604bb77-1110-461e-859e-28c50bf9b280
software/ncitbrowser/src/java/gov/nih/nci/evs/browser/properties/NCItBrowserProperties.java
Adding code to move LG_CONFIG_FILE from properties-service.xml to NCItBrowserProperties.xml.
<ide><path>oftware/ncitbrowser/src/java/gov/nih/nci/evs/browser/properties/NCItBrowserProperties.java <ide> private static List displayItemList; <ide> private static HashMap configurableItemMap; <ide> <del> //KLO <add> // KLO <ide> public static final String EVS_SERVICE_URL = "EVS_SERVICE_URL"; <add> public static final String LG_CONFIG_FILE = "LG_CONFIG_FILE"; <ide> public static final String MAXIMUM_RETURN = "MAXIMUM_RETURN"; <ide> public static final String EHCACHE_XML_PATHNAME = "EHCACHE_XML_PATHNAME"; <ide> public static final String SORT_BY_SCORE = "SORT_BY_SCORE"; <ide> private static int maxToReturn = 1000; <ide> private static int maxTreeLevel = 1000; <ide> private static String service_url = null; <add> private static String lg_config_file = null; <ide> <ide> private static String sort_by_score = null; <ide> private static String mail_smtp_server = null; <ide> public static NCItBrowserProperties getInstance() throws Exception{ <ide> if(NCItBrowserProperties == null) { <ide> synchronized(NCItBrowserProperties.class) { <add> <ide> if(NCItBrowserProperties == null) { <ide> NCItBrowserProperties = new NCItBrowserProperties(); <ide> loadProperties(); <ide> maxTreeLevel = Integer.parseInt(max_tree_level_str); <ide> <ide> service_url = NCItBrowserProperties.getProperty(NCItBrowserProperties.EVS_SERVICE_URL); <add> //System.out.println("EVS_SERVICE_URL: " + service_url); <ide> <del> //System.out.println("EVS_SERVICE_URL: " + service_url); <add> lg_config_file = NCItBrowserProperties.getProperty(NCItBrowserProperties.LG_CONFIG_FILE); <add> //System.out.println("LG_CONFIG_FILE: " + lg_config_file); <ide> <ide> sort_by_score = NCItBrowserProperties.getProperty(NCItBrowserProperties.SORT_BY_SCORE); <ide> ncicb_contact_url = NCItBrowserProperties.getProperty(NCItBrowserProperties.NCICB_CONTACT_URL); <ide> mail_smtp_server = NCItBrowserProperties.getProperty(NCItBrowserProperties.MAIL_SMTP_SERVER); <ide> terminology_subset_download_url = NCItBrowserProperties.getProperty(NCItBrowserProperties.TERMINOLOGY_SUBSET_DOWNLOAD_URL); <ide> } <add> <ide> } <ide> } <ide>
Java
apache-2.0
77fd02428287583a2a2c1e539c822c102ac35fc1
0
farmerbb/SecondScreen
/* Copyright 2015 Braden Farmer * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.farmerbb.secondscreen.fragment; import android.annotation.TargetApi; import android.app.Activity; import android.app.Fragment; import android.app.FragmentTransaction; import android.content.SharedPreferences; import android.graphics.Color; import android.graphics.PorterDuff; import android.os.Build; import android.os.Bundle; import android.os.Handler; import android.support.v4.content.ContextCompat; import android.support.v7.app.AppCompatActivity; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.LinearLayout; import android.widget.TextView; import com.farmerbb.secondscreen.R; import com.farmerbb.secondscreen.util.U; import java.io.File; // Fragment launched as part of MainActivity that shows a brief summary of a profile selected from // ProfileListActivity. It also contains a button that will either: launch the ProfileLoadService // if the profile is inactive, or launch the TurnOffService if the profile is active. public final class ProfileViewFragment extends Fragment { String filename = ""; String left; String right; int n; /* The activity that creates an instance of this fragment must * implement this interface in order to receive event call backs. */ public interface Listener { void showDeleteDialog(); void onLoadProfileButtonClick(String filename); void onTurnOffProfileButtonClick(); String generateBlurb(String key, String value); } // Use this instance of the interface to deliver action events Listener listener; // Override the Fragment.onAttach() method to instantiate the Listener @SuppressWarnings("deprecation") @Override public void onAttach(Activity activity) { super.onAttach(activity); // Verify that the host activity implements the callback interface try { // Instantiate the Listener so we can send events to the host listener = (Listener) activity; } catch (ClassCastException e) { // The activity doesn't implement the interface, throw exception throw new ClassCastException(activity.toString() + " must implement Listener"); } } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return inflater.inflate(R.layout.fragment_profile_view, container, false); } @TargetApi(Build.VERSION_CODES.LOLLIPOP) @SuppressWarnings("deprecation") @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); new Handler().post(this::showUI); } private void showUI() { // Set values setRetainInstance(true); setHasOptionsMenu(true); // Change window title if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) getActivity().setTitle(getArguments().getString("title")); else getActivity().setTitle(" " + getArguments().getString("title")); // Show the Up button in the action bar. ((AppCompatActivity) getActivity()).getSupportActionBar().setDisplayHomeAsUpEnabled(true); // Animate elevation change if(getActivity().findViewById(R.id.layoutMain).getTag().equals("main-layout-large") && Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { LinearLayout profileViewEdit = getActivity().findViewById(R.id.profileViewEdit); LinearLayout profileList = getActivity().findViewById(R.id.profileList); profileList.animate().z(0f); profileViewEdit.animate().z(getResources().getDimensionPixelSize(R.dimen.profile_view_edit_elevation)); } // Get filename of saved note filename = getArguments().getString("filename"); SharedPreferences prefSaved = U.getPrefSaved(getActivity(), filename); SharedPreferences prefCurrent = U.getPrefCurrent(getActivity()); Button button = getActivity().findViewById(R.id.pvButton); TextView resolution = getActivity().findViewById(R.id.pvResolution); TextView density = getActivity().findViewById(R.id.pvDensity); TextView profileSettingsLeft = getActivity().findViewById(R.id.pvProfileSettingsLeft); TextView profileSettingsRight = getActivity().findViewById(R.id.pvProfileSettingsRight); // Change color and/or background of the Load/Turn Off button if(Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) button.setBackground(getResources().getDrawable(R.drawable.pl_button)); else button.getBackground().setColorFilter(ContextCompat.getColor(getActivity(), R.color.pl_selected), PorterDuff.Mode.SRC); // Set listeners for Load/Turn Off button if("quick_actions".equals(prefCurrent.getString("filename", "0"))) { SharedPreferences prefQuick = U.getPrefQuickActions(getActivity()); if(filename.equals(prefQuick.getString("original_filename", "0"))) { button.setText(getResources().getString(R.string.action_turn_off_alt, getArguments().getString("title"))); button.setOnClickListener(view -> listener.onTurnOffProfileButtonClick()); } else { button.setText(getResources().getString(R.string.action_load, getArguments().getString("title"))); button.setOnClickListener(view -> listener.onLoadProfileButtonClick(filename)); } } else if(filename.equals(prefCurrent.getString("filename", "0"))) { button.setText(getResources().getString(R.string.action_turn_off_alt, getArguments().getString("title"))); button.setOnClickListener(view -> listener.onTurnOffProfileButtonClick()); } else { button.setText(getResources().getString(R.string.action_load, getArguments().getString("title"))); button.setOnClickListener(view -> listener.onLoadProfileButtonClick(filename)); } // Generate a brief overview of this profile's settings to display within the fragment // NOTE: these statements must remain in order resolution.setText(listener.generateBlurb("size", prefSaved.getString("size", "reset"))); density.setText(listener.generateBlurb("density", prefSaved.getString("density", "reset"))); left = ""; right = ""; n = 0; generateProfileSettings(prefSaved.getBoolean("bluetooth_on", false), R.string.profile_view_bluetooth_on); generateProfileSettings(prefSaved.getBoolean("chrome", false), R.string.quick_chrome); generateProfileSettings(prefSaved.getBoolean("clear_home", false), R.string.quick_clear_home); if(Build.VERSION.SDK_INT < Build.VERSION_CODES.N) generateProfileSettings(prefSaved.getBoolean("daydreams_on", false), R.string.profile_view_daydreams_on); generateProfileSettings(prefSaved.getBoolean("navbar", false), R.string.profile_view_navbar); generateProfileSettings(prefSaved.getBoolean("freeform", false), R.string.profile_view_freeform); switch(prefSaved.getString("hdmi_rotation", "landscape")) { case "portrait": generateProfileSettings(true, R.string.profile_view_hdmi_output); break; } generateProfileSettings(prefSaved.getBoolean("overscan", false), R.string.quick_overscan); switch(prefSaved.getString("rotation_lock_new", "fallback")) { case "fallback": if(prefSaved.getBoolean("rotation_lock", false)) generateProfileSettings(true, R.string.profile_view_rotation_landscape); break; case "landscape": generateProfileSettings(true, R.string.profile_view_rotation_landscape); break; case "auto-rotate": generateProfileSettings(true, R.string.profile_view_rotation_autorotate); break; case "portrait": generateProfileSettings(true, R.string.profile_view_rotation_portrait); break; } generateProfileSettings(prefSaved.getBoolean("backlight_off", false), R.string.pref_title_backlight_off); generateProfileSettings(prefSaved.getBoolean("vibration_off", false), R.string.pref_title_vibration_off); if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) generateProfileSettings(prefSaved.getBoolean("daydreams_on", false), R.string.profile_view_daydreams_on); generateProfileSettings(prefSaved.getBoolean("show_touches", false), R.string.pref_title_show_touches); switch(prefSaved.getString("immersive_new", "fallback")) { case "fallback": if(prefSaved.getBoolean("immersive", false)) generateProfileSettings(true, R.string.pref_title_immersive); break; case "status-only": generateProfileSettings(true, R.string.pref_title_immersive); break; case "immersive-mode": generateProfileSettings(true, R.string.pref_title_immersive); break; } generateProfileSettings(prefSaved.getBoolean("taskbar", false), R.string.quick_taskbar); switch(prefSaved.getString("screen_timeout", "do-nothing")) { case "always-on": generateProfileSettings(true, R.string.profile_view_screen_timeout_always_on); break; case "always-on-charging": generateProfileSettings(true, R.string.profile_view_screen_timeout_always_on_charging); break; } switch(prefSaved.getString("ui_refresh", "do-nothing")) { case "system-ui": if(getActivity().getPackageManager().hasSystemFeature("com.cyanogenmod.android") && Build.VERSION.SDK_INT == Build.VERSION_CODES.LOLLIPOP_MR1) generateProfileSettings(true, R.string.profile_view_ui_refresh_soft_reboot); else if(U.isInNonRootMode(getActivity())) generateProfileSettings(true, R.string.profile_view_ui_refresh_systemui_alt); else generateProfileSettings(true, R.string.profile_view_ui_refresh_systemui); break; case "activity-manager": if(U.isInNonRootMode(getActivity())) generateProfileSettings(true, R.string.profile_view_ui_refresh_soft_reboot_alt); else generateProfileSettings(true, R.string.profile_view_ui_refresh_soft_reboot); break; } generateProfileSettings(prefSaved.getBoolean("wifi_on", false), R.string.profile_view_wifi_on); if(!left.isEmpty()) profileSettingsLeft.setText(left); if(!right.isEmpty()) profileSettingsRight.setText(right); if(n == 0) { TextView header = getActivity().findViewById(R.id.pvHeaderProfileSettings); header.setText(" "); header.setBackgroundColor(Color.WHITE); } } @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { inflater.inflate(R.menu.profile_view, menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: // Override default Android "up" behavior to instead mimic the back button onBackPressed(); return true; // Edit button case R.id.action_edit: Bundle bundle = new Bundle(); bundle.putString("filename", filename); Fragment fragment = new ProfileEditFragment(); fragment.setArguments(bundle); getFragmentManager() .beginTransaction() .replace(R.id.profileViewEdit, fragment, "ProfileEditFragment") .setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE) .commit(); return true; // Delete button case R.id.action_delete_2: // Show toast if this is the currently active profile SharedPreferences prefCurrent = U.getPrefCurrent(getActivity()); if("quick_actions".equals(prefCurrent.getString("filename", "0"))) { SharedPreferences prefSaved = U.getPrefQuickActions(getActivity()); if(filename.equals(prefSaved.getString("original_filename", "0"))) U.showToast(getActivity(), R.string.deleting_current_profile); else listener.showDeleteDialog(); } else if(filename.equals(prefCurrent.getString("filename", "0"))) U.showToast(getActivity(), R.string.deleting_current_profile); else listener.showDeleteDialog(); return true; default: return super.onOptionsItemSelected(item); } } public void deleteProfile() { // Build the pathname to delete file, then perform delete operation File fileToDelete = new File(getActivity().getFilesDir() + File.separator + filename); fileToDelete.delete(); File xmlFileToDelete = new File(getActivity().getFilesDir().getParent() + File.separator + "shared_prefs" + File.separator + filename + ".xml"); xmlFileToDelete.delete(); U.showToast(getActivity(), R.string.profile_deleted); // Cleanup SharedPreferences prefNew = U.getPrefNew(getActivity()); SharedPreferences.Editor prefNewEditor = prefNew.edit(); prefNewEditor.clear(); prefNewEditor.apply(); // Refresh list of profiles U.listProfilesBroadcast(getActivity()); onBackPressed(); } public void onBackPressed() { // Add ProfileListFragment or WelcomeFragment Fragment fragment; if(getActivity().findViewById(R.id.layoutMain).getTag().equals("main-layout-normal")) fragment = new ProfileListFragment(); else { SharedPreferences prefMain = U.getPrefMain(getActivity()); Bundle bundle = new Bundle(); bundle.putBoolean("show-welcome-message", prefMain.getBoolean("show-welcome-message", false)); fragment = new WelcomeFragment(); fragment.setArguments(bundle); } getFragmentManager() .beginTransaction() .replace(R.id.profileViewEdit, fragment, "ProfileListFragment") .setTransition(FragmentTransaction.TRANSIT_FRAGMENT_CLOSE) .commit(); } public String getFilename() { return getArguments().getString("filename"); } private void generateProfileSettings(boolean optionIsSet, int text) { if(optionIsSet) { n++; if(n % 2 == 0) right = right + getResources().getString(R.string.bullet) + " " + getResources().getString(text) + "\n"; else left = left + getResources().getString(R.string.bullet) + " " + getResources().getString(text) + "\n"; } } }
app/src/main/java/com/farmerbb/secondscreen/fragment/ProfileViewFragment.java
/* Copyright 2015 Braden Farmer * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.farmerbb.secondscreen.fragment; import android.annotation.TargetApi; import android.app.Activity; import android.app.Fragment; import android.app.FragmentTransaction; import android.content.SharedPreferences; import android.graphics.Color; import android.graphics.PorterDuff; import android.os.Build; import android.os.Bundle; import android.support.v4.content.ContextCompat; import android.support.v7.app.AppCompatActivity; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.LinearLayout; import android.widget.TextView; import com.farmerbb.secondscreen.R; import com.farmerbb.secondscreen.util.U; import java.io.File; // Fragment launched as part of MainActivity that shows a brief summary of a profile selected from // ProfileListActivity. It also contains a button that will either: launch the ProfileLoadService // if the profile is inactive, or launch the TurnOffService if the profile is active. public final class ProfileViewFragment extends Fragment { String filename = ""; String left; String right; int n; /* The activity that creates an instance of this fragment must * implement this interface in order to receive event call backs. */ public interface Listener { void showDeleteDialog(); void onLoadProfileButtonClick(String filename); void onTurnOffProfileButtonClick(); String generateBlurb(String key, String value); } // Use this instance of the interface to deliver action events Listener listener; // Override the Fragment.onAttach() method to instantiate the Listener @SuppressWarnings("deprecation") @Override public void onAttach(Activity activity) { super.onAttach(activity); // Verify that the host activity implements the callback interface try { // Instantiate the Listener so we can send events to the host listener = (Listener) activity; } catch (ClassCastException e) { // The activity doesn't implement the interface, throw exception throw new ClassCastException(activity.toString() + " must implement Listener"); } } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return inflater.inflate(R.layout.fragment_profile_view, container, false); } @TargetApi(Build.VERSION_CODES.LOLLIPOP) @SuppressWarnings("deprecation") @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); // Set values setRetainInstance(true); setHasOptionsMenu(true); // Change window title if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) getActivity().setTitle(getArguments().getString("title")); else getActivity().setTitle(" " + getArguments().getString("title")); // Show the Up button in the action bar. ((AppCompatActivity) getActivity()).getSupportActionBar().setDisplayHomeAsUpEnabled(true); // Animate elevation change if(getActivity().findViewById(R.id.layoutMain).getTag().equals("main-layout-large") && Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { LinearLayout profileViewEdit = getActivity().findViewById(R.id.profileViewEdit); LinearLayout profileList = getActivity().findViewById(R.id.profileList); profileList.animate().z(0f); profileViewEdit.animate().z(getResources().getDimensionPixelSize(R.dimen.profile_view_edit_elevation)); } // Get filename of saved note filename = getArguments().getString("filename"); SharedPreferences prefSaved = U.getPrefSaved(getActivity(), filename); SharedPreferences prefCurrent = U.getPrefCurrent(getActivity()); Button button = getActivity().findViewById(R.id.pvButton); TextView resolution = getActivity().findViewById(R.id.pvResolution); TextView density = getActivity().findViewById(R.id.pvDensity); TextView profileSettingsLeft = getActivity().findViewById(R.id.pvProfileSettingsLeft); TextView profileSettingsRight = getActivity().findViewById(R.id.pvProfileSettingsRight); // Change color and/or background of the Load/Turn Off button if(Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) button.setBackground(getResources().getDrawable(R.drawable.pl_button)); else button.getBackground().setColorFilter(ContextCompat.getColor(getActivity(), R.color.pl_selected), PorterDuff.Mode.SRC); // Set listeners for Load/Turn Off button if("quick_actions".equals(prefCurrent.getString("filename", "0"))) { SharedPreferences prefQuick = U.getPrefQuickActions(getActivity()); if(filename.equals(prefQuick.getString("original_filename", "0"))) { button.setText(getResources().getString(R.string.action_turn_off_alt, getArguments().getString("title"))); button.setOnClickListener(view -> listener.onTurnOffProfileButtonClick()); } else { button.setText(getResources().getString(R.string.action_load, getArguments().getString("title"))); button.setOnClickListener(view -> listener.onLoadProfileButtonClick(filename)); } } else if(filename.equals(prefCurrent.getString("filename", "0"))) { button.setText(getResources().getString(R.string.action_turn_off_alt, getArguments().getString("title"))); button.setOnClickListener(view -> listener.onTurnOffProfileButtonClick()); } else { button.setText(getResources().getString(R.string.action_load, getArguments().getString("title"))); button.setOnClickListener(view -> listener.onLoadProfileButtonClick(filename)); } // Generate a brief overview of this profile's settings to display within the fragment // NOTE: these statements must remain in order resolution.setText(listener.generateBlurb("size", prefSaved.getString("size", "reset"))); density.setText(listener.generateBlurb("density", prefSaved.getString("density", "reset"))); left = ""; right = ""; n = 0; generateProfileSettings(prefSaved.getBoolean("bluetooth_on", false), R.string.profile_view_bluetooth_on); generateProfileSettings(prefSaved.getBoolean("chrome", false), R.string.quick_chrome); generateProfileSettings(prefSaved.getBoolean("clear_home", false), R.string.quick_clear_home); if(Build.VERSION.SDK_INT < Build.VERSION_CODES.N) generateProfileSettings(prefSaved.getBoolean("daydreams_on", false), R.string.profile_view_daydreams_on); generateProfileSettings(prefSaved.getBoolean("navbar", false), R.string.profile_view_navbar); generateProfileSettings(prefSaved.getBoolean("freeform", false), R.string.profile_view_freeform); switch(prefSaved.getString("hdmi_rotation", "landscape")) { case "portrait": generateProfileSettings(true, R.string.profile_view_hdmi_output); break; } generateProfileSettings(prefSaved.getBoolean("overscan", false), R.string.quick_overscan); switch(prefSaved.getString("rotation_lock_new", "fallback")) { case "fallback": if(prefSaved.getBoolean("rotation_lock", false)) generateProfileSettings(true, R.string.profile_view_rotation_landscape); break; case "landscape": generateProfileSettings(true, R.string.profile_view_rotation_landscape); break; case "auto-rotate": generateProfileSettings(true, R.string.profile_view_rotation_autorotate); break; case "portrait": generateProfileSettings(true, R.string.profile_view_rotation_portrait); break; } generateProfileSettings(prefSaved.getBoolean("backlight_off", false), R.string.pref_title_backlight_off); generateProfileSettings(prefSaved.getBoolean("vibration_off", false), R.string.pref_title_vibration_off); if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) generateProfileSettings(prefSaved.getBoolean("daydreams_on", false), R.string.profile_view_daydreams_on); generateProfileSettings(prefSaved.getBoolean("show_touches", false), R.string.pref_title_show_touches); switch(prefSaved.getString("immersive_new", "fallback")) { case "fallback": if(prefSaved.getBoolean("immersive", false)) generateProfileSettings(true, R.string.pref_title_immersive); break; case "status-only": generateProfileSettings(true, R.string.pref_title_immersive); break; case "immersive-mode": generateProfileSettings(true, R.string.pref_title_immersive); break; } generateProfileSettings(prefSaved.getBoolean("taskbar", false), R.string.quick_taskbar); switch(prefSaved.getString("screen_timeout", "do-nothing")) { case "always-on": generateProfileSettings(true, R.string.profile_view_screen_timeout_always_on); break; case "always-on-charging": generateProfileSettings(true, R.string.profile_view_screen_timeout_always_on_charging); break; } switch(prefSaved.getString("ui_refresh", "do-nothing")) { case "system-ui": if(getActivity().getPackageManager().hasSystemFeature("com.cyanogenmod.android") && Build.VERSION.SDK_INT == Build.VERSION_CODES.LOLLIPOP_MR1) generateProfileSettings(true, R.string.profile_view_ui_refresh_soft_reboot); else if(U.isInNonRootMode(getActivity())) generateProfileSettings(true, R.string.profile_view_ui_refresh_systemui_alt); else generateProfileSettings(true, R.string.profile_view_ui_refresh_systemui); break; case "activity-manager": if(U.isInNonRootMode(getActivity())) generateProfileSettings(true, R.string.profile_view_ui_refresh_soft_reboot_alt); else generateProfileSettings(true, R.string.profile_view_ui_refresh_soft_reboot); break; } generateProfileSettings(prefSaved.getBoolean("wifi_on", false), R.string.profile_view_wifi_on); if(!left.isEmpty()) profileSettingsLeft.setText(left); if(!right.isEmpty()) profileSettingsRight.setText(right); if(n == 0) { TextView header = getActivity().findViewById(R.id.pvHeaderProfileSettings); header.setText(" "); header.setBackgroundColor(Color.WHITE); } } @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { inflater.inflate(R.menu.profile_view, menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: // Override default Android "up" behavior to instead mimic the back button onBackPressed(); return true; // Edit button case R.id.action_edit: Bundle bundle = new Bundle(); bundle.putString("filename", filename); Fragment fragment = new ProfileEditFragment(); fragment.setArguments(bundle); getFragmentManager() .beginTransaction() .replace(R.id.profileViewEdit, fragment, "ProfileEditFragment") .setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE) .commit(); return true; // Delete button case R.id.action_delete_2: // Show toast if this is the currently active profile SharedPreferences prefCurrent = U.getPrefCurrent(getActivity()); if("quick_actions".equals(prefCurrent.getString("filename", "0"))) { SharedPreferences prefSaved = U.getPrefQuickActions(getActivity()); if(filename.equals(prefSaved.getString("original_filename", "0"))) U.showToast(getActivity(), R.string.deleting_current_profile); else listener.showDeleteDialog(); } else if(filename.equals(prefCurrent.getString("filename", "0"))) U.showToast(getActivity(), R.string.deleting_current_profile); else listener.showDeleteDialog(); return true; default: return super.onOptionsItemSelected(item); } } public void deleteProfile() { // Build the pathname to delete file, then perform delete operation File fileToDelete = new File(getActivity().getFilesDir() + File.separator + filename); fileToDelete.delete(); File xmlFileToDelete = new File(getActivity().getFilesDir().getParent() + File.separator + "shared_prefs" + File.separator + filename + ".xml"); xmlFileToDelete.delete(); U.showToast(getActivity(), R.string.profile_deleted); // Cleanup SharedPreferences prefNew = U.getPrefNew(getActivity()); SharedPreferences.Editor prefNewEditor = prefNew.edit(); prefNewEditor.clear(); prefNewEditor.apply(); // Refresh list of profiles U.listProfilesBroadcast(getActivity()); onBackPressed(); } public void onBackPressed() { // Add ProfileListFragment or WelcomeFragment Fragment fragment; if(getActivity().findViewById(R.id.layoutMain).getTag().equals("main-layout-normal")) fragment = new ProfileListFragment(); else { SharedPreferences prefMain = U.getPrefMain(getActivity()); Bundle bundle = new Bundle(); bundle.putBoolean("show-welcome-message", prefMain.getBoolean("show-welcome-message", false)); fragment = new WelcomeFragment(); fragment.setArguments(bundle); } getFragmentManager() .beginTransaction() .replace(R.id.profileViewEdit, fragment, "ProfileListFragment") .setTransition(FragmentTransaction.TRANSIT_FRAGMENT_CLOSE) .commit(); } public String getFilename() { return getArguments().getString("filename"); } private void generateProfileSettings(boolean optionIsSet, int text) { if(optionIsSet) { n++; if(n % 2 == 0) right = right + getResources().getString(R.string.bullet) + " " + getResources().getString(text) + "\n"; else left = left + getResources().getString(R.string.bullet) + " " + getResources().getString(text) + "\n"; } } }
Fix ProfileViewFragment not rendering correctly when switching between profiles in master-detail mode
app/src/main/java/com/farmerbb/secondscreen/fragment/ProfileViewFragment.java
Fix ProfileViewFragment not rendering correctly when switching between profiles in master-detail mode
<ide><path>pp/src/main/java/com/farmerbb/secondscreen/fragment/ProfileViewFragment.java <ide> import android.graphics.PorterDuff; <ide> import android.os.Build; <ide> import android.os.Bundle; <add>import android.os.Handler; <ide> import android.support.v4.content.ContextCompat; <ide> import android.support.v7.app.AppCompatActivity; <ide> import android.view.LayoutInflater; <ide> public void onActivityCreated(Bundle savedInstanceState) { <ide> super.onActivityCreated(savedInstanceState); <ide> <add> new Handler().post(this::showUI); <add> } <add> <add> private void showUI() { <ide> // Set values <ide> setRetainInstance(true); <ide> setHasOptionsMenu(true);
Java
apache-2.0
18a668672143850ae0c6c79fc501ab935966b42e
0
QualiMaster/Infrastructure,QualiMaster/Infrastructure
/* * Copyright 2009-2015 University of Hildesheim, Software Systems Engineering * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package eu.qualimaster.monitoring.events; import java.io.File; import java.io.FileInputStream; import java.io.FileWriter; import java.io.IOException; import java.io.Serializable; import java.util.HashMap; import java.util.Map; import java.util.Properties; import eu.qualimaster.common.QMGenerics; import eu.qualimaster.common.QMInternal; import eu.qualimaster.common.QMSupport; import eu.qualimaster.file.Utils; import eu.qualimaster.observables.IObservable; import eu.qualimaster.observables.ResourceUsage; /** * Represents a frozen system state for monitoring. * * @author Holger Eichelberger */ @QMSupport public class FrozenSystemState implements Serializable { // set to IVML type names?? public static final String INFRASTRUCTURE = "Infrastructure"; // no name public static final String INFRASTRUCTURE_NAME = ""; public static final String MACHINE = "Machine"; public static final String HWNODE = "HwNode"; public static final String CLOUDENV = "Cloud"; public static final String ALGORITHM = "Algorithm"; public static final String DATASOURCE = "DataSource"; public static final String DATASINK = "DataSink"; public static final String PIPELINE = "Pipeline"; public static final String PIPELINE_ELEMENT = "PipelineElement"; public static final String ACTUAL = "Actual"; @QMInternal public static final String SEPARATOR = ":"; private static final long serialVersionUID = 4880902220348531183L; private Map<String, Double> values; /** * Creates a frozen systems state instance. */ public FrozenSystemState() { values = new HashMap<String, Double>(); } /** * Creates a frozen systems state instance from a map of values. This allows rt-VIL * to use this class as a wrapper. * * @param values the values to be wrapped */ public FrozenSystemState( @QMGenerics(types = {String.class, Double.class }) Map<String, Double> values) { this.values = null == values ? new HashMap<String, Double>() : values; } /** * Loads a system state from a properties file. * * @param file the file to load from * @throws IOException in case of I/O exceptions */ @QMInternal public FrozenSystemState(File file) throws IOException { this.values = new HashMap<String, Double>(); Properties prop = new Properties(); FileInputStream in = new FileInputStream(file); prop.load(in); in.close(); for (Map.Entry<Object, Object> entry : prop.entrySet()) { try { String key = entry.getKey().toString(); Double value = Double.valueOf(entry.getValue().toString()); values.put(key, value); } catch (NumberFormatException e) { // ignore } } } /** * Returns the access key. * * @param prefix the prefix denoting the type * @param name the name of the individual element * @param observable the observable * @return the observed value or <b>null</b> if nothing was observed (so far) */ public static String obtainKey(String prefix, String name, IObservable observable) { return prefix + SEPARATOR + name + SEPARATOR + (null == observable ? null : observable.name()); } /** * Returns the name sub-key for a pipeline element. * * @param pipeline the pipeline name * @param element the element name * @return the observed value or <b>null</b> if nothing was observed (so far) */ @QMInternal public static String obtainPipelineElementSubkey(String pipeline, String element) { return pipeline + SEPARATOR + element; } /** * Defines the value for an observation. * * @param prefix the prefix denoting the type * @param name the name of the individual element * @param observable the observable * @param value the actual value (may be <b>null</b>) */ @QMInternal public void setObservation(String prefix, String name, IObservable observable, Double value) { values.put(obtainKey(prefix, name, observable), value); } /** * Defines the value of an observation for a pipeline element. * * @param prefix the prefix denoting the type * @param pipeline the pipeline name * @param element the element name * @param observable the observable * @param value the actual value (may be <b>null</b>) */ @QMInternal public void setObservation(String prefix, String pipeline, String element, IObservable observable, Double value) { values.put(obtainKey(prefix, obtainPipelineElementSubkey(pipeline, element), observable), value); } /** * Sets whether an algorithm is considered to be active in a pipeline at the moment of freezing. * * @param pipeline the name of the pipeline * @param nodeName the name of the node * @param algorithmName the name of the algorithm */ @QMInternal public void setActiveAlgorithm(String pipeline, String nodeName, String algorithmName) { // difficult: it would be nice to transfer the index of the algorithm from active, but if models diverge // decision: transport the name as last pseudo segment and separate during mapping // AVAILABLE and value are irrelevant values.put(composeActiveAlgorithmKey(pipeline, nodeName, algorithmName), 1.0); } /** * Composes the active algorithm key for {@code pipeline}/{@code nodeName} and {@code algorithmName} as active * algorithm. * * @param pipeline the pipeline name * @param nodeName the node name * @param algorithmName the algorithmname * @return the composed key */ private static String composeActiveAlgorithmKey(String pipeline, String nodeName, String algorithmName) { return obtainKey(ACTUAL, obtainPipelineElementSubkey(pipeline, obtainPipelineElementSubkey(nodeName, algorithmName)), ResourceUsage.AVAILABLE); } /** * Returns whether this frozen state contains {@code algorithmName} as active algorithm for * {@code pipeline}/{@code nodeName}. * * @param pipeline the pipeline name * @param nodeName the node name * @param algorithmName the algorithm name * @return {@code true} if the given algorithm is set as active on the given pipeline/node, {@code false} else */ public boolean hasActiveAlgorithm(String pipeline, String nodeName, String algorithmName) { return values.containsKey(composeActiveAlgorithmKey(pipeline, nodeName, algorithmName)); } /** * Returns the active algorithm for {@code pipeline}/{@code nodeName}. * * @param pipeline the pipeline name * @param nodeName the node name * @return the active algorithm name, <b>null</b> if none is known */ public String getActiveAlgorithm(String pipeline, String nodeName) { // not really efficient, intended for testing... String result = null; String prefix = ACTUAL + SEPARATOR + obtainPipelineElementSubkey(pipeline, nodeName) + SEPARATOR; String postfix = SEPARATOR + ResourceUsage.AVAILABLE; for (String k : values.keySet()) { if (k.startsWith(prefix) && k.endsWith(postfix)) { result = k.substring(prefix.length() + 1, k.length() - postfix.length()); break; } } return result; } /** * Returns an observation. * * @param prefix the prefix denoting the type * @param name the name of the individual element * @param observable the observable * @param dflt the default value to return if nothing was observed (so far) * @return the observed value or <code>dflt</code> if nothing was observed (so far) */ @QMInternal public Double getObservation(String prefix, String name, IObservable observable, Double dflt) { return getObservation(obtainKey(prefix, name, observable), dflt); } /** * Returns an observation. * * @param key the access key (see {@link #obtainKey(String, String, IObservable)}. * @param dflt the default value to return if nothing was observed (so far) * @return the observed value or <code>dflt</code> if nothing was observed (so far) */ @QMInternal public Double getObservation(String key, Double dflt) { Double result = values.get(key); if (null == result) { result = dflt; } return result; } /** * Returns an observation for the infrastructure. * * @param observable the observable * @return the observed value or <b>null</b> if nothing was observed (so far) */ public Double getInfrastructureObservation(IObservable observable) { return getInfrastructureObservation(observable, null); } /** * Returns an observation for the infrastructure. * * @param observable the observable * @param dflt the default value to return if nothing was observed (so far) * @return the observed value or <code>dflt</code> if nothing was observed (so far) */ public Double getInfrastructureObservation(IObservable observable, Double dflt) { return getObservation(INFRASTRUCTURE, INFRASTRUCTURE_NAME, observable, dflt); } /** * Returns an observation for a cloud environment. * @param name the name of the cloud environment * @param observable the observable * @return the observed value or <code>dflt</code> if nothing was observed (so far) */ public Double getCloudObservation(String name, IObservable observable) { return getCloudObservation(name, observable, null); } /** * Returns an observation for a cloud environment. * @param name the name of the cloud environment * @param observable the observable * @param dflt the default value to return if nothing was observed (so far) * @return the observed value or <code>dflt</code> if nothing was observed (so far) */ public Double getCloudObservation(String name, IObservable observable, Double dflt) { return getObservation(CLOUDENV, name, observable, dflt); } /** * Returns an observation for a machine. * * @param name the name of the machine * @param observable the observable * @return the observed value or <b>null</b> if nothing was observed (so far) */ public Double getMachineObservation(String name, IObservable observable) { return getMachineObservation(name, observable, null); } /** * Returns an observation for a machine. * * @param name the name of the machine * @param observable the observable * @param dflt the default value to return if nothing was observed (so far) * @return the observed value or <code>dflt</code> if nothing was observed (so far) */ public Double getMachineObservation(String name, IObservable observable, Double dflt) { return getObservation(MACHINE, name, observable, dflt); } /** * Returns an observation for a hardware node. * * @param name the name of the hardware node * @param observable the observable * @return the observed value or <b>null</b> if nothing was observed (so far) */ public Double getHwNodeObservation(String name, IObservable observable) { return getHwNodeObservation(name, observable, null); } /** * Returns an observation for a hardware node. * * @param name the name of the hardware node * @param observable the observable * @param dflt the default value to return if nothing was observed (so far) * @return the observed value or <code>dflt</code> if nothing was observed (so far) */ public Double getHwNodeObservation(String name, IObservable observable, Double dflt) { return getObservation(HWNODE, name, observable, dflt); } /** * Returns an observation for a data source used in a pipeline. * * @param pipeline the name of the pipeline * @param name the name of the data source * @param observable the observable * @return the observed value or <b>null</b> if nothing was observed (so far) */ public Double getDataSourceObservation(String pipeline, String name, IObservable observable) { return getDataSourceObservation(pipeline, name, observable, null); } /** * Returns an observation for a data source used in a pipeline. * * @param pipeline the name of the pipeline * @param name the name of the data source * @param observable the observable * @param dflt the default value to return if nothing was observed (so far) * @return the observed value or <code>dflt</code> if nothing was observed (so far) */ public Double getDataSourceObservation(String pipeline, String name, IObservable observable, Double dflt) { return getObservation(DATASOURCE, obtainPipelineElementSubkey(pipeline, name), observable, dflt); } /** * Returns an observation for a data sink used in a pipeline. * * @param pipeline the name of the pipeline * @param name the name of the data sink * @param observable the observable * @return the observed value or <b>null</b> if nothing was observed (so far) */ public Double getDataSinkObservation(String pipeline, String name, IObservable observable) { return getDataSinkObservation(pipeline, name, observable, null); } /** * Returns an observation for a data sink used in a pipeline. * * @param pipeline the name of the pipeline * @param name the name of the data sink * @param observable the observable * @param dflt the default value to return if nothing was observed (so far) * @return the observed value or <code>dflt</code> if nothing was observed (so far) */ public Double getDataSinkObservation(String pipeline, String name, IObservable observable, Double dflt) { return getObservation(DATASINK, obtainPipelineElementSubkey(pipeline, name), observable, dflt); } /** * Returns an observation for a pipeline. * * @param name the name of the pipeline * @param observable the observable * @return the observed value or <b>null</b> if nothing was observed (so far) */ public Double getPipelineObservation(String name, IObservable observable) { return getPipelineObservation(name, observable, null); } /** * Returns an observation for a pipeline. * * @param name the name of the pipeline * @param observable the observable * @param dflt the default value to return if nothing was observed (so far) * @return the observed value or <code>dflt</code> if nothing was observed (so far) */ public Double getPipelineObservation(String name, IObservable observable, Double dflt) { return getObservation(PIPELINE, name, observable, dflt); } /** * Returns an observation for a pipeline source. * * @param pipeline the name of the pipeline * @param element the name of the element * @param observable the observable * @return the observed value or <b>null</b> if nothing was observed (so far) */ public Double getPipelineElementObservation(String pipeline, String element, IObservable observable) { return getPipelineElementObservation(pipeline, element, observable, null); } /** * Returns an observation for a pipeline source. * * @param pipeline the name of the pipeline * @param element the name of the element * @param observable the observable * @param dflt the default value to return if nothing was observed (so far) * @return the observed value or <code>dflt</code> if nothing was observed (so far) */ public Double getPipelineElementObservation(String pipeline, String element, IObservable observable, Double dflt) { return getObservation(PIPELINE_ELEMENT, obtainPipelineElementSubkey(pipeline, element), observable, dflt); } /** * Returns an observation for an algorithm used in a pipeline. * * @param pipeline the name of the pipeline * @param algorithm the name of the algorithm * @param observable the observable * @return the observed value or <b>null</b> if nothing was observed (so far) */ public Double getAlgorithmObservation(String pipeline, String algorithm, IObservable observable) { return getAlgorithmObservation(pipeline, algorithm, observable, null); } /** * Returns an observation for an algorithm used in a pipeline. * * @param pipeline the name of the pipeline * @param algorithm the name of the algorithm * @param observable the observable * @param dflt the default value to return if nothing was observed (so far) * @return the observed value or <code>dflt</code> if nothing was observed (so far) */ public Double getAlgorithmObservation(String pipeline, String algorithm, IObservable observable, Double dflt) { return getObservation(ALGORITHM, obtainPipelineElementSubkey(pipeline, algorithm), observable, dflt); } /** * Returns the mapping. * * @return the mapping */ @QMInternal public Map<String, Double> getMapping() { return values; } /** * Converts the frozen system state into properties. * * @return the related properties */ @QMInternal public Properties toProperties() { Properties prop = new Properties(); for (Map.Entry<String, Double> entry : values.entrySet()) { String key = entry.getKey(); Double value = entry.getValue(); if (null != key && null != value) { prop.put(key, value.toString()); } } return prop; } /** * Stores the system state in a file. * * @param file the file * @throws IOException in case of I/O problems */ @QMInternal public void store(File file) throws IOException { Properties prop = toProperties(); FileWriter out = Utils.createFileWriter(file); prop.store(out, ""); out.close(); } @QMInternal @Override public String toString() { return values.toString(); } }
QualiMaster.Events/src/eu/qualimaster/monitoring/events/FrozenSystemState.java
/* * Copyright 2009-2015 University of Hildesheim, Software Systems Engineering * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package eu.qualimaster.monitoring.events; import java.io.File; import java.io.FileInputStream; import java.io.FileWriter; import java.io.IOException; import java.io.Serializable; import java.util.HashMap; import java.util.Map; import java.util.Properties; import eu.qualimaster.common.QMGenerics; import eu.qualimaster.common.QMInternal; import eu.qualimaster.common.QMSupport; import eu.qualimaster.file.Utils; import eu.qualimaster.observables.IObservable; import eu.qualimaster.observables.ResourceUsage; /** * Represents a frozen system state for monitoring. * * @author Holger Eichelberger */ @QMSupport public class FrozenSystemState implements Serializable { // set to IVML type names?? public static final String INFRASTRUCTURE = "Infrastructure"; // no name public static final String INFRASTRUCTURE_NAME = ""; public static final String MACHINE = "Machine"; public static final String HWNODE = "HwNode"; public static final String CLOUDENV = "Cloud"; public static final String ALGORITHM = "Algorithm"; public static final String DATASOURCE = "DataSource"; public static final String DATASINK = "DataSink"; public static final String PIPELINE = "Pipeline"; public static final String PIPELINE_ELEMENT = "PipelineElement"; @QMInternal public static final String SEPARATOR = ":"; private static final long serialVersionUID = 4880902220348531183L; private Map<String, Double> values; /** * Creates a frozen systems state instance. */ public FrozenSystemState() { values = new HashMap<String, Double>(); } /** * Creates a frozen systems state instance from a map of values. This allows rt-VIL * to use this class as a wrapper. * * @param values the values to be wrapped */ public FrozenSystemState( @QMGenerics(types = {String.class, Double.class }) Map<String, Double> values) { this.values = null == values ? new HashMap<String, Double>() : values; } /** * Loads a system state from a properties file. * * @param file the file to load from * @throws IOException in case of I/O exceptions */ @QMInternal public FrozenSystemState(File file) throws IOException { this.values = new HashMap<String, Double>(); Properties prop = new Properties(); FileInputStream in = new FileInputStream(file); prop.load(in); in.close(); for (Map.Entry<Object, Object> entry : prop.entrySet()) { try { String key = entry.getKey().toString(); Double value = Double.valueOf(entry.getValue().toString()); values.put(key, value); } catch (NumberFormatException e) { // ignore } } } /** * Returns the access key. * * @param prefix the prefix denoting the type * @param name the name of the individual element * @param observable the observable * @return the observed value or <b>null</b> if nothing was observed (so far) */ public static String obtainKey(String prefix, String name, IObservable observable) { return prefix + SEPARATOR + name + SEPARATOR + (null == observable ? null : observable.name()); } /** * Returns the name sub-key for a pipeline element. * * @param pipeline the pipeline name * @param element the element name * @return the observed value or <b>null</b> if nothing was observed (so far) */ @QMInternal public static String obtainPipelineElementSubkey(String pipeline, String element) { return pipeline + SEPARATOR + element; } /** * Defines the value for an observation. * * @param prefix the prefix denoting the type * @param name the name of the individual element * @param observable the observable * @param value the actual value (may be <b>null</b>) */ @QMInternal public void setObservation(String prefix, String name, IObservable observable, Double value) { values.put(obtainKey(prefix, name, observable), value); } /** * Defines the value of an observation for a pipeline element. * * @param prefix the prefix denoting the type * @param pipeline the pipeline name * @param element the element name * @param observable the observable * @param value the actual value (may be <b>null</b>) */ @QMInternal public void setObservation(String prefix, String pipeline, String element, IObservable observable, Double value) { values.put(obtainKey(prefix, obtainPipelineElementSubkey(pipeline, element), observable), value); } // >> preliminary /** * Sets whether an algorithm is considered to be active in a pipeline at the moment of freezing. * * @param pipeline the name of the pipeline * @param algorithmName the name of the algorithm */ @QMInternal public void setActiveAlgorithm(String pipeline, String algorithmName) { setObservation(ALGORITHM, pipeline, algorithmName, ResourceUsage.AVAILABLE, 1.0); } // << preliminary /** * Returns an observation. * * @param prefix the prefix denoting the type * @param name the name of the individual element * @param observable the observable * @param dflt the default value to return if nothing was observed (so far) * @return the observed value or <code>dflt</code> if nothing was observed (so far) */ @QMInternal public Double getObservation(String prefix, String name, IObservable observable, Double dflt) { return getObservation(obtainKey(prefix, name, observable), dflt); } /** * Returns an observation. * * @param key the access key (see {@link #obtainKey(String, String, IObservable)}. * @param dflt the default value to return if nothing was observed (so far) * @return the observed value or <code>dflt</code> if nothing was observed (so far) */ @QMInternal public Double getObservation(String key, Double dflt) { Double result = values.get(key); if (null == result) { result = dflt; } return result; } /** * Returns an observation for the infrastructure. * * @param observable the observable * @return the observed value or <b>null</b> if nothing was observed (so far) */ public Double getInfrastructureObservation(IObservable observable) { return getInfrastructureObservation(observable, null); } /** * Returns an observation for the infrastructure. * * @param observable the observable * @param dflt the default value to return if nothing was observed (so far) * @return the observed value or <code>dflt</code> if nothing was observed (so far) */ public Double getInfrastructureObservation(IObservable observable, Double dflt) { return getObservation(INFRASTRUCTURE, INFRASTRUCTURE_NAME, observable, dflt); } /** * Returns an observation for a cloud environment. * @param name the name of the cloud environment * @param observable the observable * @return the observed value or <code>dflt</code> if nothing was observed (so far) */ public Double getCloudObservation(String name, IObservable observable) { return getCloudObservation(name, observable, null); } /** * Returns an observation for a cloud environment. * @param name the name of the cloud environment * @param observable the observable * @param dflt the default value to return if nothing was observed (so far) * @return the observed value or <code>dflt</code> if nothing was observed (so far) */ public Double getCloudObservation(String name, IObservable observable, Double dflt) { return getObservation(CLOUDENV, name, observable, dflt); } /** * Returns an observation for a machine. * * @param name the name of the machine * @param observable the observable * @return the observed value or <b>null</b> if nothing was observed (so far) */ public Double getMachineObservation(String name, IObservable observable) { return getMachineObservation(name, observable, null); } /** * Returns an observation for a machine. * * @param name the name of the machine * @param observable the observable * @param dflt the default value to return if nothing was observed (so far) * @return the observed value or <code>dflt</code> if nothing was observed (so far) */ public Double getMachineObservation(String name, IObservable observable, Double dflt) { return getObservation(MACHINE, name, observable, dflt); } /** * Returns an observation for a hardware node. * * @param name the name of the hardware node * @param observable the observable * @return the observed value or <b>null</b> if nothing was observed (so far) */ public Double getHwNodeObservation(String name, IObservable observable) { return getHwNodeObservation(name, observable, null); } /** * Returns an observation for a hardware node. * * @param name the name of the hardware node * @param observable the observable * @param dflt the default value to return if nothing was observed (so far) * @return the observed value or <code>dflt</code> if nothing was observed (so far) */ public Double getHwNodeObservation(String name, IObservable observable, Double dflt) { return getObservation(HWNODE, name, observable, dflt); } /** * Returns an observation for a data source used in a pipeline. * * @param pipeline the name of the pipeline * @param name the name of the data source * @param observable the observable * @return the observed value or <b>null</b> if nothing was observed (so far) */ public Double getDataSourceObservation(String pipeline, String name, IObservable observable) { return getDataSourceObservation(pipeline, name, observable, null); } /** * Returns an observation for a data source used in a pipeline. * * @param pipeline the name of the pipeline * @param name the name of the data source * @param observable the observable * @param dflt the default value to return if nothing was observed (so far) * @return the observed value or <code>dflt</code> if nothing was observed (so far) */ public Double getDataSourceObservation(String pipeline, String name, IObservable observable, Double dflt) { return getObservation(DATASOURCE, obtainPipelineElementSubkey(pipeline, name), observable, dflt); } /** * Returns an observation for a data sink used in a pipeline. * * @param pipeline the name of the pipeline * @param name the name of the data sink * @param observable the observable * @return the observed value or <b>null</b> if nothing was observed (so far) */ public Double getDataSinkObservation(String pipeline, String name, IObservable observable) { return getDataSinkObservation(pipeline, name, observable, null); } /** * Returns an observation for a data sink used in a pipeline. * * @param pipeline the name of the pipeline * @param name the name of the data sink * @param observable the observable * @param dflt the default value to return if nothing was observed (so far) * @return the observed value or <code>dflt</code> if nothing was observed (so far) */ public Double getDataSinkObservation(String pipeline, String name, IObservable observable, Double dflt) { return getObservation(DATASINK, obtainPipelineElementSubkey(pipeline, name), observable, dflt); } /** * Returns an observation for a pipeline. * * @param name the name of the pipeline * @param observable the observable * @return the observed value or <b>null</b> if nothing was observed (so far) */ public Double getPipelineObservation(String name, IObservable observable) { return getPipelineObservation(name, observable, null); } /** * Returns an observation for a pipeline. * * @param name the name of the pipeline * @param observable the observable * @param dflt the default value to return if nothing was observed (so far) * @return the observed value or <code>dflt</code> if nothing was observed (so far) */ public Double getPipelineObservation(String name, IObservable observable, Double dflt) { return getObservation(PIPELINE, name, observable, dflt); } /** * Returns an observation for a pipeline source. * * @param pipeline the name of the pipeline * @param element the name of the element * @param observable the observable * @return the observed value or <b>null</b> if nothing was observed (so far) */ public Double getPipelineElementObservation(String pipeline, String element, IObservable observable) { return getPipelineElementObservation(pipeline, element, observable, null); } /** * Returns an observation for a pipeline source. * * @param pipeline the name of the pipeline * @param element the name of the element * @param observable the observable * @param dflt the default value to return if nothing was observed (so far) * @return the observed value or <code>dflt</code> if nothing was observed (so far) */ public Double getPipelineElementObservation(String pipeline, String element, IObservable observable, Double dflt) { return getObservation(PIPELINE_ELEMENT, obtainPipelineElementSubkey(pipeline, element), observable, dflt); } /** * Returns an observation for an algorithm used in a pipeline. * * @param pipeline the name of the pipeline * @param algorithm the name of the algorithm * @param observable the observable * @return the observed value or <b>null</b> if nothing was observed (so far) */ public Double getAlgorithmObservation(String pipeline, String algorithm, IObservable observable) { return getAlgorithmObservation(pipeline, algorithm, observable, null); } /** * Returns an observation for an algorithm used in a pipeline. * * @param pipeline the name of the pipeline * @param algorithm the name of the algorithm * @param observable the observable * @param dflt the default value to return if nothing was observed (so far) * @return the observed value or <code>dflt</code> if nothing was observed (so far) */ public Double getAlgorithmObservation(String pipeline, String algorithm, IObservable observable, Double dflt) { return getObservation(ALGORITHM, obtainPipelineElementSubkey(pipeline, algorithm), observable, dflt); } /** * Returns the mapping. * * @return the mapping */ @QMInternal public Map<String, Double> getMapping() { return values; } /** * Converts the frozen system state into properties. * * @return the related properties */ @QMInternal public Properties toProperties() { Properties prop = new Properties(); for (Map.Entry<String, Double> entry : values.entrySet()) { String key = entry.getKey(); Double value = entry.getValue(); if (null != key && null != value) { prop.put(key, value.toString()); } } return prop; } /** * Stores the system state in a file. * * @param file the file * @throws IOException in case of I/O problems */ @QMInternal public void store(File file) throws IOException { Properties prop = toProperties(); FileWriter out = Utils.createFileWriter(file); prop.store(out, ""); out.close(); } @QMInternal @Override public String toString() { return values.toString(); } }
modified/extended system state for fixing bindValues
QualiMaster.Events/src/eu/qualimaster/monitoring/events/FrozenSystemState.java
modified/extended system state for fixing bindValues
<ide><path>ualiMaster.Events/src/eu/qualimaster/monitoring/events/FrozenSystemState.java <ide> public static final String DATASINK = "DataSink"; <ide> public static final String PIPELINE = "Pipeline"; <ide> public static final String PIPELINE_ELEMENT = "PipelineElement"; <add> public static final String ACTUAL = "Actual"; <ide> <ide> @QMInternal <ide> public static final String SEPARATOR = ":"; <ide> values.put(obtainKey(prefix, obtainPipelineElementSubkey(pipeline, element), observable), value); <ide> } <ide> <del> // >> preliminary <del> <ide> /** <ide> * Sets whether an algorithm is considered to be active in a pipeline at the moment of freezing. <ide> * <ide> * @param pipeline the name of the pipeline <add> * @param nodeName the name of the node <ide> * @param algorithmName the name of the algorithm <ide> */ <ide> @QMInternal <del> public void setActiveAlgorithm(String pipeline, String algorithmName) { <del> setObservation(ALGORITHM, pipeline, algorithmName, ResourceUsage.AVAILABLE, 1.0); <del> } <del> <del> // << preliminary <add> public void setActiveAlgorithm(String pipeline, String nodeName, String algorithmName) { <add> // difficult: it would be nice to transfer the index of the algorithm from active, but if models diverge <add> // decision: transport the name as last pseudo segment and separate during mapping <add> // AVAILABLE and value are irrelevant <add> values.put(composeActiveAlgorithmKey(pipeline, nodeName, algorithmName), 1.0); <add> } <add> <add> /** <add> * Composes the active algorithm key for {@code pipeline}/{@code nodeName} and {@code algorithmName} as active <add> * algorithm. <add> * <add> * @param pipeline the pipeline name <add> * @param nodeName the node name <add> * @param algorithmName the algorithmname <add> * @return the composed key <add> */ <add> private static String composeActiveAlgorithmKey(String pipeline, String nodeName, String algorithmName) { <add> return obtainKey(ACTUAL, <add> obtainPipelineElementSubkey(pipeline, obtainPipelineElementSubkey(nodeName, algorithmName)), <add> ResourceUsage.AVAILABLE); <add> } <add> <add> /** <add> * Returns whether this frozen state contains {@code algorithmName} as active algorithm for <add> * {@code pipeline}/{@code nodeName}. <add> * <add> * @param pipeline the pipeline name <add> * @param nodeName the node name <add> * @param algorithmName the algorithm name <add> * @return {@code true} if the given algorithm is set as active on the given pipeline/node, {@code false} else <add> */ <add> public boolean hasActiveAlgorithm(String pipeline, String nodeName, String algorithmName) { <add> return values.containsKey(composeActiveAlgorithmKey(pipeline, nodeName, algorithmName)); <add> } <add> <add> /** <add> * Returns the active algorithm for {@code pipeline}/{@code nodeName}. <add> * <add> * @param pipeline the pipeline name <add> * @param nodeName the node name <add> * @return the active algorithm name, <b>null</b> if none is known <add> */ <add> public String getActiveAlgorithm(String pipeline, String nodeName) { <add> // not really efficient, intended for testing... <add> String result = null; <add> String prefix = ACTUAL + SEPARATOR + obtainPipelineElementSubkey(pipeline, nodeName) + SEPARATOR; <add> String postfix = SEPARATOR + ResourceUsage.AVAILABLE; <add> for (String k : values.keySet()) { <add> if (k.startsWith(prefix) && k.endsWith(postfix)) { <add> result = k.substring(prefix.length() + 1, k.length() - postfix.length()); <add> break; <add> } <add> } <add> return result; <add> } <ide> <ide> /** <ide> * Returns an observation.
Java
apache-2.0
dff8d527565fc5bf3030f159e22814d32c577ed0
0
liuxinglanyue/hot2hot,sdgdsffdsfff/hot2hot,xiangyong/hot2hot
/** * 启动参数配置 javaagent * -javaagent:hot2hot.jar * * @author jiaojianfeng * */ public class TestAgent { public static void main(String[] args) throws InterruptedException { A a = new A(); a.run(); while(true) { Thread.sleep(20000); a.run(); } } }
src/test/java/TestAgent.java
public class TestAgent { public static void main(String[] args) throws InterruptedException { A a = new A(); a.run(); while(true) { Thread.sleep(20000); a.run(); } } }
javaagent 注释
src/test/java/TestAgent.java
javaagent 注释
<ide><path>rc/test/java/TestAgent.java <ide> <del> <add>/** <add> * 启动参数配置 javaagent <add> * -javaagent:hot2hot.jar <add> * <add> * @author jiaojianfeng <add> * <add> */ <ide> public class TestAgent { <ide> <ide> public static void main(String[] args) throws InterruptedException {
JavaScript
apache-2.0
57ff08401373e5d5253c3eebb604f91035926e27
0
moritzp/alexa-google-search
// This skill reuses elements from the Adrian Smart Assistant project // https://github.com/TheAdrianProject/AdrianSmartAssistant/blob/master/Modules/Google/Google.js 'use strict'; var AlexaSkill = require('./AlexaSkill'); var rp = require('request-promise'); var $ = require('cheerio'); var Entities = require('html-entities').XmlEntities; var entities = new Entities(); var striptags = require('striptags'); var xray = require('x-ray')(); var cheerioTableparser = require('cheerio-tableparser'); var cheerio = require('cheerio'); var summary = require('node-tldr'); var localeResponseEN = [ 'What are you searching for?', 'Google Search Result for: ', 'Error', 'I found a table of Results.', 'dot', ' and ', ' less than ', 'I’m sorry, I wasn\'t able to find an answer.', 'There was an error processing your search.', 'I could not find an exact answer. Here is my best guess: ' ]; var localeResponseDE = [ 'Wonach soll ich googlen?', 'Google Suche nach: ', 'Fehler', 'Ich fand eine Tabelle der Ergebnisse.', 'punkt', ' und ', ' weniger als ', 'Es tut mir leid, ich konnte keine Antwort finden.', 'Bei der Suche ist leider ein Fehler aufgetreten.', 'Ich konnte keine genaue Antwort finden. Hier ist meine beste Vermutung: ' ]; // Create google search URL - this made up of the main search URL plus a languange modifier (currently only needed for German) var localeGoogleENGB = ["http://www.google.co.uk/search?q=", "&hl=en-GB"]; var localeGoogleDE = ["http://www.google.com/search?q=", "&hl=de"]; var localeGoogleENUS = ["http://www.google.com/search?q=", ""]; var sessionLocale = ''; var localeResponse = localeResponseEN; var localeGoogle = localeGoogleENUS; var APP_ID = undefined; //replace with 'amzn1.echo-sdk-ams.app.[your-unique-value-here]'; var AlexaGoogleSearch = function() { AlexaSkill.call(this, APP_ID); }; AlexaGoogleSearch.prototype = Object.create(AlexaSkill.prototype); AlexaGoogleSearch.prototype.constructor = AlexaGoogleSearch; AlexaGoogleSearch.prototype.eventHandlers.onLaunch = function(launchRequest, session, response) { console.log("AlexaGoogleSearch onLaunch requestId" + launchRequest.requestId + ", sessionId: " + session.sessionId); var speechOutput = localeResponse[0]; var repromptText = localeResponse[0]; response.ask(speechOutput, repromptText); }; AlexaGoogleSearch.prototype.intentHandlers = { "SearchIntent": function(intent, session, response) { var query = intent.slots.search.value; // Title for Alexa app card var cardTitle = (localeResponse[1] + query); // Remove spaces and replace with + query = query.replace(" ", "+"); // Remove _ and replace with + query = query.replace(/ /g, "+"); var speechOutput = localeResponse[2]; function speakResults(speechText) { // strip out html tags to leave just text var speechOutputTemp = entities.decode(striptags(speechText)); var cardOutputText = speechOutputTemp; // make sure all full stops have space after them otherwise alexa says the word dot speechOutputTemp = speechOutputTemp.split('.com').join(" " + localeResponse[4] + " com "); // deal with dot com speechOutputTemp = speechOutputTemp.split('.co.uk').join(" " + localeResponse[4] + " co " + localeResponse[3] + " uk "); // deal with .co.uk speechOutputTemp = speechOutputTemp.split('.net').join(" " + localeResponse[4] + " net "); // deal with .net speechOutputTemp = speechOutputTemp.split('.org').join(" " + localeResponse[4] + " org "); // deal with .org speechOutputTemp = speechOutputTemp.split('.org').join(" " + localeResponse[4] + " de "); // deal with .de speechOutputTemp = speechOutputTemp.split('a.m').join("am"); // deal with a.m speechOutputTemp = speechOutputTemp.split('p.m').join("pm"); // deal with a.m // deal with decimal places speechOutputTemp = speechOutputTemp.replace(/\d[\.]{1,}/g, '\$&DECIMALPOINT');// search for decimal points following a digit and add DECIMALPOINT TEXT speechOutputTemp = speechOutputTemp.replace(/.DECIMALPOINT/g, 'DECIMALPOINT');// remove decimal point // deal with characters that are illegal in SSML speechOutputTemp = speechOutputTemp.replace(/&/g, localeResponse[5]); // replace ampersands speechOutputTemp = speechOutputTemp.replace(/</g, localeResponse[6]); // replace < symbol speechOutputTemp = speechOutputTemp.replace(/""/g, ''); // replace double quotes speechOutputTemp = speechOutputTemp.split('SHORTALEXAPAUSE').join('<break time=\"250ms\"/>'); // add in SSML pauses at table ends speechOutputTemp = speechOutputTemp.split('ALEXAPAUSE').join('<break time=\"500ms\"/>'); // add in SSML pauses at table ends cardOutputText = cardOutputText.split('SHORTALEXAPAUSE').join(''); // remove pauses from card text cardOutputText = cardOutputText.split('ALEXAPAUSE').join('\r\n'); // remove pauses from card text speechOutputTemp = speechOutputTemp.split('.').join(". "); // Assume any remaining dot are concatonated sentances so turn them into full stops with a pause afterwards var speechOutput = speechOutputTemp.replace(/DECIMALPOINT/g, '.'); // Put back decimal points if (speechOutput === "") { speechOutput = localeResponse[7] } // Covert speechOutput into SSML so that pauses can be processed var SSMLspeechOutput = { speech: '<speak>' + speechOutput + '</speak>', type: 'SSML' }; response.tellWithCard(SSMLspeechOutput, cardTitle, cardOutputText); } function parsePage(url, backUpText) { console.log("Summarising first link"); summary.summarize(url, function(result, failure) { backUpText = localeResponse[9] + backUpText; if (failure) { console.log("An error occured! " + result.error); speakResults(localeResponse[8]); } if (result) { console.log(result.title); console.log(result.summary.join("\n")); var summarisedText = localeResponse[9] + result.title + "ALEXAPAUSE" + result.summary.join("\n"); if (backUpText.length >= summarisedText.length) { summarisedText = backUpText; } speakResults(summarisedText); } }); } // Parsing routine modified from // https://github.com/TheAdrianProject/AdrianSmartAssistant/blob/master/Modules/Google/Google.js //parse queries // create userAgent string from a number of selections var userAgent = [ 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36', 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36', 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_1) AppleWebKit/602.2.14 (KHTML, like Gecko) Version/10.0.1 Safari/602.2.14', 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:50.0) Gecko/20100101 Firefox/50.0', 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.95 Safari/537.36' ]; var sel = Math.floor((Math.random() * 5)); var userAgentRandom = userAgent[sel]; console.log("User Agent: - " + userAgentRandom); // Create search sring var queryString = localeGoogle[0] + query + '&oe=utf8' + localeGoogle[1]; var options = { uri: queryString, 'User-Agent': userAgentRandom }; rp(options).then(function(body) { console.log("Running parsing"); console.log("Search string is:" + queryString); console.log("HTML is:" + $('#ires', body).html()); // result variable init var found = 0; //how many 2 if (!found) { //how many var items = $('._m3b', body).get().length; // find how many lines there are in answer table if (items) { console.log(items + " how many 2 answer found"); found = $('._eGc', body).html() + ", "; for (var i = 0; i < items; i++) { found = found + $('._m3b', body).eq(i).html() + ", "; } } } //name list if (!found && $('#_vBb', body).length > 0) { found = $('#_vBb', body).html(); console.log("Found name list"); } //facts 1 if (!found && $('._tXc>span', body).length > 0) { found = $('._tXc>span', body).html(); console.log("Found facts 1"); } //facts 2 if (!found && $('._sPg', body).length > 0) { found = " " + $('._sPg', body).html(); console.log("Found facts 2"); } //instant + description 1 if (!found && $('._Oqb', body).length > 0) { found = $('._Oqb', body).html(); console.log("Found instant and desc 1"); //how many 1 if ($('._Mqb', body).length > 0) { found += " " + $('._Mqb', body).html(); console.log("Found Found instant and desc 1 - how many"); } } //instant + description 2 if (!found && $('._o0d', body).length > 0) { console.log("Found Found instant and desc 2"); var tablehtml = $('._o0d', body).html(); found = tablehtml; // fallback in case a table isn't found xray(tablehtml, ['table@html'])(function(conversionError, tableHtmlList) { if (tableHtmlList) { // xray returns the html inside each table tag, and tabletojson // expects a valid html table, so we need to re-wrap the table. // var table1 = tabletojson.convert('<table>' + tableHtmlList[0]+ '</table>'); var $table2 = cheerio.load('<table>' + tableHtmlList[0] + '</table>'); cheerioTableparser($table2); var headerStart = 0; var data2 = $table2("table").parsetable(false, false, true); var tableWidth = data2.length; var tableHeight = data2[0].length; console.log("Height " + tableHeight); console.log("Width " + tableWidth); var blankFound = 0; var headerText = ''; for (var l = 0; l < tableWidth; l++) { console.log('Table Data @@@@@' + data2[l] + '@@@@'); } // Look to see whether header row has blank cells in it. // If it does then the headers are titles can't be used so we use first row of table as headers instead for (var i = 0; i < tableWidth; i++) { console.log(data2[i][0]); if (data2[i][0] === "") { blankFound++; } else { headerText += (data2[i][0]) + '. SHORTALEXAPAUSE'; } } console.log("Number of blank cells : " + blankFound); found = localeResponse[3] + ' ALEXAPAUSE '; if (blankFound !== 0) { headerStart = 1; //found += headerText +' ALEXAPAUSE '; } // Parse table from header row onwards for (var x = headerStart; x < tableHeight; x++) { for (var y = 0; y < tableWidth; y++) { found += ( data2[y][x] + ', SHORTALEXAPAUSE'); } found += ('ALEXAPAUSE'); } console.log('Found :' + found) } if (conversionError) { console.log("There was a conversion error: " + conversionError); } }); } //Time, Date if (!found && $('._rkc._Peb', body).length > 0) { found = $('._rkc._Peb', body).html(); console.log("Found date and Time"); } //Maths if (!found && $('.nobr>.r', body).length > 0) { found = $('.nobr>.r', body).html(); console.log("Found maths"); } //simple answer if (!found && $('.obcontainer', body).length > 0) { found = $('.obcontainer', body).html(); console.log("Found Simple answer"); } //Definition if (!found && $('.r>div>span', body).first().length > 0) { found = $('.r>div>span', body).first().html() + " definition. "; console.log("Found definition"); //how many var linesInAnswer = $('.g>div>table>tr>td>ol>li', body).get().length; // find how many lines there are in answer table if (linesInAnswer) { console.log(linesInAnswer + " Type 4 answer sections result"); for (var i = 0; i < linesInAnswer; i++) { found = found + $('.g>div>table>tr>td>ol>li', body).eq(i).html() + ", "; } } } //TV show if (!found && $('._B5d', body).length > 0) { found = $('._B5d', body).html(); console.log("Found tv show"); //how many if ($('._Pxg', body).length > 0) { found += ". " + $('._Pxg', body).html(); } //how many if ($('._tXc', body).length > 0) { found += ". " + $('._tXc', body).html(); } } //Weather if (!found && $('.g>.e>h3', body).length > 0) { found = $('.g>.e>h3', body).html(); console.log("Found weather"); //how many if ($('.wob_t', body).first().length > 0) { found += " " + $('.wob_t', body).first().html(); console.log("Found weather"); } //how many if ($('._Lbd', body).length > 0) { found += " " + $('._Lbd', body).html(); console.log("Found how many"); } } if (found) { speakResults(found); } else { speakResults(localeResponse[7]); } // response.tell(speechOutput) }).catch(function(err) { console.log("ERROR " + err); speechOutput = localeResponse[8]; response.tell(speechOutput); }) }, "AMAZON.StopIntent": function(intent, session, response) { var speechOutput = ""; response.tell(speechOutput); } }; exports.handler = function(event, context) { var AlexaGoogleSearchHelper = new AlexaGoogleSearch(); sessionLocale = event.request.locale; console.log("handler locale is: " + sessionLocale); if (sessionLocale === 'de-DE') { localeResponse = localeResponseDE; localeGoogle = localeGoogleDE; console.log("Setting locale to de-DE"); } if (sessionLocale === 'en-GB') { localeResponse = localeResponseEN; localeGoogle = localeGoogleENGB; console.log("Setting locale to en-GB"); } if (sessionLocale === 'en-US') { localeResponse = localeResponseEN; localeGoogle = localeGoogleENUS; console.log("Setting locale to en-US"); } AlexaGoogleSearchHelper.execute(event, context); };
src/index.js
// This skill reuses elements from the Adrian Smart Assistant project // https://github.com/TheAdrianProject/AdrianSmartAssistant/blob/master/Modules/Google/Google.js 'use strict'; var AlexaSkill = require('./AlexaSkill'); var rp = require('request-promise'); var $ = require('cheerio'); var Entities = require('html-entities').XmlEntities; var entities = new Entities(); var striptags = require('striptags'); var xray = require('x-ray')(); var cheerioTableparser = require('cheerio-tableparser'); var cheerio = require('cheerio'); var summary = require('node-tldr'); var localeResponseEN = [ 'What are you searching for?', 'Google Search Result for: ', 'Error', 'I found a table of Results.', 'dot', ' and ', ' less than ', 'I’m sorry, I wasn\'t able to find an answer.', 'There was an error processing your search.', 'I could not find an exact answer. Here is my best guess: ', ' to ' ]; var localeResponseDE = [ 'Wonach soll ich googlen?', 'Google Suche nach: ', 'Fehler', 'Ich fand eine Tabelle der Ergebnisse.', 'Punkt', ' und ', ' weniger als ', 'Es tut mir leid, ich konnte keine Antwort finden.', 'Bei der Suche ist leider ein Fehler aufgetreten.', 'Ich konnte keine genaue Antwort finden. Hier ist meine beste Vermutung: ', ' bis ' ]; // Create google search URL - this made up of the main search URL plus a languange modifier (currently only needed for German) var localeGoogleENGB = ["http://www.google.co.uk/search?q=", "&hl=en-GB"]; var localeGoogleDE = ["http://www.google.com/search?q=", "&hl=de"]; var localeGoogleENUS = ["http://www.google.com/search?q=", ""]; var sessionLocale = ''; var localeResponse = localeResponseEN; var localeGoogle = localeGoogleENUS; var APP_ID = undefined; //replace with 'amzn1.echo-sdk-ams.app.[your-unique-value-here]'; var AlexaGoogleSearch = function() { AlexaSkill.call(this, APP_ID); }; AlexaGoogleSearch.prototype = Object.create(AlexaSkill.prototype); AlexaGoogleSearch.prototype.constructor = AlexaGoogleSearch; AlexaGoogleSearch.prototype.eventHandlers.onLaunch = function(launchRequest, session, response) { console.log("AlexaGoogleSearch onLaunch requestId" + launchRequest.requestId + ", sessionId: " + session.sessionId); var speechOutput = localeResponse[0]; var repromptText = localeResponse[0]; response.ask(speechOutput, repromptText); }; AlexaGoogleSearch.prototype.intentHandlers = { "SearchIntent": function(intent, session, response) { var query = intent.slots.search.value; // Title for Alexa app card var cardTitle = (localeResponse[1] + query); // Remove spaces and replace with + query = query.replace(" ", "+"); // Remove _ and replace with + query = query.replace(/ /g, "+"); var speechOutput = localeResponse[2]; function speakResults(speechText) { // strip out html tags to leave just text var speechOutputTemp = entities.decode(striptags(speechText)); var cardOutputText = speechOutputTemp; // make sure all full stops have space after them otherwise alexa says the word dot speechOutputTemp = speechOutputTemp.split('.com').join(" " + localeResponse[4] + " com "); // deal with dot com speechOutputTemp = speechOutputTemp.split('.co.uk').join(" " + localeResponse[4] + " co " + localeResponse[3] + " uk "); // deal with .co.uk speechOutputTemp = speechOutputTemp.split('.net').join(" " + localeResponse[4] + " net "); // deal with .net speechOutputTemp = speechOutputTemp.split('.org').join(" " + localeResponse[4] + " org "); // deal with .org speechOutputTemp = speechOutputTemp.split('.org').join(" " + localeResponse[4] + " de "); // deal with .de speechOutputTemp = speechOutputTemp.split('a.m').join("am"); // deal with a.m speechOutputTemp = speechOutputTemp.split('p.m').join("pm"); // deal with a.m // deal with decimal places speechOutputTemp = speechOutputTemp.replace(/\d[\.]{1,}/g, '\$&DECIMALPOINT');// search for decimal points following a digit and add DECIMALPOINT TEXT speechOutputTemp = speechOutputTemp.replace(/.DECIMALPOINT/g, 'DECIMALPOINT');// remove decimal point // deal with characters that are illegal in SSML speechOutputTemp = speechOutputTemp.replace(/&/g, localeResponse[5]); // replace ampersands speechOutputTemp = speechOutputTemp.replace(/-/g, localeResponse[10]); // replace ampersands speechOutputTemp = speechOutputTemp.replace(/</g, localeResponse[6]); // replace < symbol speechOutputTemp = speechOutputTemp.replace(/""/g, ''); // replace double quotes speechOutputTemp = speechOutputTemp.split('SHORTALEXAPAUSE').join('<break time=\"250ms\"/>'); // add in SSML pauses at table ends speechOutputTemp = speechOutputTemp.split('ALEXAPAUSE').join('<break time=\"500ms\"/>'); // add in SSML pauses at table ends cardOutputText = cardOutputText.split('SHORTALEXAPAUSE').join(''); // remove pauses from card text cardOutputText = cardOutputText.split('ALEXAPAUSE').join('\r\n'); // remove pauses from card text speechOutputTemp = speechOutputTemp.split('.').join(". "); // Assume any remaining dot are concatonated sentances so turn them into full stops with a pause afterwards var speechOutput = speechOutputTemp.replace(/DECIMALPOINT/g, '.'); // Put back decimal points if (speechOutput === "") { speechOutput = localeResponse[7]; } // Covert speechOutput into SSML so that pauses can be processed var SSMLspeechOutput = { speech: '<speak>' + speechOutput + '</speak>', type: 'SSML' }; response.tellWithCard(SSMLspeechOutput, cardTitle, cardOutputText); } // create userAgent string from a number of selections var userAgent = [ 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36', 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36', 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_1) AppleWebKit/602.2.14 (KHTML, like Gecko) Version/10.0.1 Safari/602.2.14', 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:50.0) Gecko/20100101 Firefox/50.0', 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.95 Safari/537.36' ]; var sel = Math.floor((Math.random() * 5)); var userAgentRandom = userAgent[sel]; console.log("User Agent: - " + userAgentRandom); // Create search sring var queryString = localeGoogle[0] + query + '&oe=utf8' + localeGoogle[1]; var options = { uri: queryString, 'User-Agent': userAgentRandom }; rp(options).then(function(body) { console.log("Running parsing"); console.log("Search string is:" + queryString); console.log("HTML is:" + $('#ires', body).html()); // result variable init var found = 0; //how many 2 if (!found) { //how many var items = $('._m3b', body).get().length; // find how many lines there are in answer table if (items) { console.log(items + " how many 2 answer found"); found = $('._eGc', body).html() + ", "; for (var i = 0; i < items; i++) { found = found + $('._m3b', body).eq(i).html() + ", "; } } } //name list if (!found && $('#_vBb', body).length > 0) { found = $('#_vBb', body).html(); console.log("Found name list"); } //facts 1 if (!found && $('._tXc>span', body).length > 0) { found = $('._tXc>span', body).html(); console.log("Found facts 1"); } //facts 2 if (!found && $('._sPg', body).length > 0) { found = " " + $('._sPg', body).html(); console.log("Found facts 2"); } //instant + description 1 if (!found && $('._Oqb', body).length > 0) { found = $('._Oqb', body).html(); console.log("Found instant and desc 1"); //how many 1 if ($('._Mqb', body).length > 0) { found += " " + $('._Mqb', body).html(); console.log("Found Found instant and desc 1 - how many"); } } //instant + description 2 if (!found && $('._o0d', body).length > 0) { console.log("Found Found instant and desc 2"); var tablehtml = $('._o0d', body).html(); found = tablehtml; // fallback in case a table isn't found xray(tablehtml, ['table@html'])(function(conversionError, tableHtmlList) { if (tableHtmlList) { // xray returns the html inside each table tag, and tabletojson // expects a valid html table, so we need to re-wrap the table. // var table1 = tabletojson.convert('<table>' + tableHtmlList[0]+ '</table>'); var $table2 = cheerio.load('<table>' + tableHtmlList[0] + '</table>'); cheerioTableparser($table2); var headerStart = 0; var data2 = $table2("table").parsetable(false, false, true); var tableWidth = data2.length; var tableHeight = data2[0].length; console.log("Height " + tableHeight); console.log("Width " + tableWidth); var blankFound = 0; var headerText = ''; for (var l = 0; l < tableWidth; l++) { console.log('Table Data @@@@@' + data2[l] + '@@@@'); } // Look to see whether header row has blank cells in it. // If it does then the headers are titles can't be used so we use first row of table as headers instead for (var i = 0; i < tableWidth; i++) { console.log(data2[i][0]); if (data2[i][0] === "") { blankFound++; } else { headerText += (data2[i][0]) + '. SHORTALEXAPAUSE'; } } console.log("Number of blank cells : " + blankFound); found = localeResponse[3] + ' ALEXAPAUSE '; if (blankFound !== 0) { headerStart = 1; //found += headerText +' ALEXAPAUSE '; } // Parse table from header row onwards for (var x = headerStart; x < tableHeight; x++) { for (var y = 0; y < tableWidth; y++) { found += ( data2[y][x] + ', SHORTALEXAPAUSE'); } found += ('ALEXAPAUSE'); } console.log('Found :' + found); } if (conversionError) { console.log("There was a conversion error: " + conversionError); } }); } //Time, Date if (!found && $('._rkc._Peb', body).length > 0) { found = $('._rkc._Peb', body).html(); console.log("Found date and Time"); } //Maths if (!found && $('.nobr>.r', body).length > 0) { found = $('.nobr>.r', body).html(); console.log("Found maths"); } //simple answer if (!found && $('.obcontainer', body).length > 0) { found = $('.obcontainer', body).html(); console.log("Found Simple answer"); } //Definition if (!found && $('.r>div>span', body).first().length > 0) { found = $('.r>div>span', body).first().html() + " definition. "; console.log("Found definition"); //how many var linesInAnswer = $('.g>div>table>tr>td>ol>li', body).get().length; // find how many lines there are in answer table if (linesInAnswer) { console.log(linesInAnswer + " Type 4 answer sections result"); for (var j = 0; j < linesInAnswer; j++) { found = found + $('.g>div>table>tr>td>ol>li', body).eq(j).html() + ", "; } } } //TV show if (!found && $('._B5d', body).length > 0) { found = $('._B5d', body).html(); console.log("Found tv show"); //how many if ($('._Pxg', body).length > 0) { found += ". " + $('._Pxg', body).html(); } //how many if ($('._tXc', body).length > 0) { found += ". " + $('._tXc', body).html(); } } //Weather if (!found && $('.g>.e>h3', body).length > 0) { found = $('.g>.e>h3', body).html(); console.log("Found weather"); //how many if ($('.wob_t', body).first().length > 0) { found += " " + $('.wob_t', body).first().html(); console.log("Found weather"); } //how many if ($('._Lbd', body).length > 0) { found += " " + $('._Lbd', body).html(); console.log("Found how many"); } } if (found) { speakResults(found); } else { speakResults(localeResponse[7]); } // response.tell(speechOutput) }).catch(function(err) { console.log("ERROR " + err); speechOutput = localeResponse[8]; response.tell(speechOutput); }); }, "AMAZON.StopIntent": function(intent, session, response) { var speechOutput = ""; response.tell(speechOutput); } }; exports.handler = function(event, context) { var AlexaGoogleSearchHelper = new AlexaGoogleSearch(); sessionLocale = event.request.locale; console.log("handler locale is: " + sessionLocale); if (sessionLocale === 'de-DE') { localeResponse = localeResponseDE; localeGoogle = localeGoogleDE; console.log("Setting locale to de-DE"); } if (sessionLocale === 'en-GB') { localeResponse = localeResponseEN; localeGoogle = localeGoogleENGB; console.log("Setting locale to en-GB"); } if (sessionLocale === 'en-US') { localeResponse = localeResponseEN; localeGoogle = localeGoogleENUS; console.log("Setting locale to en-US"); } AlexaGoogleSearchHelper.execute(event, context); };
Revert "* add "to" in SSML" This reverts commit 5dfa51c7d5c3ca4259182e17db4ca5bad552fc21.
src/index.js
Revert "* add "to" in SSML"
<ide><path>rc/index.js <ide> ' less than ', <ide> 'I’m sorry, I wasn\'t able to find an answer.', <ide> 'There was an error processing your search.', <del> 'I could not find an exact answer. Here is my best guess: ', <del> ' to ' <add> 'I could not find an exact answer. Here is my best guess: ' <add> <ide> ]; <ide> <ide> var localeResponseDE = [ <ide> 'Google Suche nach: ', <ide> 'Fehler', <ide> 'Ich fand eine Tabelle der Ergebnisse.', <del> 'Punkt', <add> 'punkt', <ide> ' und ', <ide> ' weniger als ', <ide> 'Es tut mir leid, ich konnte keine Antwort finden.', <ide> 'Bei der Suche ist leider ein Fehler aufgetreten.', <del> 'Ich konnte keine genaue Antwort finden. Hier ist meine beste Vermutung: ', <del> ' bis ' <add> 'Ich konnte keine genaue Antwort finden. Hier ist meine beste Vermutung: ' <add> <ide> ]; <ide> <ide> // Create google search URL - this made up of the main search URL plus a languange modifier (currently only needed for German) <ide> <ide> var localeResponse = localeResponseEN; <ide> var localeGoogle = localeGoogleENUS; <add> <ide> <ide> var APP_ID = undefined; //replace with 'amzn1.echo-sdk-ams.app.[your-unique-value-here]'; <ide> <ide> // deal with characters that are illegal in SSML <ide> <ide> speechOutputTemp = speechOutputTemp.replace(/&/g, localeResponse[5]); // replace ampersands <del> speechOutputTemp = speechOutputTemp.replace(/-/g, localeResponse[10]); // replace ampersands <ide> speechOutputTemp = speechOutputTemp.replace(/</g, localeResponse[6]); // replace < symbol <ide> speechOutputTemp = speechOutputTemp.replace(/""/g, ''); // replace double quotes <ide> <ide> var speechOutput = speechOutputTemp.replace(/DECIMALPOINT/g, '.'); // Put back decimal points <ide> <ide> if (speechOutput === "") { <del> speechOutput = localeResponse[7]; <add> speechOutput = localeResponse[7] <ide> } <ide> <ide> // Covert speechOutput into SSML so that pauses can be processed <ide> <ide> response.tellWithCard(SSMLspeechOutput, cardTitle, cardOutputText); <ide> } <add> <add> function parsePage(url, backUpText) { <add> console.log("Summarising first link"); <add> summary.summarize(url, function(result, failure) { <add> backUpText = localeResponse[9] + backUpText; <add> <add> if (failure) { <add> console.log("An error occured! " + result.error); <add> speakResults(localeResponse[8]); <add> } <add> <add> if (result) { <add> console.log(result.title); <add> console.log(result.summary.join("\n")); <add> var summarisedText = localeResponse[9] + result.title + "ALEXAPAUSE" + result.summary.join("\n"); <add> <add> if (backUpText.length >= summarisedText.length) { <add> <add> summarisedText = backUpText; <add> } <add> <add> speakResults(summarisedText); <add> } <add> }); <add> } <add> <add> // Parsing routine modified from <add> // https://github.com/TheAdrianProject/AdrianSmartAssistant/blob/master/Modules/Google/Google.js <add> <add> //parse queries <ide> <ide> // create userAgent string from a number of selections <ide> <ide> <ide> found += ('ALEXAPAUSE'); <ide> } <del> console.log('Found :' + found); <add> console.log('Found :' + found) <ide> } <ide> <ide> if (conversionError) { <ide> if (linesInAnswer) { <ide> console.log(linesInAnswer + " Type 4 answer sections result"); <ide> <del> for (var j = 0; j < linesInAnswer; j++) { <del> found = found + $('.g>div>table>tr>td>ol>li', body).eq(j).html() + ", "; <add> for (var i = 0; i < linesInAnswer; i++) { <add> found = found + $('.g>div>table>tr>td>ol>li', body).eq(i).html() + ", "; <ide> } <ide> } <ide> } <ide> console.log("ERROR " + err); <ide> speechOutput = localeResponse[8]; <ide> response.tell(speechOutput); <del> }); <add> }) <ide> }, <ide> <ide> "AMAZON.StopIntent": function(intent, session, response) {
JavaScript
mit
b3019cef389af5fe73e80822d3d34e0db73ed617
0
bolt-design-system/bolt,bolt-design-system/bolt,bolt-design-system/bolt,bolt-design-system/bolt,bolt-design-system/bolt
const webpack = require('webpack'); const WebpackDevServer = require('webpack-dev-server'); const chalk = require('chalk'); const createWebpackConfig = require('../create-webpack-config'); const { getConfig } = require('../utils/config-store'); const { boltWebpackMessages } = require('../utils/webpack-helpers'); let boltBuildConfig; async function compile(customWebpackConfig) { boltBuildConfig = boltBuildConfig || (await getConfig()); const webpackConfig = customWebpackConfig || (await createWebpackConfig(boltBuildConfig)); return new Promise((resolve, reject) => { const compiler = boltWebpackMessages(webpack(webpackConfig)); compiler.run((err, stats) => { if (err) { return reject(err); } else { return resolve(); } }); }); } compile.description = 'Compile Webpack'; compile.displayName = 'webpack:compile'; async function watch(customConfig) { boltBuildConfig = boltBuildConfig || (await getConfig()); const webpackConfig = customConfig || (await createWebpackConfig(boltBuildConfig)); return new Promise((resolve, reject) => { const compiler = boltWebpackMessages(webpack(webpackConfig)); compiler.watch({ // https://webpack.js.org/configuration/watch/#watchoptions aggregateTimeout: 300, }); }); } watch.description = 'Watch & fast re-compile Webpack'; watch.displayName = 'webpack:watch'; async function server(customWebpackConfig) { boltBuildConfig = boltBuildConfig || (await getConfig()); const webpackConfig = customWebpackConfig || (await createWebpackConfig(boltBuildConfig)); return new Promise((resolve, reject) => { const compiler = boltWebpackMessages(webpack(webpackConfig)); // Add Hot Module Reloading scripts to Webpack entrypoint if (webpackConfig[0].devServer.hot) { webpackConfig[0].entry['bolt-global'].unshift( `webpack-dev-server/client?http://localhost:${ webpackConfig[0].devServer.port }/`, 'webpack/hot/dev-server', ); } const server = new WebpackDevServer(compiler, webpackConfig[0].devServer); server.listen(boltBuildConfig.port, '0.0.0.0', err => { const localLabel = chalk.bold('Local: '); const localAddress = chalk.magenta( `http://localhost:${boltBuildConfig.port}/${boltBuildConfig.startPath}`, ); const externalLabel = chalk.bold('External: '); const externalAddress = chalk.magenta( `http://${boltBuildConfig.ip}:${boltBuildConfig.port}/${ boltBuildConfig.startPath }`, ); const lineBreak = chalk.gray( '--------------------------------------------', ); console.log(`\n${lineBreak}`); console.log(`${localLabel}${localAddress}`); console.log(`${externalLabel}${externalAddress}`); console.log(`${lineBreak}`); if (err) { reject(err); } }); }); } server.description = 'Webpack Dev Server'; server.displayName = 'webpack:server'; module.exports = { compile, watch, server, };
packages/build-tools/tasks/webpack-tasks.js
const webpack = require('webpack'); const WebpackDevServer = require('webpack-dev-server'); const createWebpackConfig = require('../create-webpack-config'); const { getConfig } = require('../utils/config-store'); const { boltWebpackMessages } = require('../utils/webpack-helpers'); const chalk = require('chalk'); let boltBuildConfig; async function compile(customWebpackConfig) { boltBuildConfig = boltBuildConfig || (await getConfig()); const webpackConfig = customWebpackConfig || (await createWebpackConfig(boltBuildConfig)); return new Promise((resolve, reject) => { const compiler = boltWebpackMessages(webpack(webpackConfig)); compiler.run((err, stats) => { if (err) { return reject(err); } else { return resolve(); } }); }); } compile.description = 'Compile Webpack'; compile.displayName = 'webpack:compile'; async function watch(customConfig) { boltBuildConfig = boltBuildConfig || (await getConfig()); const webpackConfig = customConfig || (await createWebpackConfig(boltBuildConfig)); return new Promise((resolve, reject) => { const compiler = boltWebpackMessages(webpack(webpackConfig)); compiler.watch({ // https://webpack.js.org/configuration/watch/#watchoptions aggregateTimeout: 300, }); }); } watch.description = 'Watch & fast re-compile Webpack'; watch.displayName = 'webpack:watch'; async function server(customWebpackConfig) { boltBuildConfig = boltBuildConfig || (await getConfig()); const webpackConfig = customWebpackConfig || (await createWebpackConfig(boltBuildConfig)); return new Promise((resolve, reject) => { const compiler = boltWebpackMessages(webpack(webpackConfig)); // Add Hot Module Reloading scripts to Webpack entrypoint if (webpackConfig[0].devServer.hot) { webpackConfig[0].entry['bolt-global'].unshift( `webpack-dev-server/client?http://localhost:${ webpackConfig[0].devServer.port }/`, 'webpack/hot/dev-server', ); } const server = new WebpackDevServer(compiler, webpackConfig[0].devServer); server.listen(boltBuildConfig.port, '0.0.0.0', err => { const localLabel = chalk.bold('Local: '); const localAddress = chalk.magenta( `http://localhost:${boltBuildConfig.port}/${boltBuildConfig.startPath}`, ); const externalLabel = chalk.bold('External: '); const externalAddress = chalk.magenta( `http://${boltBuildConfig.ip}:${boltBuildConfig.port}/${boltBuildConfig.startPath}`, ); const lineBreak = chalk.gray( '--------------------------------------------', ); console.log(`\n${lineBreak}`); console.log(`${localLabel}${localAddress}`); console.log(`${externalLabel}${externalAddress}`); console.log(`${lineBreak}`); if (err) { reject(err); } }); }); } server.description = 'Webpack Dev Server'; server.displayName = 'webpack:server'; module.exports = { compile, watch, server, };
fix: fix eslint and prettier errors
packages/build-tools/tasks/webpack-tasks.js
fix: fix eslint and prettier errors
<ide><path>ackages/build-tools/tasks/webpack-tasks.js <ide> const webpack = require('webpack'); <ide> const WebpackDevServer = require('webpack-dev-server'); <add>const chalk = require('chalk'); <ide> const createWebpackConfig = require('../create-webpack-config'); <ide> const { getConfig } = require('../utils/config-store'); <ide> const { boltWebpackMessages } = require('../utils/webpack-helpers'); <del>const chalk = require('chalk'); <ide> <ide> let boltBuildConfig; <ide> <ide> <ide> const externalLabel = chalk.bold('External: '); <ide> const externalAddress = chalk.magenta( <del> `http://${boltBuildConfig.ip}:${boltBuildConfig.port}/${boltBuildConfig.startPath}`, <add> `http://${boltBuildConfig.ip}:${boltBuildConfig.port}/${ <add> boltBuildConfig.startPath <add> }`, <ide> ); <ide> <ide> const lineBreak = chalk.gray(
Java
apache-2.0
627d5394ccdcc35af701af63cfbffb22ca749523
0
halober/ovirt-engine,zerodengxinchao/ovirt-engine,yapengsong/ovirt-engine,yingyun001/ovirt-engine,zerodengxinchao/ovirt-engine,OpenUniversity/ovirt-engine,OpenUniversity/ovirt-engine,yapengsong/ovirt-engine,yingyun001/ovirt-engine,yapengsong/ovirt-engine,walteryang47/ovirt-engine,halober/ovirt-engine,yapengsong/ovirt-engine,eayun/ovirt-engine,OpenUniversity/ovirt-engine,zerodengxinchao/ovirt-engine,walteryang47/ovirt-engine,walteryang47/ovirt-engine,yapengsong/ovirt-engine,halober/ovirt-engine,yingyun001/ovirt-engine,halober/ovirt-engine,OpenUniversity/ovirt-engine,zerodengxinchao/ovirt-engine,walteryang47/ovirt-engine,eayun/ovirt-engine,yingyun001/ovirt-engine,yingyun001/ovirt-engine,zerodengxinchao/ovirt-engine,OpenUniversity/ovirt-engine,walteryang47/ovirt-engine,eayun/ovirt-engine,eayun/ovirt-engine,eayun/ovirt-engine
package org.ovirt.engine.core.vdsbroker.gluster; import org.ovirt.engine.core.common.vdscommands.gluster.GlusterVolumeVDSParameters; public class StopRebalanceGlusterVolumeVDSCommand <P extends GlusterVolumeVDSParameters> extends AbstractGlusterBrokerCommand<P> { public StopRebalanceGlusterVolumeVDSCommand(P parameters) { super(parameters); } @Override protected void executeVdsBrokerCommand() { status = getBroker().glusterVolumeRebalanceStop(getParameters().getVolumeName()); proceedProxyReturnValue(); } }
backend/manager/modules/vdsbroker/src/main/java/org/ovirt/engine/core/vdsbroker/gluster/StopRebalanceGlusterVolumeVDSCommand.java
package org.ovirt.engine.core.vdsbroker.gluster; import org.ovirt.engine.core.common.vdscommands.gluster.GlusterVolumeVDSParameters; public class StopRebalanceGlusterVolumeVDSCommand <P extends GlusterVolumeVDSParameters> extends AbstractGlusterBrokerCommand<P> { public StopRebalanceGlusterVolumeVDSCommand(P parameters) { super(parameters); } @Override protected void ExecuteVdsBrokerCommand() { status = getBroker().glusterVolumeRebalanceStop(getParameters().getVolumeName()); proceedProxyReturnValue(); } }
gluster: Fix build break Fixed build break cause by Change-Id I6a48482fb8ce06cbe8d30a942538e056c695b195 - the method name should be executeVdsBrokerCommand() and not ExecuteVdsBrokerCommand(). Change-Id: I46147e917bd9c14b88a6905408597c423d2f21b2 Signed-off-by: Allon Mureinik <[email protected]>
backend/manager/modules/vdsbroker/src/main/java/org/ovirt/engine/core/vdsbroker/gluster/StopRebalanceGlusterVolumeVDSCommand.java
gluster: Fix build break
<ide><path>ackend/manager/modules/vdsbroker/src/main/java/org/ovirt/engine/core/vdsbroker/gluster/StopRebalanceGlusterVolumeVDSCommand.java <ide> } <ide> <ide> @Override <del> protected void ExecuteVdsBrokerCommand() { <add> protected void executeVdsBrokerCommand() { <ide> status = getBroker().glusterVolumeRebalanceStop(getParameters().getVolumeName()); <ide> proceedProxyReturnValue(); <ide> }
Java
mit
21ff8d4cbd7c69aa249b801a07c1e8f798e412cd
0
DDuarte/feup-aiad-schedule-alignment
package pt.up.fe.aiad.gui; import jade.core.*; import jade.wrapper.StaleProxyException; import javafx.fxml.FXML; import javafx.scene.control.ListView; import pt.up.fe.aiad.scheduler.SchedulerAgent; import pt.up.fe.aiad.utils.FXUtils; public class ClientController { private String _addressIp; private int _port; private String _nickname; private SchedulerAgent _agent; @FXML private ListView<String> _allAgents; @FXML void initialize() { System.out.println("ClientController.init"); } public void initData(String addressIp, int port, String nickname) { System.out.println("ClientController.initData"); _addressIp = addressIp; _port = port; _nickname = nickname; _agent = new SchedulerAgent(SchedulerAgent.Type.ABT); //TODO add type _allAgents.setItems(_agent._allAgents); } public void start() { System.out.println("ClientController.startServer: " + _nickname + " (" + _addressIp + ":" + _port + ")"); if (MainController.container != null) { try { MainController.container.acceptNewAgent(_nickname, _agent).start(); } catch (StaleProxyException e) { FXUtils.showExceptionDialog(e); } } else { ProfileImpl iae = new ProfileImpl(_addressIp, _port, _addressIp + ":" + Integer.toString(_port) + "/JADE", false); MainController.container = jade.core.Runtime.instance().createAgentContainer(iae); try { MainController.container.acceptNewAgent(_nickname, _agent).start(); } catch (StaleProxyException e) { FXUtils.showExceptionDialog(e); } } } }
src/pt/up/fe/aiad/gui/ClientController.java
package pt.up.fe.aiad.gui; import jade.wrapper.StaleProxyException; import javafx.fxml.FXML; import javafx.scene.control.ListView; import pt.up.fe.aiad.scheduler.SchedulerAgent; import pt.up.fe.aiad.utils.FXUtils; public class ClientController { private String _addressIp; private int _port; private String _nickname; private SchedulerAgent _agent; @FXML private ListView<String> _allAgents; @FXML void initialize() { System.out.println("ClientController.init"); } public void initData(String addressIp, int port, String nickname) { System.out.println("ClientController.initData"); _addressIp = addressIp; _port = port; _nickname = nickname; _agent = new SchedulerAgent(SchedulerAgent.Type.ABT); //TODO add type _allAgents.setItems(_agent._allAgents); } public void start() { System.out.println("ClientController.startServer: " + _nickname + " (" + _addressIp + ":" + _port + ")"); if (MainController.container != null) { try { MainController.container.acceptNewAgent(_nickname, _agent).start(); } catch (StaleProxyException e) { FXUtils.showExceptionDialog(e); } } } }
Create container on remote platform when launching client and no container has yet been created
src/pt/up/fe/aiad/gui/ClientController.java
Create container on remote platform when launching client and no container has yet been created
<ide><path>rc/pt/up/fe/aiad/gui/ClientController.java <ide> package pt.up.fe.aiad.gui; <ide> <add>import jade.core.*; <ide> import jade.wrapper.StaleProxyException; <ide> import javafx.fxml.FXML; <ide> import javafx.scene.control.ListView; <ide> FXUtils.showExceptionDialog(e); <ide> } <ide> } <add> else { <add> ProfileImpl iae = new ProfileImpl(_addressIp, _port, _addressIp + ":" + Integer.toString(_port) + "/JADE", false); <add> MainController.container = jade.core.Runtime.instance().createAgentContainer(iae); <add> try { <add> MainController.container.acceptNewAgent(_nickname, _agent).start(); <add> } catch (StaleProxyException e) { <add> FXUtils.showExceptionDialog(e); <add> } <add> } <ide> } <ide> }
Java
bsd-3-clause
857715ac36bfcfb0a025404dc5edf4ab2def5029
0
knopflerfish/knopflerfish.org,knopflerfish/knopflerfish.org,knopflerfish/knopflerfish.org
/* * Copyright (c) 2004-2008, KNOPFLERFISH project * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following * conditions are met: * * - Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials * provided with the distribution. * * - Neither the name of the KNOPFLERFISH project nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.knopflerfish.bundle.framework_test; import java.util.*; import java.io.*; import java.net.*; import java.lang.reflect.*; import java.security.*; import org.osgi.framework.*; import org.knopflerfish.service.framework_test.*; import junit.framework.*; public class FrameworkTestSuite extends TestSuite implements FrameworkTest { BundleContext bc; Bundle bu; Bundle buA; Bundle buB; Bundle buC; Bundle buD; Bundle buD1; Bundle buE; Bundle buF; Bundle buH; Bundle buJ; // Bundle for resource reading integrity check Bundle buR2; Bundle buR3; Bundle buR4; Bundle buR5; Bundle buR6; // Bundles for resource reading integrity check Bundle buRimp; Bundle buRexp; // Package version test bundles Bundle buP1; Bundle buP2; Bundle buP3; // the three event listeners FrameworkListener fListen; BundleListener bListen; SyncBundleListener syncBListen; ServiceListener sListen; Properties props = System.getProperties(); String lineseparator = props.getProperty("line.separator"); String test_url_base; Vector events = new Vector(); // vector for events from test bundles Vector expevents = new Vector(); // comparision vector PrintStream out = System.out; long eventDelay = 500; public FrameworkTestSuite (BundleContext bc) { super("FrameworkTestSuite"); this.bc = bc; this.bu = bc.getBundle(); test_url_base = "bundle://" + bc.getBundle().getBundleId() + "/"; try { eventDelay = Long.getLong("org.knopflerfish.framework_tests.eventdelay", new Long(eventDelay)).longValue(); } catch (Exception e) { e.printStackTrace(); } addTest(new Setup()); addTest(new Frame005a()); addTest(new Frame007a()); addTest(new Frame010a()); addTest(new Frame018a()); addTest(new Frame019a()); addTest(new Frame020a()); addTest(new Frame025a()); addTest(new Frame030a()); addTest(new Frame035a()); addTest(new Frame038a()); // addTest(new Frame040a()); skipped since not a valid test? addTest(new Frame041a()); addTest(new Frame045a()); addTest(new Frame050a()); addTest(new Frame055a()); addTest(new Frame060a()); addTest(new Frame065a()); addTest(new Frame068a()); addTest(new Frame069a()); addTest(new Frame070a()); addTest(new Frame075a()); addTest(new Frame080a()); addTest(new Frame085a()); addTest(new Frame110a()); addTest(new Frame115a()); //don't fix up security for now //addTest(new Frame120a()); addTest(new Frame125a()); addTest(new Frame130a()); addTest(new Frame160a()); addTest(new Frame161a()); addTest(new Frame162a()); addTest(new Frame163a()); addTest(new Frame170a()); addTest(new Frame175a()); addTest(new Frame180a()); addTest(new Frame181a()); addTest(new Frame185a()); addTest(new Frame186a()); addTest(new Frame190a()); addTest(new Frame210a()); addTest(new Frame211a()); addTest(new Cleanup()); } public String getDescription() { return "Tests core functionality in the framework"; } public String getDocURL() { return "https://www.knopflerfish.org/svn/knopflerfish.org/trunk/osgi/bundles_test/regression_tests/framework_test/readme.txt"; } public final static String [] HELP_FRAME005A = { "Verify information from the getHeaders() method", }; class Frame005a extends FWTestCase { public void runTest() throws Throwable { Dictionary ai = bu.getHeaders(); // check expected headers String k = "Bundle-ContactAddress"; String info = (String) ai.get(k); assertEquals("bad Bundle-ContactAddress", "http://www.knopflerfish.org", info); k = "Bundle-Description"; info = (String) ai.get(k); assertEquals("bad Bundle-Description", "Test bundle for framework", info); k = "Bundle-DocURL"; info = (String) ai.get(k); assertEquals("bad Bundle-DocURL", "http://www.knopflerfish.org", info); k = "Bundle-Name"; info = (String) ai.get(k); assertEquals("bad Bundle-Name", "framework_test", info); k = "Bundle-Vendor"; info = (String) ai.get(k); assertEquals("bad Bundle-Vendor", "Knopflerfish/Gatespace Telematics", info); k = "Bundle-Version"; info = (String) ai.get(k); assertEquals("bad Bundle-Version", "1.0.0", info); k = "Bundle-ManifestVersion"; info = (String) ai.get(k); assertEquals("bad " + k, "2", info); String version = props.getProperty("java.version"); String vendor = props.getProperty("java.vendor"); out.println("framework test bundle, Java version " + version); out.println("framework test bundle, Java vendor " + vendor); out.println("### framework test bundle :FRAME005A:PASS"); } } public final static String [] HELP_FRAME007A = { "Extract all information from the getProperty in the BundleContext interface " }; class Frame007a extends FWTestCase { public void runTest() throws Throwable { String[] NNList = new String[] { Constants.FRAMEWORK_OS_VERSION, Constants.FRAMEWORK_OS_NAME, Constants.FRAMEWORK_PROCESSOR, Constants.FRAMEWORK_VERSION, Constants.FRAMEWORK_VENDOR, Constants.FRAMEWORK_LANGUAGE, }; for(int i = 0; i < NNList.length; i++) { String k = NNList[i]; String v = bc.getProperty(k); if(v == null) { fail("'" + k + "' not set"); } } String[] TFList = new String[] { Constants.SUPPORTS_FRAMEWORK_REQUIREBUNDLE, Constants.SUPPORTS_FRAMEWORK_FRAGMENT, Constants.SUPPORTS_FRAMEWORK_EXTENSION, Constants.SUPPORTS_BOOTCLASSPATH_EXTENSION, }; for( int i = 0; i < TFList.length; i++) { String k = TFList[i]; String v = bc.getProperty(k); if(v == null) { fail("'" + k + "' not set"); } if(!("true".equals(v) || "false".equals(v))) { fail("'" + k + "' is '" + v + "', expected 'true' or 'false'"); } } } } public final static String [] HELP_FRAME010A = { "Get context id, location and status of the bundle" }; class Frame010a extends FWTestCase { public void runTest() throws Throwable { long contextid = bu.getBundleId(); out.println("CONTEXT ID: " + contextid); String location = bu.getLocation(); out.println("LOCATION: " + location); int bunstate = bu.getState(); out.println("BCACTIVE: " + bunstate); } } static int nRunCount = 0; class Setup extends FWTestCase { public void runTest() throws Throwable { if(nRunCount > 0) { fail("The FrameworkTestSuite CANNOT be run reliably more than once. Other test results in this suite are/may not be valid. Restart framework to retest :Cleanup:FAIL"); } nRunCount++; fListen = new FrameworkListener(); try { bc.addFrameworkListener(fListen); } catch (IllegalStateException ise) { fail("framework test bundle "+ ise + " :SETUP:FAIL"); } bListen = new BundleListener(); try { bc.addBundleListener(bListen); } catch (IllegalStateException ise) { fail("framework test bundle "+ ise + " :SETUP:FAIL"); } syncBListen = new SyncBundleListener(); try { bc.addBundleListener(syncBListen); } catch (IllegalStateException ise) { fail("framework test bundle "+ ise + " :SETUP:FAIL"); } sListen = new ServiceListener(); try { bc.addServiceListener(sListen); } catch (IllegalStateException ise) { fail("framework test bundle "+ ise + " :SETUP:FAIL"); } Locale.setDefault(Locale.CANADA_FRENCH); out.println("### framework test bundle :SETUP:PASS"); } } class Cleanup extends FWTestCase { public void runTest() throws Throwable { Bundle[] bundles = new Bundle[] { buA , buB , buC, buD , buD1 , buE , buH , buJ , buR2 , buR3 , buR4 , buR5 , buR6 , buRimp , buRexp , buP1 , buP2 , buP3 , }; for(int i = 0; i < bundles.length; i++) { try { bundles[i].uninstall(); } catch (Exception ignored) { } } buA = null; buB = null; buC = null; buD = null; buD1 = null; buE = null; buF = null; buH = null; buJ = null; // for resource reading integrity check buR2 = null; buR3 = null; buR4 = null; buR5 = null; buR6 = null; // Bundles for resource reading integrity check buRimp = null; buRexp = null; // Package version test bundles buP1 = null; buP2 = null; buP3 = null; try { bc.removeFrameworkListener(fListen); } catch (Exception ignored) { } fListen = null; try { bc.removeServiceListener(sListen); } catch (Exception ignored) { } sListen = null; try { bc.removeBundleListener(bListen); } catch (Exception ignored) { } bListen = null; } } public final static String [] HELP_FRAME018A = { "Test result of getService(null). Should throw NPE", }; class Frame018a extends FWTestCase { public void runTest() throws Throwable { try { Object obj = null; obj = bc.getService(null); fail("### FRAME018A:FAIL Got service object=" + obj + ", excpected NullPointerException"); } catch (NullPointerException e) { out.println("### FRAME018A:PASS: got NPE=" + e); } catch (RuntimeException e) { fail("### FRAME018A:FAIL: got RTE=" + e); } catch (Throwable e) { fail("### FRAME018A:FAIL Got " + e + ", expected NullPointerException"); } } } public final static String [] HELP_FRAME019A = { "Try bundle:// syntax, if present in FW, by installing bundleA_test", "This test is also valid if ", "new URL(bundle://) throws MalformedURLException", }; class Frame019a extends FWTestCase { public void runTest() throws Throwable { Bundle bA = null; try { try { URL url = new URL("bundle://" + bc.getBundle().getBundleId() + "/" + "bundleA_test-1.0.0.jar"); // if the URL can be created, it should be possible to install // from the URL string representation bA = bc.installBundle(url.toString()); assertNotNull("Bundle should be possible to install from " + url, bA); try { bA.start(); } catch (Exception e) { fail(url + " couldn't be started, FRAME019A:FAIL"); } assertEquals("Bundle should be in ACTIVE state", Bundle.ACTIVE, bA.getState()); out.println("### FRAME019A: PASSED, bundle URL " + url); // finally block will uninstall bundle and clean up events } catch (MalformedURLException e) { out.println("### FRAME019A: PASSED, bundle: URL not supported: " + e); } } finally { try { if(bA != null) { bA.uninstall(); } } catch (Exception e) { } clearEvents(); } } } public final static String [] HELP_FRAME020A = { "Load bundleA_test and check that it exists and that its expected service does not exist", "Also check that the expected events in the framework occurs" }; class Frame020a extends FWTestCase { public void runTest() throws Throwable { buA = null; boolean teststatus = true; try { buA = Util.installBundle(bc, "bundleA_test-1.0.0.jar"); teststatus = true; } catch (BundleException bexcA) { fail("framework test bundle "+ bexcA +" :FRAME020A:FAIL"); teststatus = false; } catch (SecurityException secA) { fail("framework test bundle "+ secA +" :FRAME020A:FAIL"); teststatus = false; } //Localization tests Dictionary dict = buA.getHeaders(); if(!dict.get(Constants.BUNDLE_SYMBOLICNAME).equals("org.knopflerfish.bundle.bundleA_test")){ fail("framework test bundle, " + Constants.BUNDLE_SYMBOLICNAME + " header does not have right value:FRAME020A:FAIL"); } // Check that no service reference exist yet. ServiceReference sr1 = bc.getServiceReference("org.knopflerfish.service.bundleA_test.BundleA"); if (sr1 != null) { fail("framework test bundle, service from test bundle A unexpectedly found :FRAME020A:FAIL"); teststatus = false; } // check the listeners for events, expect only a bundle event, of type installation boolean lStat = checkListenerEvents(out, false , 0, true , BundleEvent.INSTALLED, false, 0, buA, sr1); if (teststatus == true && buA.getState() == Bundle.INSTALLED && lStat == true) { out.println("### framework test bundle :FRAME020A:PASS"); } else { fail("### framework test bundle :FRAME020A:FAIL"); } } } public final static String [] HELP_FRAME025A = { "Start bundleA_test and check that it gets state ACTIVE", "and that the service it registers exist" }; class Frame025a extends FWTestCase { public void runTest() throws Throwable { boolean teststatus = true; boolean ungetStat = false; try { buA.start(); teststatus = true; } catch (BundleException bexcA) { fail("framework test bundle "+ bexcA +" :FRAME025A:FAIL"); teststatus = false; bexcA.printStackTrace(); } catch (IllegalStateException ise) { fail("framework test bundle "+ ise +" :FRAME025A:FAIL"); teststatus = false; ise.printStackTrace(); } catch (SecurityException sec) { fail("framework test bundle "+ sec +" :FRAME025A:FAIL"); teststatus = false; sec.printStackTrace(); } // Check if testbundleA registered the expected service ServiceReference sr1 = bc.getServiceReference("org.knopflerfish.service.bundleA_test.BundleA"); if (sr1 == null) { fail("framework test bundle, expected service not found :FRAME025A:FAIL"); teststatus = false; } else { try { Object o1 = bc.getService(sr1); if (o1 == null) { fail("framework test bundle, no service object found :FRAME025A:FAIL"); teststatus = false; } try { ungetStat = bc.ungetService(sr1); } catch (IllegalStateException ise) { fail("framework test bundle, ungetService exception " + ise + ":FRAME025A:FAIL"); } } catch (SecurityException sek) { fail("framework test bundle, getService " + sek + ":FRAME025A:FAIL"); teststatus = false; } } // check the listeners for events, expect a bundle event of started and a service event of type registered boolean lStat = checkListenerEvents( out, false, 0, true, BundleEvent.STARTED, true, ServiceEvent.REGISTERED, buA, sr1); assertTrue("BundleA should be ACTIVE", buA.getState() == Bundle.ACTIVE); assertTrue("Service unget should be true", ungetStat == true); // Changed according to KF bug #1780141 assertTrue("Unexpected events", lStat == true); if (teststatus == true && buA.getState() == Bundle.ACTIVE && ungetStat == true && lStat == true ) { out.println("### framework test bundle :FRAME025A:PASS"); } else { fail("### framework test bundle :FRAME025A:FAIL"); } } } public final static String [] HELP_FRAME030A = { "Stop bundleA_test and check that it gets state RESOLVED" }; class Frame030a extends FWTestCase { public void runTest() throws Throwable { boolean teststatus = true; ServiceReference sr1 = bc.getServiceReference("org.knopflerfish.service.bundleA_test.BundleA"); boolean lStatSync = false; try { buA.stop(); lStatSync = checkSyncListenerEvents(out, true, BundleEvent.STOPPING, buA, null); teststatus = true; } catch (IllegalStateException ise ) { fail("framework test bundle, getService " + ise + ":FRAME030A:FAIL"); teststatus = false; } catch (BundleException be ) { fail("framework test bundle, getService " + be + ":FRAME030A:FAIL"); teststatus = false; } boolean lStat = checkListenerEvents(out, false, 0, true, BundleEvent.STOPPED, true, ServiceEvent.UNREGISTERING, buA, sr1); if (teststatus == true && buA.getState() == Bundle.RESOLVED && lStat == true && lStatSync == true) { out.println("### framework test bundle :FRAME030A:PASS"); } else { fail("### framework test bundle :FRAME030A:FAIL"); } } } public final static String [] HELP_FRAME035A = { "Stop bundleA_test and check that it gets state UNINSTALLED" }; class Frame035a extends FWTestCase { public void runTest() throws Throwable { boolean teststatus = true; ServiceReference sr1 = bc.getServiceReference("org.knopflerfish.service.bundleA_test.BundleA"); try { buA.uninstall(); } catch (IllegalStateException ise ) { fail("framework test bundle, getService " + ise + ":FRAME035A:FAIL"); teststatus = false; } catch (BundleException be ) { fail("framework test bundle, getService " + be + ":FRAME035A:FAIL"); teststatus = false; } boolean lStat = checkListenerEvents(out, false, 0, true, BundleEvent.UNINSTALLED, false, 0, buA, sr1); if (teststatus == true && buA.getState() == Bundle.UNINSTALLED && lStat == true) { out.println("### framework test bundle :FRAME035A:PASS"); } else { fail("### framework test bundle :FRAME035A:Fail"); } } } public final static String [] HELP_FRAME038A = { "Install a non existent file, check that the right exception is thrown" }; class Frame038a extends FWTestCase { public void runTest() throws Throwable { boolean teststatus = true; boolean exception; buD = null; try { buD = Util.installBundle(bc, "nonexisting_bundle_file.jar"); exception = false; } catch (BundleException bexcA) { // out.println("framework test bundle "+ bexcA +" :FRAME038A:FAIL"); exception = true; } catch (SecurityException secA) { fail("framework test bundle "+ secA +" :FRAME038A:FAIL"); teststatus = false; exception = true; } if (exception == false) { teststatus = false; } // check the listeners for events, expect nothing boolean lStat = checkListenerEvents(out, false,0, false,0, false,0, buD, null); if (teststatus == true && buD == null && lStat == true) { out.println("### framework test bundle :FRAME038A:PASS"); } else { fail("### framework test bundle :FRAME038A:FAIL"); } } } // 8. Install testbundle D, check that an BundleException is thrown // as this bundle has no manifest file in its jar file // (hmmm...I don't think this is a correct test. /EW) class Frame040a extends FWTestCase { public void runTest() throws Throwable { boolean teststatus = true; boolean exception; buD = null; try { buD = Util.installBundle(bc, "bundleD_test-1.0.0.jar"); exception = false; } catch (BundleException bexcA) { System.out.println("framework test bundle "+ bexcA +" :FRAME040A:FAIL"); // This exception is expected exception = true; } catch (SecurityException secA) { fail("framework test bundle "+ secA +" :FRAME040A:FAIL"); teststatus = false; exception = true; } // Check that no service reference exist. ServiceReference sr1 = bc.getServiceReference("org.knopflerfish.service.bundleD_test.BundleD"); if (sr1 != null) { fail("framework test bundle, service from test bundle D unexpectedly found :FRAME040A:FAIL"); teststatus = false; } if (exception == false) { teststatus = false; } // check the listeners for events, expect only a bundle event, of type installation boolean lStat = checkListenerEvents(out, false, 0, false , 0, false, 0, buD, null); out.println("FRAME040A: lStat=" + lStat); if (teststatus == true && buD == null && lStat == true) { out.println("### framework test bundle :FRAME040A:PASS"); } else { fail("### framework test bundle :FRAME040A:FAIL"); } } } public final static String [] HELP_FRAME041A = { "Install bundleD1_test, which has a broken manifest file,", "an empty import statement and check", "that the expected exceptions are thrown" }; class Frame041a extends FWTestCase { public void runTest() throws Throwable { boolean teststatus = true; boolean exception; buD1 = null; try { buD1 = Util.installBundle(bc, "bundleD1_test-1.0.0.jar"); exception = false; } catch (BundleException bexcA) { // System.out.println("framework test bundle "+ bexcA +" :FRAME041A"); // Throwable tex = bexcA.getNestedException(); // if (tex != null) { // System.out.println("framework test bundle, nested exception "+ tex +" :FRAME041A"); // } // This exception is expected exception = true; } catch (SecurityException secA) { fail("framework test bundle "+ secA +" :FRAME041A:FAIL"); teststatus = false; exception = true; } // Check that no service reference exist. ServiceReference sr1 = bc.getServiceReference("org.knopflerfish.service.bundleD1_test.BundleD1"); if (sr1 != null) { fail("framework test bundle, service from test bundle D1 unexpectedly found :FRAME041A:FAIL"); teststatus = false; } if (exception == false) { teststatus = false; } // check the listeners for events, expect only a bundle event, of type installation boolean lStat = checkListenerEvents(out, false, 0, false , 0, false, 0, buD, null); if (teststatus == true && buD == null && lStat == true) { out.println("### framework test bundle :FRAME041A:PASS"); } else { fail("### framework test bundle :FRAME041A:FAIL"); } } } public final static String [] HELP_FRAME045A = { "Add a service listener with a broken LDAP filter to get an exception" }; class Frame045a extends FWTestCase { public void runTest() throws Throwable { ServiceListener sListen1 = new ServiceListener(); String brokenFilter = "A broken LDAP filter"; try { bc.addServiceListener(sListen1, brokenFilter); out.println("Frame045a: Added LDAP filter"); } catch (InvalidSyntaxException ise) { assertEquals("InvalidSyntaxException.getFilter should be same as input string", brokenFilter, ise.getFilter()); } catch (Exception e) { fail("framework test bundle, wroing exception on broken LDAP filter, FREME045A:FAIL " + e); } out.println("### framework test bundle :FRAME045A:PASS"); } } public final static String [] HELP_FRAME050A = { "Loads and starts bundleB_test, checks that it gets the state ACTIVE.", "Checks that it implements the Configurable interface." }; class Frame050a extends FWTestCase { public void runTest() throws Throwable { boolean teststatus = true; try { buB = Util.installBundle(bc, "bundleB_test-1.0.0.jar"); buB.start(); teststatus = true; } catch (BundleException bexcB) { fail("framework test bundle "+ bexcB +" :FRAME050A:FAIL"); teststatus = false; bexcB.printStackTrace(); } catch (SecurityException secB) { fail("framework test bundle "+ secB +" :FRAME050A:FAIL"); teststatus = false; secB.printStackTrace(); } catch (IllegalStateException ise) { fail("framework test bundle "+ ise +" :FRAME050A:FAIL"); teststatus = false; ise.printStackTrace(); } // Check if testbundleB registered the expected service ServiceReference sr1 = bc.getServiceReference("org.knopflerfish.service.bundleB_test.BundleB"); if (sr1 == null) { fail("framework test bundle, expected service not found :FRAME050A:FAIL"); teststatus = false; } else { Object o1 = bc.getService(sr1); // out.println("o1 = " + o1); if (!(o1 instanceof Configurable)) { fail("framework test bundle, service does not support Configurable :FRAME050A:FAIL"); teststatus = false; } else { // out.println("framework test bundle got service ref"); Configurable c1 = (Configurable) o1; // out.println("c1 = " + c1); Object o2 = c1.getConfigurationObject(); if (o2 != c1) { teststatus = false; fail("framework test bundle, configuration object is not the same as service object :FRAME050A:FAIL"); } // out.println("o2 = " + o2 + " bundle = " + buB); // out.println("bxx " + sr1.getBundle()); } } // Check that the dictionary from the bundle seems to be ok, keys[1-4], value[1-4] String keys [] = sr1.getPropertyKeys(); for (int k=0; k< keys.length; k++) { if (keys[k].equals("key"+k)) { if (!(sr1.getProperty(keys[k]).equals("value"+k))) { teststatus = false; fail("framework test bundle, key/value mismatch in propety list :FRAME050A:FAIL"); } } } if (teststatus == true && buB.getState() == Bundle.ACTIVE) { out.println("### framework test bundle :FRAME050A:PASS"); } else { fail("### framework test bundle :FRAME050A:FAIL"); } } } public final static String [] HELP_FRAME055A = { "Load and start bundleC_test, checks that it gets the state ACTIVE.", "Checks that it is available under more than one name.", "Then stop the bundle, check that no exception is thrown", "as the bundle unregisters itself in its stop method." }; class Frame055a extends FWTestCase { public void runTest() throws Throwable { boolean teststatus = true; try { buC = Util.installBundle(bc, "bundleC_test-1.0.0.jar"); buC.start(); teststatus = true; } catch (BundleException bexcB) { teststatus = false; bexcB.printStackTrace(); fail("framework test bundle "+ bexcB +" :FRAME055A:FAIL"); } catch (SecurityException secB) { teststatus = false; secB.printStackTrace(); fail("framework test bundle "+ secB +" :FRAME055A:FAIL"); } catch (IllegalStateException ise) { teststatus = false; ise.printStackTrace(); fail("framework test bundle "+ ise +" :FRAME055A:FAIL"); } Dictionary dict = buC.getHeaders(); if(!dict.get(Constants.BUNDLE_SYMBOLICNAME).equals("org.knopflerfish.bundle.bundleC_test")){ fail("framework test bundle, " + Constants.BUNDLE_SYMBOLICNAME + " header does not have right value:FRAME055A:FAIL"); } // Check if testbundleC registered the expected service ServiceReference sr1 = bc.getServiceReference("org.knopflerfish.service.bundleC_test.BundleC"); if (sr1 == null) { teststatus = false; fail("framework test bundle, expected service not found :FRAME055A:FAIL"); } else { // get objectClass service name array int hits = 0; String [] packnames = (String[]) sr1.getProperty("objectClass"); for (int j = 0; j< packnames.length; j++) { if (packnames[j].equals("org.knopflerfish.service.bundleC_test.BundleC")) { hits++; } if (packnames[j].equals("java.lang.Object")) { hits++; } } if (hits !=2) { teststatus = false; fail("framework test bundle, expected service not registered under the two expected names :FRAME055A:FAIL"); } } // Check if testbundleC registered the expected service with java.lang.Object as well ServiceReference sref [] = null; try { sref = bc.getServiceReferences("java.lang.Object",null); if (sref == null) { fail("framework test bundle, expected service not found :FRAME055A:FAIL"); teststatus = false; } else { // get objectClass service name array int hits = 0; String [] packnames = (String[]) sr1.getProperty("objectClass"); for (int j = 0; j< packnames.length; j++) { if (packnames[j].equals("org.knopflerfish.service.bundleC_test.BundleC")) { hits++; } if (packnames[j].equals("java.lang.Object")) { hits++; } } if (hits !=2) { teststatus = false; fail("framework test bundle, expected service not registered under the two expected names :FRAME055A:FAIL"); } } } catch (InvalidSyntaxException ise) { fail("framework test bundle, invalid syntax in LDAP filter :" + ise + " :FRAME055A:FAIL"); teststatus = false; } // 11a. check the getProperty after registration, something should come back // Check that both keys in the service have their expected values boolean h1 = false; boolean h2 = false; if (sref != null) { for (int i = 0; i< sref.length; i++) { String sn1[] = (String[]) sref[i].getProperty("objectClass"); for (int j = 0; j < sn1.length; j++) { if (sn1[j].equals("org.knopflerfish.service.bundleC_test.BundleC")) { String keys[] = sref[i].getPropertyKeys(); if (keys != null) { for (int k = 0; k< keys.length; k++) { try { String s1 = (String) sref[i].getProperty(keys[k]); if (s1.equals("value1")) {h1 = true;} if (s1.equals("value2")) {h2 = true;} } catch (Exception e1) { // out.println("framework test bundle exception " + e1 ); } } } } } } } if (! (h1 == true && h2 == true)) { teststatus = false; fail("framework test bundle, expected property values from registered bundleC_test not found :FRAME055A:FAIL"); } try { buC.stop(); } catch (BundleException bexp) { teststatus = false; fail("framework test bundle, exception in stop method :" + bexp + " :FRAME055A:FAIL"); } catch (Throwable thr) { teststatus = false; fail("framework test bundle, exception in stop method :" + thr + " :FRAME055A:FAIL"); } // 11a. check the getProperty after unregistration, something should come back // Check that both keys i the service still have their expected values h1 = false; h2 = false; if (sref != null) { for (int i = 0; i< sref.length; i++) { String sn1[] = (String[]) sref[i].getProperty("objectClass"); if (sn1 != null) { for (int j = 0; j < sn1.length; j++) { if (sn1[j].equals("org.knopflerfish.service.bundleC_test.BundleC")) { String keys[] = sref[i].getPropertyKeys(); if (keys != null) { for (int k = 0; k< keys.length; k++) { try { String s1 = (String) sref[i].getProperty(keys[k]); if (s1.equals("value1")) {h1 = true;} if (s1.equals("value2")) {h2 = true;} } catch (Exception e1) { // out.println("framework test bundle exception " + e1 ); } } } } } } } } if (!(h1 == true && h2 == true)) { teststatus = false; fail("framework test bundle, expected property values from unregistered bundleC_test not found :FRAME055A:FAIL"); } out.println("framework test bundle, buC.getState() = " + buC.getState()); if (teststatus == true && buC.getState() == Bundle.RESOLVED) { out.println("### framework test bundle :FRAME055A:PASS"); } else { fail("### framework test bundle :FRAME055A:FAIL"); } } } public final static String [] HELP_FRAME060A = { "Gets the configurable object from testbundle B,", "update its properties and check that a ServiceEvent occurs.", "Also get the ServiceRegistration object from bundle", "and check that the bundle is the same and that", "unregistration causes a ServiceEvent.UNREGISTERING." }; class Frame060a extends FWTestCase { public void runTest() throws Throwable { boolean teststatus = true; boolean lStat = false; boolean lStat2 = false; ServiceRegistration servRegB = null; Method m; Class c, parameters[]; ServiceRegistration ServReg; // clear the listeners clearEvents(); // get rid of all prevoius events ServiceReference sr1 = bc.getServiceReference("org.knopflerfish.service.bundleB_test.BundleB"); if (sr1 == null) { fail("framework test bundle, expected service not found :FRAME060A:FAIL"); teststatus = false; } else { Object o1 = bc.getService(sr1); // out.println("o1 = " + o1); if (!(o1 instanceof Configurable)) { fail("framework test bundle, service does not support Configurable :FRAME060A:FAIL"); teststatus = false; } else { Hashtable h1 = new Hashtable(); h1.put ("key1","value7"); h1.put ("key2","value8"); // now for some reflection exercises Object[] arguments = new Object[1]; c = o1.getClass(); parameters = new Class[1]; parameters[0] = h1.getClass(); // new Class[0]; arguments[0] = h1; try { m = c.getMethod("setServReg", parameters); servRegB = (ServiceRegistration) m.invoke(o1, arguments); // System.out.println("servRegB= " + servRegB); } catch (IllegalAccessException ia) { out.println("Frame test IllegaleAccessException" + ia); } catch (InvocationTargetException ita) { out.println("Frame test InvocationTargetException" + ita); out.println("Frame test nested InvocationTargetException" + ita.getTargetException() ); } catch (NoSuchMethodException nme) { out.println("Frame test NoSuchMethodException" + nme); } // Check that the dictionary from the bundle seems to be ok, keys[1-2], value[7-8] String keys [] = sr1.getPropertyKeys(); for (int k=0; k< keys.length; k++) { // out.println("key=" + keys[k] +" val= " + sr1.getProperty(keys[k])); int l = k + 6; if (keys[k].equals("key"+l)) { if (!(sr1.getProperty(keys[k]).equals("value"+k))) { teststatus = false; fail("framework test bundle, key/value mismatch in propety list :FRAME060A:FAIL"); } } } // check the listeners for events, in this case service event MODIFIED lStat = checkListenerEvents(out, false,0, false,0, true,ServiceEvent.MODIFIED, buB, sr1); clearEvents(); // now to get the service reference as well for some manipulation arguments = new Object [0]; parameters = new Class [0]; try { m = c.getMethod("getServReg", parameters); servRegB = (ServiceRegistration) m.invoke(o1, arguments); ServiceReference sri = servRegB.getReference(); if (sri.getBundle() != buB) { teststatus = false; fail("framework test bundle, bundle not as expected :FRAME060A:FAIL"); } else { servRegB.unregister(); out.println("servRegB= " + servRegB); } } catch (IllegalAccessException ia) { out.println("Frame test IllegaleAccessException" + ia); } catch (InvocationTargetException ita) { out.println("Frame test InvocationTargetException" + ita); } catch (NoSuchMethodException nme) { out.println("Frame test NoSuchMethodException" + nme); } lStat2 = checkListenerEvents(out, false,0, false,0, true,ServiceEvent.UNREGISTERING, buB, sr1); } } if (teststatus == true && buB.getState() == Bundle.ACTIVE && lStat == true && lStat2 == true) { out.println("### framework test bundle :FRAME060A:PASS"); } else { fail("### framework test bundle :FRAME060A:FAIL"); } } } public final static String [] HELP_FRAME065A = { "Load and try to start bundleE_test, ", "It should be possible to load , but should not be possible to start", "as the start method in the manifest is not available in the bundle." }; class Frame065a extends FWTestCase { public void runTest() throws Throwable { boolean teststatus = true; boolean catchstatus = true; buE = null; try { buE = Util.installBundle(bc, "bundleE_test-1.0.0.jar"); teststatus = true; } catch (BundleException bexcA) { teststatus = false; fail("framework test bundle "+ bexcA +" :FRAME065A:FAIL"); } catch (SecurityException secA) { teststatus = false; fail("framework test bundle "+ secA +" :FRAME065A:FAIL"); } clearEvents(); // now try and start it, which should generate a BundleException try { buE.start(); catchstatus = false; } catch (BundleException bexcA) { // the nested exception should be a ClassNotFoundException, check that Throwable t1 = bexcA.getNestedException(); if (t1 instanceof ClassNotFoundException) { catchstatus = true; } else { catchstatus = false; bexcA.printStackTrace(); fail("framework test bundle, unexpected nested exception "+ t1 +" :FRAME065A:FAIL"); } //System.out.println("framework test bundle "+ bexcA +" :FRAME065A:FAIL"); } catch (IllegalStateException ise) { teststatus = false; ise.printStackTrace(); fail("framework test bundle "+ ise +" :FRAME065A:FAIL"); } catch (SecurityException sec) { teststatus = false; sec.printStackTrace(); fail("framework test bundle "+ sec +" :FRAME065A:FAIL"); } // check the events, only BundleEvent.RESOLVED and BundleEvent.STARTING should have happened boolean lStat = checkListenerEvents(out, false, 0, true, BundleEvent.RESOLVED, false, 0, buE, null); boolean lStatSync = checkSyncListenerEvents(out, true, BundleEvent.STARTING, buE, null); if (catchstatus == false) { teststatus = false; } Dictionary dict = buE.getHeaders(); if(!dict.get(Constants.BUNDLE_SYMBOLICNAME).equals("org.knopflerfish.bundle.bundleE_test")){ fail("framework test bundle, " + Constants.BUNDLE_SYMBOLICNAME + " header does not have right value:FRAME065A:FAIL"); } if (teststatus == true && lStat == true && lStatSync == true) { out.println("### framework test bundle :FRAME065A:PASS"); } else { fail("### framework test bundle :FRAME065A:FAIL"); } } } public final static String [] HELP_FRAME068A = { "Tests accessing multiple resources inside the test bundle itself", "using ClassLoader.getResource" }; class Frame068a extends FWTestCase { public void runTest() throws Throwable { int n; // first check that correct number of files exists // the fw_test_multi.txt resources are present in // res1.jar, subdir/res1.jar, res2.jar and in the top bundle n = countResources("/fw_test_multi.txt"); assertEquals("Multiple resources should be reflected by CL.getResources() > 1", 4, n); //bundle.loadClass test boolean cauchtException = false; try{ bc.getBundle().loadClass("org.knopflerfish.bundle.io.Activato"); } catch(ClassNotFoundException e){ cauchtException = true; } if(!cauchtException){ fail("bundle.loadclass failed to generate exception for non-existent class"); } try{ bc.getBundle().loadClass("org.knopflerfish.bundle.io.Activator"); } catch(ClassNotFoundException e){ fail("bundle.loadclass failed"); } try{ bc.getBundle().loadClass("org.osgi.service.io.ConnectionFactory"); } catch(ClassNotFoundException e){ fail("bundle.loadclass failed"); } //existing directory Enumeration enume = bc.getBundle().getEntryPaths("/"); if(enume == null ){ fail("GetEntryPaths did not retrieve the correct number of elements, " +"/"); } out.println("bc.getBundle().getEntryPaths(\"/\")"); int i = 0; while(enume.hasMoreElements()){ i++; out.println(enume.nextElement()); } // This test needs to be updated every time a the // framework_tests bundle is changed in such a way that new // files or directories are added or removed to / from the top // level of the bundle jar-file. if(i != 43){ fail("GetEntryPaths did not retrieve the correct number of elements, " +"43 != "+ i); } //another existing directory out.println("getEntryPaths(\"/org/knopflerfish/bundle/framework_test\")"); enume = bc.getBundle() .getEntryPaths("/org/knopflerfish/bundle/framework_test"); if(enume == null ){ fail("GetEntryPaths did not retrieve the correct number of elements, " +"framework_test"); } i = 0; while(enume.hasMoreElements()){ i++; out.println(enume.nextElement()); } // This test needs to be updated every time a the // FrameworkTestSuite is changed in such a way that new files // or directories are added or removed to/from the sub-dir // "org/knopflerfish/bundle/framework_test" of the jar-file. if(i!=111){ fail("GetEntryPaths did not retrieve the correct number of elements, " +"111 != " + i); } //existing file, non-directory, ending with slash enume = bc.getBundle().getEntryPaths("/bundleA_test-1.0.0.jar/"); if(enume != null ){ fail("GetEntryPaths did not retrieve the correct number of elements"); } //existing file, non-directory enume = bc.getBundle().getEntryPaths("/bundleA_test-1.0.0.jar"); if(enume != null ){ fail("GetEntryPaths did not retrieve the correct number of elements"); } //non-existing file enume = bc.getBundle().getEntryPaths("/e"); if(enume != null){ fail("GetEntryPaths did not retrieve the correct number of elements"); } //empty dir enume = bc.getBundle().getEntryPaths("/emptySubDir"); if(enume != null){ fail("GetEntryPaths did not retrieve the correct number of elements"); } //dir with only one entry enume = bc.getBundle().getEntryPaths("/org/knopflerfish/bundle"); if(enume == null ){ fail("GetEntryPaths did not retrieve the correct number of elements"); } i = 0; while(enume.hasMoreElements()){ i++; enume.nextElement(); } if(i != 1){ fail("GetEntryPaths did not retrieve the correct number of elements"); } //TODO more, extensive loadClass tests // the fw_test_single.txt resource is present just // res2.jar n = countResources("/fw_test_single.txt"); assertEquals("Single resources should be reflected by CL.getResources() == 1", 1, n); // getEntry test URL url = bc.getBundle().getEntry("/fw_test_multi.txt"); assertURLExists(url); // the fw_test_nonexistent.txt is not present at all n = countResources("/fw_test_nonexistent.txt"); assertEquals("Multiple nonexistent resources should be reflected by CL.getResources() == 0", 0, n); // Try to get the top level URL of the bundle url = bc.getBundle().getResource("/"); out.println("bc.getBundle().getResource(\"/\") -> " +url); assertNotNull("bc.getBundle().getResource(\"/\")",url); // Check that we can build a usable URL from root URL. url = new URL(url,"META-INF/MANIFEST.MF"); assertURLExists(url); // Try to get the top level URLs of the bundle and check them { out.println("bc.getBundle().getResources(\"/\") -> "); Enumeration e = bc.getBundle().getResources("/"); assertNotNull("bc.getBundle().getResources(\"/\")", e); while(e.hasMoreElements()) { url = (URL)e.nextElement(); out.println("\t" +url); assertNotNull("Bundle root URL", url); } } out.println("### framework test bundle :FRAME068A:PASS"); } int countResources(String name) throws Exception { return countResources(name, false); } int countResources(String name, boolean verbose ) throws Exception { Bundle bundle = bc.getBundle(); int n = 0; Enumeration e = bundle.getResources(name); if (verbose) { out.println("bc.getBundle().getResources(\"" + name +"\") -> "); } if(e == null) return 0; while(e.hasMoreElements()) { URL url = (URL)e.nextElement(); if (verbose) { out.println("\t" +url); } assertURLExists(url); n++; } return n; } void testRes(String name, int count) throws Exception { out.println("testRes(" + name + ")"); ClassLoader cl = getClass().getClassLoader(); URL url1 = cl.getResource(name); out.println(" ClassLoader url = " + url1); assertURLExists(url1); URL url2 = bc.getBundle().getResource(name); out.println(" bundle url = " + url1); assertURLExists(url2); int n = 1; for(Enumeration e = cl.getResources(name); e.hasMoreElements(); ) { URL url = (URL)e.nextElement(); out.println(" " + n + " = " + url); assertURLExists(url); n++; } } void assertURLExists(URL url) throws Exception { InputStream is = null; try { is = url.openStream(); assertNotNull("URL " + url + " should give a non-null stream", is); return; } finally { try { is.close(); } catch (Exception ignored) { } } } } public final static String [] HELP_FRAME069A = { "Tests contents of multiple resources inside the test bundle itself", "using ClassLoader.getResource" }; class Frame069a extends FWTestCase { public void runTest() throws Throwable { Hashtable texts = new Hashtable(); texts.put("This is a resource in the bundle's res2.jar internal jar file", Boolean.FALSE); texts.put("This is a resource in the bundle's res1.jar internal jar file", Boolean.FALSE); texts.put("This is a resource in the bundle's main package", Boolean.FALSE); verifyContent("/fw_test_multi.txt", texts); texts = new Hashtable(); texts.put("This is a single resource in the bundle's res2.jar internal jar file.", Boolean.FALSE); verifyContent("/fw_test_single.txt", texts); out.println("### framework test bundle :FRAME069A:PASS"); } void verifyContent(String name, Hashtable texts) throws Exception { ClassLoader cl = getClass().getClassLoader(); for(Enumeration e = cl.getResources(name); e.hasMoreElements();) { URL url = (URL)e.nextElement(); out.println("Loading text from "+url); String s = new String(Util.loadURL(url)); if(!texts.containsKey(s)) { fail("Checking resource name '" + name + "', found unexpected content '" + s + "' in " + url); } texts.put(s, Boolean.TRUE); } for(Enumeration e = texts.keys(); e.hasMoreElements();) { String s = (String)e.nextElement(); Boolean b = (Boolean)texts.get(s); if(!b.booleanValue()) { fail("Checking resource name '" + name + "', did not find content '" + s + "'"); } } } } public final static String [] HELP_FRAME070A = { "Reinstalls and the updates testbundle_A.", "The version is checked to see if an update has been made." }; class Frame070a extends FWTestCase { public void runTest() throws Throwable { boolean teststatus = true; boolean catchstatus = true; String jarA = "bundleA_test-1.0.0.jar"; String jarA1 = "bundleA1_test-1.0.1.jar"; InputStream fis; String versionA; String versionA1; buA = null; try { buA = Util.installBundle(bc, jarA); teststatus = true; } catch (BundleException bexcA) { fail("framework test bundle "+ bexcA +" :FRAME070A:FAIL"); teststatus = false; } catch (SecurityException secA) { fail("framework test bundle "+ secA +" :FRAME070A:FAIL"); teststatus = false; } Dictionary ai = buA.getHeaders(); if(false) { // debugging for (Enumeration e = ai.keys(); e.hasMoreElements();) { Object key = e.nextElement(); Object value = ai.get(key); String s = key.toString(); String v = value.toString(); out.println("A: Manifest info: " + s + ", " + v); } } versionA = (String) ai.get("Bundle-Version"); clearEvents(); out.println("Before version = " + versionA); try { URL urk = bc.getBundle().getResource(jarA1); out.println("update from " + urk); // URLConnection url1 = URLConnection (urk); fis = urk.openStream(); if(fis == null) { fail("No data at " + urk + ":FRAME070A:FAIL"); } try { // TODO rework, does not always work long lastModified = buA.getLastModified(); buA.update(fis); /* if(buA.getLastModified() <= lastModified){ fail("framework test bundle, update does not change lastModified value :FRAME070A:FAIL"); }*/ } catch (BundleException be ) { teststatus = false; fail("framework test bundle, update without new bundle source :FRAME070A:FAIL"); } } catch (MalformedURLException murk) { teststatus = false; fail("framework test bundle, update file not found " + murk+ " :FRAME070A:FAIL"); } catch (FileNotFoundException fnf) { teststatus = false; fail("framework test bundle, update file not found " + fnf+ " :FRAME070A:FAIL"); } catch (IOException ioe) { teststatus = false; fail("framework test bundle, update file not found " + ioe+ " :FRAME070A:FAIL"); } Dictionary a1i = buA.getHeaders(); if(false) { // debugging for (Enumeration e = a1i.keys(); e.hasMoreElements();) { Object key = e.nextElement(); Object value = a1i.get(key); String s = key.toString(); String v = value.toString(); out.println("A1: Manifest info: " + s + ", " + v); } } a1i = buA.getHeaders(); versionA1 = (String) a1i.get("Bundle-Version"); out.println("After version = " + versionA1); // check the events, none should have happened boolean lStat = checkListenerEvents(out, false, 0, true ,BundleEvent.UPDATED , false, 0, buA, null); if (versionA1.equals(versionA)) { teststatus = false; fail("framework test bundle, update of bundle failed, version info unchanged :FRAME070A:Fail"); } if (teststatus == true ) { out.println("### framework test bundle :FRAME070A:PASS"); } else { fail("### framework test bundle :FRAME070A:FAIL"); } } } // 15. Uninstall a the testbundle B and then try to start and stop it // In both cases exceptions should be thrown. public final static String [] HELP_FRAME075A = { "Uninstall bundleB_test and the try to start and stop it.", "In both cases exceptions should be thrown." }; class Frame075a extends FWTestCase { public void runTest() throws Throwable { boolean teststatus = true; boolean exep1 = false; boolean exep2 = false; try { buB.uninstall(); } catch (BundleException be) { teststatus = false; fail("framework test bundle, uninstall of bundleB failed:" + be +" :FRAME075A:FAIL"); } catch (Exception e) { fail("framework test bundle, got unexpected exception " + e + " :FRAME075A:FAIL"); e.printStackTrace(); } try { buB.start(); } catch (BundleException be) { teststatus = false; fail("framework test bundle, got unexpected exception " + be + "at start :FRAME075A:FAIL"); } catch (IllegalStateException ise) { exep1 = true; // out.println("Got expected exception" + ise); } catch (SecurityException sec) { teststatus = false; fail("framework test bundle, got unexpected exception " + sec + " :FRAME075A:FAIL"); } catch (Exception e) { fail("framework test bundle, got unexpected exception " + e + " :FRAME075A:FAIL"); e.printStackTrace(); } try { buB.stop(); } catch (BundleException be) { teststatus = false; fail("framework test bundle, got unexpected exception " + be + "at stop :FRAME075A:FAIL"); } catch (IllegalStateException ise) { exep2 = true; // out.println("Got expected exception" + ise); } catch (SecurityException sec) { teststatus = false; fail("framework test bundle, got unexpected exception " + sec + " :FRAME075A:FAIL"); } catch (Exception e) { fail("framework test bundle, got unexpected exception " + e + " :FRAME075A:FAIL"); e.printStackTrace(); } // System.err.println("teststatus=" + teststatus + " exep1= " + exep1 + " exep2= " + exep2); teststatus = teststatus && exep1 && exep2; if (teststatus == true ) { out.println("### framework test bundle :FRAME075A:PASS"); } else { fail("### framework test bundle :FRAME075A:FAIL"); } } } // 16. Install and start testbundle F and then try to and stop it // In this case a bundeException is expected public final static String [] HELP_FRAME080A = { "Installs and starts bundleF_test and then try to and stop it.", "A BundleException is expected." }; class Frame080a extends FWTestCase { public void runTest() throws Throwable { boolean teststatus = true; boolean catchstatus = true; buF = null; try { buF = Util.installBundle(bc, "bundleF_test-1.0.0.jar"); } catch (BundleException bexcA) { fail("framework test bundle "+ bexcA +" :FRAME080A:FAIL"); teststatus = false; } catch (SecurityException secA) { fail("framework test bundle "+ secA +" :FRAME080A:FAIL"); teststatus = false; } Dictionary dict = buF.getHeaders("fr_CA"); if(!dict.get(Constants.BUNDLE_SYMBOLICNAME).equals("org.knopflerfish.bundle.bundleF_test")){ fail("framework test bundle, " + Constants.BUNDLE_SYMBOLICNAME + " header does not have correct value:FRAME080A:FAIL"); } if(!dict.get(Constants.BUNDLE_DESCRIPTION).equals("Test")){ fail("framework test bundle, " + Constants.BUNDLE_DESCRIPTION + " header does not have correct localized value:FRAME080A:FAIL"); } dict = buF.getHeaders("fr"); if(!dict.get(Constants.BUNDLE_DESCRIPTION).equals("Tezt")){ fail("framework test bundle, " + Constants.BUNDLE_DESCRIPTION + " header does not have correct localized value:FRAME080A:FAIL"); } // now start it try { buF.start(); } catch (BundleException bexcA) { fail("framework test bundle, unexpected exception "+ bexcA +" :FRAME080A:FAIL"); teststatus = false; bexcA.printStackTrace(); } catch (IllegalStateException ise) { fail("framework test bundle "+ ise +" :FRAME080A:FAIL"); teststatus = false; ise.printStackTrace(); } catch (SecurityException sec) { fail("framework test bundle "+ sec +" :FRAME080A:FAIL"); teststatus = false; sec.printStackTrace(); } // now for the test of a stop that should casue an exception ServiceReference sr1 = bc.getServiceReference("org.knopflerfish.service.bundleF_test.BundleF"); clearEvents (); try { buF.stop(); } catch (BundleException be) { Throwable t1 = be.getNestedException(); if (t1.getMessage().equals("BundleF stop")) { catchstatus = true; // out.println("Got expected exception" + be); } else { catchstatus = false; } } catch (IllegalStateException ise) { teststatus = false; fail("framework test bundle, got unexpected exception " + ise + "at stop :FRAME080A:FAIL"); } catch (SecurityException sec) { teststatus = false; fail("framework test bundle, got unexpected exception " + sec + " :FRAME080A:FAIL"); } catch (Exception e) { fail("framework test bundle, got unexpected exception " + e + " :FRAME080A:FAIL"); e.printStackTrace(); } // check the events, boolean lStat = checkListenerEvents(out, false, 0, true ,BundleEvent.STOPPED , true, ServiceEvent.UNREGISTERING, buF, sr1); // out.println("lStat = "+ lStat); if (catchstatus == false) { teststatus = false; } if (teststatus == true && lStat == true ) { out.println("### framework test bundle :FRAME080A:PASS"); } else { fail("### framework test bundle :FRAME080A:FAIL"); } } } // 17. Install and start testbundle H, a service factory and test that the methods // in that interface works. public final static String [] HELP_FRAME085A = { "Installs and starts bundleH_test, a service factory", "and tests that the methods in that API works." }; class Frame085a extends FWTestCase { public void runTest() throws Throwable { buH = null; boolean teststatus = true; try { buH = Util.installBundle(bc, "bundleH_test-1.0.0.jar"); buH.start(); teststatus = true; } catch (BundleException bexcA) { fail("framework test bundle "+ bexcA +" :FRAME085A:FAIL"); teststatus = false; } catch (SecurityException secA) { fail("framework test bundle "+ secA +" :FRAME085A:FAIL"); teststatus = false; } Dictionary dict = buH.getHeaders("en_US"); if(!dict.get(Constants.BUNDLE_SYMBOLICNAME).equals("org.knopflerfish.bundle.bundleH_test")){ fail("framework test bundle, " + Constants.BUNDLE_SYMBOLICNAME + " header does not have rightt value:FRAME085A:FAIL"); } if(!dict.get(Constants.BUNDLE_DESCRIPTION).equals("Test bundle for framework, bundleH_test")){ fail("framework test bundle, " + Constants.BUNDLE_DESCRIPTION + " header does not have rightt value:FRAME085A:FAIL"); } if(!dict.get(Constants.BUNDLE_NAME).equals("bundle_H")){ fail("framework test bundle, " + Constants.BUNDLE_NAME + " header does not have rightt value:FRAME085A:FAIL"); } if(!dict.get(Constants.BUNDLE_VERSION).equals("2.0.0")){ fail("framework test bundle, " + Constants.BUNDLE_VERSION + " header does not have right value:FRAME085A:FAIL"); } // Check that a service reference exist ServiceReference sr1 = bc.getServiceReference("org.knopflerfish.service.bundleH_test.BundleH"); if (sr1 == null) { fail("framework test bundle, no service from test bundle H found :FRAME085A:FAIL"); teststatus = false; } // check the listeners for events, expect only a bundle event, of type installation boolean lStat = checkListenerEvents(out, false , 0, true , BundleEvent.STARTED, true, ServiceEvent.REGISTERED, buH, sr1); // Object sf = bc.getService(sr1); // System.out.println("SERVICE = "+ sf); // Object sf1 = bc.getService(sr1); // System.out.println("SERVICE = "+ sf1); try { buH.stop(); } catch (BundleException bexp) { out.println("framework test bundle, exception in stop method :" + bexp + " FRAME085A"); teststatus = false; } catch (Throwable thr) { fail("framework test bundle, exception in stop method :" + thr + " :FRAME085A:Fail"); teststatus = false; } if (teststatus == true && buH.getState() == Bundle.RESOLVED && lStat == true) { out.println("### framework test bundle :FRAME085A:PASS"); } else { fail("### framework test bundle :FRAME085A:FAIL"); } } } // 22. Install testbundle J, which should throw an exception at start // then check if the framework removes all traces of the bundle // as it registers one service itself before the bundle exception is thrown public final static String [] HELP_FRAME110A = { "Install and start bundleJ_test, which should throw an exception at start.", "then check if the framework removes all traces of the bundle", "as it registers one service (itself) before the bundle exception is thrown" }; class Frame110a extends FWTestCase { public void runTest() throws Throwable { clearEvents(); buJ = null; boolean lStat1 = false; boolean teststatus = true; boolean bex = false; try { buJ = Util.installBundle(bc, "bundleJ_test-1.0.0.jar"); lStat1 = checkListenerEvents(out, false, 0, true, BundleEvent.INSTALLED, false, 0, buJ, null); buJ.start(); teststatus = false; } catch (BundleException bexcA) { out.println("framework test bundle "+ bexcA +" :FRAME110A:expexted"); bex = true; } catch (SecurityException secA) { teststatus = false; fail("framework test bundle "+ secA +" :FRAME110A:FAIL"); } if (bex != true ) { teststatus = false; fail("framework test bundle, expected bundle exception missing :FRAME110A"); } if(buJ == null) { fail("No installed bundle: :FRAME110A:FAIL"); } // check the listeners for events, expect only a bundle event, of type installation boolean lStat2 = checkListenerEvents(out, false , 0, true , BundleEvent.RESOLVED, true, ServiceEvent.UNREGISTERING, buJ, null); if (teststatus == true && buJ.getState() == Bundle.RESOLVED && lStat1 == true && lStat2 == true) { out.println("### framework test bundle :FRAME110A:PASS"); } else { fail("### framework test bundle :FRAME110A:FAIL"); } // Check that no service reference exist from the crashed bundle J. ServiceReference sr1 = bc.getServiceReference("org.knopflerfish.service.bundleJ_test.BundleJ"); if (sr1 != null) { fail("framework test bundle, service from test bundle J unexpectedly found :FRAME110A:FAIL"); } } } public final static String [] HELP_FRAME115A = { "Test getDataFile() method." }; class Frame115a extends FWTestCase { public void runTest() throws Throwable { boolean teststatus = true; String filename = "testfile_1"; byte [] testdata = {1,2,3,4,5}; File testFile = bc.getDataFile(filename); if (testFile != null ) { try { FileOutputStream fout = new FileOutputStream (testFile); fout.write(testdata); fout.close(); } catch (IOException ioe) { teststatus = false; fail("framework test bundle, I/O error on write in FRAME115A " + ioe); } try { FileInputStream fin = new FileInputStream (testFile); byte [] indata = new byte [5]; int incount; incount = fin.read(indata); fin.close(); if (incount == 5) { for (int i = 0; i< incount; i++ ) { if (indata[i] != testdata[i]) { teststatus = false; fail("framework test bundle FRAME115A, is " + indata [i] + ", should be " + testdata [i]); } } } else { teststatus = false; fail("framework test bundle, I/O data error in FRAME115A"); out.println("Should be 5 bytes, was " + incount ); } } catch (IOException ioe) { teststatus = false; fail("framework test bundle, I/O error on read in FRAME115A " + ioe); } } else { // nothing to test fail("framework test bundle, no persistent data storage FRAME115A"); teststatus = true; } // Remove testfile_1 testFile.delete(); if (teststatus == true) { out.println("### framework test bundle :FRAME115A:PASS"); } else { fail("### framework test bundle :FRAME115A:FAIL"); } } } // 24. Test of the AdminPermission class public final static String [] HELP_FRAME120A = { "Test of the AdminPermission class" }; class Frame120a extends FWTestCase { public void runTest() throws Throwable { boolean teststatus = true; String s1 = null; String s2 = null; AdminPermission ap1 = new AdminPermission(); AdminPermission ap2 = null; SocketPermission sp1 = new SocketPermission("localhost:6666","listen"); // to test of cats among hermelins Object testObject = new Object(); // constructor and getName method check if (!ap1.getName().equals("*")) { out.println("framework test bundle, Name of AdminPermission object is " + ap1.getName() + " in FRAME120A"); fail("framework test bundle, Name of AdminPermission object should be: AdminPermission"); teststatus = false; } //this is no longer valid! try { ap2 = new AdminPermission(s1,s2); } catch (Exception e) { fail("framework test bundle, constructor with two null strings failed in FRAME120A"); teststatus = false; } if (ap2 != null && !ap2.getName().equals("AdminPermission")) { out.println("framework test bundle, Name of AdminPermission object is " + ap2.getName() + " in FRAME120A"); out.println("framework test bundle, Name of AdminPermission object should be: AdminPermission"); teststatus = false; } // implies method check AdminPermission ap3 = new AdminPermission(); if (!ap1.implies(ap3)) { out.println("framework test bundle, implies method failed, returned "+ ap1.implies(ap3) + " should have been true, FRAME120A"); teststatus = false; } if (ap1.implies(sp1)) { out.println("framework test bundle, implies method failed, returned "+ ap1.implies(sp1) + " should have been false, FRAME120A"); teststatus = false; } // equals method check if (!ap1.equals(ap2)) { out.println("framework test bundle, equals method failed, returned "+ ap1.equals(ap2) + " should have been true, FRAME120A"); teststatus = false; } if (ap1.equals(sp1)) { out.println("framework test bundle, equals method failed, returned "+ ap1.equals(sp1) + " should have been false, FRAME120A"); teststatus = false; } // newPermissionCollection method check, also check the implemented // abstract methods of the PermissionCollection PermissionCollection pc1 = ap1.newPermissionCollection(); if (pc1 != null) { pc1.add (ap1); boolean trig = false; try { // add a permission that is not an AdminPermission pc1.add (sp1); trig = true; } catch (RuntimeException ex1) { trig = false; } if (trig == true) { out.println("framework test bundle, add method on PermissionCollection failed, FRAME120A"); out.println("permission with type different from AdminPermission succeded unexpectedly FRAME120A"); teststatus = false; } pc1.add (ap2); if (!pc1.implies(ap3)) { out.println("framework test bundle, implies method on PermissionCollection failed, FRAME120A"); teststatus = false; } boolean hit1 = false; int count = 0; /* The enumeration of this kind of permission is a bit weird as it actually returns a new AdminPermission if an element has been added, thus the test becomes a bit odd. This comes from looking at the source code, i.e a bit of peeking behind the screens but in this case it was necessary as the functionality is not possible to understand otherwise. */ for (Enumeration e = pc1.elements(); e.hasMoreElements(); ) { AdminPermission ap4 = (AdminPermission) e.nextElement(); // out.println("DEBUG framework test bundle, got AdminPermission " + ap4 +" FRAME120A"); count++; if (ap4 != null) { hit1 = true;} } if (hit1 != true || count != 1) { teststatus = false; out.println("framework test bundle, elements method on PermissionCollection failed, FRAME120A"); if (hit1 != true) { out.println("framework test bundle, no AdminPermission retrieved, FRAME120A"); } if (count != 1) { out.println("framework test bundle, number of entered objects: 1, number retrieved: " + count + " , FRAME120A"); } } if (pc1.isReadOnly() == true) { teststatus = false; out.println("framework test bundle, isReadOnly method on PermissionCollection is: "+pc1.isReadOnly() +" should be false, FRAME120A"); } pc1.setReadOnly(); if (pc1.isReadOnly() == false) { teststatus = false; out.println("framework test bundle, isReadOnly method on PermissionCollection is: "+pc1.isReadOnly() +" should be true, FRAME120A"); } } else { out.println("framework test bundle, newPermissionCollection method failed, returned null, FRAME120A"); teststatus = false; } if (teststatus == true) { out.println("### framework test bundle :FRAME120A:PASS"); } else { fail("### framework test bundle :FRAME120A:FAIL"); } } } // 25. Test of the PackagePermission class public final static String [] HELP_FRAME125A = { "Test of the PackagePermission class" }; class Frame125a extends FWTestCase { public void runTest() throws Throwable { boolean teststatus = true; String validName = "valid.name.test"; String validName1 = "valid.name.test1"; String validName2 = "valid.name.test2"; String invalidName = null; String validAction = PackagePermission.EXPORT+","+PackagePermission.IMPORT; String invalidAction = "apa"; PackagePermission pp1 = null; PackagePermission pp2 = null; PackagePermission pp3 = null; PackagePermission pp4 = null; // constructor check try { pp1 = new PackagePermission(validName,validAction); } catch (RuntimeException re) { out.println("framework test bundle, PackagePermission constructor("+ validName +"," + validAction + ") failed, in FRAME125A"); teststatus = false; } try { pp1 = new PackagePermission(invalidName,validAction); out.println("framework test bundle, PackagePermission constructor("+ invalidName +"," + validAction + ") succeded unexpected, in FRAME125A"); teststatus = false; } catch (RuntimeException re) { } try { pp1 = new PackagePermission(validName,invalidAction); out.println("framework test bundle, PackagePermission constructor("+ validName +"," + invalidAction + ") succeded unexpected, in FRAME125A"); teststatus = false; } catch (RuntimeException re) { } try { pp1 = new PackagePermission(invalidName,invalidAction); out.println("framework test bundle, PackagePermission constructor("+ invalidName +"," + invalidAction + ") succeded unexpected, in FRAME125A"); teststatus = false; } catch (RuntimeException re) { } // equals test pp1 = new PackagePermission(validName,validAction); pp2 = new PackagePermission(validName,validAction); if (!pp1.equals(pp2)) { out.println("framework test bundle, PackagePermission equals method failed for identical objects, in FRAME125A"); teststatus = false; } pp3 = new PackagePermission(validName,PackagePermission.IMPORT); if (pp1.equals(pp3)) { out.println("framework test bundle, PackagePermission equals method failed for non identical objects, in FRAME125A"); teststatus = false; } pp3 = new PackagePermission(validName2,validAction); if (pp1.equals(pp3)) { out.println("framework test bundle, PackagePermission equals method failed for non identical objects, in FRAME125A"); teststatus = false; } // getActions test pp1 = new PackagePermission(validName,PackagePermission.IMPORT); pp2 = new PackagePermission(validName,PackagePermission.EXPORT); pp3 = new PackagePermission(validName,PackagePermission.IMPORT+","+PackagePermission.EXPORT); pp4 = new PackagePermission(validName,PackagePermission.EXPORT+","+PackagePermission.IMPORT); if (!pp1.getActions().equals(PackagePermission.IMPORT)) { out.println("framework test bundle, PackagePermission getActions method failed in FRAME125A"); out.println("framework test bundle, expected: "+PackagePermission.IMPORT); out.println("framework test bundle, got:" + pp1.getActions()); teststatus = false; } if (!pp2.getActions().equals(PackagePermission.EXPORT+","+PackagePermission.IMPORT)) { out.println("framework test bundle, PackagePermission getActions method failed in FRAME125A"); out.println("framework test bundle, expected: "+PackagePermission.EXPORT); out.println("framework test bundle, got:" + pp2.getActions()); teststatus = false; } if (!pp3.getActions().equals(PackagePermission.EXPORT+","+PackagePermission.IMPORT)) { out.println("framework test bundle, PackagePermission getActions method failed in FRAME125A"); out.println("framework test bundle, expected: "+PackagePermission.EXPORT +","+PackagePermission.IMPORT); out.println("framework test bundle, got:" + pp3.getActions()); teststatus = false; } if (!pp4.getActions().equals(PackagePermission.EXPORT+","+PackagePermission.IMPORT)) { out.println("framework test bundle, PackagePermission getActions method failed in FRAME125A"); out.println("framework test bundle, expected: "+PackagePermission.EXPORT +","+PackagePermission.IMPORT); out.println("framework test bundle, got:" + pp4.getActions()); teststatus = false; } // implies test boolean impstatus = true; pp1 = new PackagePermission(validName,PackagePermission.IMPORT); pp2 = new PackagePermission(validName,PackagePermission.EXPORT); impstatus = impstatus && implyCheck (out, true, pp2, pp1); // export implies import impstatus = impstatus && implyCheck (out, false, pp1, pp2); // import does not imply export pp1 = new PackagePermission("test1.*",PackagePermission.EXPORT); pp2 = new PackagePermission("test2.*",PackagePermission.EXPORT); impstatus = impstatus && implyCheck (out, false, pp2, pp1); // different packet names, implication = false impstatus = impstatus && implyCheck (out, false, pp1, pp2); // different packet names, implication = false pp1 = new PackagePermission("test1.*",PackagePermission.EXPORT); pp2 = new PackagePermission("test1.a", PackagePermission.EXPORT); impstatus = impstatus && implyCheck (out, false, pp2, pp1); // test1.a does not imply test1.*, implication = false impstatus = impstatus && implyCheck (out, true, pp1, pp2); // test1.* implies test1.a, implication = true pp1 = new PackagePermission("test1.*",PackagePermission.EXPORT); pp2 = new PackagePermission("test1.a",PackagePermission.IMPORT); pp3 = new PackagePermission("test1.*",PackagePermission.IMPORT); pp4 = new PackagePermission("test1.a",PackagePermission.EXPORT); impstatus = impstatus && implyCheck (out, true, pp1, pp1); // test1.* & export implies test1.* & export, implication = true impstatus = impstatus && implyCheck (out, true, pp1, pp2); // test1.* & export implies test1.a & import, implication = true impstatus = impstatus && implyCheck (out, true, pp1, pp3); // test1.* & export implies test1.* & import, implication = true impstatus = impstatus && implyCheck (out, true, pp1, pp4); // test1.* & export implies test1.a & export, implication = true impstatus = impstatus && implyCheck (out, false, pp2, pp1); // test1.a & import does not imply test1.* & export, implication = false impstatus = impstatus && implyCheck (out, true, pp2, pp2); // test1.a & import implies test1.a & import, implication = true impstatus = impstatus && implyCheck (out, false, pp2, pp3); // test1.a & import does not imply test1.* & import, implication = false impstatus = impstatus && implyCheck (out, false, pp2, pp4); // test1.a & import does not imply test1.a & export, implication = false impstatus = impstatus && implyCheck (out, false, pp3, pp1); // test1.* & import does not imply test1.* & export, implication = false impstatus = impstatus && implyCheck (out, true, pp3, pp2); // test1.* & import implies test1.a & import, implication = true impstatus = impstatus && implyCheck (out, true, pp3, pp3); // test1.* & import implies test1.* & import, implication = true impstatus = impstatus && implyCheck (out, false, pp3, pp4); // test1.* & import does not imply test1.a & export, implication = false impstatus = impstatus && implyCheck (out, false, pp4, pp1); // test1.a & export does not imply test1.* & export, implication = false impstatus = impstatus && implyCheck (out, true, pp4, pp2); // test1.a & export implies test1.a & import, implication = true impstatus = impstatus && implyCheck (out, false, pp4, pp3); // test1.a & export does not imply test1.* & import, implication = false impstatus = impstatus && implyCheck (out, true, pp4, pp4); // test1.a & export implies test1.a & export, implication = true // newPermissionCollection tests PackagePermission pp5 = new PackagePermission("test1.*",PackagePermission.EXPORT); PackagePermission pp6 = new PackagePermission("test1.a",PackagePermission.IMPORT); PackagePermission pp7 = new PackagePermission("test2.*",PackagePermission.IMPORT); PackagePermission pp8 = new PackagePermission("test2.a",PackagePermission.EXPORT); PackagePermission pp9 = new PackagePermission("test3.a",PackagePermission.EXPORT); PermissionCollection pc1 = pp5.newPermissionCollection(); if (pc1 != null) { int count = 0; boolean b1 = false; boolean b2 = false; boolean b3 = false; boolean b4 = false; try { pc1.add(pp5); pc1.add(pp6); pc1.add(pp7); pc1.add(pp8); for (Enumeration e = pc1.elements(); e.hasMoreElements(); ) { PackagePermission ptmp = (PackagePermission) e.nextElement(); // out.println("DEBUG framework test bundle, got AdminPermission " + ptmp +" FRAME125A"); count++; if (ptmp == pp5) { b1 = true;} if (ptmp == pp6) { b2 = true;} if (ptmp == pp7) { b3 = true;} if (ptmp == pp8) { b4 = true;} } if (count != 4 || b1 != true || b2 != true || b3 != true || b4 != true) { teststatus = false; out.println("framework test bundle, elements method on PermissionCollection failed, FRAME125A"); if (count != 4) { out.println("framework test bundle, number of entered PackagePermissions: 4, number retrieved: " + count + " , FRAME125A"); } } boolean ipcstat = true; ipcstat = ipcstat && implyCheck (out, true, pc1, pp5); // test1.* & export implies test1.* & export, implication = true ipcstat = ipcstat && implyCheck (out, false, pc1, pp9); // test1.* & export does not imply test3.a & export, implication = false if (ipcstat != true) { teststatus = false; } } catch (Throwable ex) { out.println("DEBUG framework test bundle, Exception " + ex); ex.printStackTrace(); ex.printStackTrace(out); } } else { // teststatus = false; out.println("framework test bundle, newPermissionsCollection method on PackagePermission returned null,FRAME125A"); } if (teststatus == true && impstatus == true) { out.println("### framework test bundle :FRAME125A:PASS"); } else { fail("### framework test bundle :FRAME125A:FAIL"); } } } // 26. Test of the ServicePermission class public final static String [] HELP_FRAME130A = { "Test of the ServicePermission class" }; class Frame130a extends FWTestCase { public void runTest() throws Throwable { boolean teststatus = true; String validClass = "valid.class.name"; String validClass1 = "valid.class.name.1"; String validClass2 = "valid.class.name.2"; String invalidClass = null; String validAction = ServicePermission.GET+","+ServicePermission.REGISTER; String invalidAction = "skunk"; ServicePermission sp1 = null; ServicePermission sp2 = null; ServicePermission sp3 = null; ServicePermission sp4 = null; ServicePermission sp5 = null; ServicePermission sp6 = null; ServicePermission sp7 = null; ServicePermission sp8 = null; // constructor check try { sp1 = new ServicePermission (validClass,validAction); } catch (RuntimeException re) { out.println("framework test bundle, ServicePermission constructor("+ validClass +"," + validAction + ") failed, in FRAME130A"); teststatus = false; } try { sp1 = new ServicePermission(invalidClass,validAction); out.println("framework test bundle, ServicePermission constructor("+ invalidClass +"," + validAction + ") succeded unexpected, in FRAME130A"); teststatus = false; } catch (RuntimeException re) { } try { sp1 = new ServicePermission(validClass,invalidAction); out.println("framework test bundle, ServicePermission constructor("+ validClass +"," + invalidAction + ") succeded unexpected, in FRAME130A"); teststatus = false; } catch (RuntimeException re) { } try { sp1 = new ServicePermission(invalidClass,invalidAction); out.println("framework test bundle, ServicePermission constructor("+ invalidClass +"," + invalidAction + ") succeded unexpected, in FRAME130A"); teststatus = false; } catch (RuntimeException re) { } // equals test sp1 = new ServicePermission(validClass,validAction); sp2 = new ServicePermission(validClass,validAction); if (!sp1.equals(sp2)) { out.println("framework test bundle, ServicePermission equals method failed for identical objects, in FRAME130A"); teststatus = false; } sp3 = new ServicePermission(validClass,ServicePermission.GET); if (sp1.equals(sp3)) { out.println("framework test bundle, ServicePermission equals method failed for non identical objects, in FRAME130A"); teststatus = false; } sp3 = new ServicePermission(validClass2,validAction); if (sp1.equals(sp3)) { out.println("framework test bundle, ServicePermission equals method failed for non identical objects, in FRAME130A"); teststatus = false; } // getActions test sp1 = new ServicePermission(validClass,ServicePermission.GET); sp2 = new ServicePermission(validClass,ServicePermission.REGISTER); sp3 = new ServicePermission(validClass,ServicePermission.GET+","+ServicePermission.REGISTER); sp4 = new ServicePermission(validClass,ServicePermission.REGISTER+","+ServicePermission.GET); if (!sp1.getActions().equals(ServicePermission.GET)) { out.println("framework test bundle, ServicePermission getActions method failed in FRAME130A"); out.println("framework test bundle, expected: "+ServicePermission.GET); out.println("framework test bundle, got: " + sp1.getActions()); teststatus = false; } if (!sp2.getActions().equals(ServicePermission.REGISTER)) { out.println("framework test bundle, ServicePermission getActions method failed in FRAME130A"); out.println("framework test bundle, expected: "+ServicePermission.REGISTER); out.println("framework test bundle, got: " + sp2.getActions()); teststatus = false; } if (!sp3.getActions().equals(ServicePermission.GET+","+ServicePermission.REGISTER)) { out.println("framework test bundle, ServicePermission getActions method failed in FRAME130A"); out.println("framework test bundle, expected: "+ServicePermission.GET +","+ServicePermission.REGISTER); out.println("framework test bundle, got: " + sp3.getActions()); teststatus = false; } if (!sp4.getActions().equals(ServicePermission.GET+","+ServicePermission.REGISTER)) { out.println("framework test bundle, ServicePermission getActions method failed in FRAME130A"); out.println("framework test bundle, expected: "+ServicePermission.GET +","+ServicePermission.REGISTER); out.println("framework test bundle, got: " + sp4.getActions()); teststatus = false; } // implies test boolean impstatus = true; sp1 = new ServicePermission(validClass,ServicePermission.GET); sp2 = new ServicePermission(validClass,ServicePermission.REGISTER); impstatus = impstatus && implyCheck (out, false, sp2, sp1); // get does not imply register impstatus = impstatus && implyCheck (out, false, sp1, sp2); // register does not imply get sp1 = new ServicePermission("validClass1.*", ServicePermission.REGISTER+","+ServicePermission.GET); sp2 = new ServicePermission("validClass2.*", ServicePermission.REGISTER+","+ServicePermission.GET); impstatus = impstatus && implyCheck (out, false, sp2, sp1); // different class names, implication = false impstatus = impstatus && implyCheck (out, false, sp1, sp2); // different class names, implication = false sp1 = new ServicePermission("validClass1.*", ServicePermission.REGISTER+","+ServicePermission.GET); sp2 = new ServicePermission("validClass1.a", ServicePermission.REGISTER+","+ServicePermission.GET); impstatus = impstatus && implyCheck (out, false, sp2, sp1); // validClass1.a does not imply validClass1.*, implication = false impstatus = impstatus && implyCheck (out, true, sp1, sp2); // validClass1.* implies validClass1.a, implication = true sp1 = new ServicePermission("test1.*",ServicePermission.REGISTER); sp2 = new ServicePermission("test1.*",ServicePermission.GET); sp3 = new ServicePermission("test1.*",ServicePermission.REGISTER+","+ServicePermission.GET); sp4 = new ServicePermission("test1.a",ServicePermission.REGISTER); sp5 = new ServicePermission("test1.a",ServicePermission.GET); sp6 = new ServicePermission("test1.a",ServicePermission.REGISTER+","+ServicePermission.GET); impstatus = impstatus && implyCheck (out, true, sp1, sp1); // test1.* & register implies test1.* & register, impstatus = impstatus && implyCheck (out, false, sp1, sp2); // test1.* & register implies not test1.* & get, impstatus = impstatus && implyCheck (out, false, sp1, sp3); // test1.* & register implies not test1.* & reg & get, impstatus = impstatus && implyCheck (out, true, sp1, sp4); // test1.* & register implies test1.a & register, impstatus = impstatus && implyCheck (out, false, sp1, sp5); // test1.* & register implies not test1.a & get, impstatus = impstatus && implyCheck (out, false, sp1, sp6); // test1.* & register implies not test1.a & reg & g, impstatus = impstatus && implyCheck (out, false, sp2, sp1); // test1.* & get implies not test1.* & register, impstatus = impstatus && implyCheck (out, true, sp2, sp2); // test1.* & get implies test1.* & get, impstatus = impstatus && implyCheck (out, false, sp2, sp3); // test1.* & get implies not test1.* & reg & get, impstatus = impstatus && implyCheck (out, false, sp2, sp4); // test1.* & get implies test1.a & register, impstatus = impstatus && implyCheck (out, true, sp2, sp5); // test1.* & get implies test1.a & get, impstatus = impstatus && implyCheck (out, false, sp2, sp6); // test1.* & get implies not test1.a & reg & g, impstatus = impstatus && implyCheck (out, true, sp3, sp1); // test1.* & get&reg implies test1.* & register, impstatus = impstatus && implyCheck (out, true, sp3, sp2); // test1.* & get&reg implies test1.* & get, impstatus = impstatus && implyCheck (out, true, sp3, sp3); // test1.* & get&reg implies test1.* & reg & get, impstatus = impstatus && implyCheck (out, true, sp3, sp4); // test1.* & get&reg implies test1.a & register, impstatus = impstatus && implyCheck (out, true, sp3, sp5); // test1.* & get&reg implies test1.a & get, impstatus = impstatus && implyCheck (out, true, sp3, sp6); // test1.* & get&reg implies test1.a & reg & g, impstatus = impstatus && implyCheck (out, false, sp4, sp1); // test1.a & reg implies not test1.* & register, impstatus = impstatus && implyCheck (out, false, sp4, sp2); // test1.a & reg implies not test1.* & get, impstatus = impstatus && implyCheck (out, false, sp4, sp3); // test1.a & reg implies not test1.* & reg & get, impstatus = impstatus && implyCheck (out, true, sp4, sp4); // test1.a & reg implies test1.a & register, impstatus = impstatus && implyCheck (out, false, sp4, sp5); // test1.a & reg implies not test1.a & get, impstatus = impstatus && implyCheck (out, false, sp4, sp6); // test1.a & reg implies not test1.a & reg & g, impstatus = impstatus && implyCheck (out, false, sp5, sp1); // test1.a & get implies not test1.* & register, impstatus = impstatus && implyCheck (out, false, sp5, sp2); // test1.a & get implies not test1.* & get, impstatus = impstatus && implyCheck (out, false, sp5, sp3); // test1.a & get implies not test1.* & reg & get, impstatus = impstatus && implyCheck (out, false, sp5, sp4); // test1.a & get implies not test1.a & register, impstatus = impstatus && implyCheck (out, true, sp5, sp5); // test1.a & get implies test1.a & get, impstatus = impstatus && implyCheck (out, false, sp5, sp6); // test1.a & get implies not test1.a & reg & g, impstatus = impstatus && implyCheck (out, false, sp6, sp1); // test1.a & get & reg implies not test1.* & register, impstatus = impstatus && implyCheck (out, false, sp6, sp2); // test1.a & get & reg implies not test1.* & get, impstatus = impstatus && implyCheck (out, false, sp6, sp3); // test1.a & get & reg implies not test1.* & reg & get, impstatus = impstatus && implyCheck (out, true, sp6, sp4); // test1.a & get & reg implies test1.a & register, impstatus = impstatus && implyCheck (out, true, sp6, sp5); // test1.a & get & reg implies test1.a & get, impstatus = impstatus && implyCheck (out, true, sp6, sp6); // test1.a & get & reg implies test1.a & reg & g, sp7 = new ServicePermission("test2.a",ServicePermission.REGISTER+","+ServicePermission.GET); sp8 = new ServicePermission("*",ServicePermission.REGISTER+","+ServicePermission.GET); impstatus = impstatus && implyCheck (out, false, sp7, sp1); // test2.a & get & reg implies not test1.* & register, impstatus = impstatus && implyCheck (out, false, sp7, sp2); // test2.a & get & reg implies not test1.* & get, impstatus = impstatus && implyCheck (out, false, sp7, sp3); // test2.a & get & reg implies not test1.* & reg & get, impstatus = impstatus && implyCheck (out, false, sp7, sp4); // test2.a & get & reg implies not test1.a & register, impstatus = impstatus && implyCheck (out, false, sp7, sp5); // test2.a & get & reg implies not test1.a & get, impstatus = impstatus && implyCheck (out, false, sp7, sp6); // test2.a & get & reg implies not test1.a & reg & g, impstatus = impstatus && implyCheck (out, true, sp8, sp1); // * & get & reg implies test1.* & register, impstatus = impstatus && implyCheck (out, true, sp8, sp2); // * & get & reg implies test1.* & get, impstatus = impstatus && implyCheck (out, true, sp8, sp3); // * & get & reg implies test1.* & reg & get, impstatus = impstatus && implyCheck (out, true, sp8, sp4); // * & get & reg implies test1.a & register, impstatus = impstatus && implyCheck (out, true, sp8, sp5); // * & get & reg implies test1.a & get, impstatus = impstatus && implyCheck (out, true, sp8, sp6); // * & get & reg implies test1.a & reg & g, PermissionCollection pc1 = sp1.newPermissionCollection(); if (pc1 != null) { int count = 0; boolean b1 = false; boolean b2 = false; boolean b3 = false; boolean b4 = false; try { pc1.add(sp1); pc1.add(sp2); pc1.add(sp3); pc1.add(sp4); // the combination of these four servicepermissions should create // a servicecollection that implies the following boolean ipcstat = true; ipcstat = ipcstat && implyCheck (out, true, pc1, sp1); // permission is in collection ipcstat = ipcstat && implyCheck (out, true, pc1, sp2); // permission is in collection ipcstat = ipcstat && implyCheck (out, true, pc1, sp3); // permission is in collection ipcstat = ipcstat && implyCheck (out, true, pc1, sp4); // permission is in collection ipcstat = ipcstat && implyCheck (out, true, pc1, sp5); // permission is in collection ipcstat = ipcstat && implyCheck (out, false, pc1, sp7); // permission is not in collection if (ipcstat != true) { teststatus = false; } } catch (Throwable ex) { out.println("DEBUG framework test bundle, Exception " + ex); ex.printStackTrace(); ex.printStackTrace(out); } } else { // teststatus = false; out.println("framework test bundle, newPermissionsCollection method on ServicePermission returned null,FRAME130A"); } if (teststatus == true && impstatus == true) { out.println("### framework test bundle :FRAME130A:PASS"); } else { out.println("### framework test bundle :FRAME130A:FAIL"); } } } public final static String [] HELP_FRAME160A = { "Test bundle resource retrieval." }; class Frame160a extends FWTestCase { public void runTest() throws Throwable { boolean pass = true; Bundle buR = null; Bundle buR1 = null; try { try { buR = Util.installBundle(bc, "bundleR_test-1.0.0.jar"); } catch (BundleException e) { out.println("Failed install R: " + e.getNestedException() + ", in FRAME160A"); pass = false; } try { buR1 = Util.installBundle(bc, "bundleR1_test-1.0.0.jar"); } catch (BundleException e) { pass = false; fail("Failed install R1: " + e.getNestedException() + ", in FRAME160A:FAIL"); } try { buR.start(); } catch (BundleException e) { e.getNestedException().printStackTrace(out); pass = false; fail("Failed start of R in FRAME160A:FAIL"); } if (pass == true) { out.println("### framework test bundle :FRAME160A:PASS"); } else { fail("### framework test bundle :FRAME160A:FAIL"); } } finally { if (buR != null) { try { buR.uninstall(); } catch (BundleException ignore) { } } if (buR1 != null) { try { buR1.uninstall(); } catch (BundleException ignore) { } } } } } public final static String [] HELP_FRAME161A = { "Test bundle resource retrieval from boot class path; " +" a resource in-side the java package." }; class Frame161a extends FWTestCase { public void runTest() throws Throwable { boolean pass = true; String resourceName = "java/lang/Thread.class"; URL url1 = bc.getBundle().getResource(resourceName); URL url2 = this.getClass().getClassLoader().getResource(resourceName); //System.out.println("URL from bundle.getResource() = "+url1); //System.out.println("URL from classLoader.getResource() = "+url2); // Bundle.getResource() as well as ClassLoader.getResource() // should return resources according to the class space // (classpath), i.e., delegate to parent class loader before // searching its own paths. assertNotNull("bundle.getResource(\"" +resourceName+"\")" , url1); assertNotNull("bundleClassLoader.getResource(\""+resourceName+"\")",url2); assertEquals("Same URL returned from booth classloader and bundle", url1,url2); if (pass == true) { out.println("### framework test bundle :FRAME161A:PASS"); } else { fail("### framework test bundle :FRAME161A:FAIL"); } } } public final static String [] HELP_FRAME162A = { "Test bundle resource retrieval from boot class path; " +" a resource outside the java package." }; class Frame162a extends FWTestCase { public void runTest() throws Throwable { boolean pass = true; // The Any class have been present since 1.2 String resourceName = "org/omg/CORBA/Any.class"; URL url1 = bc.getBundle().getResource(resourceName); URL url2 = this.getClass().getClassLoader().getResource(resourceName); //System.out.println("URL from bundle.getResource() = "+url1); //System.out.println("URL from classLoader.getResource() = "+url2); // Bundle.getResource() and BundleClassLoader.getResource() // should both return resources according to the class space // (classpath), i.e., don't delgate to parent in this case since // the resource does not belong to the java-package. assertNull("bundle.getResource(\"" +resourceName+"\")" , url1); assertNull("bundleClassLoader.getResource(\""+resourceName+"\")",url2); if (pass == true) { out.println("### framework test bundle :FRAME162A:PASS"); } else { fail("### framework test bundle :FRAME162A:FAIL"); } } } public final static String [] HELP_FRAME163A = { "Test bundle resource retrieval from boot class path; " +" a resource via boot delegation." }; class Frame163a extends FWTestCase { public void runTest() throws Throwable { boolean pass = true; // The Context class have been present in Java SE since 1.3 String resourceName = "javax/naming/Context.class"; URL url1 = bc.getBundle().getResource(resourceName); URL url2 = this.getClass().getClassLoader().getResource(resourceName); //System.out.println("URL from bundle.getResource() = "+url1); //System.out.println("URL from classLoader.getResource() = "+url2); // Bundle.getResource() as well as ClassLoader.getResource() // should return resources according to the class space // (classpath), i.e., delegate to parent class loader before // searching its own paths. assertNotNull("bundle.getResource(\"" +resourceName+"\")" , url1); assertNotNull("bundleClassLoader.getResource(\""+resourceName+"\")",url2); assertEquals("Same URL returned from booth classloader and bundle", url1,url2); if (pass == true) { out.println("### framework test bundle :FRAME163A:PASS"); } else { fail("### framework test bundle :FRAME163A:FAIL"); } } } boolean callReturned; Integer doneSyncListener; String errorFrame170; public final static String [] HELP_FRAME170A = { "Test of ServiceReference.getUsingBundles() and SynchronousBundleListener." }; class Frame170a extends FWTestCase { public void runTest() throws Throwable { ServiceRegistration tsr = null; Bundle buQ = null; Bundle buQ1 = null; try { boolean pass = true; // Make sure that there are no pending BundleListener calls. try { Thread.sleep(500); } catch (InterruptedException ignore) {} BundleListener bl1 = new BundleListener() { public void bundleChanged(BundleEvent be) { if (doneSyncListener.intValue() == 0) { errorFrame170 = "Called BundleListener before SBL"; } synchronized (doneSyncListener) { doneSyncListener = new Integer(doneSyncListener.intValue() + 1); } } }; bc.addBundleListener(bl1); SynchronousBundleListener bl2 = new SynchronousBundleListener() { public void bundleChanged(BundleEvent be) { if (callReturned) { errorFrame170 = "Returned from bundle operation before SBL was done"; } else { try { Thread.sleep(1000); } catch (InterruptedException ignore) {} if (callReturned) { errorFrame170 = "Returned from bundle operation before SBL was done"; } } synchronized (doneSyncListener) { doneSyncListener = new Integer(doneSyncListener.intValue() + 1); } } }; bc.addBundleListener(bl2); BundleListener bl3 = new BundleListener() { public void bundleChanged(BundleEvent be) { if (doneSyncListener.intValue() == 0) { errorFrame170 = "Called BundleListener before SBL"; } synchronized (doneSyncListener) { doneSyncListener = new Integer(doneSyncListener.intValue() + 1); } } }; bc.addBundleListener(bl3); doneSyncListener = new Integer(0); callReturned = false; errorFrame170 = null; try { buQ = Util.installBundle(bc, "bundleQ_test-1.0.0.jar"); callReturned = true; try { Thread.sleep(1000); } catch (InterruptedException ignore) {} if (errorFrame170 != null) { out.println(errorFrame170 + ", in FRAME170A"); pass = false; } if (doneSyncListener.intValue() != 3) { out.println("Failed to call all bundleListeners (only " + doneSyncListener + "), in FRAME170A"); pass = false; } } catch (BundleException e) { out.println("Failed install Q: " + e.getNestedException() + ", in FRAME170A"); pass = false; } bc.removeBundleListener(bl1); bc.removeBundleListener(bl2); bc.removeBundleListener(bl3); try { buQ1 = bc.installBundle("Q1", bc.getBundle().getResource("bundleQ_test-1.0.0.jar").openStream()); } catch (BundleException e) { pass = false; fail("Failed install Q1: " + e.getNestedException() + ", in FRAME170A:FAIL"); } catch (IOException e) { pass = false; fail("Failed to open Q1 url: " + e + ", in FRAME170A:FAIL"); } Hashtable props = new Hashtable(); props.put("bundleQ", "secret"); try { tsr = bc.registerService ("java.lang.Object", this, props); } catch (Exception e) { fail("Failed to register service in FRAME170A:FAIL"); } if (tsr.getReference().getUsingBundles() != null) { pass = false; String ids = "" + tsr.getReference().getUsingBundles()[0].getBundleId(); for (int i=1; i<tsr.getReference().getUsingBundles().length; i++) { ids += "," + tsr.getReference().getUsingBundles()[i].getBundleId(); } fail("Unknown bundle (" + ids + ") using service in FRAME170A:FAIL"); } try { buQ.start(); } catch (BundleException e) { e.getNestedException().printStackTrace(out); pass = false; fail("Failed start of Q in FRAME170A:FAIL"); } Bundle[] bs = tsr.getReference().getUsingBundles(); if (bs.length != 1) { pass = false; fail("Wrong number (" + bs.length + " not 1) of bundles using service in FRAME170A:FAIL"); } else if (bs[0] != buQ) { pass = false; fail("Unknown bundle using service instead of bundle Q in FRAME170A:FAIL"); } try { buQ1.start(); } catch (BundleException e) { e.getNestedException().printStackTrace(out); pass = false; fail("Failed start of Q1 in FRAME170A:FAIL"); } bs = tsr.getReference().getUsingBundles(); if (bs.length != 2) { pass = false; fail("Wrong number (" + bs.length + " not 2) of bundles using service in FRAME170A:FAIL"); } else if ((bs[0] != buQ || bs[1] != buQ1) && (bs[1] != buQ || bs[0] != buQ1)) { pass = false; fail("Unknown bundle using service instead of bundle Q and Q1 in FRAME170A:FAIL"); } try { buQ.stop(); } catch (BundleException e) { e.getNestedException().printStackTrace(out); pass = false; fail("Failed stop of Q in FRAME170A:FAIL"); } bs = tsr.getReference().getUsingBundles(); if (bs.length != 1) { pass = false; fail("After stop wrong number (" + bs.length + " not 1) of bundles using service in FRAME170A:FAIL"); } else if (bs[0] != buQ1) { pass = false; fail("Unknown bundle using service instead of bundle Q1 in FRAME170A:FAIL"); } // Check that we haven't called any bundle listeners if (doneSyncListener.intValue() != 3) { pass = false; fail("Called bundle listeners after removal (" + doneSyncListener + "), in FRAME170A:FAIL"); } if (pass == true) { out.println("### framework test bundle :FRAME170A:PASS"); } else { fail("### framework test bundle :FRAME170A:FAIL"); } } finally { // clean up if (tsr != null) { tsr.unregister(); } try { buQ.uninstall(); } catch (BundleException ignore) { } try { buQ1.uninstall(); } catch (BundleException ignore) { } } } } // 175A. Resource integrity when reading different resources of a bundle public final static String [] HELP_FRAME175A = { "Check of resource integrity when using intermixed reading of differenent resources from bundleR2_test." }; class Frame175a extends FWTestCase { public void runTest() throws Throwable { buR2 = null; boolean teststatus = true; try { buR2 = Util.installBundle(bc, "bundleR2_test-1.0.0.jar"); teststatus = true; } catch (BundleException bexcA) { teststatus = false; fail("framework test bundle "+ bexcA +" :FRAME175A:FAIL"); } catch (SecurityException secA) { teststatus = false; fail("framework test bundle "+ secA +" :FRAME175A:FAIL"); } // Now read resources A and B intermixed // A is 50 A:s , B is 50 B:s int a_cnt1 = 0; int a_cnt2 = 0; int b_cnt = 0; byte [] a1 = new byte[50]; byte [] b1 = new byte[50]; String A = "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"; String B = "BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB"; InputStream is1 = null ; InputStream is2 = null ; try { URL u1 = buR2.getResource("org/knopflerfish/bundle/bundleR2_test/A"); is1 = u1.openStream(); a_cnt1 = is1.read(a1, 0, 10); URL u2 = buR2.getResource("org/knopflerfish/bundle/bundleR2_test/B"); is2 = u2.openStream(); b_cnt = is2.read(b1, 0, 50); // continue reading from is1 now, what do we get ?? a_cnt2 = is1.read(a1, a_cnt1, 50-a_cnt1); } catch (Throwable tt) { tt.printStackTrace(); teststatus = false; fail("Failed to read resource" + " ,FRAME175A:FAIL"); } finally { try { is1.close(); is2.close(); } catch (Throwable tt) { out.println("Failed to read close input streams" + " ,FRAME175A:FAIL"); tt.printStackTrace(); teststatus = false; } } if (A.compareTo(new String(a1)) != 0) { teststatus = false; fail("framework test bundle expected: " + A + "\n got: " + new String(a1) +" :FRAME175A:FAIL"); } if (B.compareTo(new String(b1)) != 0) { teststatus = false; fail("framework test bundle expected: " + B + "\n got: " + new String(b1) +" :FRAME175A:FAIL"); } // check the resulting events if (teststatus == true) { out.println("### framework test bundle :FRAME175A:PASS"); } else { fail("### framework test bundle :FRAME175A:FAIL"); } } } // 180. Resource integrity when reading different resources of a bundle // on the top level in the namespace of the bundle. public final static String [] HELP_FRAME180A = { "Check of resource on top of bundle name space from bundleR3_test." }; class Frame180a extends FWTestCase { public void runTest() throws Throwable { buR3 = null; boolean teststatus = true; try { buR3 = Util.installBundle(bc, "bundleR3_test-1.0.0.jar"); teststatus = true; } catch (BundleException bexcA) { out.println("framework test bundle "+ bexcA +" :FRAME180A:FAIL"); teststatus = false; } catch (SecurityException secA) { out.println("framework test bundle "+ secA +" :FRAME180A:FAIL"); teststatus = false; } // Now read resources A // A is 50 A:s int a_cnt1 = 0; int b_cnt = 0; byte [] a1 = new byte[50]; String A = "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"; InputStream is1 = null ; try { URL u1 = buR3.getResource("/A"); is1 = u1.openStream(); a_cnt1 = is1.read(a1); } catch (Throwable tt) { out.println("Failed to read resource" + " ,FRAME180A:FAIL"); tt.printStackTrace(); teststatus = false; } finally { try { if (is1 != null) { is1.close(); } } catch (Throwable tt) { out.println("Failed to close input streams" + " ,FRAME180A:FAIL"); tt.printStackTrace(); teststatus = false; } } if (A.compareTo(new String(a1)) != 0) { teststatus = false; out.println("framework test bundle expected: " + A + "\n got: " + xlateData(a1) +" :FRAME180A:FAIL"); } // check the resulting events if (teststatus == true) { out.println("### framework test bundle :FRAME180A:PASS"); } else { fail("### framework test bundle :FRAME180A:FAIL"); } } } // 181. Resource integrity when reading different resources of a bundle // on the top level in the namespace of the bundle. (180 without leading / in resource name) public final static String [] HELP_FRAME181A = { "Check of resource on top of bundle name space from bundleR3_test." }; class Frame181a extends FWTestCase { public void runTest() throws Throwable { buR3 = null; boolean teststatus = true; try { buR3 = Util.installBundle(bc, "bundleR3_test-1.0.0.jar"); teststatus = true; } catch (BundleException bexcA) { out.println("framework test bundle "+ bexcA +" :FRAME181A:FAIL"); teststatus = false; } catch (SecurityException secA) { out.println("framework test bundle "+ secA +" :FRAME181A:FAIL"); teststatus = false; } // Now read resources A // A is 50 A:s int a_cnt1 = 0; int b_cnt = 0; byte [] a1 = new byte[50]; String A = "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"; InputStream is1 = null ; try { URL u1 = buR3.getResource("A"); is1 = u1.openStream(); a_cnt1 = is1.read(a1); } catch (Throwable tt) { out.println("Failed to read resource" + " ,FRAME181A:FAIL"); tt.printStackTrace(); teststatus = false; } finally { try { if (is1 != null) { is1.close(); } } catch (Throwable tt) { out.println("Failed to close input streams" + " ,FRAME181A:FAIL"); tt.printStackTrace(); teststatus = false; } } if (A.compareTo(new String(a1)) != 0) { teststatus = false; out.println("framework test bundle expected: " + A + "\n got: " + xlateData(a1) +" :FRAME181A:FAIL"); } // check the resulting events if (teststatus == true) { out.println("### framework test bundle :FRAME181A:PASS"); } else { fail("### framework test bundle :FRAME181A:FAIL"); } } } // 185. Resource integrity when reading different resources of a bundle // on the top level in the namespace of the bundle. public final static String [] HELP_FRAME185A = { "Check of resource on top of bundle name space from bundleR4_test,", "that has an unresolvable package imported" }; class Frame185a extends FWTestCase { public void runTest() throws Throwable { buR4 = null; boolean teststatus = true; try { buR4 = Util.installBundle(bc, "bundleR4_test-1.0.0.jar"); teststatus = true; } catch (BundleException bexcA) { out.println("framework test bundle "+ bexcA +" :FRAME185A:FAIL"); teststatus = false; } catch (SecurityException secA) { out.println("framework test bundle "+ secA +" :FRAME185A:FAIL"); teststatus = false; } // Now read resources A // A is 50 A:s int a_cnt1 = 0; int b_cnt = 0; byte [] a1 = new byte[50]; String A = "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"; InputStream is1 = null ; try { URL u1 = buR4.getEntry("/A"); is1 = u1.openStream(); a_cnt1 = is1.read(a1); } catch (Throwable tt) { out.println("Failed to read resource" + " ,FRAME185A:FAIL"); tt.printStackTrace(); teststatus = false; } finally { try { if (is1 != null) { is1.close(); } } catch (Throwable tt) { tt.printStackTrace(); teststatus = false; fail("Failed to close input streams" + " ,FRAME185A:FAIL"); } } if (A.compareTo(new String(a1)) != 0) { teststatus = false; fail("framework test bundle expected: " + A + "\n got: " + xlateData(a1) +" :FRAME185A:FAIL"); } // check the resulting events if (teststatus == true) { out.println("### framework test bundle :FRAME185A:PASS"); } else { fail("### framework test bundle :FRAME185A:FAIL"); } } } // 186. Resource integrity when reading different resources of a bundle // on the top level in the namespace of the bundle. (185 without leading / in resource name) public final static String [] HELP_FRAME186A = { "Check of resource on top of bundle name space from bundleR4_test,", "that has an unresolvable package imported" }; class Frame186a extends FWTestCase { public void runTest() throws Throwable { buR4 = null; boolean teststatus = true; try { buR4 = Util.installBundle(bc, "bundleR4_test-1.0.0.jar"); teststatus = true; } catch (BundleException bexcA) { teststatus = false; fail("framework test bundle "+ bexcA +" :FRAME186A:FAIL"); } catch (SecurityException secA) { teststatus = false; fail("framework test bundle "+ secA +" :FRAME186A:FAIL"); } // Now read resources A // A is 50 A:s int a_cnt1 = 0; int b_cnt = 0; byte [] a1 = new byte[50]; String A = "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"; InputStream is1 = null ; try { URL u1 = buR4.getEntry("A"); is1 = u1.openStream(); a_cnt1 = is1.read(a1); } catch (Throwable tt) { fail("Failed to read resource" + " ,FRAME186A:FAIL"); tt.printStackTrace(); teststatus = false; } finally { try { if (is1 != null) { is1.close(); } } catch (Throwable tt) { tt.printStackTrace(); teststatus = false; fail("Failed to close input streams" + " ,FRAME186A:FAIL"); } } if (A.compareTo(new String(a1)) != 0) { teststatus = false; fail("framework test bundle expected: " + A + "\n got: " + xlateData(a1) +" :FRAME186A:FAIL"); } // check the resulting events if (teststatus == true) { out.println("### framework test bundle :FRAME186A:PASS"); } else { fail("### framework test bundle :FRAME186A:FAIL"); } } } public final static String [] HELP_FRAME190A = { "Check of resource access inside bundle name space from bundleR5_test and", "bundleR6_test, that bundleR5_test exports a resource that is accessed via ", "the bundle context of bundleR6_test" }; class Frame190a extends FWTestCase { public void runTest() throws Throwable { buR5 = null; boolean teststatus = true; try { buR5 = Util.installBundle(bc, "bundleR5_test-1.0.0.jar"); teststatus = true; } catch (BundleException bexcA) { fail("framework test bundle "+ bexcA +" :FRAME190A:FAIL"); teststatus = false; } catch (SecurityException secA) { fail("framework test bundle "+ secA +" :FRAME190A:FAIL"); teststatus = false; } buR6 = null; try { buR6 = Util.installBundle(bc, "bundleR6_test-1.0.0.jar"); teststatus = teststatus && true; } catch (BundleException bexcA) { fail("framework test bundle "+ bexcA +" :FRAME190A:FAIL"); teststatus = false; } catch (SecurityException secA) { fail("framework test bundle "+ secA +" :FRAME190A:FAIL"); teststatus = false; } // out.println("Bundle R5 state: " + buR5.getState()); // out.println("Bundle R6 state: " + buR6.getState()); // Now try to access resource in R5, which should give null // as bundle R5 is not resolved yet // int a_cnt1 = 0; int b_cnt = 0; byte [] a1 = new byte[50]; String A = "R5R5R5R5R5R5R5R5R5R5R5R5R5R5R5R5R5R5R5R5R5R5R5R5R5"; InputStream is1 = null ; // this part removed since the spec is really vague about // resolving inside of getResource() if(false) { // if buR6 not has been automatically resolved, verify that // getResource doesn't do it. (yes there might be a timing p // problem here) if(buR6.getState() == Bundle.INSTALLED) { URL u1 = null;; try { u1 = buR6.getResource("/org/knopflerfish/bundle/bundleR5_test/R5"); } catch (Throwable tt) { fail("Failed to read resource" + " ,FRAME190A:FAIL"); tt.printStackTrace(); teststatus = false; } if (u1 != null) { teststatus = false; fail("Unexpected access to resource in bundle R5 " + " ,FRAME190A:FAIL"); } } } // Start R6, so that it defintely gets state resolved try { buR6.start(); } catch (BundleException be) { fail("Failed to start bundle R6 " + be.toString() + " ,FRAME190A:FAIL"); teststatus = false; } // out.println("Bundle R5 state: " + buR5.getState()); // out.println("Bundle R6 state: " + buR6.getState()); try { URL u2 = buR6.getResource("/org/knopflerfish/bundle/bundleR5_test/R5"); is1 = u2.openStream(); a_cnt1 = is1.read(a1); } catch (Throwable tt) { fail("Failed to read resource '/org/knopflerfish/bundle/bundleR5_test/R5' via bundleR6_test" + " ,FRAME190A:FAIL"); tt.printStackTrace(); teststatus = false; } finally { try { if (is1 != null) { is1.close(); } } catch (Throwable tt) { fail("Failed to close input streams" + " ,FRAME190A:FAIL"); tt.printStackTrace(); teststatus = false; } } if (A.compareTo(new String(a1)) != 0) { teststatus = false; fail("framework test bundle expected: " + A + "\n got: " + xlateData(a1) +" :FRAME190A:FAIL"); } // check the resulting events if (teststatus == true) { out.println("### framework test bundle :FRAME190A:PASS"); } else { fail("### framework test bundle :FRAME190A:FAIL"); } } } // 210. Check that no deadlock is created when // using synchronous event handling, by // creating threads that register and unregister // services in a syncronous way public final static String [] HELP_FRAME210A = { "Deadlock test when using synchronous serviceChange listener and updating different threads." }; class Frame210a extends FWTestCase { public void runTest() throws Throwable { boolean teststatus = true; RegServThread rst = null; RegListenThread rlt = null; try { rst = new RegServThread (bc,out); rlt = new RegListenThread (bc,out); } catch (Exception ex) { teststatus = false; fail("### framework test bundle :FRAME210A exception"); ex.printStackTrace(out); } // Start the service registering thread int ID = 1; Thread t1 = new Thread(rst, "thread id= " + ID + " "); t1.start(); // System.out.println("Start of thread " + String.valueOf(ID)); // Start the listener thread ID = 2; Thread t2 = new Thread(rlt, "thread id= " + ID + " "); t2.start(); // System.out.println("Start of thread " + String.valueOf(ID)); // sleep to give the threads t1 and t2 time to create a possible deadlock. try { Thread.sleep(1500); } catch (Exception ex) { out.println("### framework test bundle :FRAME210A exception"); ex.printStackTrace(out); } // Ask the listener thread if it succeded to make a synchroized serviceChange if (rlt.getStatus() != true) { teststatus = false; fail("### framework test bundle :FRAME210A failed to execute sychnronized serviceChanged()"); } // Ask the registering thread if it succeded to make a service update if (rst.getStatus() != true) { teststatus = false; fail("### framework test bundle :FRAME210A failed to execute sychnronized service update"); } // Stop the threads rst.stop(); rlt.stop(); if (teststatus == true) { out.println("### framework test bundle :FRAME210A:PASS"); } else { fail("### framework test bundle :FRAME210A:FAIL"); } } } class Frame211a extends FWTestCase { public void runTest() throws Throwable { //existing directory Enumeration enume = buF.getEntryPaths("/"); if(enume == null ){ fail("GetEntryPaths did not retrieve the correct number of elements"); } int i = 0; while(enume.hasMoreElements()){ i++; enume.nextElement(); } if(i != 3 && i != 2){ //manifest gets skipped fail("GetEntryPaths did not retrieve the correct number of elements"); } //another existing directory enume = buF.getEntryPaths("/org/knopflerfish/bundle/"); if(enume == null ){ fail("GetEntryPaths did not retrieve the correct number of elements"); } i = 0; while(enume.hasMoreElements()){ i++; enume.nextElement(); } if(i != 1 ){ fail("GetEntryPaths did not retrieve the correct number of elements"); } //existing file, non-directory, ending with slash enume = buF.getEntryPaths("/BundF.class/"); if(enume != null ){ fail("GetEntryPaths did not retrieve the correct number of elements"); } //existing file, non-directory enume = buF.getEntryPaths("/BundF.class"); if(enume != null ){ fail("GetEntryPaths did not retrieve the correct number of elements"); } //non-existing file enume = buF.getEntryPaths("/e"); if(enume != null){ fail("GetEntryPaths did not retrieve the correct number of elements"); } //dir with only one entry enume = buF.getEntryPaths("/OSGI-INF"); if(enume == null ){ fail("GetEntryPaths did not retrieve the correct number of elements"); } i = 0; while(enume.hasMoreElements()){ i++; enume.nextElement(); } if(i != 1){ fail("GetEntryPaths did not retrieve the correct number of elements"); } if (buF != null) { try { buF.uninstall(); } catch (BundleException ignore) { } } Dictionary dict = buF.getHeaders(); if(!dict.get(Constants.BUNDLE_SYMBOLICNAME).equals("org.knopflerfish.bundle.bundleF_test")){ fail("framework test bundle, " + Constants.BUNDLE_SYMBOLICNAME + " header does not have right value:FRAME211A:FAIL"); } dict = buF.getHeaders(""); if(!dict.get(Constants.BUNDLE_DESCRIPTION).equals("%description")){ fail("framework test bundle, " + Constants.BUNDLE_DESCRIPTION + " header does not have raw value, " + dict.get(Constants.BUNDLE_DESCRIPTION) + ":FRAME211A:FAIL"); } } } // General status check functions // prevent control characters to be printed private String xlateData(byte [] b1) { StringBuffer sb = new StringBuffer(); for (int i = 0; i < b1.length ; i++) { if (-128 <= b1[i] && b1[i] < 0) { sb.append(new String(b1, i, 1)); } if (0 <= b1[i] && b1[i] < 32) { sb.append("^"); sb.append(String.valueOf(b1[i])); } else { if (32 <= b1[i] && b1[i] < 127) { sb.append(new String(b1, i, 1)); } } } return sb.toString(); } // Check that the expected implications occur public boolean implyCheck (Object _out, boolean expected, Permission p1, Permission p2) { boolean result = true; if (p1.implies(p2) == expected) { result = true; } else { out.println("framework test bundle, ...Permission implies method failed"); out.println("Permission p1: " + p1.toString()); out.println("Permission p2: " + p2.toString()); result = false; } // out.println("DEBUG implies method in FRAME125A"); // out.println("DEBUG p1: " + p1.toString()); // out.println("DEBUG p2: " + p2.toString()); return result; } public boolean implyCheck (Object _out, boolean expected, PermissionCollection p1, Permission p2) { boolean result = true; if (p1.implies(p2) == expected) { result = true; } else { out.println("framework test bundle, ...Permission implies method failed"); out.println("Permission p1: " + p1.toString()); out.println("Permission p2: " + p2.toString()); result = false; } return result; } /* Interface implementations for this class */ public java.lang.Object getConfigurationObject() { return this; } // Check that the expected events has reached the listeners and reset the events in the listeners private boolean checkListenerEvents(Object _out, boolean fwexp, int fwtype, boolean buexp, int butype, boolean sexp, int stype, Bundle bunX, ServiceReference servX ) { boolean listenState = true; // assume everything will work // Sleep a while to allow events to arrive try { Thread.sleep(eventDelay); } catch (Exception e) { e.printStackTrace(); return false; } if (fwexp == true) { if (fListen.getEvent() != null) { if (fListen.getEvent().getType() != fwtype || fListen.getEvent().getBundle() != bunX) { System.out.println("framework test bundle, wrong type of framework event/bundle : " + fListen.getEvent().getType()); System.out.println("framework test bundle, event was from bundle: " + fListen.getEvent().getBundle()); Throwable th1 = fListen.getEvent().getThrowable(); if (th1 != null) { System.out.println("framework test bundle, exception was: " + th1); } listenState = false; } } else { System.out.println("framework test bundle, missing framework event"); listenState = false; } } else { if (fListen.getEvent() != null) { listenState = false; System.out.println("framework test bundle, unexpected framework event: " + fListen.getEvent().getType()); System.out.println("framework test bundle, event was from bundle: " + fListen.getEvent().getBundle()); Throwable th1 = fListen.getEvent().getThrowable(); if (th1 != null) { System.out.println("framework test bundle, exception was: " + th1); } } } if (buexp == true) { if (bListen.getEvent() != null) { if (bListen.getEvent().getType() != butype || bListen.getEvent().getBundle() != bunX) { System.out.println("framework test bundle, wrong type of bundle event/bundle: " + bListen.getEvent().getType()); System.out.println("framework test bundle, event was from bundle: " + bListen.getEvent().getBundle().getLocation()); listenState = false; } } else { System.out.println("framework test bundle, missing bundle event"); listenState = false; } } else { if (bListen.getEvent() != null) { listenState = false; System.out.println("framework test bundle, unexpected bundle event: " + bListen.getEvent().getType()); System.out.println("framework test bundle, event was from bundle: " + bListen.getEvent().getBundle()); } } if (sexp == true) { if (sListen.getEvent() != null) { if (servX != null) { if (sListen.getEvent().getType() != stype || servX != sListen.getEvent().getServiceReference() ) { System.out.println("framework test bundle, wrong type of service event: " + sListen.getEvent().getType()); listenState = false; } } else { // ignore from which service reference the event came if (sListen.getEvent().getType() != stype ) { System.out.println("framework test bundle, wrong type of service event: " + sListen.getEvent().getType()); listenState = false; } } } else { System.out.println("framework test bundle, missing service event"); listenState = false; } } else { if (sListen.getEvent() != null) { listenState = false; System.out.println("framework test bundle, unexpected service event: " + sListen.getEvent().getType()); } } fListen.clearEvent(); bListen.clearEvent(); sListen.clearEvent(); return listenState; } // Check that the expected events has reached the listeners and reset the events in the listeners private boolean checkSyncListenerEvents(Object _out, boolean buexp, int butype, Bundle bunX, ServiceReference servX ) { boolean listenState = true; // assume everything will work // Sleep a while to allow events to arrive try { Thread.sleep(eventDelay); } catch (Exception e) { e.printStackTrace(); return false; } if (buexp == true) { if (syncBListen.getEvent() != null) { if (syncBListen.getEvent().getType() != butype || syncBListen.getEvent().getBundle() != bunX) { System.out.println("framework test bundle, wrong type of sync bundle event/bundle: " + syncBListen.getEvent().getType()); System.out.println("framework test bundle, event was from bundle: " + syncBListen.getEvent().getBundle().getLocation()); listenState = false; } } else { System.out.println("framework test bundle, missing sync bundle event"); listenState = false; } } else { if (syncBListen.getEvent() != null) { listenState = false; System.out.println("framework test bundle, unexpected sync bundle event: " + syncBListen.getEvent().getType()); System.out.println("framework test bundle, event was from bundle: " + syncBListen.getEvent().getBundle()); } } syncBListen.clearEvent(); return listenState; } private void clearEvents() { fListen.clearEvent(); bListen.clearEvent(); syncBListen.clearEvent(); sListen.clearEvent(); } // Get the bundle that caused the event private Bundle getFEBundle () { if (fListen.getEvent() != null) { return fListen.getEvent().getBundle(); } else { return null; } } private Bundle getBEBundle () { if (bListen.getEvent() != null) { return bListen.getEvent().getBundle(); } else { return null; } } // So that other bundles in the test may get the base url public String getBaseURL() { return test_url_base; } // to access test service methods via reflection private void bundleLoad (Object _out, ServiceReference sr, String bundle) { Method m; Class c, parameters[]; Object obj1 = bc.getService(sr); // System.out.println("servref = "+ sr); // System.out.println("object = "+ obj1); Object[] arguments = new Object[1]; arguments[0] = bundle; // the bundle to load packages from c = obj1.getClass(); parameters = new Class[1]; parameters[0] = arguments[0].getClass(); // System.out.println("Parameters [0] " + parameters[0].toString()); try { m = c.getMethod("tryPackage", parameters); m.invoke(obj1, arguments); } catch (IllegalAccessException ia) { System.out.println("Framework test IllegaleAccessException" + ia); } catch (InvocationTargetException ita) { System.out.println("Framework test InvocationTargetException" + ita); System.out.println("Framework test nested InvocationTargetException" + ita.getTargetException() ); } catch (NoSuchMethodException nme) { System.out.println("Framework test NoSuchMethodException " + nme); nme.printStackTrace(); } catch (Throwable thr) { System.out.println("Unexpected " + thr); thr.printStackTrace(); } } public synchronized void putEvent (String device, String method, Integer value) { // System.out.println("putEvent" + device + " " + method + " " + value); events.addElement(new devEvent(device, method, value)); } class devEvent { String dev; String met; int val; public devEvent (String dev, String met , Integer val) { this.dev = dev; this.met = met; this.val = val.intValue(); } public devEvent (String dev, String met , int val) { this.dev = dev; this.met = met; this.val = val; } public String getDevice() { return dev; } public String getMethod() { return met; } public int getValue() { return val; } } private boolean checkEvents(Object _out, Vector expevents, Vector events) { boolean state = true; if (events.size() != expevents.size()) { state = false; out.println("Real events"); for (int i = 0; i< events.size() ; i++) { devEvent dee = (devEvent) events.elementAt(i); out.print("Bundle " + dee.getDevice()); out.print(" Method " + dee.getMethod()); out.println(" Value " + dee.getValue()); } out.println("Expected events"); for (int i = 0; i< expevents.size() ; i++) { devEvent dee = (devEvent) expevents.elementAt(i); out.print("Bundle " + dee.getDevice()); out.print(" Method " + dee.getMethod()); out.println(" Value " + dee.getValue()); } } else { for (int i = 0; i< events.size() ; i++) { devEvent dee = (devEvent) events.elementAt(i); devEvent exp = (devEvent) expevents.elementAt(i); if (!(dee.getDevice().equals(exp.getDevice()) && dee.getMethod().equals(exp.getMethod()) && dee.getValue() == exp.getValue())) { out.println("Event no = " + i); if (!(dee.getDevice().equals(exp.getDevice()))) { out.println ("Bundle is " + dee.getDevice() + " should be " + exp.getDevice()); } if (!(dee.getMethod().equals(exp.getMethod()))) { out.println ("Method is " + dee.getMethod() + " should be " + exp.getMethod()); } if (!(dee.getValue() == exp.getValue())) { out.println ("Value is " + dee.getValue() + " should be " + exp.getValue()); } state = false; } } } return state; } private String getStateString(int bundleState) { switch (bundleState) { case 0x01: return "UNINSTALLED"; case 0x02: return "INSTALLED"; case 0x04: return "RESOLVED"; case 0x08: return "STARTING"; case 0x10: return "STOPPING"; case 0x20: return "ACTIVE"; default: return "Unknow state"; } } class FrameworkListener implements org.osgi.framework.FrameworkListener { FrameworkEvent fwe; public void frameworkEvent(FrameworkEvent evt) { this.fwe = evt; // System.out.println("FrameworkEvent: "+ evt.getType()); } public FrameworkEvent getEvent() { return fwe; } public void clearEvent() { fwe = null; } } class ServiceListener implements org.osgi.framework.ServiceListener { ServiceEvent serve = null; public void serviceChanged(ServiceEvent evt) { this.serve = evt; // System.out.println("ServiceEvent: " + evt.getType()); } public ServiceEvent getEvent() { return serve; } public void clearEvent() { serve = null; } } class BundleListener implements org.osgi.framework.BundleListener { BundleEvent bunEvent = null; public void bundleChanged (BundleEvent evt) { this.bunEvent = evt; // System.out.println("BundleEvent: "+ evt.getType()); } public BundleEvent getEvent() { return bunEvent; } public void clearEvent() { bunEvent = null; } } class SyncBundleListener implements SynchronousBundleListener { BundleEvent bunEvent = null; public void bundleChanged (BundleEvent evt) { if(evt.getType() == BundleEvent.STARTING || evt.getType() == BundleEvent.STOPPING) this.bunEvent = evt; // System.out.println("BundleEvent: "+ evt.getType()); } public BundleEvent getEvent() { return bunEvent; } public void clearEvent() { bunEvent = null; } } }
osgi/bundles_test/regression_tests/framework_test/src/org/knopflerfish/bundle/framework_test/FrameworkTestSuite.java
/* * Copyright (c) 2004-2008, KNOPFLERFISH project * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following * conditions are met: * * - Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials * provided with the distribution. * * - Neither the name of the KNOPFLERFISH project nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.knopflerfish.bundle.framework_test; import java.util.*; import java.io.*; import java.net.*; import java.lang.reflect.*; import java.security.*; import org.osgi.framework.*; import org.knopflerfish.service.framework_test.*; import junit.framework.*; public class FrameworkTestSuite extends TestSuite implements FrameworkTest { BundleContext bc; Bundle bu; Bundle buA; Bundle buB; Bundle buC; Bundle buD; Bundle buD1; Bundle buE; Bundle buF; Bundle buH; Bundle buJ; // Bundle for resource reading integrity check Bundle buR2; Bundle buR3; Bundle buR4; Bundle buR5; Bundle buR6; // Bundles for resource reading integrity check Bundle buRimp; Bundle buRexp; // Package version test bundles Bundle buP1; Bundle buP2; Bundle buP3; // the three event listeners FrameworkListener fListen; BundleListener bListen; SyncBundleListener syncBListen; ServiceListener sListen; Properties props = System.getProperties(); String lineseparator = props.getProperty("line.separator"); String test_url_base; Vector events = new Vector(); // vector for events from test bundles Vector expevents = new Vector(); // comparision vector PrintStream out = System.out; long eventDelay = 500; public FrameworkTestSuite (BundleContext bc) { super("FrameworkTestSuite"); this.bc = bc; this.bu = bc.getBundle(); test_url_base = "bundle://" + bc.getBundle().getBundleId() + "/"; try { eventDelay = Long.getLong("org.knopflerfish.framework_tests.eventdelay", new Long(eventDelay)).longValue(); } catch (Exception e) { e.printStackTrace(); } addTest(new Setup()); addTest(new Frame005a()); addTest(new Frame007a()); addTest(new Frame010a()); addTest(new Frame018a()); addTest(new Frame019a()); addTest(new Frame020a()); addTest(new Frame025a()); addTest(new Frame030a()); addTest(new Frame035a()); addTest(new Frame038a()); // addTest(new Frame040a()); skipped since not a valid test? addTest(new Frame041a()); addTest(new Frame045a()); addTest(new Frame050a()); addTest(new Frame055a()); addTest(new Frame060a()); addTest(new Frame065a()); addTest(new Frame068a()); addTest(new Frame069a()); addTest(new Frame070a()); addTest(new Frame075a()); addTest(new Frame080a()); addTest(new Frame085a()); addTest(new Frame110a()); addTest(new Frame115a()); //don't fix up security for now //addTest(new Frame120a()); addTest(new Frame125a()); addTest(new Frame130a()); addTest(new Frame160a()); addTest(new Frame161a()); addTest(new Frame162a()); addTest(new Frame163a()); addTest(new Frame170a()); addTest(new Frame175a()); addTest(new Frame180a()); addTest(new Frame181a()); addTest(new Frame185a()); addTest(new Frame186a()); addTest(new Frame190a()); addTest(new Frame210a()); addTest(new Frame211a()); addTest(new Cleanup()); } public String getDescription() { return "Tests core functionality in the framework"; } public String getDocURL() { return "https://www.knopflerfish.org/svn/knopflerfish.org/trunk/osgi/bundles_test/regression_tests/framework_test/readme.txt"; } public final static String [] HELP_FRAME005A = { "Verify information from the getHeaders() method", }; class Frame005a extends FWTestCase { public void runTest() throws Throwable { Dictionary ai = bu.getHeaders(); // check expected headers String k = "Bundle-ContactAddress"; String info = (String) ai.get(k); assertEquals("bad Bundle-ContactAddress", "http://www.knopflerfish.org", info); k = "Bundle-Description"; info = (String) ai.get(k); assertEquals("bad Bundle-Description", "Test bundle for framework", info); k = "Bundle-DocURL"; info = (String) ai.get(k); assertEquals("bad Bundle-DocURL", "http://www.knopflerfish.org", info); k = "Bundle-Name"; info = (String) ai.get(k); assertEquals("bad Bundle-Name", "framework_test", info); k = "Bundle-Vendor"; info = (String) ai.get(k); assertEquals("bad Bundle-Vendor", "Knopflerfish/Gatespace Telematics", info); k = "Bundle-Version"; info = (String) ai.get(k); assertEquals("bad Bundle-Version", "1.0.0", info); k = "Bundle-ManifestVersion"; info = (String) ai.get(k); assertEquals("bad " + k, "2", info); String version = props.getProperty("java.version"); String vendor = props.getProperty("java.vendor"); out.println("framework test bundle, Java version " + version); out.println("framework test bundle, Java vendor " + vendor); out.println("### framework test bundle :FRAME005A:PASS"); } } public final static String [] HELP_FRAME007A = { "Extract all information from the getProperty in the BundleContext interface " }; class Frame007a extends FWTestCase { public void runTest() throws Throwable { boolean teststatus = true; String trunk = "org.osgi.framework."; String stem = "version"; String data = bc.getProperty(trunk+stem); if (data == null) { teststatus = false; } out.println(trunk + stem + " " + data); stem = "vendor"; data = bc.getProperty(trunk+stem); if (data == null) { teststatus = false; } out.println(trunk + stem + " " + data); stem = "language"; data = bc.getProperty(trunk+stem); if (data == null) { teststatus = false; } out.println(trunk + stem + " " + data); stem = "os.name"; data = bc.getProperty(trunk+stem); if (data == null) { teststatus = false; } out.println(trunk + stem + " " + data); stem = "os.version"; data = bc.getProperty(trunk+stem); if (data == null) { teststatus = false; } out.println(trunk + stem + " " + data); stem = "processor"; data = bc.getProperty(trunk+stem); if (data == null) { teststatus = false; } out.println(trunk + stem + " " + data); if (teststatus == true ) { out.println("### framework test bundle :FRAME007A:PASS"); } else { fail("### framework test bundle :FRAME007A:FAIL"); } } } public final static String [] HELP_FRAME010A = { "Get context id, location and status of the bundle" }; class Frame010a extends FWTestCase { public void runTest() throws Throwable { long contextid = bu.getBundleId(); out.println("CONTEXT ID: " + contextid); String location = bu.getLocation(); out.println("LOCATION: " + location); int bunstate = bu.getState(); out.println("BCACTIVE: " + bunstate); } } static int nRunCount = 0; class Setup extends FWTestCase { public void runTest() throws Throwable { if(nRunCount > 0) { fail("The FrameworkTestSuite CANNOT be run reliably more than once. Other test results in this suite are/may not be valid. Restart framework to retest :Cleanup:FAIL"); } nRunCount++; fListen = new FrameworkListener(); try { bc.addFrameworkListener(fListen); } catch (IllegalStateException ise) { fail("framework test bundle "+ ise + " :SETUP:FAIL"); } bListen = new BundleListener(); try { bc.addBundleListener(bListen); } catch (IllegalStateException ise) { fail("framework test bundle "+ ise + " :SETUP:FAIL"); } syncBListen = new SyncBundleListener(); try { bc.addBundleListener(syncBListen); } catch (IllegalStateException ise) { fail("framework test bundle "+ ise + " :SETUP:FAIL"); } sListen = new ServiceListener(); try { bc.addServiceListener(sListen); } catch (IllegalStateException ise) { fail("framework test bundle "+ ise + " :SETUP:FAIL"); } Locale.setDefault(Locale.CANADA_FRENCH); out.println("### framework test bundle :SETUP:PASS"); } } class Cleanup extends FWTestCase { public void runTest() throws Throwable { Bundle[] bundles = new Bundle[] { buA , buB , buC, buD , buD1 , buE , buH , buJ , buR2 , buR3 , buR4 , buR5 , buR6 , buRimp , buRexp , buP1 , buP2 , buP3 , }; for(int i = 0; i < bundles.length; i++) { try { bundles[i].uninstall(); } catch (Exception ignored) { } } buA = null; buB = null; buC = null; buD = null; buD1 = null; buE = null; buF = null; buH = null; buJ = null; // for resource reading integrity check buR2 = null; buR3 = null; buR4 = null; buR5 = null; buR6 = null; // Bundles for resource reading integrity check buRimp = null; buRexp = null; // Package version test bundles buP1 = null; buP2 = null; buP3 = null; try { bc.removeFrameworkListener(fListen); } catch (Exception ignored) { } fListen = null; try { bc.removeServiceListener(sListen); } catch (Exception ignored) { } sListen = null; try { bc.removeBundleListener(bListen); } catch (Exception ignored) { } bListen = null; } } public final static String [] HELP_FRAME018A = { "Test result of getService(null). Should throw NPE", }; class Frame018a extends FWTestCase { public void runTest() throws Throwable { try { Object obj = null; obj = bc.getService(null); fail("### FRAME018A:FAIL Got service object=" + obj + ", excpected NullPointerException"); } catch (NullPointerException e) { out.println("### FRAME018A:PASS: got NPE=" + e); } catch (RuntimeException e) { fail("### FRAME018A:FAIL: got RTE=" + e); } catch (Throwable e) { fail("### FRAME018A:FAIL Got " + e + ", expected NullPointerException"); } } } public final static String [] HELP_FRAME019A = { "Try bundle:// syntax, if present in FW, by installing bundleA_test", "This test is also valid if ", "new URL(bundle://) throws MalformedURLException", }; class Frame019a extends FWTestCase { public void runTest() throws Throwable { Bundle bA = null; try { try { URL url = new URL("bundle://" + bc.getBundle().getBundleId() + "/" + "bundleA_test-1.0.0.jar"); // if the URL can be created, it should be possible to install // from the URL string representation bA = bc.installBundle(url.toString()); assertNotNull("Bundle should be possible to install from " + url, bA); try { bA.start(); } catch (Exception e) { fail(url + " couldn't be started, FRAME019A:FAIL"); } assertEquals("Bundle should be in ACTIVE state", Bundle.ACTIVE, bA.getState()); out.println("### FRAME019A: PASSED, bundle URL " + url); // finally block will uninstall bundle and clean up events } catch (MalformedURLException e) { out.println("### FRAME019A: PASSED, bundle: URL not supported: " + e); } } finally { try { if(bA != null) { bA.uninstall(); } } catch (Exception e) { } clearEvents(); } } } public final static String [] HELP_FRAME020A = { "Load bundleA_test and check that it exists and that its expected service does not exist", "Also check that the expected events in the framework occurs" }; class Frame020a extends FWTestCase { public void runTest() throws Throwable { buA = null; boolean teststatus = true; try { buA = Util.installBundle(bc, "bundleA_test-1.0.0.jar"); teststatus = true; } catch (BundleException bexcA) { fail("framework test bundle "+ bexcA +" :FRAME020A:FAIL"); teststatus = false; } catch (SecurityException secA) { fail("framework test bundle "+ secA +" :FRAME020A:FAIL"); teststatus = false; } //Localization tests Dictionary dict = buA.getHeaders(); if(!dict.get(Constants.BUNDLE_SYMBOLICNAME).equals("org.knopflerfish.bundle.bundleA_test")){ fail("framework test bundle, " + Constants.BUNDLE_SYMBOLICNAME + " header does not have right value:FRAME020A:FAIL"); } // Check that no service reference exist yet. ServiceReference sr1 = bc.getServiceReference("org.knopflerfish.service.bundleA_test.BundleA"); if (sr1 != null) { fail("framework test bundle, service from test bundle A unexpectedly found :FRAME020A:FAIL"); teststatus = false; } // check the listeners for events, expect only a bundle event, of type installation boolean lStat = checkListenerEvents(out, false , 0, true , BundleEvent.INSTALLED, false, 0, buA, sr1); if (teststatus == true && buA.getState() == Bundle.INSTALLED && lStat == true) { out.println("### framework test bundle :FRAME020A:PASS"); } else { fail("### framework test bundle :FRAME020A:FAIL"); } } } public final static String [] HELP_FRAME025A = { "Start bundleA_test and check that it gets state ACTIVE", "and that the service it registers exist" }; class Frame025a extends FWTestCase { public void runTest() throws Throwable { boolean teststatus = true; boolean ungetStat = false; try { buA.start(); teststatus = true; } catch (BundleException bexcA) { fail("framework test bundle "+ bexcA +" :FRAME025A:FAIL"); teststatus = false; bexcA.printStackTrace(); } catch (IllegalStateException ise) { fail("framework test bundle "+ ise +" :FRAME025A:FAIL"); teststatus = false; ise.printStackTrace(); } catch (SecurityException sec) { fail("framework test bundle "+ sec +" :FRAME025A:FAIL"); teststatus = false; sec.printStackTrace(); } // Check if testbundleA registered the expected service ServiceReference sr1 = bc.getServiceReference("org.knopflerfish.service.bundleA_test.BundleA"); if (sr1 == null) { fail("framework test bundle, expected service not found :FRAME025A:FAIL"); teststatus = false; } else { try { Object o1 = bc.getService(sr1); if (o1 == null) { fail("framework test bundle, no service object found :FRAME025A:FAIL"); teststatus = false; } try { ungetStat = bc.ungetService(sr1); } catch (IllegalStateException ise) { fail("framework test bundle, ungetService exception " + ise + ":FRAME025A:FAIL"); } } catch (SecurityException sek) { fail("framework test bundle, getService " + sek + ":FRAME025A:FAIL"); teststatus = false; } } // check the listeners for events, expect a bundle event of started and a service event of type registered boolean lStat = checkListenerEvents( out, false, 0, true, BundleEvent.STARTED, true, ServiceEvent.REGISTERED, buA, sr1); assertTrue("BundleA should be ACTIVE", buA.getState() == Bundle.ACTIVE); assertTrue("Service unget should be true", ungetStat == true); // Changed according to KF bug #1780141 assertTrue("Unexpected events", lStat == true); if (teststatus == true && buA.getState() == Bundle.ACTIVE && ungetStat == true && lStat == true ) { out.println("### framework test bundle :FRAME025A:PASS"); } else { fail("### framework test bundle :FRAME025A:FAIL"); } } } public final static String [] HELP_FRAME030A = { "Stop bundleA_test and check that it gets state RESOLVED" }; class Frame030a extends FWTestCase { public void runTest() throws Throwable { boolean teststatus = true; ServiceReference sr1 = bc.getServiceReference("org.knopflerfish.service.bundleA_test.BundleA"); boolean lStatSync = false; try { buA.stop(); lStatSync = checkSyncListenerEvents(out, true, BundleEvent.STOPPING, buA, null); teststatus = true; } catch (IllegalStateException ise ) { fail("framework test bundle, getService " + ise + ":FRAME030A:FAIL"); teststatus = false; } catch (BundleException be ) { fail("framework test bundle, getService " + be + ":FRAME030A:FAIL"); teststatus = false; } boolean lStat = checkListenerEvents(out, false, 0, true, BundleEvent.STOPPED, true, ServiceEvent.UNREGISTERING, buA, sr1); if (teststatus == true && buA.getState() == Bundle.RESOLVED && lStat == true && lStatSync == true) { out.println("### framework test bundle :FRAME030A:PASS"); } else { fail("### framework test bundle :FRAME030A:FAIL"); } } } public final static String [] HELP_FRAME035A = { "Stop bundleA_test and check that it gets state UNINSTALLED" }; class Frame035a extends FWTestCase { public void runTest() throws Throwable { boolean teststatus = true; ServiceReference sr1 = bc.getServiceReference("org.knopflerfish.service.bundleA_test.BundleA"); try { buA.uninstall(); } catch (IllegalStateException ise ) { fail("framework test bundle, getService " + ise + ":FRAME035A:FAIL"); teststatus = false; } catch (BundleException be ) { fail("framework test bundle, getService " + be + ":FRAME035A:FAIL"); teststatus = false; } boolean lStat = checkListenerEvents(out, false, 0, true, BundleEvent.UNINSTALLED, false, 0, buA, sr1); if (teststatus == true && buA.getState() == Bundle.UNINSTALLED && lStat == true) { out.println("### framework test bundle :FRAME035A:PASS"); } else { fail("### framework test bundle :FRAME035A:Fail"); } } } public final static String [] HELP_FRAME038A = { "Install a non existent file, check that the right exception is thrown" }; class Frame038a extends FWTestCase { public void runTest() throws Throwable { boolean teststatus = true; boolean exception; buD = null; try { buD = Util.installBundle(bc, "nonexisting_bundle_file.jar"); exception = false; } catch (BundleException bexcA) { // out.println("framework test bundle "+ bexcA +" :FRAME038A:FAIL"); exception = true; } catch (SecurityException secA) { fail("framework test bundle "+ secA +" :FRAME038A:FAIL"); teststatus = false; exception = true; } if (exception == false) { teststatus = false; } // check the listeners for events, expect nothing boolean lStat = checkListenerEvents(out, false,0, false,0, false,0, buD, null); if (teststatus == true && buD == null && lStat == true) { out.println("### framework test bundle :FRAME038A:PASS"); } else { fail("### framework test bundle :FRAME038A:FAIL"); } } } // 8. Install testbundle D, check that an BundleException is thrown // as this bundle has no manifest file in its jar file // (hmmm...I don't think this is a correct test. /EW) class Frame040a extends FWTestCase { public void runTest() throws Throwable { boolean teststatus = true; boolean exception; buD = null; try { buD = Util.installBundle(bc, "bundleD_test-1.0.0.jar"); exception = false; } catch (BundleException bexcA) { System.out.println("framework test bundle "+ bexcA +" :FRAME040A:FAIL"); // This exception is expected exception = true; } catch (SecurityException secA) { fail("framework test bundle "+ secA +" :FRAME040A:FAIL"); teststatus = false; exception = true; } // Check that no service reference exist. ServiceReference sr1 = bc.getServiceReference("org.knopflerfish.service.bundleD_test.BundleD"); if (sr1 != null) { fail("framework test bundle, service from test bundle D unexpectedly found :FRAME040A:FAIL"); teststatus = false; } if (exception == false) { teststatus = false; } // check the listeners for events, expect only a bundle event, of type installation boolean lStat = checkListenerEvents(out, false, 0, false , 0, false, 0, buD, null); out.println("FRAME040A: lStat=" + lStat); if (teststatus == true && buD == null && lStat == true) { out.println("### framework test bundle :FRAME040A:PASS"); } else { fail("### framework test bundle :FRAME040A:FAIL"); } } } public final static String [] HELP_FRAME041A = { "Install bundleD1_test, which has a broken manifest file,", "an empty import statement and check", "that the expected exceptions are thrown" }; class Frame041a extends FWTestCase { public void runTest() throws Throwable { boolean teststatus = true; boolean exception; buD1 = null; try { buD1 = Util.installBundle(bc, "bundleD1_test-1.0.0.jar"); exception = false; } catch (BundleException bexcA) { // System.out.println("framework test bundle "+ bexcA +" :FRAME041A"); // Throwable tex = bexcA.getNestedException(); // if (tex != null) { // System.out.println("framework test bundle, nested exception "+ tex +" :FRAME041A"); // } // This exception is expected exception = true; } catch (SecurityException secA) { fail("framework test bundle "+ secA +" :FRAME041A:FAIL"); teststatus = false; exception = true; } // Check that no service reference exist. ServiceReference sr1 = bc.getServiceReference("org.knopflerfish.service.bundleD1_test.BundleD1"); if (sr1 != null) { fail("framework test bundle, service from test bundle D1 unexpectedly found :FRAME041A:FAIL"); teststatus = false; } if (exception == false) { teststatus = false; } // check the listeners for events, expect only a bundle event, of type installation boolean lStat = checkListenerEvents(out, false, 0, false , 0, false, 0, buD, null); if (teststatus == true && buD == null && lStat == true) { out.println("### framework test bundle :FRAME041A:PASS"); } else { fail("### framework test bundle :FRAME041A:FAIL"); } } } public final static String [] HELP_FRAME045A = { "Add a service listener with a broken LDAP filter to get an exception" }; class Frame045a extends FWTestCase { public void runTest() throws Throwable { ServiceListener sListen1 = new ServiceListener(); String brokenFilter = "A broken LDAP filter"; try { bc.addServiceListener(sListen1, brokenFilter); out.println("Frame045a: Added LDAP filter"); } catch (InvalidSyntaxException ise) { assertEquals("InvalidSyntaxException.getFilter should be same as input string", brokenFilter, ise.getFilter()); } catch (Exception e) { fail("framework test bundle, wroing exception on broken LDAP filter, FREME045A:FAIL " + e); } out.println("### framework test bundle :FRAME045A:PASS"); } } public final static String [] HELP_FRAME050A = { "Loads and starts bundleB_test, checks that it gets the state ACTIVE.", "Checks that it implements the Configurable interface." }; class Frame050a extends FWTestCase { public void runTest() throws Throwable { boolean teststatus = true; try { buB = Util.installBundle(bc, "bundleB_test-1.0.0.jar"); buB.start(); teststatus = true; } catch (BundleException bexcB) { fail("framework test bundle "+ bexcB +" :FRAME050A:FAIL"); teststatus = false; bexcB.printStackTrace(); } catch (SecurityException secB) { fail("framework test bundle "+ secB +" :FRAME050A:FAIL"); teststatus = false; secB.printStackTrace(); } catch (IllegalStateException ise) { fail("framework test bundle "+ ise +" :FRAME050A:FAIL"); teststatus = false; ise.printStackTrace(); } // Check if testbundleB registered the expected service ServiceReference sr1 = bc.getServiceReference("org.knopflerfish.service.bundleB_test.BundleB"); if (sr1 == null) { fail("framework test bundle, expected service not found :FRAME050A:FAIL"); teststatus = false; } else { Object o1 = bc.getService(sr1); // out.println("o1 = " + o1); if (!(o1 instanceof Configurable)) { fail("framework test bundle, service does not support Configurable :FRAME050A:FAIL"); teststatus = false; } else { // out.println("framework test bundle got service ref"); Configurable c1 = (Configurable) o1; // out.println("c1 = " + c1); Object o2 = c1.getConfigurationObject(); if (o2 != c1) { teststatus = false; fail("framework test bundle, configuration object is not the same as service object :FRAME050A:FAIL"); } // out.println("o2 = " + o2 + " bundle = " + buB); // out.println("bxx " + sr1.getBundle()); } } // Check that the dictionary from the bundle seems to be ok, keys[1-4], value[1-4] String keys [] = sr1.getPropertyKeys(); for (int k=0; k< keys.length; k++) { if (keys[k].equals("key"+k)) { if (!(sr1.getProperty(keys[k]).equals("value"+k))) { teststatus = false; fail("framework test bundle, key/value mismatch in propety list :FRAME050A:FAIL"); } } } if (teststatus == true && buB.getState() == Bundle.ACTIVE) { out.println("### framework test bundle :FRAME050A:PASS"); } else { fail("### framework test bundle :FRAME050A:FAIL"); } } } public final static String [] HELP_FRAME055A = { "Load and start bundleC_test, checks that it gets the state ACTIVE.", "Checks that it is available under more than one name.", "Then stop the bundle, check that no exception is thrown", "as the bundle unregisters itself in its stop method." }; class Frame055a extends FWTestCase { public void runTest() throws Throwable { boolean teststatus = true; try { buC = Util.installBundle(bc, "bundleC_test-1.0.0.jar"); buC.start(); teststatus = true; } catch (BundleException bexcB) { teststatus = false; bexcB.printStackTrace(); fail("framework test bundle "+ bexcB +" :FRAME055A:FAIL"); } catch (SecurityException secB) { teststatus = false; secB.printStackTrace(); fail("framework test bundle "+ secB +" :FRAME055A:FAIL"); } catch (IllegalStateException ise) { teststatus = false; ise.printStackTrace(); fail("framework test bundle "+ ise +" :FRAME055A:FAIL"); } Dictionary dict = buC.getHeaders(); if(!dict.get(Constants.BUNDLE_SYMBOLICNAME).equals("org.knopflerfish.bundle.bundleC_test")){ fail("framework test bundle, " + Constants.BUNDLE_SYMBOLICNAME + " header does not have right value:FRAME055A:FAIL"); } // Check if testbundleC registered the expected service ServiceReference sr1 = bc.getServiceReference("org.knopflerfish.service.bundleC_test.BundleC"); if (sr1 == null) { teststatus = false; fail("framework test bundle, expected service not found :FRAME055A:FAIL"); } else { // get objectClass service name array int hits = 0; String [] packnames = (String[]) sr1.getProperty("objectClass"); for (int j = 0; j< packnames.length; j++) { if (packnames[j].equals("org.knopflerfish.service.bundleC_test.BundleC")) { hits++; } if (packnames[j].equals("java.lang.Object")) { hits++; } } if (hits !=2) { teststatus = false; fail("framework test bundle, expected service not registered under the two expected names :FRAME055A:FAIL"); } } // Check if testbundleC registered the expected service with java.lang.Object as well ServiceReference sref [] = null; try { sref = bc.getServiceReferences("java.lang.Object",null); if (sref == null) { fail("framework test bundle, expected service not found :FRAME055A:FAIL"); teststatus = false; } else { // get objectClass service name array int hits = 0; String [] packnames = (String[]) sr1.getProperty("objectClass"); for (int j = 0; j< packnames.length; j++) { if (packnames[j].equals("org.knopflerfish.service.bundleC_test.BundleC")) { hits++; } if (packnames[j].equals("java.lang.Object")) { hits++; } } if (hits !=2) { teststatus = false; fail("framework test bundle, expected service not registered under the two expected names :FRAME055A:FAIL"); } } } catch (InvalidSyntaxException ise) { fail("framework test bundle, invalid syntax in LDAP filter :" + ise + " :FRAME055A:FAIL"); teststatus = false; } // 11a. check the getProperty after registration, something should come back // Check that both keys in the service have their expected values boolean h1 = false; boolean h2 = false; if (sref != null) { for (int i = 0; i< sref.length; i++) { String sn1[] = (String[]) sref[i].getProperty("objectClass"); for (int j = 0; j < sn1.length; j++) { if (sn1[j].equals("org.knopflerfish.service.bundleC_test.BundleC")) { String keys[] = sref[i].getPropertyKeys(); if (keys != null) { for (int k = 0; k< keys.length; k++) { try { String s1 = (String) sref[i].getProperty(keys[k]); if (s1.equals("value1")) {h1 = true;} if (s1.equals("value2")) {h2 = true;} } catch (Exception e1) { // out.println("framework test bundle exception " + e1 ); } } } } } } } if (! (h1 == true && h2 == true)) { teststatus = false; fail("framework test bundle, expected property values from registered bundleC_test not found :FRAME055A:FAIL"); } try { buC.stop(); } catch (BundleException bexp) { teststatus = false; fail("framework test bundle, exception in stop method :" + bexp + " :FRAME055A:FAIL"); } catch (Throwable thr) { teststatus = false; fail("framework test bundle, exception in stop method :" + thr + " :FRAME055A:FAIL"); } // 11a. check the getProperty after unregistration, something should come back // Check that both keys i the service still have their expected values h1 = false; h2 = false; if (sref != null) { for (int i = 0; i< sref.length; i++) { String sn1[] = (String[]) sref[i].getProperty("objectClass"); if (sn1 != null) { for (int j = 0; j < sn1.length; j++) { if (sn1[j].equals("org.knopflerfish.service.bundleC_test.BundleC")) { String keys[] = sref[i].getPropertyKeys(); if (keys != null) { for (int k = 0; k< keys.length; k++) { try { String s1 = (String) sref[i].getProperty(keys[k]); if (s1.equals("value1")) {h1 = true;} if (s1.equals("value2")) {h2 = true;} } catch (Exception e1) { // out.println("framework test bundle exception " + e1 ); } } } } } } } } if (!(h1 == true && h2 == true)) { teststatus = false; fail("framework test bundle, expected property values from unregistered bundleC_test not found :FRAME055A:FAIL"); } out.println("framework test bundle, buC.getState() = " + buC.getState()); if (teststatus == true && buC.getState() == Bundle.RESOLVED) { out.println("### framework test bundle :FRAME055A:PASS"); } else { fail("### framework test bundle :FRAME055A:FAIL"); } } } public final static String [] HELP_FRAME060A = { "Gets the configurable object from testbundle B,", "update its properties and check that a ServiceEvent occurs.", "Also get the ServiceRegistration object from bundle", "and check that the bundle is the same and that", "unregistration causes a ServiceEvent.UNREGISTERING." }; class Frame060a extends FWTestCase { public void runTest() throws Throwable { boolean teststatus = true; boolean lStat = false; boolean lStat2 = false; ServiceRegistration servRegB = null; Method m; Class c, parameters[]; ServiceRegistration ServReg; // clear the listeners clearEvents(); // get rid of all prevoius events ServiceReference sr1 = bc.getServiceReference("org.knopflerfish.service.bundleB_test.BundleB"); if (sr1 == null) { fail("framework test bundle, expected service not found :FRAME060A:FAIL"); teststatus = false; } else { Object o1 = bc.getService(sr1); // out.println("o1 = " + o1); if (!(o1 instanceof Configurable)) { fail("framework test bundle, service does not support Configurable :FRAME060A:FAIL"); teststatus = false; } else { Hashtable h1 = new Hashtable(); h1.put ("key1","value7"); h1.put ("key2","value8"); // now for some reflection exercises Object[] arguments = new Object[1]; c = o1.getClass(); parameters = new Class[1]; parameters[0] = h1.getClass(); // new Class[0]; arguments[0] = h1; try { m = c.getMethod("setServReg", parameters); servRegB = (ServiceRegistration) m.invoke(o1, arguments); // System.out.println("servRegB= " + servRegB); } catch (IllegalAccessException ia) { out.println("Frame test IllegaleAccessException" + ia); } catch (InvocationTargetException ita) { out.println("Frame test InvocationTargetException" + ita); out.println("Frame test nested InvocationTargetException" + ita.getTargetException() ); } catch (NoSuchMethodException nme) { out.println("Frame test NoSuchMethodException" + nme); } // Check that the dictionary from the bundle seems to be ok, keys[1-2], value[7-8] String keys [] = sr1.getPropertyKeys(); for (int k=0; k< keys.length; k++) { // out.println("key=" + keys[k] +" val= " + sr1.getProperty(keys[k])); int l = k + 6; if (keys[k].equals("key"+l)) { if (!(sr1.getProperty(keys[k]).equals("value"+k))) { teststatus = false; fail("framework test bundle, key/value mismatch in propety list :FRAME060A:FAIL"); } } } // check the listeners for events, in this case service event MODIFIED lStat = checkListenerEvents(out, false,0, false,0, true,ServiceEvent.MODIFIED, buB, sr1); clearEvents(); // now to get the service reference as well for some manipulation arguments = new Object [0]; parameters = new Class [0]; try { m = c.getMethod("getServReg", parameters); servRegB = (ServiceRegistration) m.invoke(o1, arguments); ServiceReference sri = servRegB.getReference(); if (sri.getBundle() != buB) { teststatus = false; fail("framework test bundle, bundle not as expected :FRAME060A:FAIL"); } else { servRegB.unregister(); out.println("servRegB= " + servRegB); } } catch (IllegalAccessException ia) { out.println("Frame test IllegaleAccessException" + ia); } catch (InvocationTargetException ita) { out.println("Frame test InvocationTargetException" + ita); } catch (NoSuchMethodException nme) { out.println("Frame test NoSuchMethodException" + nme); } lStat2 = checkListenerEvents(out, false,0, false,0, true,ServiceEvent.UNREGISTERING, buB, sr1); } } if (teststatus == true && buB.getState() == Bundle.ACTIVE && lStat == true && lStat2 == true) { out.println("### framework test bundle :FRAME060A:PASS"); } else { fail("### framework test bundle :FRAME060A:FAIL"); } } } public final static String [] HELP_FRAME065A = { "Load and try to start bundleE_test, ", "It should be possible to load , but should not be possible to start", "as the start method in the manifest is not available in the bundle." }; class Frame065a extends FWTestCase { public void runTest() throws Throwable { boolean teststatus = true; boolean catchstatus = true; buE = null; try { buE = Util.installBundle(bc, "bundleE_test-1.0.0.jar"); teststatus = true; } catch (BundleException bexcA) { teststatus = false; fail("framework test bundle "+ bexcA +" :FRAME065A:FAIL"); } catch (SecurityException secA) { teststatus = false; fail("framework test bundle "+ secA +" :FRAME065A:FAIL"); } clearEvents(); // now try and start it, which should generate a BundleException try { buE.start(); catchstatus = false; } catch (BundleException bexcA) { // the nested exception should be a ClassNotFoundException, check that Throwable t1 = bexcA.getNestedException(); if (t1 instanceof ClassNotFoundException) { catchstatus = true; } else { catchstatus = false; bexcA.printStackTrace(); fail("framework test bundle, unexpected nested exception "+ t1 +" :FRAME065A:FAIL"); } //System.out.println("framework test bundle "+ bexcA +" :FRAME065A:FAIL"); } catch (IllegalStateException ise) { teststatus = false; ise.printStackTrace(); fail("framework test bundle "+ ise +" :FRAME065A:FAIL"); } catch (SecurityException sec) { teststatus = false; sec.printStackTrace(); fail("framework test bundle "+ sec +" :FRAME065A:FAIL"); } // check the events, only BundleEvent.RESOLVED and BundleEvent.STARTING should have happened boolean lStat = checkListenerEvents(out, false, 0, true, BundleEvent.RESOLVED, false, 0, buE, null); boolean lStatSync = checkSyncListenerEvents(out, true, BundleEvent.STARTING, buE, null); if (catchstatus == false) { teststatus = false; } Dictionary dict = buE.getHeaders(); if(!dict.get(Constants.BUNDLE_SYMBOLICNAME).equals("org.knopflerfish.bundle.bundleE_test")){ fail("framework test bundle, " + Constants.BUNDLE_SYMBOLICNAME + " header does not have right value:FRAME065A:FAIL"); } if (teststatus == true && lStat == true && lStatSync == true) { out.println("### framework test bundle :FRAME065A:PASS"); } else { fail("### framework test bundle :FRAME065A:FAIL"); } } } public final static String [] HELP_FRAME068A = { "Tests accessing multiple resources inside the test bundle itself", "using ClassLoader.getResource" }; class Frame068a extends FWTestCase { public void runTest() throws Throwable { int n; // first check that correct number of files exists // the fw_test_multi.txt resources are present in // res1.jar, subdir/res1.jar, res2.jar and in the top bundle n = countResources("/fw_test_multi.txt"); assertEquals("Multiple resources should be reflected by CL.getResources() > 1", 4, n); //bundle.loadClass test boolean cauchtException = false; try{ bc.getBundle().loadClass("org.knopflerfish.bundle.io.Activato"); } catch(ClassNotFoundException e){ cauchtException = true; } if(!cauchtException){ fail("bundle.loadclass failed to generate exception for non-existent class"); } try{ bc.getBundle().loadClass("org.knopflerfish.bundle.io.Activator"); } catch(ClassNotFoundException e){ fail("bundle.loadclass failed"); } try{ bc.getBundle().loadClass("org.osgi.service.io.ConnectionFactory"); } catch(ClassNotFoundException e){ fail("bundle.loadclass failed"); } //existing directory Enumeration enume = bc.getBundle().getEntryPaths("/"); if(enume == null ){ fail("GetEntryPaths did not retrieve the correct number of elements, " +"/"); } out.println("bc.getBundle().getEntryPaths(\"/\")"); int i = 0; while(enume.hasMoreElements()){ i++; out.println(enume.nextElement()); } // This test needs to be updated every time a the // framework_tests bundle is changed in such a way that new // files or directories are added or removed to / from the top // level of the bundle jar-file. if(i != 43){ fail("GetEntryPaths did not retrieve the correct number of elements, " +"43 != "+ i); } //another existing directory out.println("getEntryPaths(\"/org/knopflerfish/bundle/framework_test\")"); enume = bc.getBundle() .getEntryPaths("/org/knopflerfish/bundle/framework_test"); if(enume == null ){ fail("GetEntryPaths did not retrieve the correct number of elements, " +"framework_test"); } i = 0; while(enume.hasMoreElements()){ i++; out.println(enume.nextElement()); } // This test needs to be updated every time a the // FrameworkTestSuite is changed in such a way that new files // or directories are added or removed to/from the sub-dir // "org/knopflerfish/bundle/framework_test" of the jar-file. if(i!=111){ fail("GetEntryPaths did not retrieve the correct number of elements, " +"111 != " + i); } //existing file, non-directory, ending with slash enume = bc.getBundle().getEntryPaths("/bundleA_test-1.0.0.jar/"); if(enume != null ){ fail("GetEntryPaths did not retrieve the correct number of elements"); } //existing file, non-directory enume = bc.getBundle().getEntryPaths("/bundleA_test-1.0.0.jar"); if(enume != null ){ fail("GetEntryPaths did not retrieve the correct number of elements"); } //non-existing file enume = bc.getBundle().getEntryPaths("/e"); if(enume != null){ fail("GetEntryPaths did not retrieve the correct number of elements"); } //empty dir enume = bc.getBundle().getEntryPaths("/emptySubDir"); if(enume != null){ fail("GetEntryPaths did not retrieve the correct number of elements"); } //dir with only one entry enume = bc.getBundle().getEntryPaths("/org/knopflerfish/bundle"); if(enume == null ){ fail("GetEntryPaths did not retrieve the correct number of elements"); } i = 0; while(enume.hasMoreElements()){ i++; enume.nextElement(); } if(i != 1){ fail("GetEntryPaths did not retrieve the correct number of elements"); } //TODO more, extensive loadClass tests // the fw_test_single.txt resource is present just // res2.jar n = countResources("/fw_test_single.txt"); assertEquals("Single resources should be reflected by CL.getResources() == 1", 1, n); // getEntry test URL url = bc.getBundle().getEntry("/fw_test_multi.txt"); assertURLExists(url); // the fw_test_nonexistent.txt is not present at all n = countResources("/fw_test_nonexistent.txt"); assertEquals("Multiple nonexistent resources should be reflected by CL.getResources() == 0", 0, n); // Try to get the top level URL of the bundle url = bc.getBundle().getResource("/"); out.println("bc.getBundle().getResource(\"/\") -> " +url); assertNotNull("bc.getBundle().getResource(\"/\")",url); // Check that we can build a usable URL from root URL. url = new URL(url,"META-INF/MANIFEST.MF"); assertURLExists(url); // Try to get the top level URLs of the bundle and check them { out.println("bc.getBundle().getResources(\"/\") -> "); Enumeration e = bc.getBundle().getResources("/"); assertNotNull("bc.getBundle().getResources(\"/\")", e); while(e.hasMoreElements()) { url = (URL)e.nextElement(); out.println("\t" +url); assertNotNull("Bundle root URL", url); } } out.println("### framework test bundle :FRAME068A:PASS"); } int countResources(String name) throws Exception { return countResources(name, false); } int countResources(String name, boolean verbose ) throws Exception { Bundle bundle = bc.getBundle(); int n = 0; Enumeration e = bundle.getResources(name); if (verbose) { out.println("bc.getBundle().getResources(\"" + name +"\") -> "); } if(e == null) return 0; while(e.hasMoreElements()) { URL url = (URL)e.nextElement(); if (verbose) { out.println("\t" +url); } assertURLExists(url); n++; } return n; } void testRes(String name, int count) throws Exception { out.println("testRes(" + name + ")"); ClassLoader cl = getClass().getClassLoader(); URL url1 = cl.getResource(name); out.println(" ClassLoader url = " + url1); assertURLExists(url1); URL url2 = bc.getBundle().getResource(name); out.println(" bundle url = " + url1); assertURLExists(url2); int n = 1; for(Enumeration e = cl.getResources(name); e.hasMoreElements(); ) { URL url = (URL)e.nextElement(); out.println(" " + n + " = " + url); assertURLExists(url); n++; } } void assertURLExists(URL url) throws Exception { InputStream is = null; try { is = url.openStream(); assertNotNull("URL " + url + " should give a non-null stream", is); return; } finally { try { is.close(); } catch (Exception ignored) { } } } } public final static String [] HELP_FRAME069A = { "Tests contents of multiple resources inside the test bundle itself", "using ClassLoader.getResource" }; class Frame069a extends FWTestCase { public void runTest() throws Throwable { Hashtable texts = new Hashtable(); texts.put("This is a resource in the bundle's res2.jar internal jar file", Boolean.FALSE); texts.put("This is a resource in the bundle's res1.jar internal jar file", Boolean.FALSE); texts.put("This is a resource in the bundle's main package", Boolean.FALSE); verifyContent("/fw_test_multi.txt", texts); texts = new Hashtable(); texts.put("This is a single resource in the bundle's res2.jar internal jar file.", Boolean.FALSE); verifyContent("/fw_test_single.txt", texts); out.println("### framework test bundle :FRAME069A:PASS"); } void verifyContent(String name, Hashtable texts) throws Exception { ClassLoader cl = getClass().getClassLoader(); for(Enumeration e = cl.getResources(name); e.hasMoreElements();) { URL url = (URL)e.nextElement(); out.println("Loading text from "+url); String s = new String(Util.loadURL(url)); if(!texts.containsKey(s)) { fail("Checking resource name '" + name + "', found unexpected content '" + s + "' in " + url); } texts.put(s, Boolean.TRUE); } for(Enumeration e = texts.keys(); e.hasMoreElements();) { String s = (String)e.nextElement(); Boolean b = (Boolean)texts.get(s); if(!b.booleanValue()) { fail("Checking resource name '" + name + "', did not find content '" + s + "'"); } } } } public final static String [] HELP_FRAME070A = { "Reinstalls and the updates testbundle_A.", "The version is checked to see if an update has been made." }; class Frame070a extends FWTestCase { public void runTest() throws Throwable { boolean teststatus = true; boolean catchstatus = true; String jarA = "bundleA_test-1.0.0.jar"; String jarA1 = "bundleA1_test-1.0.1.jar"; InputStream fis; String versionA; String versionA1; buA = null; try { buA = Util.installBundle(bc, jarA); teststatus = true; } catch (BundleException bexcA) { fail("framework test bundle "+ bexcA +" :FRAME070A:FAIL"); teststatus = false; } catch (SecurityException secA) { fail("framework test bundle "+ secA +" :FRAME070A:FAIL"); teststatus = false; } Dictionary ai = buA.getHeaders(); if(false) { // debugging for (Enumeration e = ai.keys(); e.hasMoreElements();) { Object key = e.nextElement(); Object value = ai.get(key); String s = key.toString(); String v = value.toString(); out.println("A: Manifest info: " + s + ", " + v); } } versionA = (String) ai.get("Bundle-Version"); clearEvents(); out.println("Before version = " + versionA); try { URL urk = bc.getBundle().getResource(jarA1); out.println("update from " + urk); // URLConnection url1 = URLConnection (urk); fis = urk.openStream(); if(fis == null) { fail("No data at " + urk + ":FRAME070A:FAIL"); } try { // TODO rework, does not always work long lastModified = buA.getLastModified(); buA.update(fis); /* if(buA.getLastModified() <= lastModified){ fail("framework test bundle, update does not change lastModified value :FRAME070A:FAIL"); }*/ } catch (BundleException be ) { teststatus = false; fail("framework test bundle, update without new bundle source :FRAME070A:FAIL"); } } catch (MalformedURLException murk) { teststatus = false; fail("framework test bundle, update file not found " + murk+ " :FRAME070A:FAIL"); } catch (FileNotFoundException fnf) { teststatus = false; fail("framework test bundle, update file not found " + fnf+ " :FRAME070A:FAIL"); } catch (IOException ioe) { teststatus = false; fail("framework test bundle, update file not found " + ioe+ " :FRAME070A:FAIL"); } Dictionary a1i = buA.getHeaders(); if(false) { // debugging for (Enumeration e = a1i.keys(); e.hasMoreElements();) { Object key = e.nextElement(); Object value = a1i.get(key); String s = key.toString(); String v = value.toString(); out.println("A1: Manifest info: " + s + ", " + v); } } a1i = buA.getHeaders(); versionA1 = (String) a1i.get("Bundle-Version"); out.println("After version = " + versionA1); // check the events, none should have happened boolean lStat = checkListenerEvents(out, false, 0, true ,BundleEvent.UPDATED , false, 0, buA, null); if (versionA1.equals(versionA)) { teststatus = false; fail("framework test bundle, update of bundle failed, version info unchanged :FRAME070A:Fail"); } if (teststatus == true ) { out.println("### framework test bundle :FRAME070A:PASS"); } else { fail("### framework test bundle :FRAME070A:FAIL"); } } } // 15. Uninstall a the testbundle B and then try to start and stop it // In both cases exceptions should be thrown. public final static String [] HELP_FRAME075A = { "Uninstall bundleB_test and the try to start and stop it.", "In both cases exceptions should be thrown." }; class Frame075a extends FWTestCase { public void runTest() throws Throwable { boolean teststatus = true; boolean exep1 = false; boolean exep2 = false; try { buB.uninstall(); } catch (BundleException be) { teststatus = false; fail("framework test bundle, uninstall of bundleB failed:" + be +" :FRAME075A:FAIL"); } catch (Exception e) { fail("framework test bundle, got unexpected exception " + e + " :FRAME075A:FAIL"); e.printStackTrace(); } try { buB.start(); } catch (BundleException be) { teststatus = false; fail("framework test bundle, got unexpected exception " + be + "at start :FRAME075A:FAIL"); } catch (IllegalStateException ise) { exep1 = true; // out.println("Got expected exception" + ise); } catch (SecurityException sec) { teststatus = false; fail("framework test bundle, got unexpected exception " + sec + " :FRAME075A:FAIL"); } catch (Exception e) { fail("framework test bundle, got unexpected exception " + e + " :FRAME075A:FAIL"); e.printStackTrace(); } try { buB.stop(); } catch (BundleException be) { teststatus = false; fail("framework test bundle, got unexpected exception " + be + "at stop :FRAME075A:FAIL"); } catch (IllegalStateException ise) { exep2 = true; // out.println("Got expected exception" + ise); } catch (SecurityException sec) { teststatus = false; fail("framework test bundle, got unexpected exception " + sec + " :FRAME075A:FAIL"); } catch (Exception e) { fail("framework test bundle, got unexpected exception " + e + " :FRAME075A:FAIL"); e.printStackTrace(); } // System.err.println("teststatus=" + teststatus + " exep1= " + exep1 + " exep2= " + exep2); teststatus = teststatus && exep1 && exep2; if (teststatus == true ) { out.println("### framework test bundle :FRAME075A:PASS"); } else { fail("### framework test bundle :FRAME075A:FAIL"); } } } // 16. Install and start testbundle F and then try to and stop it // In this case a bundeException is expected public final static String [] HELP_FRAME080A = { "Installs and starts bundleF_test and then try to and stop it.", "A BundleException is expected." }; class Frame080a extends FWTestCase { public void runTest() throws Throwable { boolean teststatus = true; boolean catchstatus = true; buF = null; try { buF = Util.installBundle(bc, "bundleF_test-1.0.0.jar"); } catch (BundleException bexcA) { fail("framework test bundle "+ bexcA +" :FRAME080A:FAIL"); teststatus = false; } catch (SecurityException secA) { fail("framework test bundle "+ secA +" :FRAME080A:FAIL"); teststatus = false; } Dictionary dict = buF.getHeaders("fr_CA"); if(!dict.get(Constants.BUNDLE_SYMBOLICNAME).equals("org.knopflerfish.bundle.bundleF_test")){ fail("framework test bundle, " + Constants.BUNDLE_SYMBOLICNAME + " header does not have correct value:FRAME080A:FAIL"); } if(!dict.get(Constants.BUNDLE_DESCRIPTION).equals("Test")){ fail("framework test bundle, " + Constants.BUNDLE_DESCRIPTION + " header does not have correct localized value:FRAME080A:FAIL"); } dict = buF.getHeaders("fr"); if(!dict.get(Constants.BUNDLE_DESCRIPTION).equals("Tezt")){ fail("framework test bundle, " + Constants.BUNDLE_DESCRIPTION + " header does not have correct localized value:FRAME080A:FAIL"); } // now start it try { buF.start(); } catch (BundleException bexcA) { fail("framework test bundle, unexpected exception "+ bexcA +" :FRAME080A:FAIL"); teststatus = false; bexcA.printStackTrace(); } catch (IllegalStateException ise) { fail("framework test bundle "+ ise +" :FRAME080A:FAIL"); teststatus = false; ise.printStackTrace(); } catch (SecurityException sec) { fail("framework test bundle "+ sec +" :FRAME080A:FAIL"); teststatus = false; sec.printStackTrace(); } // now for the test of a stop that should casue an exception ServiceReference sr1 = bc.getServiceReference("org.knopflerfish.service.bundleF_test.BundleF"); clearEvents (); try { buF.stop(); } catch (BundleException be) { Throwable t1 = be.getNestedException(); if (t1.getMessage().equals("BundleF stop")) { catchstatus = true; // out.println("Got expected exception" + be); } else { catchstatus = false; } } catch (IllegalStateException ise) { teststatus = false; fail("framework test bundle, got unexpected exception " + ise + "at stop :FRAME080A:FAIL"); } catch (SecurityException sec) { teststatus = false; fail("framework test bundle, got unexpected exception " + sec + " :FRAME080A:FAIL"); } catch (Exception e) { fail("framework test bundle, got unexpected exception " + e + " :FRAME080A:FAIL"); e.printStackTrace(); } // check the events, boolean lStat = checkListenerEvents(out, false, 0, true ,BundleEvent.STOPPED , true, ServiceEvent.UNREGISTERING, buF, sr1); // out.println("lStat = "+ lStat); if (catchstatus == false) { teststatus = false; } if (teststatus == true && lStat == true ) { out.println("### framework test bundle :FRAME080A:PASS"); } else { fail("### framework test bundle :FRAME080A:FAIL"); } } } // 17. Install and start testbundle H, a service factory and test that the methods // in that interface works. public final static String [] HELP_FRAME085A = { "Installs and starts bundleH_test, a service factory", "and tests that the methods in that API works." }; class Frame085a extends FWTestCase { public void runTest() throws Throwable { buH = null; boolean teststatus = true; try { buH = Util.installBundle(bc, "bundleH_test-1.0.0.jar"); buH.start(); teststatus = true; } catch (BundleException bexcA) { fail("framework test bundle "+ bexcA +" :FRAME085A:FAIL"); teststatus = false; } catch (SecurityException secA) { fail("framework test bundle "+ secA +" :FRAME085A:FAIL"); teststatus = false; } Dictionary dict = buH.getHeaders("en_US"); if(!dict.get(Constants.BUNDLE_SYMBOLICNAME).equals("org.knopflerfish.bundle.bundleH_test")){ fail("framework test bundle, " + Constants.BUNDLE_SYMBOLICNAME + " header does not have rightt value:FRAME085A:FAIL"); } if(!dict.get(Constants.BUNDLE_DESCRIPTION).equals("Test bundle for framework, bundleH_test")){ fail("framework test bundle, " + Constants.BUNDLE_DESCRIPTION + " header does not have rightt value:FRAME085A:FAIL"); } if(!dict.get(Constants.BUNDLE_NAME).equals("bundle_H")){ fail("framework test bundle, " + Constants.BUNDLE_NAME + " header does not have rightt value:FRAME085A:FAIL"); } if(!dict.get(Constants.BUNDLE_VERSION).equals("2.0.0")){ fail("framework test bundle, " + Constants.BUNDLE_VERSION + " header does not have right value:FRAME085A:FAIL"); } // Check that a service reference exist ServiceReference sr1 = bc.getServiceReference("org.knopflerfish.service.bundleH_test.BundleH"); if (sr1 == null) { fail("framework test bundle, no service from test bundle H found :FRAME085A:FAIL"); teststatus = false; } // check the listeners for events, expect only a bundle event, of type installation boolean lStat = checkListenerEvents(out, false , 0, true , BundleEvent.STARTED, true, ServiceEvent.REGISTERED, buH, sr1); // Object sf = bc.getService(sr1); // System.out.println("SERVICE = "+ sf); // Object sf1 = bc.getService(sr1); // System.out.println("SERVICE = "+ sf1); try { buH.stop(); } catch (BundleException bexp) { out.println("framework test bundle, exception in stop method :" + bexp + " FRAME085A"); teststatus = false; } catch (Throwable thr) { fail("framework test bundle, exception in stop method :" + thr + " :FRAME085A:Fail"); teststatus = false; } if (teststatus == true && buH.getState() == Bundle.RESOLVED && lStat == true) { out.println("### framework test bundle :FRAME085A:PASS"); } else { fail("### framework test bundle :FRAME085A:FAIL"); } } } // 22. Install testbundle J, which should throw an exception at start // then check if the framework removes all traces of the bundle // as it registers one service itself before the bundle exception is thrown public final static String [] HELP_FRAME110A = { "Install and start bundleJ_test, which should throw an exception at start.", "then check if the framework removes all traces of the bundle", "as it registers one service (itself) before the bundle exception is thrown" }; class Frame110a extends FWTestCase { public void runTest() throws Throwable { clearEvents(); buJ = null; boolean lStat1 = false; boolean teststatus = true; boolean bex = false; try { buJ = Util.installBundle(bc, "bundleJ_test-1.0.0.jar"); lStat1 = checkListenerEvents(out, false, 0, true, BundleEvent.INSTALLED, false, 0, buJ, null); buJ.start(); teststatus = false; } catch (BundleException bexcA) { out.println("framework test bundle "+ bexcA +" :FRAME110A:expexted"); bex = true; } catch (SecurityException secA) { teststatus = false; fail("framework test bundle "+ secA +" :FRAME110A:FAIL"); } if (bex != true ) { teststatus = false; fail("framework test bundle, expected bundle exception missing :FRAME110A"); } if(buJ == null) { fail("No installed bundle: :FRAME110A:FAIL"); } // check the listeners for events, expect only a bundle event, of type installation boolean lStat2 = checkListenerEvents(out, false , 0, true , BundleEvent.RESOLVED, true, ServiceEvent.UNREGISTERING, buJ, null); if (teststatus == true && buJ.getState() == Bundle.RESOLVED && lStat1 == true && lStat2 == true) { out.println("### framework test bundle :FRAME110A:PASS"); } else { fail("### framework test bundle :FRAME110A:FAIL"); } // Check that no service reference exist from the crashed bundle J. ServiceReference sr1 = bc.getServiceReference("org.knopflerfish.service.bundleJ_test.BundleJ"); if (sr1 != null) { fail("framework test bundle, service from test bundle J unexpectedly found :FRAME110A:FAIL"); } } } public final static String [] HELP_FRAME115A = { "Test getDataFile() method." }; class Frame115a extends FWTestCase { public void runTest() throws Throwable { boolean teststatus = true; String filename = "testfile_1"; byte [] testdata = {1,2,3,4,5}; File testFile = bc.getDataFile(filename); if (testFile != null ) { try { FileOutputStream fout = new FileOutputStream (testFile); fout.write(testdata); fout.close(); } catch (IOException ioe) { teststatus = false; fail("framework test bundle, I/O error on write in FRAME115A " + ioe); } try { FileInputStream fin = new FileInputStream (testFile); byte [] indata = new byte [5]; int incount; incount = fin.read(indata); fin.close(); if (incount == 5) { for (int i = 0; i< incount; i++ ) { if (indata[i] != testdata[i]) { teststatus = false; fail("framework test bundle FRAME115A, is " + indata [i] + ", should be " + testdata [i]); } } } else { teststatus = false; fail("framework test bundle, I/O data error in FRAME115A"); out.println("Should be 5 bytes, was " + incount ); } } catch (IOException ioe) { teststatus = false; fail("framework test bundle, I/O error on read in FRAME115A " + ioe); } } else { // nothing to test fail("framework test bundle, no persistent data storage FRAME115A"); teststatus = true; } // Remove testfile_1 testFile.delete(); if (teststatus == true) { out.println("### framework test bundle :FRAME115A:PASS"); } else { fail("### framework test bundle :FRAME115A:FAIL"); } } } // 24. Test of the AdminPermission class public final static String [] HELP_FRAME120A = { "Test of the AdminPermission class" }; class Frame120a extends FWTestCase { public void runTest() throws Throwable { boolean teststatus = true; String s1 = null; String s2 = null; AdminPermission ap1 = new AdminPermission(); AdminPermission ap2 = null; SocketPermission sp1 = new SocketPermission("localhost:6666","listen"); // to test of cats among hermelins Object testObject = new Object(); // constructor and getName method check if (!ap1.getName().equals("*")) { out.println("framework test bundle, Name of AdminPermission object is " + ap1.getName() + " in FRAME120A"); fail("framework test bundle, Name of AdminPermission object should be: AdminPermission"); teststatus = false; } //this is no longer valid! try { ap2 = new AdminPermission(s1,s2); } catch (Exception e) { fail("framework test bundle, constructor with two null strings failed in FRAME120A"); teststatus = false; } if (ap2 != null && !ap2.getName().equals("AdminPermission")) { out.println("framework test bundle, Name of AdminPermission object is " + ap2.getName() + " in FRAME120A"); out.println("framework test bundle, Name of AdminPermission object should be: AdminPermission"); teststatus = false; } // implies method check AdminPermission ap3 = new AdminPermission(); if (!ap1.implies(ap3)) { out.println("framework test bundle, implies method failed, returned "+ ap1.implies(ap3) + " should have been true, FRAME120A"); teststatus = false; } if (ap1.implies(sp1)) { out.println("framework test bundle, implies method failed, returned "+ ap1.implies(sp1) + " should have been false, FRAME120A"); teststatus = false; } // equals method check if (!ap1.equals(ap2)) { out.println("framework test bundle, equals method failed, returned "+ ap1.equals(ap2) + " should have been true, FRAME120A"); teststatus = false; } if (ap1.equals(sp1)) { out.println("framework test bundle, equals method failed, returned "+ ap1.equals(sp1) + " should have been false, FRAME120A"); teststatus = false; } // newPermissionCollection method check, also check the implemented // abstract methods of the PermissionCollection PermissionCollection pc1 = ap1.newPermissionCollection(); if (pc1 != null) { pc1.add (ap1); boolean trig = false; try { // add a permission that is not an AdminPermission pc1.add (sp1); trig = true; } catch (RuntimeException ex1) { trig = false; } if (trig == true) { out.println("framework test bundle, add method on PermissionCollection failed, FRAME120A"); out.println("permission with type different from AdminPermission succeded unexpectedly FRAME120A"); teststatus = false; } pc1.add (ap2); if (!pc1.implies(ap3)) { out.println("framework test bundle, implies method on PermissionCollection failed, FRAME120A"); teststatus = false; } boolean hit1 = false; int count = 0; /* The enumeration of this kind of permission is a bit weird as it actually returns a new AdminPermission if an element has been added, thus the test becomes a bit odd. This comes from looking at the source code, i.e a bit of peeking behind the screens but in this case it was necessary as the functionality is not possible to understand otherwise. */ for (Enumeration e = pc1.elements(); e.hasMoreElements(); ) { AdminPermission ap4 = (AdminPermission) e.nextElement(); // out.println("DEBUG framework test bundle, got AdminPermission " + ap4 +" FRAME120A"); count++; if (ap4 != null) { hit1 = true;} } if (hit1 != true || count != 1) { teststatus = false; out.println("framework test bundle, elements method on PermissionCollection failed, FRAME120A"); if (hit1 != true) { out.println("framework test bundle, no AdminPermission retrieved, FRAME120A"); } if (count != 1) { out.println("framework test bundle, number of entered objects: 1, number retrieved: " + count + " , FRAME120A"); } } if (pc1.isReadOnly() == true) { teststatus = false; out.println("framework test bundle, isReadOnly method on PermissionCollection is: "+pc1.isReadOnly() +" should be false, FRAME120A"); } pc1.setReadOnly(); if (pc1.isReadOnly() == false) { teststatus = false; out.println("framework test bundle, isReadOnly method on PermissionCollection is: "+pc1.isReadOnly() +" should be true, FRAME120A"); } } else { out.println("framework test bundle, newPermissionCollection method failed, returned null, FRAME120A"); teststatus = false; } if (teststatus == true) { out.println("### framework test bundle :FRAME120A:PASS"); } else { fail("### framework test bundle :FRAME120A:FAIL"); } } } // 25. Test of the PackagePermission class public final static String [] HELP_FRAME125A = { "Test of the PackagePermission class" }; class Frame125a extends FWTestCase { public void runTest() throws Throwable { boolean teststatus = true; String validName = "valid.name.test"; String validName1 = "valid.name.test1"; String validName2 = "valid.name.test2"; String invalidName = null; String validAction = PackagePermission.EXPORT+","+PackagePermission.IMPORT; String invalidAction = "apa"; PackagePermission pp1 = null; PackagePermission pp2 = null; PackagePermission pp3 = null; PackagePermission pp4 = null; // constructor check try { pp1 = new PackagePermission(validName,validAction); } catch (RuntimeException re) { out.println("framework test bundle, PackagePermission constructor("+ validName +"," + validAction + ") failed, in FRAME125A"); teststatus = false; } try { pp1 = new PackagePermission(invalidName,validAction); out.println("framework test bundle, PackagePermission constructor("+ invalidName +"," + validAction + ") succeded unexpected, in FRAME125A"); teststatus = false; } catch (RuntimeException re) { } try { pp1 = new PackagePermission(validName,invalidAction); out.println("framework test bundle, PackagePermission constructor("+ validName +"," + invalidAction + ") succeded unexpected, in FRAME125A"); teststatus = false; } catch (RuntimeException re) { } try { pp1 = new PackagePermission(invalidName,invalidAction); out.println("framework test bundle, PackagePermission constructor("+ invalidName +"," + invalidAction + ") succeded unexpected, in FRAME125A"); teststatus = false; } catch (RuntimeException re) { } // equals test pp1 = new PackagePermission(validName,validAction); pp2 = new PackagePermission(validName,validAction); if (!pp1.equals(pp2)) { out.println("framework test bundle, PackagePermission equals method failed for identical objects, in FRAME125A"); teststatus = false; } pp3 = new PackagePermission(validName,PackagePermission.IMPORT); if (pp1.equals(pp3)) { out.println("framework test bundle, PackagePermission equals method failed for non identical objects, in FRAME125A"); teststatus = false; } pp3 = new PackagePermission(validName2,validAction); if (pp1.equals(pp3)) { out.println("framework test bundle, PackagePermission equals method failed for non identical objects, in FRAME125A"); teststatus = false; } // getActions test pp1 = new PackagePermission(validName,PackagePermission.IMPORT); pp2 = new PackagePermission(validName,PackagePermission.EXPORT); pp3 = new PackagePermission(validName,PackagePermission.IMPORT+","+PackagePermission.EXPORT); pp4 = new PackagePermission(validName,PackagePermission.EXPORT+","+PackagePermission.IMPORT); if (!pp1.getActions().equals(PackagePermission.IMPORT)) { out.println("framework test bundle, PackagePermission getActions method failed in FRAME125A"); out.println("framework test bundle, expected: "+PackagePermission.IMPORT); out.println("framework test bundle, got:" + pp1.getActions()); teststatus = false; } if (!pp2.getActions().equals(PackagePermission.EXPORT+","+PackagePermission.IMPORT)) { out.println("framework test bundle, PackagePermission getActions method failed in FRAME125A"); out.println("framework test bundle, expected: "+PackagePermission.EXPORT); out.println("framework test bundle, got:" + pp2.getActions()); teststatus = false; } if (!pp3.getActions().equals(PackagePermission.EXPORT+","+PackagePermission.IMPORT)) { out.println("framework test bundle, PackagePermission getActions method failed in FRAME125A"); out.println("framework test bundle, expected: "+PackagePermission.EXPORT +","+PackagePermission.IMPORT); out.println("framework test bundle, got:" + pp3.getActions()); teststatus = false; } if (!pp4.getActions().equals(PackagePermission.EXPORT+","+PackagePermission.IMPORT)) { out.println("framework test bundle, PackagePermission getActions method failed in FRAME125A"); out.println("framework test bundle, expected: "+PackagePermission.EXPORT +","+PackagePermission.IMPORT); out.println("framework test bundle, got:" + pp4.getActions()); teststatus = false; } // implies test boolean impstatus = true; pp1 = new PackagePermission(validName,PackagePermission.IMPORT); pp2 = new PackagePermission(validName,PackagePermission.EXPORT); impstatus = impstatus && implyCheck (out, true, pp2, pp1); // export implies import impstatus = impstatus && implyCheck (out, false, pp1, pp2); // import does not imply export pp1 = new PackagePermission("test1.*",PackagePermission.EXPORT); pp2 = new PackagePermission("test2.*",PackagePermission.EXPORT); impstatus = impstatus && implyCheck (out, false, pp2, pp1); // different packet names, implication = false impstatus = impstatus && implyCheck (out, false, pp1, pp2); // different packet names, implication = false pp1 = new PackagePermission("test1.*",PackagePermission.EXPORT); pp2 = new PackagePermission("test1.a", PackagePermission.EXPORT); impstatus = impstatus && implyCheck (out, false, pp2, pp1); // test1.a does not imply test1.*, implication = false impstatus = impstatus && implyCheck (out, true, pp1, pp2); // test1.* implies test1.a, implication = true pp1 = new PackagePermission("test1.*",PackagePermission.EXPORT); pp2 = new PackagePermission("test1.a",PackagePermission.IMPORT); pp3 = new PackagePermission("test1.*",PackagePermission.IMPORT); pp4 = new PackagePermission("test1.a",PackagePermission.EXPORT); impstatus = impstatus && implyCheck (out, true, pp1, pp1); // test1.* & export implies test1.* & export, implication = true impstatus = impstatus && implyCheck (out, true, pp1, pp2); // test1.* & export implies test1.a & import, implication = true impstatus = impstatus && implyCheck (out, true, pp1, pp3); // test1.* & export implies test1.* & import, implication = true impstatus = impstatus && implyCheck (out, true, pp1, pp4); // test1.* & export implies test1.a & export, implication = true impstatus = impstatus && implyCheck (out, false, pp2, pp1); // test1.a & import does not imply test1.* & export, implication = false impstatus = impstatus && implyCheck (out, true, pp2, pp2); // test1.a & import implies test1.a & import, implication = true impstatus = impstatus && implyCheck (out, false, pp2, pp3); // test1.a & import does not imply test1.* & import, implication = false impstatus = impstatus && implyCheck (out, false, pp2, pp4); // test1.a & import does not imply test1.a & export, implication = false impstatus = impstatus && implyCheck (out, false, pp3, pp1); // test1.* & import does not imply test1.* & export, implication = false impstatus = impstatus && implyCheck (out, true, pp3, pp2); // test1.* & import implies test1.a & import, implication = true impstatus = impstatus && implyCheck (out, true, pp3, pp3); // test1.* & import implies test1.* & import, implication = true impstatus = impstatus && implyCheck (out, false, pp3, pp4); // test1.* & import does not imply test1.a & export, implication = false impstatus = impstatus && implyCheck (out, false, pp4, pp1); // test1.a & export does not imply test1.* & export, implication = false impstatus = impstatus && implyCheck (out, true, pp4, pp2); // test1.a & export implies test1.a & import, implication = true impstatus = impstatus && implyCheck (out, false, pp4, pp3); // test1.a & export does not imply test1.* & import, implication = false impstatus = impstatus && implyCheck (out, true, pp4, pp4); // test1.a & export implies test1.a & export, implication = true // newPermissionCollection tests PackagePermission pp5 = new PackagePermission("test1.*",PackagePermission.EXPORT); PackagePermission pp6 = new PackagePermission("test1.a",PackagePermission.IMPORT); PackagePermission pp7 = new PackagePermission("test2.*",PackagePermission.IMPORT); PackagePermission pp8 = new PackagePermission("test2.a",PackagePermission.EXPORT); PackagePermission pp9 = new PackagePermission("test3.a",PackagePermission.EXPORT); PermissionCollection pc1 = pp5.newPermissionCollection(); if (pc1 != null) { int count = 0; boolean b1 = false; boolean b2 = false; boolean b3 = false; boolean b4 = false; try { pc1.add(pp5); pc1.add(pp6); pc1.add(pp7); pc1.add(pp8); for (Enumeration e = pc1.elements(); e.hasMoreElements(); ) { PackagePermission ptmp = (PackagePermission) e.nextElement(); // out.println("DEBUG framework test bundle, got AdminPermission " + ptmp +" FRAME125A"); count++; if (ptmp == pp5) { b1 = true;} if (ptmp == pp6) { b2 = true;} if (ptmp == pp7) { b3 = true;} if (ptmp == pp8) { b4 = true;} } if (count != 4 || b1 != true || b2 != true || b3 != true || b4 != true) { teststatus = false; out.println("framework test bundle, elements method on PermissionCollection failed, FRAME125A"); if (count != 4) { out.println("framework test bundle, number of entered PackagePermissions: 4, number retrieved: " + count + " , FRAME125A"); } } boolean ipcstat = true; ipcstat = ipcstat && implyCheck (out, true, pc1, pp5); // test1.* & export implies test1.* & export, implication = true ipcstat = ipcstat && implyCheck (out, false, pc1, pp9); // test1.* & export does not imply test3.a & export, implication = false if (ipcstat != true) { teststatus = false; } } catch (Throwable ex) { out.println("DEBUG framework test bundle, Exception " + ex); ex.printStackTrace(); ex.printStackTrace(out); } } else { // teststatus = false; out.println("framework test bundle, newPermissionsCollection method on PackagePermission returned null,FRAME125A"); } if (teststatus == true && impstatus == true) { out.println("### framework test bundle :FRAME125A:PASS"); } else { fail("### framework test bundle :FRAME125A:FAIL"); } } } // 26. Test of the ServicePermission class public final static String [] HELP_FRAME130A = { "Test of the ServicePermission class" }; class Frame130a extends FWTestCase { public void runTest() throws Throwable { boolean teststatus = true; String validClass = "valid.class.name"; String validClass1 = "valid.class.name.1"; String validClass2 = "valid.class.name.2"; String invalidClass = null; String validAction = ServicePermission.GET+","+ServicePermission.REGISTER; String invalidAction = "skunk"; ServicePermission sp1 = null; ServicePermission sp2 = null; ServicePermission sp3 = null; ServicePermission sp4 = null; ServicePermission sp5 = null; ServicePermission sp6 = null; ServicePermission sp7 = null; ServicePermission sp8 = null; // constructor check try { sp1 = new ServicePermission (validClass,validAction); } catch (RuntimeException re) { out.println("framework test bundle, ServicePermission constructor("+ validClass +"," + validAction + ") failed, in FRAME130A"); teststatus = false; } try { sp1 = new ServicePermission(invalidClass,validAction); out.println("framework test bundle, ServicePermission constructor("+ invalidClass +"," + validAction + ") succeded unexpected, in FRAME130A"); teststatus = false; } catch (RuntimeException re) { } try { sp1 = new ServicePermission(validClass,invalidAction); out.println("framework test bundle, ServicePermission constructor("+ validClass +"," + invalidAction + ") succeded unexpected, in FRAME130A"); teststatus = false; } catch (RuntimeException re) { } try { sp1 = new ServicePermission(invalidClass,invalidAction); out.println("framework test bundle, ServicePermission constructor("+ invalidClass +"," + invalidAction + ") succeded unexpected, in FRAME130A"); teststatus = false; } catch (RuntimeException re) { } // equals test sp1 = new ServicePermission(validClass,validAction); sp2 = new ServicePermission(validClass,validAction); if (!sp1.equals(sp2)) { out.println("framework test bundle, ServicePermission equals method failed for identical objects, in FRAME130A"); teststatus = false; } sp3 = new ServicePermission(validClass,ServicePermission.GET); if (sp1.equals(sp3)) { out.println("framework test bundle, ServicePermission equals method failed for non identical objects, in FRAME130A"); teststatus = false; } sp3 = new ServicePermission(validClass2,validAction); if (sp1.equals(sp3)) { out.println("framework test bundle, ServicePermission equals method failed for non identical objects, in FRAME130A"); teststatus = false; } // getActions test sp1 = new ServicePermission(validClass,ServicePermission.GET); sp2 = new ServicePermission(validClass,ServicePermission.REGISTER); sp3 = new ServicePermission(validClass,ServicePermission.GET+","+ServicePermission.REGISTER); sp4 = new ServicePermission(validClass,ServicePermission.REGISTER+","+ServicePermission.GET); if (!sp1.getActions().equals(ServicePermission.GET)) { out.println("framework test bundle, ServicePermission getActions method failed in FRAME130A"); out.println("framework test bundle, expected: "+ServicePermission.GET); out.println("framework test bundle, got: " + sp1.getActions()); teststatus = false; } if (!sp2.getActions().equals(ServicePermission.REGISTER)) { out.println("framework test bundle, ServicePermission getActions method failed in FRAME130A"); out.println("framework test bundle, expected: "+ServicePermission.REGISTER); out.println("framework test bundle, got: " + sp2.getActions()); teststatus = false; } if (!sp3.getActions().equals(ServicePermission.GET+","+ServicePermission.REGISTER)) { out.println("framework test bundle, ServicePermission getActions method failed in FRAME130A"); out.println("framework test bundle, expected: "+ServicePermission.GET +","+ServicePermission.REGISTER); out.println("framework test bundle, got: " + sp3.getActions()); teststatus = false; } if (!sp4.getActions().equals(ServicePermission.GET+","+ServicePermission.REGISTER)) { out.println("framework test bundle, ServicePermission getActions method failed in FRAME130A"); out.println("framework test bundle, expected: "+ServicePermission.GET +","+ServicePermission.REGISTER); out.println("framework test bundle, got: " + sp4.getActions()); teststatus = false; } // implies test boolean impstatus = true; sp1 = new ServicePermission(validClass,ServicePermission.GET); sp2 = new ServicePermission(validClass,ServicePermission.REGISTER); impstatus = impstatus && implyCheck (out, false, sp2, sp1); // get does not imply register impstatus = impstatus && implyCheck (out, false, sp1, sp2); // register does not imply get sp1 = new ServicePermission("validClass1.*", ServicePermission.REGISTER+","+ServicePermission.GET); sp2 = new ServicePermission("validClass2.*", ServicePermission.REGISTER+","+ServicePermission.GET); impstatus = impstatus && implyCheck (out, false, sp2, sp1); // different class names, implication = false impstatus = impstatus && implyCheck (out, false, sp1, sp2); // different class names, implication = false sp1 = new ServicePermission("validClass1.*", ServicePermission.REGISTER+","+ServicePermission.GET); sp2 = new ServicePermission("validClass1.a", ServicePermission.REGISTER+","+ServicePermission.GET); impstatus = impstatus && implyCheck (out, false, sp2, sp1); // validClass1.a does not imply validClass1.*, implication = false impstatus = impstatus && implyCheck (out, true, sp1, sp2); // validClass1.* implies validClass1.a, implication = true sp1 = new ServicePermission("test1.*",ServicePermission.REGISTER); sp2 = new ServicePermission("test1.*",ServicePermission.GET); sp3 = new ServicePermission("test1.*",ServicePermission.REGISTER+","+ServicePermission.GET); sp4 = new ServicePermission("test1.a",ServicePermission.REGISTER); sp5 = new ServicePermission("test1.a",ServicePermission.GET); sp6 = new ServicePermission("test1.a",ServicePermission.REGISTER+","+ServicePermission.GET); impstatus = impstatus && implyCheck (out, true, sp1, sp1); // test1.* & register implies test1.* & register, impstatus = impstatus && implyCheck (out, false, sp1, sp2); // test1.* & register implies not test1.* & get, impstatus = impstatus && implyCheck (out, false, sp1, sp3); // test1.* & register implies not test1.* & reg & get, impstatus = impstatus && implyCheck (out, true, sp1, sp4); // test1.* & register implies test1.a & register, impstatus = impstatus && implyCheck (out, false, sp1, sp5); // test1.* & register implies not test1.a & get, impstatus = impstatus && implyCheck (out, false, sp1, sp6); // test1.* & register implies not test1.a & reg & g, impstatus = impstatus && implyCheck (out, false, sp2, sp1); // test1.* & get implies not test1.* & register, impstatus = impstatus && implyCheck (out, true, sp2, sp2); // test1.* & get implies test1.* & get, impstatus = impstatus && implyCheck (out, false, sp2, sp3); // test1.* & get implies not test1.* & reg & get, impstatus = impstatus && implyCheck (out, false, sp2, sp4); // test1.* & get implies test1.a & register, impstatus = impstatus && implyCheck (out, true, sp2, sp5); // test1.* & get implies test1.a & get, impstatus = impstatus && implyCheck (out, false, sp2, sp6); // test1.* & get implies not test1.a & reg & g, impstatus = impstatus && implyCheck (out, true, sp3, sp1); // test1.* & get&reg implies test1.* & register, impstatus = impstatus && implyCheck (out, true, sp3, sp2); // test1.* & get&reg implies test1.* & get, impstatus = impstatus && implyCheck (out, true, sp3, sp3); // test1.* & get&reg implies test1.* & reg & get, impstatus = impstatus && implyCheck (out, true, sp3, sp4); // test1.* & get&reg implies test1.a & register, impstatus = impstatus && implyCheck (out, true, sp3, sp5); // test1.* & get&reg implies test1.a & get, impstatus = impstatus && implyCheck (out, true, sp3, sp6); // test1.* & get&reg implies test1.a & reg & g, impstatus = impstatus && implyCheck (out, false, sp4, sp1); // test1.a & reg implies not test1.* & register, impstatus = impstatus && implyCheck (out, false, sp4, sp2); // test1.a & reg implies not test1.* & get, impstatus = impstatus && implyCheck (out, false, sp4, sp3); // test1.a & reg implies not test1.* & reg & get, impstatus = impstatus && implyCheck (out, true, sp4, sp4); // test1.a & reg implies test1.a & register, impstatus = impstatus && implyCheck (out, false, sp4, sp5); // test1.a & reg implies not test1.a & get, impstatus = impstatus && implyCheck (out, false, sp4, sp6); // test1.a & reg implies not test1.a & reg & g, impstatus = impstatus && implyCheck (out, false, sp5, sp1); // test1.a & get implies not test1.* & register, impstatus = impstatus && implyCheck (out, false, sp5, sp2); // test1.a & get implies not test1.* & get, impstatus = impstatus && implyCheck (out, false, sp5, sp3); // test1.a & get implies not test1.* & reg & get, impstatus = impstatus && implyCheck (out, false, sp5, sp4); // test1.a & get implies not test1.a & register, impstatus = impstatus && implyCheck (out, true, sp5, sp5); // test1.a & get implies test1.a & get, impstatus = impstatus && implyCheck (out, false, sp5, sp6); // test1.a & get implies not test1.a & reg & g, impstatus = impstatus && implyCheck (out, false, sp6, sp1); // test1.a & get & reg implies not test1.* & register, impstatus = impstatus && implyCheck (out, false, sp6, sp2); // test1.a & get & reg implies not test1.* & get, impstatus = impstatus && implyCheck (out, false, sp6, sp3); // test1.a & get & reg implies not test1.* & reg & get, impstatus = impstatus && implyCheck (out, true, sp6, sp4); // test1.a & get & reg implies test1.a & register, impstatus = impstatus && implyCheck (out, true, sp6, sp5); // test1.a & get & reg implies test1.a & get, impstatus = impstatus && implyCheck (out, true, sp6, sp6); // test1.a & get & reg implies test1.a & reg & g, sp7 = new ServicePermission("test2.a",ServicePermission.REGISTER+","+ServicePermission.GET); sp8 = new ServicePermission("*",ServicePermission.REGISTER+","+ServicePermission.GET); impstatus = impstatus && implyCheck (out, false, sp7, sp1); // test2.a & get & reg implies not test1.* & register, impstatus = impstatus && implyCheck (out, false, sp7, sp2); // test2.a & get & reg implies not test1.* & get, impstatus = impstatus && implyCheck (out, false, sp7, sp3); // test2.a & get & reg implies not test1.* & reg & get, impstatus = impstatus && implyCheck (out, false, sp7, sp4); // test2.a & get & reg implies not test1.a & register, impstatus = impstatus && implyCheck (out, false, sp7, sp5); // test2.a & get & reg implies not test1.a & get, impstatus = impstatus && implyCheck (out, false, sp7, sp6); // test2.a & get & reg implies not test1.a & reg & g, impstatus = impstatus && implyCheck (out, true, sp8, sp1); // * & get & reg implies test1.* & register, impstatus = impstatus && implyCheck (out, true, sp8, sp2); // * & get & reg implies test1.* & get, impstatus = impstatus && implyCheck (out, true, sp8, sp3); // * & get & reg implies test1.* & reg & get, impstatus = impstatus && implyCheck (out, true, sp8, sp4); // * & get & reg implies test1.a & register, impstatus = impstatus && implyCheck (out, true, sp8, sp5); // * & get & reg implies test1.a & get, impstatus = impstatus && implyCheck (out, true, sp8, sp6); // * & get & reg implies test1.a & reg & g, PermissionCollection pc1 = sp1.newPermissionCollection(); if (pc1 != null) { int count = 0; boolean b1 = false; boolean b2 = false; boolean b3 = false; boolean b4 = false; try { pc1.add(sp1); pc1.add(sp2); pc1.add(sp3); pc1.add(sp4); // the combination of these four servicepermissions should create // a servicecollection that implies the following boolean ipcstat = true; ipcstat = ipcstat && implyCheck (out, true, pc1, sp1); // permission is in collection ipcstat = ipcstat && implyCheck (out, true, pc1, sp2); // permission is in collection ipcstat = ipcstat && implyCheck (out, true, pc1, sp3); // permission is in collection ipcstat = ipcstat && implyCheck (out, true, pc1, sp4); // permission is in collection ipcstat = ipcstat && implyCheck (out, true, pc1, sp5); // permission is in collection ipcstat = ipcstat && implyCheck (out, false, pc1, sp7); // permission is not in collection if (ipcstat != true) { teststatus = false; } } catch (Throwable ex) { out.println("DEBUG framework test bundle, Exception " + ex); ex.printStackTrace(); ex.printStackTrace(out); } } else { // teststatus = false; out.println("framework test bundle, newPermissionsCollection method on ServicePermission returned null,FRAME130A"); } if (teststatus == true && impstatus == true) { out.println("### framework test bundle :FRAME130A:PASS"); } else { out.println("### framework test bundle :FRAME130A:FAIL"); } } } public final static String [] HELP_FRAME160A = { "Test bundle resource retrieval." }; class Frame160a extends FWTestCase { public void runTest() throws Throwable { boolean pass = true; Bundle buR = null; Bundle buR1 = null; try { try { buR = Util.installBundle(bc, "bundleR_test-1.0.0.jar"); } catch (BundleException e) { out.println("Failed install R: " + e.getNestedException() + ", in FRAME160A"); pass = false; } try { buR1 = Util.installBundle(bc, "bundleR1_test-1.0.0.jar"); } catch (BundleException e) { pass = false; fail("Failed install R1: " + e.getNestedException() + ", in FRAME160A:FAIL"); } try { buR.start(); } catch (BundleException e) { e.getNestedException().printStackTrace(out); pass = false; fail("Failed start of R in FRAME160A:FAIL"); } if (pass == true) { out.println("### framework test bundle :FRAME160A:PASS"); } else { fail("### framework test bundle :FRAME160A:FAIL"); } } finally { if (buR != null) { try { buR.uninstall(); } catch (BundleException ignore) { } } if (buR1 != null) { try { buR1.uninstall(); } catch (BundleException ignore) { } } } } } public final static String [] HELP_FRAME161A = { "Test bundle resource retrieval from boot class path; " +" a resource in-side the java package." }; class Frame161a extends FWTestCase { public void runTest() throws Throwable { boolean pass = true; String resourceName = "java/lang/Thread.class"; URL url1 = bc.getBundle().getResource(resourceName); URL url2 = this.getClass().getClassLoader().getResource(resourceName); //System.out.println("URL from bundle.getResource() = "+url1); //System.out.println("URL from classLoader.getResource() = "+url2); // Bundle.getResource() as well as ClassLoader.getResource() // should return resources according to the class space // (classpath), i.e., delegate to parent class loader before // searching its own paths. assertNotNull("bundle.getResource(\"" +resourceName+"\")" , url1); assertNotNull("bundleClassLoader.getResource(\""+resourceName+"\")",url2); assertEquals("Same URL returned from booth classloader and bundle", url1,url2); if (pass == true) { out.println("### framework test bundle :FRAME161A:PASS"); } else { fail("### framework test bundle :FRAME161A:FAIL"); } } } public final static String [] HELP_FRAME162A = { "Test bundle resource retrieval from boot class path; " +" a resource outside the java package." }; class Frame162a extends FWTestCase { public void runTest() throws Throwable { boolean pass = true; // The Any class have been present since 1.2 String resourceName = "org/omg/CORBA/Any.class"; URL url1 = bc.getBundle().getResource(resourceName); URL url2 = this.getClass().getClassLoader().getResource(resourceName); //System.out.println("URL from bundle.getResource() = "+url1); //System.out.println("URL from classLoader.getResource() = "+url2); // Bundle.getResource() and BundleClassLoader.getResource() // should both return resources according to the class space // (classpath), i.e., don't delgate to parent in this case since // the resource does not belong to the java-package. assertNull("bundle.getResource(\"" +resourceName+"\")" , url1); assertNull("bundleClassLoader.getResource(\""+resourceName+"\")",url2); if (pass == true) { out.println("### framework test bundle :FRAME162A:PASS"); } else { fail("### framework test bundle :FRAME162A:FAIL"); } } } public final static String [] HELP_FRAME163A = { "Test bundle resource retrieval from boot class path; " +" a resource via boot delegation." }; class Frame163a extends FWTestCase { public void runTest() throws Throwable { boolean pass = true; // The Context class have been present in Java SE since 1.3 String resourceName = "javax/naming/Context.class"; URL url1 = bc.getBundle().getResource(resourceName); URL url2 = this.getClass().getClassLoader().getResource(resourceName); //System.out.println("URL from bundle.getResource() = "+url1); //System.out.println("URL from classLoader.getResource() = "+url2); // Bundle.getResource() as well as ClassLoader.getResource() // should return resources according to the class space // (classpath), i.e., delegate to parent class loader before // searching its own paths. assertNotNull("bundle.getResource(\"" +resourceName+"\")" , url1); assertNotNull("bundleClassLoader.getResource(\""+resourceName+"\")",url2); assertEquals("Same URL returned from booth classloader and bundle", url1,url2); if (pass == true) { out.println("### framework test bundle :FRAME163A:PASS"); } else { fail("### framework test bundle :FRAME163A:FAIL"); } } } boolean callReturned; Integer doneSyncListener; String errorFrame170; public final static String [] HELP_FRAME170A = { "Test of ServiceReference.getUsingBundles() and SynchronousBundleListener." }; class Frame170a extends FWTestCase { public void runTest() throws Throwable { ServiceRegistration tsr = null; Bundle buQ = null; Bundle buQ1 = null; try { boolean pass = true; // Make sure that there are no pending BundleListener calls. try { Thread.sleep(500); } catch (InterruptedException ignore) {} BundleListener bl1 = new BundleListener() { public void bundleChanged(BundleEvent be) { if (doneSyncListener.intValue() == 0) { errorFrame170 = "Called BundleListener before SBL"; } synchronized (doneSyncListener) { doneSyncListener = new Integer(doneSyncListener.intValue() + 1); } } }; bc.addBundleListener(bl1); SynchronousBundleListener bl2 = new SynchronousBundleListener() { public void bundleChanged(BundleEvent be) { if (callReturned) { errorFrame170 = "Returned from bundle operation before SBL was done"; } else { try { Thread.sleep(1000); } catch (InterruptedException ignore) {} if (callReturned) { errorFrame170 = "Returned from bundle operation before SBL was done"; } } synchronized (doneSyncListener) { doneSyncListener = new Integer(doneSyncListener.intValue() + 1); } } }; bc.addBundleListener(bl2); BundleListener bl3 = new BundleListener() { public void bundleChanged(BundleEvent be) { if (doneSyncListener.intValue() == 0) { errorFrame170 = "Called BundleListener before SBL"; } synchronized (doneSyncListener) { doneSyncListener = new Integer(doneSyncListener.intValue() + 1); } } }; bc.addBundleListener(bl3); doneSyncListener = new Integer(0); callReturned = false; errorFrame170 = null; try { buQ = Util.installBundle(bc, "bundleQ_test-1.0.0.jar"); callReturned = true; try { Thread.sleep(1000); } catch (InterruptedException ignore) {} if (errorFrame170 != null) { out.println(errorFrame170 + ", in FRAME170A"); pass = false; } if (doneSyncListener.intValue() != 3) { out.println("Failed to call all bundleListeners (only " + doneSyncListener + "), in FRAME170A"); pass = false; } } catch (BundleException e) { out.println("Failed install Q: " + e.getNestedException() + ", in FRAME170A"); pass = false; } bc.removeBundleListener(bl1); bc.removeBundleListener(bl2); bc.removeBundleListener(bl3); try { buQ1 = bc.installBundle("Q1", bc.getBundle().getResource("bundleQ_test-1.0.0.jar").openStream()); } catch (BundleException e) { pass = false; fail("Failed install Q1: " + e.getNestedException() + ", in FRAME170A:FAIL"); } catch (IOException e) { pass = false; fail("Failed to open Q1 url: " + e + ", in FRAME170A:FAIL"); } Hashtable props = new Hashtable(); props.put("bundleQ", "secret"); try { tsr = bc.registerService ("java.lang.Object", this, props); } catch (Exception e) { fail("Failed to register service in FRAME170A:FAIL"); } if (tsr.getReference().getUsingBundles() != null) { pass = false; String ids = "" + tsr.getReference().getUsingBundles()[0].getBundleId(); for (int i=1; i<tsr.getReference().getUsingBundles().length; i++) { ids += "," + tsr.getReference().getUsingBundles()[i].getBundleId(); } fail("Unknown bundle (" + ids + ") using service in FRAME170A:FAIL"); } try { buQ.start(); } catch (BundleException e) { e.getNestedException().printStackTrace(out); pass = false; fail("Failed start of Q in FRAME170A:FAIL"); } Bundle[] bs = tsr.getReference().getUsingBundles(); if (bs.length != 1) { pass = false; fail("Wrong number (" + bs.length + " not 1) of bundles using service in FRAME170A:FAIL"); } else if (bs[0] != buQ) { pass = false; fail("Unknown bundle using service instead of bundle Q in FRAME170A:FAIL"); } try { buQ1.start(); } catch (BundleException e) { e.getNestedException().printStackTrace(out); pass = false; fail("Failed start of Q1 in FRAME170A:FAIL"); } bs = tsr.getReference().getUsingBundles(); if (bs.length != 2) { pass = false; fail("Wrong number (" + bs.length + " not 2) of bundles using service in FRAME170A:FAIL"); } else if ((bs[0] != buQ || bs[1] != buQ1) && (bs[1] != buQ || bs[0] != buQ1)) { pass = false; fail("Unknown bundle using service instead of bundle Q and Q1 in FRAME170A:FAIL"); } try { buQ.stop(); } catch (BundleException e) { e.getNestedException().printStackTrace(out); pass = false; fail("Failed stop of Q in FRAME170A:FAIL"); } bs = tsr.getReference().getUsingBundles(); if (bs.length != 1) { pass = false; fail("After stop wrong number (" + bs.length + " not 1) of bundles using service in FRAME170A:FAIL"); } else if (bs[0] != buQ1) { pass = false; fail("Unknown bundle using service instead of bundle Q1 in FRAME170A:FAIL"); } // Check that we haven't called any bundle listeners if (doneSyncListener.intValue() != 3) { pass = false; fail("Called bundle listeners after removal (" + doneSyncListener + "), in FRAME170A:FAIL"); } if (pass == true) { out.println("### framework test bundle :FRAME170A:PASS"); } else { fail("### framework test bundle :FRAME170A:FAIL"); } } finally { // clean up if (tsr != null) { tsr.unregister(); } try { buQ.uninstall(); } catch (BundleException ignore) { } try { buQ1.uninstall(); } catch (BundleException ignore) { } } } } // 175A. Resource integrity when reading different resources of a bundle public final static String [] HELP_FRAME175A = { "Check of resource integrity when using intermixed reading of differenent resources from bundleR2_test." }; class Frame175a extends FWTestCase { public void runTest() throws Throwable { buR2 = null; boolean teststatus = true; try { buR2 = Util.installBundle(bc, "bundleR2_test-1.0.0.jar"); teststatus = true; } catch (BundleException bexcA) { teststatus = false; fail("framework test bundle "+ bexcA +" :FRAME175A:FAIL"); } catch (SecurityException secA) { teststatus = false; fail("framework test bundle "+ secA +" :FRAME175A:FAIL"); } // Now read resources A and B intermixed // A is 50 A:s , B is 50 B:s int a_cnt1 = 0; int a_cnt2 = 0; int b_cnt = 0; byte [] a1 = new byte[50]; byte [] b1 = new byte[50]; String A = "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"; String B = "BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB"; InputStream is1 = null ; InputStream is2 = null ; try { URL u1 = buR2.getResource("org/knopflerfish/bundle/bundleR2_test/A"); is1 = u1.openStream(); a_cnt1 = is1.read(a1, 0, 10); URL u2 = buR2.getResource("org/knopflerfish/bundle/bundleR2_test/B"); is2 = u2.openStream(); b_cnt = is2.read(b1, 0, 50); // continue reading from is1 now, what do we get ?? a_cnt2 = is1.read(a1, a_cnt1, 50-a_cnt1); } catch (Throwable tt) { tt.printStackTrace(); teststatus = false; fail("Failed to read resource" + " ,FRAME175A:FAIL"); } finally { try { is1.close(); is2.close(); } catch (Throwable tt) { out.println("Failed to read close input streams" + " ,FRAME175A:FAIL"); tt.printStackTrace(); teststatus = false; } } if (A.compareTo(new String(a1)) != 0) { teststatus = false; fail("framework test bundle expected: " + A + "\n got: " + new String(a1) +" :FRAME175A:FAIL"); } if (B.compareTo(new String(b1)) != 0) { teststatus = false; fail("framework test bundle expected: " + B + "\n got: " + new String(b1) +" :FRAME175A:FAIL"); } // check the resulting events if (teststatus == true) { out.println("### framework test bundle :FRAME175A:PASS"); } else { fail("### framework test bundle :FRAME175A:FAIL"); } } } // 180. Resource integrity when reading different resources of a bundle // on the top level in the namespace of the bundle. public final static String [] HELP_FRAME180A = { "Check of resource on top of bundle name space from bundleR3_test." }; class Frame180a extends FWTestCase { public void runTest() throws Throwable { buR3 = null; boolean teststatus = true; try { buR3 = Util.installBundle(bc, "bundleR3_test-1.0.0.jar"); teststatus = true; } catch (BundleException bexcA) { out.println("framework test bundle "+ bexcA +" :FRAME180A:FAIL"); teststatus = false; } catch (SecurityException secA) { out.println("framework test bundle "+ secA +" :FRAME180A:FAIL"); teststatus = false; } // Now read resources A // A is 50 A:s int a_cnt1 = 0; int b_cnt = 0; byte [] a1 = new byte[50]; String A = "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"; InputStream is1 = null ; try { URL u1 = buR3.getResource("/A"); is1 = u1.openStream(); a_cnt1 = is1.read(a1); } catch (Throwable tt) { out.println("Failed to read resource" + " ,FRAME180A:FAIL"); tt.printStackTrace(); teststatus = false; } finally { try { if (is1 != null) { is1.close(); } } catch (Throwable tt) { out.println("Failed to close input streams" + " ,FRAME180A:FAIL"); tt.printStackTrace(); teststatus = false; } } if (A.compareTo(new String(a1)) != 0) { teststatus = false; out.println("framework test bundle expected: " + A + "\n got: " + xlateData(a1) +" :FRAME180A:FAIL"); } // check the resulting events if (teststatus == true) { out.println("### framework test bundle :FRAME180A:PASS"); } else { fail("### framework test bundle :FRAME180A:FAIL"); } } } // 181. Resource integrity when reading different resources of a bundle // on the top level in the namespace of the bundle. (180 without leading / in resource name) public final static String [] HELP_FRAME181A = { "Check of resource on top of bundle name space from bundleR3_test." }; class Frame181a extends FWTestCase { public void runTest() throws Throwable { buR3 = null; boolean teststatus = true; try { buR3 = Util.installBundle(bc, "bundleR3_test-1.0.0.jar"); teststatus = true; } catch (BundleException bexcA) { out.println("framework test bundle "+ bexcA +" :FRAME181A:FAIL"); teststatus = false; } catch (SecurityException secA) { out.println("framework test bundle "+ secA +" :FRAME181A:FAIL"); teststatus = false; } // Now read resources A // A is 50 A:s int a_cnt1 = 0; int b_cnt = 0; byte [] a1 = new byte[50]; String A = "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"; InputStream is1 = null ; try { URL u1 = buR3.getResource("A"); is1 = u1.openStream(); a_cnt1 = is1.read(a1); } catch (Throwable tt) { out.println("Failed to read resource" + " ,FRAME181A:FAIL"); tt.printStackTrace(); teststatus = false; } finally { try { if (is1 != null) { is1.close(); } } catch (Throwable tt) { out.println("Failed to close input streams" + " ,FRAME181A:FAIL"); tt.printStackTrace(); teststatus = false; } } if (A.compareTo(new String(a1)) != 0) { teststatus = false; out.println("framework test bundle expected: " + A + "\n got: " + xlateData(a1) +" :FRAME181A:FAIL"); } // check the resulting events if (teststatus == true) { out.println("### framework test bundle :FRAME181A:PASS"); } else { fail("### framework test bundle :FRAME181A:FAIL"); } } } // 185. Resource integrity when reading different resources of a bundle // on the top level in the namespace of the bundle. public final static String [] HELP_FRAME185A = { "Check of resource on top of bundle name space from bundleR4_test,", "that has an unresolvable package imported" }; class Frame185a extends FWTestCase { public void runTest() throws Throwable { buR4 = null; boolean teststatus = true; try { buR4 = Util.installBundle(bc, "bundleR4_test-1.0.0.jar"); teststatus = true; } catch (BundleException bexcA) { out.println("framework test bundle "+ bexcA +" :FRAME185A:FAIL"); teststatus = false; } catch (SecurityException secA) { out.println("framework test bundle "+ secA +" :FRAME185A:FAIL"); teststatus = false; } // Now read resources A // A is 50 A:s int a_cnt1 = 0; int b_cnt = 0; byte [] a1 = new byte[50]; String A = "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"; InputStream is1 = null ; try { URL u1 = buR4.getEntry("/A"); is1 = u1.openStream(); a_cnt1 = is1.read(a1); } catch (Throwable tt) { out.println("Failed to read resource" + " ,FRAME185A:FAIL"); tt.printStackTrace(); teststatus = false; } finally { try { if (is1 != null) { is1.close(); } } catch (Throwable tt) { tt.printStackTrace(); teststatus = false; fail("Failed to close input streams" + " ,FRAME185A:FAIL"); } } if (A.compareTo(new String(a1)) != 0) { teststatus = false; fail("framework test bundle expected: " + A + "\n got: " + xlateData(a1) +" :FRAME185A:FAIL"); } // check the resulting events if (teststatus == true) { out.println("### framework test bundle :FRAME185A:PASS"); } else { fail("### framework test bundle :FRAME185A:FAIL"); } } } // 186. Resource integrity when reading different resources of a bundle // on the top level in the namespace of the bundle. (185 without leading / in resource name) public final static String [] HELP_FRAME186A = { "Check of resource on top of bundle name space from bundleR4_test,", "that has an unresolvable package imported" }; class Frame186a extends FWTestCase { public void runTest() throws Throwable { buR4 = null; boolean teststatus = true; try { buR4 = Util.installBundle(bc, "bundleR4_test-1.0.0.jar"); teststatus = true; } catch (BundleException bexcA) { teststatus = false; fail("framework test bundle "+ bexcA +" :FRAME186A:FAIL"); } catch (SecurityException secA) { teststatus = false; fail("framework test bundle "+ secA +" :FRAME186A:FAIL"); } // Now read resources A // A is 50 A:s int a_cnt1 = 0; int b_cnt = 0; byte [] a1 = new byte[50]; String A = "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"; InputStream is1 = null ; try { URL u1 = buR4.getEntry("A"); is1 = u1.openStream(); a_cnt1 = is1.read(a1); } catch (Throwable tt) { fail("Failed to read resource" + " ,FRAME186A:FAIL"); tt.printStackTrace(); teststatus = false; } finally { try { if (is1 != null) { is1.close(); } } catch (Throwable tt) { tt.printStackTrace(); teststatus = false; fail("Failed to close input streams" + " ,FRAME186A:FAIL"); } } if (A.compareTo(new String(a1)) != 0) { teststatus = false; fail("framework test bundle expected: " + A + "\n got: " + xlateData(a1) +" :FRAME186A:FAIL"); } // check the resulting events if (teststatus == true) { out.println("### framework test bundle :FRAME186A:PASS"); } else { fail("### framework test bundle :FRAME186A:FAIL"); } } } public final static String [] HELP_FRAME190A = { "Check of resource access inside bundle name space from bundleR5_test and", "bundleR6_test, that bundleR5_test exports a resource that is accessed via ", "the bundle context of bundleR6_test" }; class Frame190a extends FWTestCase { public void runTest() throws Throwable { buR5 = null; boolean teststatus = true; try { buR5 = Util.installBundle(bc, "bundleR5_test-1.0.0.jar"); teststatus = true; } catch (BundleException bexcA) { fail("framework test bundle "+ bexcA +" :FRAME190A:FAIL"); teststatus = false; } catch (SecurityException secA) { fail("framework test bundle "+ secA +" :FRAME190A:FAIL"); teststatus = false; } buR6 = null; try { buR6 = Util.installBundle(bc, "bundleR6_test-1.0.0.jar"); teststatus = teststatus && true; } catch (BundleException bexcA) { fail("framework test bundle "+ bexcA +" :FRAME190A:FAIL"); teststatus = false; } catch (SecurityException secA) { fail("framework test bundle "+ secA +" :FRAME190A:FAIL"); teststatus = false; } // out.println("Bundle R5 state: " + buR5.getState()); // out.println("Bundle R6 state: " + buR6.getState()); // Now try to access resource in R5, which should give null // as bundle R5 is not resolved yet // int a_cnt1 = 0; int b_cnt = 0; byte [] a1 = new byte[50]; String A = "R5R5R5R5R5R5R5R5R5R5R5R5R5R5R5R5R5R5R5R5R5R5R5R5R5"; InputStream is1 = null ; // this part removed since the spec is really vague about // resolving inside of getResource() if(false) { // if buR6 not has been automatically resolved, verify that // getResource doesn't do it. (yes there might be a timing p // problem here) if(buR6.getState() == Bundle.INSTALLED) { URL u1 = null;; try { u1 = buR6.getResource("/org/knopflerfish/bundle/bundleR5_test/R5"); } catch (Throwable tt) { fail("Failed to read resource" + " ,FRAME190A:FAIL"); tt.printStackTrace(); teststatus = false; } if (u1 != null) { teststatus = false; fail("Unexpected access to resource in bundle R5 " + " ,FRAME190A:FAIL"); } } } // Start R6, so that it defintely gets state resolved try { buR6.start(); } catch (BundleException be) { fail("Failed to start bundle R6 " + be.toString() + " ,FRAME190A:FAIL"); teststatus = false; } // out.println("Bundle R5 state: " + buR5.getState()); // out.println("Bundle R6 state: " + buR6.getState()); try { URL u2 = buR6.getResource("/org/knopflerfish/bundle/bundleR5_test/R5"); is1 = u2.openStream(); a_cnt1 = is1.read(a1); } catch (Throwable tt) { fail("Failed to read resource '/org/knopflerfish/bundle/bundleR5_test/R5' via bundleR6_test" + " ,FRAME190A:FAIL"); tt.printStackTrace(); teststatus = false; } finally { try { if (is1 != null) { is1.close(); } } catch (Throwable tt) { fail("Failed to close input streams" + " ,FRAME190A:FAIL"); tt.printStackTrace(); teststatus = false; } } if (A.compareTo(new String(a1)) != 0) { teststatus = false; fail("framework test bundle expected: " + A + "\n got: " + xlateData(a1) +" :FRAME190A:FAIL"); } // check the resulting events if (teststatus == true) { out.println("### framework test bundle :FRAME190A:PASS"); } else { fail("### framework test bundle :FRAME190A:FAIL"); } } } // 210. Check that no deadlock is created when // using synchronous event handling, by // creating threads that register and unregister // services in a syncronous way public final static String [] HELP_FRAME210A = { "Deadlock test when using synchronous serviceChange listener and updating different threads." }; class Frame210a extends FWTestCase { public void runTest() throws Throwable { boolean teststatus = true; RegServThread rst = null; RegListenThread rlt = null; try { rst = new RegServThread (bc,out); rlt = new RegListenThread (bc,out); } catch (Exception ex) { teststatus = false; fail("### framework test bundle :FRAME210A exception"); ex.printStackTrace(out); } // Start the service registering thread int ID = 1; Thread t1 = new Thread(rst, "thread id= " + ID + " "); t1.start(); // System.out.println("Start of thread " + String.valueOf(ID)); // Start the listener thread ID = 2; Thread t2 = new Thread(rlt, "thread id= " + ID + " "); t2.start(); // System.out.println("Start of thread " + String.valueOf(ID)); // sleep to give the threads t1 and t2 time to create a possible deadlock. try { Thread.sleep(1500); } catch (Exception ex) { out.println("### framework test bundle :FRAME210A exception"); ex.printStackTrace(out); } // Ask the listener thread if it succeded to make a synchroized serviceChange if (rlt.getStatus() != true) { teststatus = false; fail("### framework test bundle :FRAME210A failed to execute sychnronized serviceChanged()"); } // Ask the registering thread if it succeded to make a service update if (rst.getStatus() != true) { teststatus = false; fail("### framework test bundle :FRAME210A failed to execute sychnronized service update"); } // Stop the threads rst.stop(); rlt.stop(); if (teststatus == true) { out.println("### framework test bundle :FRAME210A:PASS"); } else { fail("### framework test bundle :FRAME210A:FAIL"); } } } class Frame211a extends FWTestCase { public void runTest() throws Throwable { //existing directory Enumeration enume = buF.getEntryPaths("/"); if(enume == null ){ fail("GetEntryPaths did not retrieve the correct number of elements"); } int i = 0; while(enume.hasMoreElements()){ i++; enume.nextElement(); } if(i != 3 && i != 2){ //manifest gets skipped fail("GetEntryPaths did not retrieve the correct number of elements"); } //another existing directory enume = buF.getEntryPaths("/org/knopflerfish/bundle/"); if(enume == null ){ fail("GetEntryPaths did not retrieve the correct number of elements"); } i = 0; while(enume.hasMoreElements()){ i++; enume.nextElement(); } if(i != 1 ){ fail("GetEntryPaths did not retrieve the correct number of elements"); } //existing file, non-directory, ending with slash enume = buF.getEntryPaths("/BundF.class/"); if(enume != null ){ fail("GetEntryPaths did not retrieve the correct number of elements"); } //existing file, non-directory enume = buF.getEntryPaths("/BundF.class"); if(enume != null ){ fail("GetEntryPaths did not retrieve the correct number of elements"); } //non-existing file enume = buF.getEntryPaths("/e"); if(enume != null){ fail("GetEntryPaths did not retrieve the correct number of elements"); } //dir with only one entry enume = buF.getEntryPaths("/OSGI-INF"); if(enume == null ){ fail("GetEntryPaths did not retrieve the correct number of elements"); } i = 0; while(enume.hasMoreElements()){ i++; enume.nextElement(); } if(i != 1){ fail("GetEntryPaths did not retrieve the correct number of elements"); } if (buF != null) { try { buF.uninstall(); } catch (BundleException ignore) { } } Dictionary dict = buF.getHeaders(); if(!dict.get(Constants.BUNDLE_SYMBOLICNAME).equals("org.knopflerfish.bundle.bundleF_test")){ fail("framework test bundle, " + Constants.BUNDLE_SYMBOLICNAME + " header does not have right value:FRAME211A:FAIL"); } dict = buF.getHeaders(""); if(!dict.get(Constants.BUNDLE_DESCRIPTION).equals("%description")){ fail("framework test bundle, " + Constants.BUNDLE_DESCRIPTION + " header does not have raw value, " + dict.get(Constants.BUNDLE_DESCRIPTION) + ":FRAME211A:FAIL"); } } } // General status check functions // prevent control characters to be printed private String xlateData(byte [] b1) { StringBuffer sb = new StringBuffer(); for (int i = 0; i < b1.length ; i++) { if (-128 <= b1[i] && b1[i] < 0) { sb.append(new String(b1, i, 1)); } if (0 <= b1[i] && b1[i] < 32) { sb.append("^"); sb.append(String.valueOf(b1[i])); } else { if (32 <= b1[i] && b1[i] < 127) { sb.append(new String(b1, i, 1)); } } } return sb.toString(); } // Check that the expected implications occur public boolean implyCheck (Object _out, boolean expected, Permission p1, Permission p2) { boolean result = true; if (p1.implies(p2) == expected) { result = true; } else { out.println("framework test bundle, ...Permission implies method failed"); out.println("Permission p1: " + p1.toString()); out.println("Permission p2: " + p2.toString()); result = false; } // out.println("DEBUG implies method in FRAME125A"); // out.println("DEBUG p1: " + p1.toString()); // out.println("DEBUG p2: " + p2.toString()); return result; } public boolean implyCheck (Object _out, boolean expected, PermissionCollection p1, Permission p2) { boolean result = true; if (p1.implies(p2) == expected) { result = true; } else { out.println("framework test bundle, ...Permission implies method failed"); out.println("Permission p1: " + p1.toString()); out.println("Permission p2: " + p2.toString()); result = false; } return result; } /* Interface implementations for this class */ public java.lang.Object getConfigurationObject() { return this; } // Check that the expected events has reached the listeners and reset the events in the listeners private boolean checkListenerEvents(Object _out, boolean fwexp, int fwtype, boolean buexp, int butype, boolean sexp, int stype, Bundle bunX, ServiceReference servX ) { boolean listenState = true; // assume everything will work // Sleep a while to allow events to arrive try { Thread.sleep(eventDelay); } catch (Exception e) { e.printStackTrace(); return false; } if (fwexp == true) { if (fListen.getEvent() != null) { if (fListen.getEvent().getType() != fwtype || fListen.getEvent().getBundle() != bunX) { System.out.println("framework test bundle, wrong type of framework event/bundle : " + fListen.getEvent().getType()); System.out.println("framework test bundle, event was from bundle: " + fListen.getEvent().getBundle()); Throwable th1 = fListen.getEvent().getThrowable(); if (th1 != null) { System.out.println("framework test bundle, exception was: " + th1); } listenState = false; } } else { System.out.println("framework test bundle, missing framework event"); listenState = false; } } else { if (fListen.getEvent() != null) { listenState = false; System.out.println("framework test bundle, unexpected framework event: " + fListen.getEvent().getType()); System.out.println("framework test bundle, event was from bundle: " + fListen.getEvent().getBundle()); Throwable th1 = fListen.getEvent().getThrowable(); if (th1 != null) { System.out.println("framework test bundle, exception was: " + th1); } } } if (buexp == true) { if (bListen.getEvent() != null) { if (bListen.getEvent().getType() != butype || bListen.getEvent().getBundle() != bunX) { System.out.println("framework test bundle, wrong type of bundle event/bundle: " + bListen.getEvent().getType()); System.out.println("framework test bundle, event was from bundle: " + bListen.getEvent().getBundle().getLocation()); listenState = false; } } else { System.out.println("framework test bundle, missing bundle event"); listenState = false; } } else { if (bListen.getEvent() != null) { listenState = false; System.out.println("framework test bundle, unexpected bundle event: " + bListen.getEvent().getType()); System.out.println("framework test bundle, event was from bundle: " + bListen.getEvent().getBundle()); } } if (sexp == true) { if (sListen.getEvent() != null) { if (servX != null) { if (sListen.getEvent().getType() != stype || servX != sListen.getEvent().getServiceReference() ) { System.out.println("framework test bundle, wrong type of service event: " + sListen.getEvent().getType()); listenState = false; } } else { // ignore from which service reference the event came if (sListen.getEvent().getType() != stype ) { System.out.println("framework test bundle, wrong type of service event: " + sListen.getEvent().getType()); listenState = false; } } } else { System.out.println("framework test bundle, missing service event"); listenState = false; } } else { if (sListen.getEvent() != null) { listenState = false; System.out.println("framework test bundle, unexpected service event: " + sListen.getEvent().getType()); } } fListen.clearEvent(); bListen.clearEvent(); sListen.clearEvent(); return listenState; } // Check that the expected events has reached the listeners and reset the events in the listeners private boolean checkSyncListenerEvents(Object _out, boolean buexp, int butype, Bundle bunX, ServiceReference servX ) { boolean listenState = true; // assume everything will work // Sleep a while to allow events to arrive try { Thread.sleep(eventDelay); } catch (Exception e) { e.printStackTrace(); return false; } if (buexp == true) { if (syncBListen.getEvent() != null) { if (syncBListen.getEvent().getType() != butype || syncBListen.getEvent().getBundle() != bunX) { System.out.println("framework test bundle, wrong type of sync bundle event/bundle: " + syncBListen.getEvent().getType()); System.out.println("framework test bundle, event was from bundle: " + syncBListen.getEvent().getBundle().getLocation()); listenState = false; } } else { System.out.println("framework test bundle, missing sync bundle event"); listenState = false; } } else { if (syncBListen.getEvent() != null) { listenState = false; System.out.println("framework test bundle, unexpected sync bundle event: " + syncBListen.getEvent().getType()); System.out.println("framework test bundle, event was from bundle: " + syncBListen.getEvent().getBundle()); } } syncBListen.clearEvent(); return listenState; } private void clearEvents() { fListen.clearEvent(); bListen.clearEvent(); syncBListen.clearEvent(); sListen.clearEvent(); } // Get the bundle that caused the event private Bundle getFEBundle () { if (fListen.getEvent() != null) { return fListen.getEvent().getBundle(); } else { return null; } } private Bundle getBEBundle () { if (bListen.getEvent() != null) { return bListen.getEvent().getBundle(); } else { return null; } } // So that other bundles in the test may get the base url public String getBaseURL() { return test_url_base; } // to access test service methods via reflection private void bundleLoad (Object _out, ServiceReference sr, String bundle) { Method m; Class c, parameters[]; Object obj1 = bc.getService(sr); // System.out.println("servref = "+ sr); // System.out.println("object = "+ obj1); Object[] arguments = new Object[1]; arguments[0] = bundle; // the bundle to load packages from c = obj1.getClass(); parameters = new Class[1]; parameters[0] = arguments[0].getClass(); // System.out.println("Parameters [0] " + parameters[0].toString()); try { m = c.getMethod("tryPackage", parameters); m.invoke(obj1, arguments); } catch (IllegalAccessException ia) { System.out.println("Framework test IllegaleAccessException" + ia); } catch (InvocationTargetException ita) { System.out.println("Framework test InvocationTargetException" + ita); System.out.println("Framework test nested InvocationTargetException" + ita.getTargetException() ); } catch (NoSuchMethodException nme) { System.out.println("Framework test NoSuchMethodException " + nme); nme.printStackTrace(); } catch (Throwable thr) { System.out.println("Unexpected " + thr); thr.printStackTrace(); } } public synchronized void putEvent (String device, String method, Integer value) { // System.out.println("putEvent" + device + " " + method + " " + value); events.addElement(new devEvent(device, method, value)); } class devEvent { String dev; String met; int val; public devEvent (String dev, String met , Integer val) { this.dev = dev; this.met = met; this.val = val.intValue(); } public devEvent (String dev, String met , int val) { this.dev = dev; this.met = met; this.val = val; } public String getDevice() { return dev; } public String getMethod() { return met; } public int getValue() { return val; } } private boolean checkEvents(Object _out, Vector expevents, Vector events) { boolean state = true; if (events.size() != expevents.size()) { state = false; out.println("Real events"); for (int i = 0; i< events.size() ; i++) { devEvent dee = (devEvent) events.elementAt(i); out.print("Bundle " + dee.getDevice()); out.print(" Method " + dee.getMethod()); out.println(" Value " + dee.getValue()); } out.println("Expected events"); for (int i = 0; i< expevents.size() ; i++) { devEvent dee = (devEvent) expevents.elementAt(i); out.print("Bundle " + dee.getDevice()); out.print(" Method " + dee.getMethod()); out.println(" Value " + dee.getValue()); } } else { for (int i = 0; i< events.size() ; i++) { devEvent dee = (devEvent) events.elementAt(i); devEvent exp = (devEvent) expevents.elementAt(i); if (!(dee.getDevice().equals(exp.getDevice()) && dee.getMethod().equals(exp.getMethod()) && dee.getValue() == exp.getValue())) { out.println("Event no = " + i); if (!(dee.getDevice().equals(exp.getDevice()))) { out.println ("Bundle is " + dee.getDevice() + " should be " + exp.getDevice()); } if (!(dee.getMethod().equals(exp.getMethod()))) { out.println ("Method is " + dee.getMethod() + " should be " + exp.getMethod()); } if (!(dee.getValue() == exp.getValue())) { out.println ("Value is " + dee.getValue() + " should be " + exp.getValue()); } state = false; } } } return state; } private String getStateString(int bundleState) { switch (bundleState) { case 0x01: return "UNINSTALLED"; case 0x02: return "INSTALLED"; case 0x04: return "RESOLVED"; case 0x08: return "STARTING"; case 0x10: return "STOPPING"; case 0x20: return "ACTIVE"; default: return "Unknow state"; } } class FrameworkListener implements org.osgi.framework.FrameworkListener { FrameworkEvent fwe; public void frameworkEvent(FrameworkEvent evt) { this.fwe = evt; // System.out.println("FrameworkEvent: "+ evt.getType()); } public FrameworkEvent getEvent() { return fwe; } public void clearEvent() { fwe = null; } } class ServiceListener implements org.osgi.framework.ServiceListener { ServiceEvent serve = null; public void serviceChanged(ServiceEvent evt) { this.serve = evt; // System.out.println("ServiceEvent: " + evt.getType()); } public ServiceEvent getEvent() { return serve; } public void clearEvent() { serve = null; } } class BundleListener implements org.osgi.framework.BundleListener { BundleEvent bunEvent = null; public void bundleChanged (BundleEvent evt) { this.bunEvent = evt; // System.out.println("BundleEvent: "+ evt.getType()); } public BundleEvent getEvent() { return bunEvent; } public void clearEvent() { bunEvent = null; } } class SyncBundleListener implements SynchronousBundleListener { BundleEvent bunEvent = null; public void bundleChanged (BundleEvent evt) { if(evt.getType() == BundleEvent.STARTING || evt.getType() == BundleEvent.STOPPING) this.bunEvent = evt; // System.out.println("BundleEvent: "+ evt.getType()); } public BundleEvent getEvent() { return bunEvent; } public void clearEvent() { bunEvent = null; } } }
better messages for missing bundle property test
osgi/bundles_test/regression_tests/framework_test/src/org/knopflerfish/bundle/framework_test/FrameworkTestSuite.java
better messages for missing bundle property test
<ide><path>sgi/bundles_test/regression_tests/framework_test/src/org/knopflerfish/bundle/framework_test/FrameworkTestSuite.java <ide> <ide> class Frame007a extends FWTestCase { <ide> public void runTest() throws Throwable { <del> boolean teststatus = true; <del> String trunk = "org.osgi.framework."; <del> <del> String stem = "version"; <del> String data = bc.getProperty(trunk+stem); <del> if (data == null) { <del> teststatus = false; <del> } <del> out.println(trunk + stem + " " + data); <del> <del> stem = "vendor"; <del> data = bc.getProperty(trunk+stem); <del> if (data == null) { <del> teststatus = false; <del> } <del> out.println(trunk + stem + " " + data); <del> <del> stem = "language"; <del> data = bc.getProperty(trunk+stem); <del> if (data == null) { <del> teststatus = false; <del> } <del> out.println(trunk + stem + " " + data); <del> <del> stem = "os.name"; <del> data = bc.getProperty(trunk+stem); <del> if (data == null) { <del> teststatus = false; <del> } <del> out.println(trunk + stem + " " + data); <del> <del> stem = "os.version"; <del> data = bc.getProperty(trunk+stem); <del> if (data == null) { <del> teststatus = false; <del> } <del> out.println(trunk + stem + " " + data); <del> <del> stem = "processor"; <del> data = bc.getProperty(trunk+stem); <del> if (data == null) { <del> teststatus = false; <del> } <del> out.println(trunk + stem + " " + data); <del> <del> if (teststatus == true ) { <del> out.println("### framework test bundle :FRAME007A:PASS"); <del> } <del> else { <del> fail("### framework test bundle :FRAME007A:FAIL"); <add> String[] NNList = new String[] { <add> Constants.FRAMEWORK_OS_VERSION, <add> Constants.FRAMEWORK_OS_NAME, <add> Constants.FRAMEWORK_PROCESSOR, <add> Constants.FRAMEWORK_VERSION, <add> Constants.FRAMEWORK_VENDOR, <add> Constants.FRAMEWORK_LANGUAGE, <add> }; <add> <add> for(int i = 0; i < NNList.length; i++) { <add> String k = NNList[i]; <add> String v = bc.getProperty(k); <add> if(v == null) { <add> fail("'" + k + "' not set"); <add> } <add> } <add> <add> String[] TFList = new String[] { <add> Constants.SUPPORTS_FRAMEWORK_REQUIREBUNDLE, <add> Constants.SUPPORTS_FRAMEWORK_FRAGMENT, <add> Constants.SUPPORTS_FRAMEWORK_EXTENSION, <add> Constants.SUPPORTS_BOOTCLASSPATH_EXTENSION, <add> }; <add> <add> for( int i = 0; i < TFList.length; i++) { <add> String k = TFList[i]; <add> String v = bc.getProperty(k); <add> if(v == null) { <add> fail("'" + k + "' not set"); <add> } <add> if(!("true".equals(v) || "false".equals(v))) { <add> fail("'" + k + "' is '" + v + "', expected 'true' or 'false'"); <add> } <ide> } <ide> } <ide> }
Java
agpl-3.0
5e9dd56a4abbfbb727a928a48f5cb40f93b99de9
0
cryptomator/cryptolib
package org.cryptomator.cryptolib; import org.cryptomator.cryptolib.api.Cryptor; import org.cryptomator.cryptolib.api.FileContentCryptor; import org.cryptomator.cryptolib.api.FileHeader; import org.cryptomator.cryptolib.api.FileHeaderCryptor; import org.cryptomator.cryptolib.common.SeekableByteChannelMock; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.Mockito; import java.io.ByteArrayInputStream; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.channels.Channels; import java.nio.channels.ReadableByteChannel; import java.nio.charset.Charset; import java.util.Arrays; class EncryptingReadableByteChannelTest { private static final Charset UTF_8 = Charset.forName("UTF-8"); private ByteBuffer dstFile; private ReadableByteChannel srcFileChannel; private Cryptor cryptor; private FileContentCryptor contentCryptor; private FileHeaderCryptor headerCryptor; private FileHeader header; @BeforeEach public void setup() { dstFile = ByteBuffer.allocate(100); srcFileChannel = new SeekableByteChannelMock(dstFile); cryptor = Mockito.mock(Cryptor.class); contentCryptor = Mockito.mock(FileContentCryptor.class); headerCryptor = Mockito.mock(FileHeaderCryptor.class); header = Mockito.mock(FileHeader.class); Mockito.when(cryptor.fileContentCryptor()).thenReturn(contentCryptor); Mockito.when(cryptor.fileHeaderCryptor()).thenReturn(headerCryptor); Mockito.when(contentCryptor.cleartextChunkSize()).thenReturn(10); Mockito.when(headerCryptor.create()).thenReturn(header); Mockito.when(headerCryptor.encryptHeader(header)).thenReturn(ByteBuffer.wrap("hhhhh".getBytes())); Mockito.when(contentCryptor.encryptChunk(Mockito.any(ByteBuffer.class), Mockito.anyLong(), Mockito.any(FileHeader.class))).thenAnswer(invocation -> { ByteBuffer input = invocation.getArgument(0); String inStr = UTF_8.decode(input).toString(); return ByteBuffer.wrap(inStr.toUpperCase().getBytes(UTF_8)); }); } @Test public void testEncryptionOfEmptyCleartext() throws IOException { ReadableByteChannel src = Channels.newChannel(new ByteArrayInputStream(new byte[0])); ByteBuffer result = ByteBuffer.allocate(10); try (EncryptingReadableByteChannel ch = new EncryptingReadableByteChannel(src, cryptor)) { int read1 = ch.read(result); Assertions.assertEquals(5, read1); int read2 = ch.read(result); Assertions.assertEquals(-1, read2); Assertions.assertArrayEquals("hhhhh".getBytes(), Arrays.copyOfRange(result.array(), 0, read1)); } Mockito.verify(contentCryptor, Mockito.never()).encryptChunk(Mockito.any(), Mockito.anyLong(), Mockito.any()); } @Test public void testEncryptionOfCleartext() throws IOException { ReadableByteChannel src = Channels.newChannel(new ByteArrayInputStream("hello world 1 hello world 2".getBytes())); ByteBuffer result = ByteBuffer.allocate(50); try (EncryptingReadableByteChannel ch = new EncryptingReadableByteChannel(src, cryptor)) { int read1 = ch.read(result); Assertions.assertEquals(32, read1); int read2 = ch.read(result); Assertions.assertEquals(-1, read2); Assertions.assertArrayEquals("hhhhhHELLO WORLD 1 HELLO WORLD 2".getBytes(), Arrays.copyOfRange(result.array(), 0, read1)); } Mockito.verify(contentCryptor).encryptChunk(Mockito.any(), Mockito.eq(0l), Mockito.eq(header)); Mockito.verify(contentCryptor).encryptChunk(Mockito.any(), Mockito.eq(1l), Mockito.eq(header)); } }
src/test/java/org/cryptomator/cryptolib/EncryptingReadableByteChannelTest.java
package org.cryptomator.cryptolib; import org.cryptomator.cryptolib.api.Cryptor; import org.cryptomator.cryptolib.api.FileContentCryptor; import org.cryptomator.cryptolib.api.FileHeader; import org.cryptomator.cryptolib.api.FileHeaderCryptor; import org.cryptomator.cryptolib.common.SeekableByteChannelMock; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.Mockito; import java.io.ByteArrayInputStream; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.channels.Channels; import java.nio.channels.ReadableByteChannel; import java.nio.channels.WritableByteChannel; import java.nio.charset.Charset; import java.util.Arrays; class EncryptingReadableByteChannelTest { private static final Charset UTF_8 = Charset.forName("UTF-8"); private ByteBuffer dstFile; private ReadableByteChannel srcFileChannel; private Cryptor cryptor; private FileContentCryptor contentCryptor; private FileHeaderCryptor headerCryptor; private FileHeader header; @BeforeEach public void setup() { dstFile = ByteBuffer.allocate(100); srcFileChannel = new SeekableByteChannelMock(dstFile); cryptor = Mockito.mock(Cryptor.class); contentCryptor = Mockito.mock(FileContentCryptor.class); headerCryptor = Mockito.mock(FileHeaderCryptor.class); header = Mockito.mock(FileHeader.class); Mockito.when(cryptor.fileContentCryptor()).thenReturn(contentCryptor); Mockito.when(cryptor.fileHeaderCryptor()).thenReturn(headerCryptor); Mockito.when(contentCryptor.cleartextChunkSize()).thenReturn(10); Mockito.when(headerCryptor.create()).thenReturn(header); Mockito.when(headerCryptor.encryptHeader(header)).thenReturn(ByteBuffer.wrap("hhhhh".getBytes())); Mockito.when(contentCryptor.encryptChunk(Mockito.any(ByteBuffer.class), Mockito.anyLong(), Mockito.any(FileHeader.class))).thenAnswer(invocation -> { ByteBuffer input = invocation.getArgument(0); String inStr = UTF_8.decode(input).toString(); return ByteBuffer.wrap(inStr.toUpperCase().getBytes(UTF_8)); }); } @Test public void testEncryption() throws IOException { ReadableByteChannel src = Channels.newChannel(new ByteArrayInputStream("hello world 1 hello world 2".getBytes())); ByteBuffer result = ByteBuffer.allocate(50); try (EncryptingReadableByteChannel ch = new EncryptingReadableByteChannel(src, cryptor)) { int read1 = ch.read(result); Assertions.assertEquals(32, read1); int read2 = ch.read(result); Assertions.assertEquals(-1, read2); Assertions.assertArrayEquals("hhhhhHELLO WORLD 1 HELLO WORLD 2".getBytes(), Arrays.copyOfRange(result.array(), 0, read1)); } Mockito.verify(contentCryptor).encryptChunk(Mockito.any(), Mockito.eq(0l), Mockito.eq(header)); Mockito.verify(contentCryptor).encryptChunk(Mockito.any(), Mockito.eq(1l), Mockito.eq(header)); } }
added test
src/test/java/org/cryptomator/cryptolib/EncryptingReadableByteChannelTest.java
added test
<ide><path>rc/test/java/org/cryptomator/cryptolib/EncryptingReadableByteChannelTest.java <ide> import java.nio.ByteBuffer; <ide> import java.nio.channels.Channels; <ide> import java.nio.channels.ReadableByteChannel; <del>import java.nio.channels.WritableByteChannel; <ide> import java.nio.charset.Charset; <ide> import java.util.Arrays; <ide> <ide> } <ide> <ide> @Test <del> public void testEncryption() throws IOException { <add> public void testEncryptionOfEmptyCleartext() throws IOException { <add> ReadableByteChannel src = Channels.newChannel(new ByteArrayInputStream(new byte[0])); <add> ByteBuffer result = ByteBuffer.allocate(10); <add> try (EncryptingReadableByteChannel ch = new EncryptingReadableByteChannel(src, cryptor)) { <add> int read1 = ch.read(result); <add> Assertions.assertEquals(5, read1); <add> int read2 = ch.read(result); <add> Assertions.assertEquals(-1, read2); <add> Assertions.assertArrayEquals("hhhhh".getBytes(), Arrays.copyOfRange(result.array(), 0, read1)); <add> } <add> Mockito.verify(contentCryptor, Mockito.never()).encryptChunk(Mockito.any(), Mockito.anyLong(), Mockito.any()); <add> } <add> <add> @Test <add> public void testEncryptionOfCleartext() throws IOException { <ide> ReadableByteChannel src = Channels.newChannel(new ByteArrayInputStream("hello world 1 hello world 2".getBytes())); <ide> ByteBuffer result = ByteBuffer.allocate(50); <ide> try (EncryptingReadableByteChannel ch = new EncryptingReadableByteChannel(src, cryptor)) {
Java
apache-2.0
0a310f53f86586a5c19597e187ca0d06b914a5e4
0
UniTime/unitime,UniTime/unitime,UniTime/unitime
/* urse * Licensed to The Apereo Foundation under one or more contributor license * agreements. See the NOTICE file distributed with this work for * additional information regarding copyright ownership. * * The Apereo Foundation licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except in * compliance with the License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * * See the License for the specific language governing permissions and * limitations under the License. * */ package org.unitime.timetable.onlinesectioning.custom.purdue; import java.lang.reflect.Type; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Collection; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeSet; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.cpsolver.ifs.assignment.Assignment; import org.cpsolver.ifs.assignment.AssignmentMap; import org.cpsolver.studentsct.model.Config; import org.cpsolver.studentsct.model.Course; import org.cpsolver.studentsct.model.CourseRequest; import org.cpsolver.studentsct.model.Enrollment; import org.cpsolver.studentsct.model.Request; import org.cpsolver.studentsct.model.SctAssignment; import org.cpsolver.studentsct.model.Section; import org.cpsolver.studentsct.model.Subpart; import org.joda.time.DateTime; import org.joda.time.DateTimeZone; import org.restlet.Client; import org.restlet.Context; import org.restlet.data.MediaType; import org.restlet.data.Protocol; import org.restlet.resource.ClientResource; import org.unitime.localization.impl.Localization; import org.unitime.timetable.ApplicationProperties; import org.unitime.timetable.defaults.ApplicationProperty; import org.unitime.timetable.gwt.resources.StudentSectioningConstants; import org.unitime.timetable.gwt.resources.StudentSectioningMessages; import org.unitime.timetable.gwt.shared.CourseRequestInterface; import org.unitime.timetable.gwt.shared.PageAccessException; import org.unitime.timetable.gwt.shared.SectioningException; import org.unitime.timetable.gwt.shared.CourseRequestInterface.CheckCoursesResponse; import org.unitime.timetable.gwt.shared.CourseRequestInterface.CourseMessage; import org.unitime.timetable.gwt.shared.CourseRequestInterface.RequestedCourse; import org.unitime.timetable.gwt.shared.CourseRequestInterface.RequestedCourseStatus; import org.unitime.timetable.gwt.shared.OnlineSectioningInterface.EligibilityCheck; import org.unitime.timetable.gwt.shared.OnlineSectioningInterface.EligibilityCheck.EligibilityFlag; import org.unitime.timetable.gwt.shared.OnlineSectioningInterface.WaitListMode; import org.unitime.timetable.model.CourseDemand; import org.unitime.timetable.model.Student; import org.unitime.timetable.model.StudentClassEnrollment; import org.unitime.timetable.model.StudentSectioningStatus; import org.unitime.timetable.model.dao.CourseDemandDAO; import org.unitime.timetable.model.dao.StudentDAO; import org.unitime.timetable.model.CourseRequest.CourseRequestOverrideIntent; import org.unitime.timetable.model.CourseRequest.CourseRequestOverrideStatus; import org.unitime.timetable.onlinesectioning.AcademicSessionInfo; import org.unitime.timetable.onlinesectioning.OnlineSectioningHelper; import org.unitime.timetable.onlinesectioning.OnlineSectioningLog; import org.unitime.timetable.onlinesectioning.OnlineSectioningLog.Action.Builder; import org.unitime.timetable.onlinesectioning.OnlineSectioningServer; import org.unitime.timetable.onlinesectioning.custom.ExternalTermProvider; import org.unitime.timetable.onlinesectioning.custom.WaitListValidationProvider; import org.unitime.timetable.onlinesectioning.custom.purdue.SpecialRegistrationInterface.ApiMode; import org.unitime.timetable.onlinesectioning.custom.purdue.SpecialRegistrationInterface.Change; import org.unitime.timetable.onlinesectioning.custom.purdue.SpecialRegistrationInterface.ChangeError; import org.unitime.timetable.onlinesectioning.custom.purdue.SpecialRegistrationInterface.ChangeOperation; import org.unitime.timetable.onlinesectioning.custom.purdue.SpecialRegistrationInterface.ChangeStatus; import org.unitime.timetable.onlinesectioning.custom.purdue.SpecialRegistrationInterface.CheckEligibilityResponse; import org.unitime.timetable.onlinesectioning.custom.purdue.SpecialRegistrationInterface.CheckRestrictionsRequest; import org.unitime.timetable.onlinesectioning.custom.purdue.SpecialRegistrationInterface.CheckRestrictionsResponse; import org.unitime.timetable.onlinesectioning.custom.purdue.SpecialRegistrationInterface.CourseCredit; import org.unitime.timetable.onlinesectioning.custom.purdue.SpecialRegistrationInterface.DeniedMaxCredit; import org.unitime.timetable.onlinesectioning.custom.purdue.SpecialRegistrationInterface.DeniedRequest; import org.unitime.timetable.onlinesectioning.custom.purdue.SpecialRegistrationInterface.EligibilityProblem; import org.unitime.timetable.onlinesectioning.custom.purdue.SpecialRegistrationInterface.Problem; import org.unitime.timetable.onlinesectioning.custom.purdue.SpecialRegistrationInterface.RequestorRole; import org.unitime.timetable.onlinesectioning.custom.purdue.SpecialRegistrationInterface.ResponseStatus; import org.unitime.timetable.onlinesectioning.custom.purdue.SpecialRegistrationInterface.SpecialRegistration; import org.unitime.timetable.onlinesectioning.custom.purdue.SpecialRegistrationInterface.SpecialRegistrationMultipleStatusResponse; import org.unitime.timetable.onlinesectioning.custom.purdue.SpecialRegistrationInterface.SpecialRegistrationRequest; import org.unitime.timetable.onlinesectioning.custom.purdue.SpecialRegistrationInterface.SpecialRegistrationResponseList; import org.unitime.timetable.onlinesectioning.custom.purdue.SpecialRegistrationInterface.SpecialRegistrationStatus; import org.unitime.timetable.onlinesectioning.custom.purdue.SpecialRegistrationInterface.SpecialRegistrationStatusResponse; import org.unitime.timetable.onlinesectioning.model.XCourse; import org.unitime.timetable.onlinesectioning.model.XCourseId; import org.unitime.timetable.onlinesectioning.model.XCourseRequest; import org.unitime.timetable.onlinesectioning.model.XEnrollment; import org.unitime.timetable.onlinesectioning.model.XOffering; import org.unitime.timetable.onlinesectioning.model.XOverride; import org.unitime.timetable.onlinesectioning.model.XRequest; import org.unitime.timetable.onlinesectioning.model.XSection; import org.unitime.timetable.onlinesectioning.model.XStudent; import org.unitime.timetable.onlinesectioning.server.DatabaseServer; import org.unitime.timetable.onlinesectioning.solver.SectioningRequest; import org.unitime.timetable.onlinesectioning.updates.ReloadStudent; import org.unitime.timetable.util.Formats; import org.unitime.timetable.util.Formats.Format; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonDeserializationContext; import com.google.gson.JsonDeserializer; import com.google.gson.JsonElement; import com.google.gson.JsonParseException; import com.google.gson.JsonPrimitive; import com.google.gson.JsonSerializationContext; import com.google.gson.JsonSerializer; /** * @author Tomas Muller */ public class PurdueWaitListValidationProvider implements WaitListValidationProvider { private static Log sLog = LogFactory.getLog(PurdueWaitListValidationProvider.class); protected static final StudentSectioningMessages MESSAGES = Localization.create(StudentSectioningMessages.class); protected static final StudentSectioningConstants CONSTANTS = Localization.create(StudentSectioningConstants.class); protected static Format<Number> sCreditFormat = Formats.getNumberFormat("0.##"); private Client iClient; private ExternalTermProvider iExternalTermProvider; public PurdueWaitListValidationProvider() { List<Protocol> protocols = new ArrayList<Protocol>(); protocols.add(Protocol.HTTP); protocols.add(Protocol.HTTPS); iClient = new Client(protocols); Context cx = new Context(); cx.getParameters().add("readTimeout", getSpecialRegistrationApiReadTimeout()); iClient.setContext(cx); try { String clazz = ApplicationProperty.CustomizationExternalTerm.value(); if (clazz == null || clazz.isEmpty()) iExternalTermProvider = new BannerTermProvider(); else iExternalTermProvider = (ExternalTermProvider)Class.forName(clazz).getConstructor().newInstance(); } catch (Exception e) { sLog.error("Failed to create external term provider, using the default one instead.", e); iExternalTermProvider = new BannerTermProvider(); } } protected String getSpecialRegistrationApiReadTimeout() { return ApplicationProperties.getProperty("purdue.specreg.readTimeout", "60000"); } protected String getSpecialRegistrationApiSite() { return ApplicationProperties.getProperty("purdue.specreg.site"); } protected String getSpecialRegistrationApiSiteCheckEligibility() { return ApplicationProperties.getProperty("purdue.specreg.site.checkEligibility", getSpecialRegistrationApiSite() + "/checkEligibility"); } protected String getSpecialRegistrationApiValidationSite() { return ApplicationProperties.getProperty("purdue.specreg.site.validation", getSpecialRegistrationApiSite() + "/checkRestrictions"); } protected String getSpecialRegistrationApiSiteSubmitRegistration() { return ApplicationProperties.getProperty("purdue.specreg.site.submitRegistration", getSpecialRegistrationApiSite() + "/submitRegistration"); } protected String getSpecialRegistrationApiSiteCheckSpecialRegistrationStatus() { return ApplicationProperties.getProperty("purdue.specreg.site.checkSpecialRegistrationStatus", getSpecialRegistrationApiSite() + "/checkSpecialRegistrationStatus"); } protected String getSpecialRegistrationApiSiteCheckAllSpecialRegistrationStatus() { return ApplicationProperties.getProperty("purdue.specreg.site.checkAllSpecialRegistrationStatus", getSpecialRegistrationApiSite() + "/checkAllSpecialRegistrationStatus"); } protected String getSpecialRegistrationApiKey() { return ApplicationProperties.getProperty("purdue.specreg.apiKey"); } protected ApiMode getSpecialRegistrationApiMode() { return ApiMode.valueOf(ApplicationProperties.getProperty("purdue.specreg.mode.waitlist", "WAITL")); } protected String getBannerId(org.unitime.timetable.model.Student student) { String id = student.getExternalUniqueId(); while (id.length() < 9) id = "0" + id; return id; } protected String getBannerId(XStudent student) { String id = student.getExternalId(); while (id.length() < 9) id = "0" + id; return id; } protected String getBannerTerm(AcademicSessionInfo session) { return iExternalTermProvider.getExternalTerm(session); } protected String getBannerCampus(AcademicSessionInfo session) { return iExternalTermProvider.getExternalCampus(session); } protected String getRequestorId(OnlineSectioningLog.Entity user) { if (user == null || user.getExternalId() == null) return null; String id = user.getExternalId(); while (id.length() < 9) id = "0" + id; return id; } protected RequestorRole getRequestorType(OnlineSectioningLog.Entity user, XStudent student) { if (user == null || user.getExternalId() == null) return null; if (student != null) return (user.getExternalId().equals(student.getExternalId()) ? RequestorRole.STUDENT : RequestorRole.MANAGER); if (user.hasType()) { switch (user.getType()) { case MANAGER: return RequestorRole.MANAGER; case STUDENT: return RequestorRole.STUDENT; default: return RequestorRole.MANAGER; } } return null; } protected Gson getGson(OnlineSectioningHelper helper) { GsonBuilder builder = new GsonBuilder() .registerTypeAdapter(DateTime.class, new JsonSerializer<DateTime>() { @Override public JsonElement serialize(DateTime src, Type typeOfSrc, JsonSerializationContext context) { return new JsonPrimitive(src.toString("yyyy-MM-dd'T'HH:mm:ss'Z'")); } }) .registerTypeAdapter(DateTime.class, new JsonDeserializer<DateTime>() { @Override public DateTime deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { return new DateTime(json.getAsJsonPrimitive().getAsString(), DateTimeZone.UTC); } }) .registerTypeAdapter(Date.class, new JsonSerializer<Date>() { @Override public JsonElement serialize(Date src, Type typeOfSrc, JsonSerializationContext context) { return new JsonPrimitive(new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'").format(src)); } }) .registerTypeAdapter(Date.class, new JsonDeserializer<Date>() { @Override public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { try { return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(json.getAsJsonPrimitive().getAsString()); } catch (ParseException e) { throw new JsonParseException(e.getMessage(), e); } } }); if (helper.isDebugEnabled()) builder.setPrettyPrinting(); return builder.create(); } protected String getCRN(Section section, Course course) { String name = section.getName(course.getId()); if (name != null && name.indexOf('-') >= 0) return name.substring(0, name.indexOf('-')); return name; } protected boolean isValidationEnabled(org.unitime.timetable.model.Student student) { if (student == null) return false; StudentSectioningStatus status = student.getEffectiveStatus(); return status != null && status.hasOption(StudentSectioningStatus.Option.waitlist) && status.hasOption(StudentSectioningStatus.Option.specreg); } protected boolean isValidationEnabled(OnlineSectioningServer server, OnlineSectioningHelper helper, XStudent student) { String status = student.getStatus(); if (status == null) status = server.getAcademicSession().getDefaultSectioningStatus(); if (status == null) return true; StudentSectioningStatus dbStatus = StudentSectioningStatus.getPresentStatus(status, server.getAcademicSession().getUniqueId(), helper.getHibSession()); return dbStatus != null && dbStatus.hasOption(StudentSectioningStatus.Option.waitlist) && dbStatus.hasOption(StudentSectioningStatus.Option.specreg); } protected Enrollment firstEnrollment(CourseRequest request, Assignment<Request, Enrollment> assignment, Course course, Config config, HashSet<Section> sections, int idx) { if (config.getSubparts().size() == idx) { Enrollment e = new Enrollment(request, request.getCourses().indexOf(course), null, config, new HashSet<SctAssignment>(sections), null); if (request.isNotAllowed(e)) return null; return e; } else { Subpart subpart = config.getSubparts().get(idx); List<Section> sectionsThisSubpart = subpart.getSections(); List<Section> matchingSectionsThisSubpart = new ArrayList<Section>(subpart.getSections().size()); for (Section section : sectionsThisSubpart) { if (section.isCancelled()) continue; if (section.getParent() != null && !sections.contains(section.getParent())) continue; if (section.isOverlapping(sections)) continue; if (request.isNotAllowed(course, section)) continue; matchingSectionsThisSubpart.add(section); } for (Section section: matchingSectionsThisSubpart) { sections.add(section); Enrollment e = firstEnrollment(request, assignment, course, config, sections, idx + 1); if (e != null) return e; sections.remove(section); } } return null; } protected RequestedCourseStatus status(ChangeStatus status) { if (status == null) return RequestedCourseStatus.OVERRIDE_PENDING; switch (status) { case denied: return RequestedCourseStatus.OVERRIDE_REJECTED; case approved: return RequestedCourseStatus.OVERRIDE_APPROVED; case cancelled: return RequestedCourseStatus.OVERRIDE_CANCELLED; default: return RequestedCourseStatus.OVERRIDE_PENDING; } } protected RequestedCourseStatus combine(RequestedCourseStatus s1, RequestedCourseStatus s2) { if (s1 == null) return s2; if (s2 == null) return s1; if (s1 == s2) return s1; if (s1 == RequestedCourseStatus.OVERRIDE_REJECTED || s2 == RequestedCourseStatus.OVERRIDE_REJECTED) return RequestedCourseStatus.OVERRIDE_REJECTED; if (s1 == RequestedCourseStatus.OVERRIDE_PENDING || s2 == RequestedCourseStatus.OVERRIDE_PENDING) return RequestedCourseStatus.OVERRIDE_PENDING; if (s1 == RequestedCourseStatus.OVERRIDE_APPROVED || s2 == RequestedCourseStatus.OVERRIDE_APPROVED) return RequestedCourseStatus.OVERRIDE_APPROVED; if (s1 == RequestedCourseStatus.OVERRIDE_CANCELLED || s2 == RequestedCourseStatus.OVERRIDE_CANCELLED) return RequestedCourseStatus.OVERRIDE_CANCELLED; return s1; } protected RequestedCourseStatus status(SpecialRegistration request, boolean credit) { RequestedCourseStatus ret = null; if (request.changes != null) for (Change ch: request.changes) { if (ch.status == null) continue; if (credit && ch.subject == null && ch.courseNbr == null) ret = combine(ret, status(ch.status)); if (!credit && ch.subject != null && ch.courseNbr != null) ret = combine(ret, status(ch.status)); } if (ret != null) return ret; if (request.completionStatus != null) switch (request.completionStatus) { case completed: return RequestedCourseStatus.OVERRIDE_APPROVED; case cancelled: return RequestedCourseStatus.OVERRIDE_CANCELLED; case inProgress: return RequestedCourseStatus.OVERRIDE_PENDING; } return RequestedCourseStatus.OVERRIDE_PENDING; } public void validate(OnlineSectioningServer server, OnlineSectioningHelper helper, CourseRequestInterface request, CheckCoursesResponse response) throws SectioningException { XStudent original = (request.getStudentId() == null ? null : server.getStudent(request.getStudentId())); if (original == null) throw new PageAccessException(MESSAGES.exceptionEnrollNotStudent(server.getAcademicSession().toString())); // Do not validate when validation is disabled if (!isValidationEnabled(server, helper, original)) return; Integer CONF_NONE = null; Integer CONF_BANNER = 1; String creditError = null; Float maxCreditNeeded = null; for (CourseRequestInterface.Request line: request.getCourses()) { // only for wait-listed course requests if (line.isWaitList() && line.hasRequestedCourse()) { // skip enrolled courses XEnrollment enrolled = null; for (RequestedCourse rc: line.getRequestedCourse()) { if (rc.hasCourseId()) { XCourseRequest cr = original.getRequestForCourse(rc.getCourseId()); if (cr != null && cr.getEnrollment() != null) { enrolled = cr.getEnrollment(); break; } } } // when enrolled, only continue when swap for enrolled course is enabled (section wait-list) if (enrolled != null && !enrolled.getCourseId().equals(line.getWaitListSwapWithCourseOfferingId())) continue; XCourse dropCourse = null; Set<String> dropCrns = null; if (line.hasWaitListSwapWithCourseOfferingId()) { dropCourse = server.getCourse(line.getWaitListSwapWithCourseOfferingId()); XCourseRequest cr = original.getRequestForCourse(line.getWaitListSwapWithCourseOfferingId()); if (cr != null && cr.getEnrollment() != null && cr.getEnrollment().getCourseId().equals(line.getWaitListSwapWithCourseOfferingId())) { dropCrns = new TreeSet<String>(); XOffering dropOffering = server.getOffering(dropCourse.getOfferingId()); for (XSection section: dropOffering.getSections(cr.getEnrollment())) { dropCrns.add(section.getExternalId(line.getWaitListSwapWithCourseOfferingId())); } } } for (RequestedCourse rc: line.getRequestedCourse()) { if (rc.hasCourseId()) { XCourse xcourse = server.getCourse(rc.getCourseId()); if (xcourse == null) continue; // when enrolled, skip courses of lower choice than the enrollment if (enrolled != null && line.getIndex(rc.getCourseId()) > line.getIndex(enrolled.getCourseId())) continue; // skip offerings that cannot be wait-listed XOffering offering = server.getOffering(xcourse.getOfferingId()); if (offering == null || !offering.isWaitList()) continue; // when enrolled, skip the enrolled course if the enrollment matches the requirements if (enrolled != null && enrolled.getCourseId().equals(rc.getCourseId()) && enrolled.isRequired(rc, offering)) continue; // get possible enrollments into the course Assignment<Request, Enrollment> assignment = new AssignmentMap<Request, Enrollment>(); CourseRequest courseRequest = SectioningRequest.convert(assignment, new XCourseRequest(original, xcourse, rc), dropCourse, server, WaitListMode.WaitList); Collection<Enrollment> enrls = courseRequest.getEnrollmentsSkipSameTime(assignment); // get a test enrollment (preferably a non-conflicting one) Enrollment testEnrollment = null; for (Iterator<Enrollment> e = enrls.iterator(); e.hasNext();) { testEnrollment = e.next(); boolean overlaps = false; for (Request q: testEnrollment.getStudent().getRequests()) { if (q.equals(courseRequest)) continue; Enrollment x = assignment.getValue(q); if (x == null || x.getAssignments() == null || x.getAssignments().isEmpty()) continue; for (Iterator<SctAssignment> i = x.getAssignments().iterator(); i.hasNext();) { SctAssignment a = i.next(); if (a.isOverlapping(testEnrollment.getAssignments())) { overlaps = true; } } } if (!overlaps) break; } // no test enrollment, take first possible enrollment if (testEnrollment == null) { Course c = courseRequest.getCourses().get(0); for (Config config: c.getOffering().getConfigs()) { if (courseRequest.isNotAllowed(c, config)) continue; testEnrollment = firstEnrollment(courseRequest, assignment, c, config, new HashSet<Section>(), 0); } } // still no test enrollment -> ignore if (testEnrollment == null) continue; // create request CheckRestrictionsRequest req = new CheckRestrictionsRequest(); req.studentId = getBannerId(original); req.term = getBannerTerm(server.getAcademicSession()); req.campus = getBannerCampus(server.getAcademicSession()); req.mode = getSpecialRegistrationApiMode(); Set<String> crns = new HashSet<String>(); Set<String> keep = new HashSet<String>(); for (Section section: testEnrollment.getSections()) { String crn = getCRN(section, testEnrollment.getCourse()); if (dropCrns != null && dropCrns.contains(crn)) { keep.add(crn); } else { SpecialRegistrationHelper.addWaitListCrn(req, crn); crns.add(crn); } } if (dropCrns != null) for (String crn: dropCrns) { if (!keep.contains(crn)) { SpecialRegistrationHelper.dropWaitListCrn(req, crn); crns.add(crn); } } // no CRNs to check -> continue if (crns.isEmpty()) continue; // call validation CheckRestrictionsResponse resp = null; ClientResource resource = null; try { resource = new ClientResource(getSpecialRegistrationApiValidationSite()); resource.setNext(iClient); resource.addQueryParameter("apiKey", getSpecialRegistrationApiKey()); Gson gson = getGson(helper); if (helper.isDebugEnabled()) helper.debug("Request: " + gson.toJson(req)); helper.getAction().addOptionBuilder().setKey("wl-req-" + testEnrollment.getCourse().getName().replace(" ", "").toLowerCase()).setValue(gson.toJson(req)); long t1 = System.currentTimeMillis(); resource.post(new GsonRepresentation<CheckRestrictionsRequest>(req)); helper.getAction().setApiPostTime( (helper.getAction().hasApiPostTime() ? helper.getAction().getApiPostTime() : 0) + System.currentTimeMillis() - t1); resp = (CheckRestrictionsResponse)new GsonRepresentation<CheckRestrictionsResponse>(resource.getResponseEntity(), CheckRestrictionsResponse.class).getObject(); if (helper.isDebugEnabled()) helper.debug("Response: " + gson.toJson(resp)); helper.getAction().addOptionBuilder().setKey("wl-resp-" + testEnrollment.getCourse().getName().replace(" ", "").toLowerCase()).setValue(gson.toJson(resp)); if (ResponseStatus.success != resp.status) throw new SectioningException(resp.message == null || resp.message.isEmpty() ? "Failed to check student eligibility (" + resp.status + ")." : resp.message); } catch (SectioningException e) { helper.getAction().setApiException(e.getMessage()); throw (SectioningException)e; } catch (Exception e) { helper.getAction().setApiException(e.getMessage()); sLog.error(e.getMessage(), e); throw new SectioningException(e.getMessage()); } finally { if (resource != null) { if (resource.getResponse() != null) resource.getResponse().release(); resource.release(); } } // student max credit Float maxCredit = resp.maxCredit; if (maxCredit == null) maxCredit = Float.parseFloat(ApplicationProperties.getProperty("purdue.specreg.maxCreditDefault", "18")); Float maxCreditDenied = null; if (resp.deniedMaxCreditRequests != null) { for (DeniedMaxCredit r: resp.deniedMaxCreditRequests) { if (r.maxCredit != null && r.maxCredit > maxCredit && (maxCreditDenied == null || maxCreditDenied > r.maxCredit)) maxCreditDenied = r.maxCredit; } } Map<String, Map<String, RequestedCourseStatus>> overrides = new HashMap<String, Map<String, RequestedCourseStatus>>(); Float maxCreditOverride = null; RequestedCourseStatus maxCreditOverrideStatus = null; if (resp.cancelRegistrationRequests != null) for (SpecialRegistration r: resp.cancelRegistrationRequests) { if (r.changes == null || r.changes.isEmpty()) continue; for (Change ch: r.changes) { if (ch.status == ChangeStatus.cancelled || ch.status == ChangeStatus.denied) continue; if (ch.subject != null && ch.courseNbr != null) { String course = ch.subject + " " + ch.courseNbr; Map<String, RequestedCourseStatus> problems = overrides.get(course); if (problems == null) { problems = new HashMap<String, RequestedCourseStatus>(); overrides.put(course, problems); } if (ch.errors != null) for (ChangeError err: ch.errors) { if (err.code != null) problems.put(err.code, status(ch.status)); } } else if (r.maxCredit != null && (maxCreditOverride == null || maxCreditOverride < r.maxCredit)) { maxCreditOverride = r.maxCredit; maxCreditOverrideStatus = status(ch.status); } } } Float neededCredit = null; if (resp.outJson != null && resp.outJson.maxHoursCalc != null) neededCredit = resp.outJson.maxHoursCalc; if (neededCredit != null) { if (maxCreditNeeded == null || maxCreditNeeded < neededCredit) maxCreditNeeded = neededCredit; } if (maxCreditDenied != null && neededCredit != null && neededCredit >= maxCreditDenied) { response.addMessage(rc.getCourseId(), rc.getCourseName(), "WL-CREDIT", ApplicationProperties.getProperty("purdue.specreg.messages.maxCredit", "Maximum of {max} credit hours exceeded.").replace("{max}", sCreditFormat.format(maxCredit)).replace("{credit}", sCreditFormat.format(neededCredit)) , CONF_NONE); response.setCreditWarning(ApplicationProperties.getProperty("purdue.specreg.messages.maxCredit", "Maximum of {max} credit hours exceeded.") .replace("{max}", sCreditFormat.format(maxCredit)).replace("{credit}", sCreditFormat.format(neededCredit)).replace("{maxCreditDenied}", sCreditFormat.format(maxCreditDenied)) ); response.setMaxCreditOverrideStatus(RequestedCourseStatus.OVERRIDE_REJECTED); creditError = ApplicationProperties.getProperty("purdue.specreg.messages.maxCreditDeniedError", "Maximum of {max} credit hours exceeded.\nThe request to increase the maximum credit hours to {maxCreditDenied} has been denied.\nYou may not be able to get a full schedule.") .replace("{max}", sCreditFormat.format(maxCredit)).replace("{credit}", sCreditFormat.format(neededCredit)).replace("{maxCreditDenied}", sCreditFormat.format(maxCreditDenied)); response.setMaxCreditNeeded(maxCreditNeeded); } if (creditError == null && neededCredit != null && maxCredit < neededCredit) { response.addMessage(rc.getCourseId(), rc.getCourseName(), "WL-CREDIT", ApplicationProperties.getProperty("purdue.specreg.messages.maxCredit", "Maximum of {max} credit hours exceeded.").replace("{max}", sCreditFormat.format(maxCredit)).replace("{credit}", sCreditFormat.format(neededCredit)), maxCreditOverride == null || maxCreditOverride < neededCredit ? CONF_BANNER : CONF_NONE); response.setCreditWarning(ApplicationProperties.getProperty("purdue.specreg.messages.maxCredit", "Maximum of {max} credit hours exceeded.").replace("{max}", sCreditFormat.format(maxCredit)).replace("{credit}", sCreditFormat.format(neededCredit))); response.setMaxCreditOverrideStatus(maxCreditOverrideStatus == null || maxCreditOverride < neededCredit ? RequestedCourseStatus.OVERRIDE_NEEDED : maxCreditOverrideStatus); response.setMaxCreditNeeded(maxCreditNeeded); } Map<String, Set<String>> deniedOverrides = new HashMap<String, Set<String>>(); if (resp.deniedRequests != null) for (DeniedRequest r: resp.deniedRequests) { if (r.mode != req.mode) continue; String course = r.subject + " " + r.courseNbr; Set<String> problems = deniedOverrides.get(course); if (problems == null) { problems = new TreeSet<String>(); deniedOverrides.put(course, problems); } problems.add(r.code); } if (resp.outJson != null && resp.outJson.message != null && resp.outJson.status != null && resp.outJson.status != ResponseStatus.success) { response.addError(null, null, "Failure", resp.outJson.message); response.setErrorMessage(resp.outJson.message); } if (resp.outJson != null && resp.outJson.problems != null) for (Problem problem: resp.outJson.problems) { if ("HOLD".equals(problem.code)) { response.addError(null, null, problem.code, problem.message); response.setErrorMessage(ApplicationProperties.getProperty("purdue.specreg.messages.holdError", problem.message)); //throw new SectioningException(problem.message); } if ("DUPL".equals(problem.code)) continue; if ("MAXI".equals(problem.code)) continue; if ("CLOS".equals(problem.code)) continue; if ("TIME".equals(problem.code)) continue; if (!crns.contains(problem.crn)) continue; String bc = xcourse.getSubjectArea() + " " + xcourse.getCourseNumber(); Map<String, RequestedCourseStatus> problems = (bc == null ? null : overrides.get(bc)); Set<String> denied = (bc == null ? null : deniedOverrides.get(bc)); if (denied != null && denied.contains(problem.code)) { response.addMessage(xcourse.getCourseId(), xcourse.getCourseName(), problem.code, "Denied " + problem.message, CONF_NONE).setStatus(RequestedCourseStatus.OVERRIDE_REJECTED); } else { RequestedCourseStatus status = (problems == null ? null : problems.get(problem.code)); if (status == null) { if (resp.overrides != null && !resp.overrides.contains(problem.code)) { response.addError(xcourse.getCourseId(), xcourse.getCourseName(), problem.code, "Not Allowed " + problem.message).setStatus(RequestedCourseStatus.OVERRIDE_REJECTED); response.setErrorMessage(ApplicationProperties.getProperty("purdue.specreg.messages.waitlist.deniedOverrideError", "One or more wait-listed courses require registration overrides which is not allowed.\nYou cannot wait-list these courses.")); continue; } else { if (!xcourse.isOverrideEnabled(problem.code)) { response.addError(xcourse.getCourseId(), xcourse.getCourseName(), problem.code, "Not Allowed " + problem.message).setStatus(RequestedCourseStatus.OVERRIDE_REJECTED); response.setErrorMessage(ApplicationProperties.getProperty("purdue.specreg.messages.waitlist.deniedOverrideError", "One or more wait-listed courses require registration overrides which is not allowed.\nYou cannot wait-list these courses.")); continue; } } } response.addMessage(xcourse.getCourseId(), xcourse.getCourseName(), problem.code, problem.message, status == null ? CONF_BANNER : CONF_NONE) .setStatus(status == null ? RequestedCourseStatus.OVERRIDE_NEEDED : status); } } if (response.hasMessages()) for (CourseMessage m: response.getMessages()) { if (m.getCourse() != null && m.getMessage().indexOf("this section") >= 0) m.setMessage(m.getMessage().replace("this section", m.getCourse())); if (m.getCourse() != null && m.getMessage().indexOf(" (CRN ") >= 0) m.setMessage(m.getMessage().replaceFirst(" \\(CRN [0-9][0-9][0-9][0-9][0-9]\\) ", " ")); } } } } } if (response.getConfirms().contains(CONF_BANNER)) { response.addConfirmation(ApplicationProperties.getProperty("purdue.specreg.messages.waitlist.bannerProblemsFound", "The following registration errors for the wait-listed courses have been detected:"), CONF_BANNER, -1); String note = ApplicationProperties.getProperty("purdue.specreg.messages.waitlist.courseRequestNote", "<b>Request Note:</b>"); int idx = 1; if (note != null && !note.isEmpty()) { response.addConfirmation(note, CONF_BANNER, idx++); CourseMessage cm = response.addConfirmation("", CONF_BANNER, idx++); cm.setCode("REQUEST_NOTE"); for (String suggestion: ApplicationProperties.getProperty("purdue.specreg.waitlist.requestorNoteSuggestions", "").split("[\r\n]+")) if (!suggestion.isEmpty()) cm.addSuggestion(suggestion); } response.addConfirmation( ApplicationProperties.getProperty("purdue.specreg.messages.waitlist.requestOverrides", "\nIf you have already discussed these courses with your advisor and were advised to request " + "registration in them please select Request Overrides. If you aren’t sure, click Cancel Submit and " + "consult with your advisor before wait-listing these courses."), CONF_BANNER, idx++); } Set<Integer> conf = response.getConfirms(); if (conf.contains(CONF_BANNER)) { response.setConfirmation(CONF_BANNER, ApplicationProperties.getProperty("purdue.specreg.confirm.waitlist.bannerDialogName", "Request Wait-List Overrides"), ApplicationProperties.getProperty("purdue.specreg.confirm.waitlist.bannerYesButton", "Request Overrides"), ApplicationProperties.getProperty("purdue.specreg.confirm.waitlist.bannerNoButton", "Cancel Submit"), ApplicationProperties.getProperty("purdue.specreg.confirm.waitlist.bannerYesButtonTitle", "Request overrides for the above registration errors"), ApplicationProperties.getProperty("purdue.specreg.confirm.waitlist.bannerNoButtonTitle", "Go back to Scheduling Assistant")); } } @Override public void submit(OnlineSectioningServer server, OnlineSectioningHelper helper, CourseRequestInterface request, Float neededCredit) throws SectioningException { XStudent original = (request.getStudentId() == null ? null : server.getStudent(request.getStudentId())); if (original == null) return; // Do not submit when validation is disabled if (!isValidationEnabled(server, helper, original)) return; request.setMaxCreditOverrideStatus(RequestedCourseStatus.SAVED); ClientResource resource = null; Map<String, Set<String>> overrides = new HashMap<String, Set<String>>(); Float maxCredit = null; Float oldCredit = null; try { resource = new ClientResource(getSpecialRegistrationApiSiteCheckSpecialRegistrationStatus()); resource.setNext(iClient); AcademicSessionInfo session = server.getAcademicSession(); String term = getBannerTerm(session); String campus = getBannerCampus(session); resource.addQueryParameter("term", term); resource.addQueryParameter("campus", campus); resource.addQueryParameter("studentId", getBannerId(original)); resource.addQueryParameter("mode", getSpecialRegistrationApiMode().name()); helper.getAction().addOptionBuilder().setKey("term").setValue(term); helper.getAction().addOptionBuilder().setKey("campus").setValue(campus); helper.getAction().addOptionBuilder().setKey("studentId").setValue(getBannerId(original)); resource.addQueryParameter("apiKey", getSpecialRegistrationApiKey()); long t1 = System.currentTimeMillis(); resource.get(MediaType.APPLICATION_JSON); helper.getAction().setApiGetTime(System.currentTimeMillis() - t1); SpecialRegistrationStatusResponse status = (SpecialRegistrationStatusResponse)new GsonRepresentation<SpecialRegistrationStatusResponse>(resource.getResponseEntity(), SpecialRegistrationStatusResponse.class).getObject(); Gson gson = getGson(helper); if (helper.isDebugEnabled()) helper.debug("Status: " + gson.toJson(status)); helper.getAction().addOptionBuilder().setKey("wl-status").setValue(gson.toJson(status)); if (status != null && status.data != null) { maxCredit = status.data.maxCredit; request.setMaxCredit(status.data.maxCredit); } if (maxCredit == null) maxCredit = Float.parseFloat(ApplicationProperties.getProperty("purdue.specreg.maxCreditDefault", "18")); if (status != null && status.data != null && status.data.requests != null) { for (SpecialRegistration r: status.data.requests) { if (r.changes != null) for (Change ch: r.changes) { if (status(ch.status) == RequestedCourseStatus.OVERRIDE_PENDING && ch.subject != null && ch.courseNbr != null) { String course = ch.subject + " " + ch.courseNbr; Set<String> problems = overrides.get(course); if (problems == null) { problems = new TreeSet<String>(); overrides.put(course, problems); } if (ch.errors != null) for (ChangeError err: ch.errors) { if (err.code != null) problems.add(err.code); } } else if (status(ch.status) == RequestedCourseStatus.OVERRIDE_PENDING && r.maxCredit != null) { oldCredit = r.maxCredit; } } } } } catch (SectioningException e) { helper.getAction().setApiException(e.getMessage()); throw (SectioningException)e; } catch (Exception e) { helper.getAction().setApiException(e.getMessage()); sLog.error(e.getMessage(), e); throw new SectioningException(e.getMessage()); } finally { if (resource != null) { if (resource.getResponse() != null) resource.getResponse().release(); resource.release(); } } SpecialRegistrationRequest req = new SpecialRegistrationRequest(); req.studentId = getBannerId(original); req.term = getBannerTerm(server.getAcademicSession()); req.campus = getBannerCampus(server.getAcademicSession()); req.mode = getSpecialRegistrationApiMode(); req.changes = new ArrayList<Change>(); if (helper.getUser() != null) { req.requestorId = getRequestorId(helper.getUser()); req.requestorRole = getRequestorType(helper.getUser(), original); } if (request.hasConfirmations()) { for (CourseMessage m: request.getConfirmations()) { if ("REQUEST_NOTE".equals(m.getCode()) && m.getMessage() != null && !m.getMessage().isEmpty()) { req.requestorNotes = m.getMessage(); } } for (CourseRequestInterface.Request c: request.getCourses()) if (c.hasRequestedCourse() && c.isWaitList()) { for (CourseRequestInterface.RequestedCourse rc: c.getRequestedCourse()) { XCourseId cid = server.getCourse(rc.getCourseId(), rc.getCourseName()); if (cid == null) continue; XCourse course = (cid instanceof XCourse ? (XCourse)cid : server.getCourse(cid.getCourseId())); if (course == null) continue; String subject = course.getSubjectArea(); String courseNbr = course.getCourseNumber(); List<ChangeError> errors = new ArrayList<ChangeError>(); for (CourseMessage m: request.getConfirmations()) { if ("WL-CREDIT".equals(m.getCode())) continue; if ("NO_ALT".equals(m.getCode())) continue; if ("DROP_CRIT".equals(m.getCode())) continue; if ("WL-OVERLAP".equals(m.getCode())) continue; if ("NOT-ONLINE".equals(m.getCode())) continue; if ("NOT-RESIDENTIAL".equals(m.getCode())) continue; if (!m.hasCourse()) continue; if (!m.isError() && (course.getCourseId().equals(m.getCourseId()) || course.getCourseName().equals(m.getCourse()))) { ChangeError e = new ChangeError(); e.code = m.getCode(); e.message = m.getMessage(); errors.add(e); } } if (!errors.isEmpty()) { Change ch = new Change(); ch.setCourse(subject, courseNbr, iExternalTermProvider, server.getAcademicSession()); ch.crn = ""; ch.errors = errors; ch.operation = ChangeOperation.ADD; req.changes.add(ch); overrides.remove(subject + " " + courseNbr); } } } } req.courseCreditHrs = new ArrayList<CourseCredit>(); Float wlCredit = null; for (CourseRequestInterface.Request r: request.getCourses()) { if (r.hasRequestedCourse() && r.isWaitList()) { CourseCredit cc = null; Float credit = null; for (RequestedCourse rc: r.getRequestedCourse()) { XCourseId cid = server.getCourse(rc.getCourseId(), rc.getCourseName()); if (cid == null) continue; XCourse course = (cid instanceof XCourse ? (XCourse)cid : server.getCourse(cid.getCourseId())); if (course == null) continue; if (cc == null) { cc = new CourseCredit(); cc.setCourse(course.getSubjectArea(), course.getCourseNumber(), iExternalTermProvider, server.getAcademicSession()); cc.title = course.getTitle(); cc.creditHrs = (course.hasCredit() ? course.getMinCredit() : 0f); } else { if (cc.alternatives == null) cc.alternatives = new ArrayList<CourseCredit>(); CourseCredit acc = new CourseCredit(); acc.setCourse(course.getSubjectArea(), course.getCourseNumber(), iExternalTermProvider, server.getAcademicSession()); acc.title = course.getTitle(); acc.creditHrs = (course.hasCredit() ? course.getMinCredit() : 0f); cc.alternatives.add(acc); } if (rc.hasCredit() && (credit == null || credit < rc.getCreditMin())) credit = rc.getCreditMin(); } if (cc != null) req.courseCreditHrs.add(cc); if (credit != null && (wlCredit == null || wlCredit < credit)) wlCredit = credit; } } if (neededCredit != null && maxCredit < neededCredit) { req.maxCredit = neededCredit; } if (!req.changes.isEmpty() || !overrides.isEmpty() || req.maxCredit != null || oldCredit != null) { resource = null; try { resource = new ClientResource(getSpecialRegistrationApiSiteSubmitRegistration()); resource.setNext(iClient); resource.addQueryParameter("apiKey", getSpecialRegistrationApiKey()); Gson gson = getGson(helper); if (helper.isDebugEnabled()) helper.debug("Request: " + gson.toJson(req)); helper.getAction().addOptionBuilder().setKey("wl-request").setValue(gson.toJson(req)); long t1 = System.currentTimeMillis(); resource.post(new GsonRepresentation<SpecialRegistrationRequest>(req)); helper.getAction().setApiPostTime(System.currentTimeMillis() - t1); SpecialRegistrationResponseList response = (SpecialRegistrationResponseList)new GsonRepresentation<SpecialRegistrationResponseList>(resource.getResponseEntity(), SpecialRegistrationResponseList.class).getObject(); if (helper.isDebugEnabled()) helper.debug("Response: " + gson.toJson(response)); helper.getAction().addOptionBuilder().setKey("wl-response").setValue(gson.toJson(response)); if (ResponseStatus.success != response.status) throw new SectioningException(response.message == null || response.message.isEmpty() ? "Failed to request overrides (" + response.status + ")." : response.message); if (response.data != null) { for (CourseRequestInterface.Request c: request.getCourses()) if (c.hasRequestedCourse()) { for (CourseRequestInterface.RequestedCourse rc: c.getRequestedCourse()) { if (rc.getStatus() != null && rc.getStatus() != RequestedCourseStatus.OVERRIDE_REJECTED && rc.getStatus() != RequestedCourseStatus.WAITLIST_INACTIVE) { rc.setStatus(null); rc.setOverrideExternalId(null); rc.setOverrideTimeStamp(null); } XCourseId cid = server.getCourse(rc.getCourseId(), rc.getCourseName()); if (cid == null) continue; XCourse course = (cid instanceof XCourse ? (XCourse)cid : server.getCourse(cid.getCourseId())); if (course == null) continue; String subject = course.getSubjectArea(); String courseNbr = course.getCourseNumber(); for (SpecialRegistration r: response.data) { if (r.changes != null) for (Change ch: r.changes) { if (subject.equals(ch.subject) && courseNbr.equals(ch.courseNbr)) { rc.setOverrideTimeStamp(r.dateCreated == null ? null : r.dateCreated.toDate()); rc.setOverrideExternalId(r.regRequestId); rc.setStatus(status(r, false)); rc.setStatusNote(SpecialRegistrationHelper.note(r, false)); rc.setRequestId(r.regRequestId); rc.setRequestorNote(r.requestorNotes); break; } } } } } for (CourseRequestInterface.Request c: request.getAlternatives()) if (c.hasRequestedCourse()) { for (CourseRequestInterface.RequestedCourse rc: c.getRequestedCourse()) { if (rc.getStatus() != null && rc.getStatus() != RequestedCourseStatus.OVERRIDE_REJECTED && rc.getStatus() != RequestedCourseStatus.WAITLIST_INACTIVE) { rc.setStatus(null); rc.setOverrideExternalId(null); rc.setOverrideTimeStamp(null); } XCourseId cid = server.getCourse(rc.getCourseId(), rc.getCourseName()); if (cid == null) continue; XCourse course = (cid instanceof XCourse ? (XCourse)cid : server.getCourse(cid.getCourseId())); if (course == null) continue; String subject = course.getSubjectArea(); String courseNbr = course.getCourseNumber(); for (SpecialRegistration r: response.data) if (r.changes != null) for (Change ch: r.changes) { if (subject.equals(ch.subject) && courseNbr.equals(ch.courseNbr)) { rc.setOverrideTimeStamp(r.dateCreated == null ? null : r.dateCreated.toDate()); rc.setOverrideExternalId(r.regRequestId); rc.setStatus(status(r, false)); rc.setStatusNote(SpecialRegistrationHelper.note(r, false)); break; } } } } if (req.maxCredit != null) { for (SpecialRegistration r: response.data) { if (r.maxCredit != null) { request.setMaxCreditOverride(r.maxCredit); request.setMaxCreditOverrideExternalId(r.regRequestId); request.setMaxCreditOverrideTimeStamp(r.dateCreated == null ? null : r.dateCreated.toDate()); request.setMaxCreditOverrideStatus(status(r, true)); request.setCreditWarning( ApplicationProperties.getProperty("purdue.specreg.messages.maxCredit", "Maximum of {max} credit hours exceeded.") .replace("{max}", sCreditFormat.format(maxCredit)).replace("{credit}", sCreditFormat.format(req.maxCredit)) ); request.setCreditNote(SpecialRegistrationHelper.note(r, true)); request.setRequestorNote(r.requestorNotes); request.setRequestId(r.regRequestId); break; } } } else { request.setMaxCreditOverrideStatus(RequestedCourseStatus.SAVED); } } if (request.hasConfirmations()) { for (CourseMessage message: request.getConfirmations()) { if (message.getStatus() == RequestedCourseStatus.OVERRIDE_NEEDED) message.setStatus(RequestedCourseStatus.OVERRIDE_PENDING); } } } catch (SectioningException e) { helper.getAction().setApiException(e.getMessage()); throw (SectioningException)e; } catch (Exception e) { helper.getAction().setApiException(e.getMessage()); sLog.error(e.getMessage(), e); throw new SectioningException(e.getMessage()); } finally { if (resource != null) { if (resource.getResponse() != null) resource.getResponse().release(); resource.release(); } } } else { for (CourseRequestInterface.Request c: request.getCourses()) if (c.hasRequestedCourse()) { for (CourseRequestInterface.RequestedCourse rc: c.getRequestedCourse()) { if (rc.getStatus() != null && rc.getStatus() != RequestedCourseStatus.OVERRIDE_REJECTED && rc.getStatus() != RequestedCourseStatus.WAITLIST_INACTIVE) { rc.setStatus(null); rc.setOverrideExternalId(null); rc.setOverrideTimeStamp(null); } } } for (CourseRequestInterface.Request c: request.getAlternatives()) if (c.hasRequestedCourse()) { for (CourseRequestInterface.RequestedCourse rc: c.getRequestedCourse()) { if (rc.getStatus() != null && rc.getStatus() != RequestedCourseStatus.OVERRIDE_REJECTED && rc.getStatus() != RequestedCourseStatus.WAITLIST_INACTIVE) { rc.setStatus(null); rc.setOverrideExternalId(null); rc.setOverrideTimeStamp(null); } } } } } @Override public void check(OnlineSectioningServer server, OnlineSectioningHelper helper, CourseRequestInterface request) throws SectioningException { XStudent original = (request.getStudentId() == null ? null : server.getStudent(request.getStudentId())); if (original == null) return; // Do not check when validation is disabled if (!isValidationEnabled(server, helper, original)) return; Map<String, RequestedCourse> rcs = new HashMap<String, RequestedCourse>(); for (CourseRequestInterface.Request r: request.getCourses()) { if (r.hasRequestedCourse() && r.isWaitList()) for (RequestedCourse rc: r.getRequestedCourse()) { if (rc.getOverrideExternalId() != null) rcs.put(rc.getOverrideExternalId(), rc); rcs.put(rc.getCourseName(), rc); if (rc.getStatus() == RequestedCourseStatus.OVERRIDE_NEEDED && "TBD".equals(rc.getOverrideExternalId())) { request.addConfirmationMessage( rc.getCourseId(), rc.getCourseName(), "NOT_REQUESTED", ApplicationProperties.getProperty("purdue.specreg.messages.waitlist.notRequested", "Overrides not requested, wait-list inactive."), RequestedCourseStatus.OVERRIDE_NEEDED, 1 ); } } } if (request.getMaxCreditOverrideStatus() == null) { request.setMaxCreditOverrideStatus(RequestedCourseStatus.SAVED); } if (rcs.isEmpty() && !request.hasMaxCreditOverride()) return; Integer ORD_BANNER = 1; ClientResource resource = null; try { resource = new ClientResource(getSpecialRegistrationApiSiteCheckSpecialRegistrationStatus()); resource.setNext(iClient); AcademicSessionInfo session = server.getAcademicSession(); String term = getBannerTerm(session); String campus = getBannerCampus(session); resource.addQueryParameter("term", term); resource.addQueryParameter("campus", campus); resource.addQueryParameter("studentId", getBannerId(original)); resource.addQueryParameter("mode", getSpecialRegistrationApiMode().name()); helper.getAction().addOptionBuilder().setKey("term").setValue(term); helper.getAction().addOptionBuilder().setKey("campus").setValue(campus); helper.getAction().addOptionBuilder().setKey("studentId").setValue(getBannerId(original)); resource.addQueryParameter("apiKey", getSpecialRegistrationApiKey()); long t0 = System.currentTimeMillis(); resource.get(MediaType.APPLICATION_JSON); helper.getAction().setApiGetTime(System.currentTimeMillis() - t0); SpecialRegistrationStatusResponse status = (SpecialRegistrationStatusResponse)new GsonRepresentation<SpecialRegistrationStatusResponse>(resource.getResponseEntity(), SpecialRegistrationStatusResponse.class).getObject(); Gson gson = getGson(helper); if (helper.isDebugEnabled()) helper.debug("Status: " + gson.toJson(status)); helper.getAction().addOptionBuilder().setKey("wl-status").setValue(gson.toJson(status)); Float maxCredit = null; if (status != null && status.data != null) { maxCredit = status.data.maxCredit; request.setMaxCredit(status.data.maxCredit); } if (maxCredit == null) maxCredit = Float.parseFloat(ApplicationProperties.getProperty("purdue.specreg.maxCreditDefault", "18")); if (status != null && status.data != null && status.data.requests != null) { // Retrieve max credit request SpecialRegistration maxCreditReq = null; // Try matching request first if (request.getMaxCreditOverrideExternalId() != null) for (SpecialRegistration r: status.data.requests) { if (r.maxCredit != null && request.getMaxCreditOverrideExternalId().equals(r.regRequestId)) { maxCreditReq = r; break; } } // Get latest not-cancelled max credit override request otherwise if (maxCreditReq == null) for (SpecialRegistration r: status.data.requests) { if (r.maxCredit != null && status(r, true) != RequestedCourseStatus.OVERRIDE_CANCELLED && (maxCreditReq == null || r.dateCreated.isAfter(maxCreditReq.dateCreated))) { maxCreditReq = r; } } if (maxCreditReq != null) { request.setMaxCreditOverrideExternalId(maxCreditReq.regRequestId); request.setMaxCreditOverrideStatus(status(maxCreditReq, true)); request.setMaxCreditOverride(maxCreditReq.maxCredit); request.setMaxCreditOverrideTimeStamp(maxCreditReq.dateCreated == null ? null : maxCreditReq.dateCreated.toDate()); request.setCreditNote(SpecialRegistrationHelper.note(maxCreditReq, true)); String warning = null; if (maxCreditReq.changes != null) for (Change ch: maxCreditReq.changes) if (ch.subject == null && ch.courseNbr == null) if (ch.errors != null) for (ChangeError er: ch.errors) if ("MAXI".equals(er.code) && er.message != null) warning = (warning == null ? "" : warning + "\n") + er.message; request.setCreditWarning(warning); request.setRequestorNote(maxCreditReq.requestorNotes); request.setRequestId(maxCreditReq.regRequestId); for (String suggestion: ApplicationProperties.getProperty("purdue.specreg.waitlist.requestorNoteSuggestions", "").split("[\r\n]+")) if (!suggestion.isEmpty()) request.addRequestorNoteSuggestion(suggestion); } for (SpecialRegistration r: status.data.requests) { if (r.regRequestId == null) continue; RequestedCourse rc = rcs.get(r.regRequestId); if (rc == null) { if (r.changes != null) for (Change ch: r.changes) if (ch.status == ChangeStatus.approved) { rc = rcs.get(ch.subject + " " + ch.courseNbr); if (rc != null) { for (ChangeError er: ch.errors) request.addConfirmationMessage(rc.getCourseId(), rc.getCourseName(), er.code, "Approved " + er.message, status(ch.status), ORD_BANNER); if (rc.getRequestId() == null) { rc.setStatusNote(SpecialRegistrationHelper.note(r, false)); rc.setRequestorNote(r.requestorNotes); if (rc.getStatus() != RequestedCourseStatus.ENROLLED) rc.setStatus(RequestedCourseStatus.OVERRIDE_APPROVED); } } } continue; } if (rc.getStatus() != RequestedCourseStatus.ENROLLED) { rc.setStatus(status(r, false)); } if (r.changes != null) for (Change ch: r.changes) if (ch.errors != null && ch.courseNbr != null && ch.subject != null && ch.status != null) for (ChangeError er: ch.errors) { if (ch.status == ChangeStatus.denied) { request.addConfirmationError(rc.getCourseId(), rc.getCourseName(), er.code, "Denied " + er.message, status(ch.status), ORD_BANNER); request.setErrorMessage(ApplicationProperties.getProperty("purdue.specreg.messages.waitlist.deniedOverrideError", "One or more wait-listed courses require registration overrides which have been denied.\nYou cannot wait-list these courses.")); } else if (ch.status == ChangeStatus.approved) { request.addConfirmationMessage(rc.getCourseId(), rc.getCourseName(), er.code, "Approved " + er.message, status(ch.status), ORD_BANNER); } else { request.addConfirmationMessage(rc.getCourseId(), rc.getCourseName(), er.code, er.message, status(ch.status), ORD_BANNER); } } rc.setStatusNote(SpecialRegistrationHelper.note(r, false)); rc.setRequestorNote(r.requestorNotes); rc.setRequestId(r.regRequestId); for (String suggestion: ApplicationProperties.getProperty("purdue.specreg.waitlist.requestorNoteSuggestions", "").split("[\r\n]+")) if (!suggestion.isEmpty()) rc.addRequestorNoteSuggestion(suggestion); } } } catch (SectioningException e) { helper.getAction().setApiException(e.getMessage()); throw (SectioningException)e; } catch (Exception e) { helper.getAction().setApiException(e.getMessage() == null ? "Null" : e.getMessage()); sLog.error(e.getMessage(), e); throw new SectioningException(e.getMessage()); } finally { if (resource != null) { if (resource.getResponse() != null) resource.getResponse().release(); resource.release(); } } } @Override public void checkEligibility(OnlineSectioningServer server, OnlineSectioningHelper helper, EligibilityCheck check, XStudent student) throws SectioningException { if (student == null) return; // Do not check eligibility when validation is disabled if (!isValidationEnabled(server, helper, student)) return; if (!check.hasFlag(EligibilityCheck.EligibilityFlag.CAN_ENROLL)) return; ClientResource resource = null; try { resource = new ClientResource(getSpecialRegistrationApiSiteCheckEligibility()); resource.setNext(iClient); AcademicSessionInfo session = server.getAcademicSession(); String term = getBannerTerm(session); String campus = getBannerCampus(session); resource.addQueryParameter("term", term); resource.addQueryParameter("campus", campus); resource.addQueryParameter("studentId", getBannerId(student)); resource.addQueryParameter("mode", getSpecialRegistrationApiMode().name()); helper.getAction().addOptionBuilder().setKey("term").setValue(term); helper.getAction().addOptionBuilder().setKey("campus").setValue(campus); helper.getAction().addOptionBuilder().setKey("studentId").setValue(getBannerId(student)); resource.addQueryParameter("apiKey", getSpecialRegistrationApiKey()); long t0 = System.currentTimeMillis(); resource.get(MediaType.APPLICATION_JSON); helper.getAction().setApiGetTime( (helper.getAction().hasApiGetTime() ? helper.getAction().getApiGetTime() : 0l) + System.currentTimeMillis() - t0); CheckEligibilityResponse eligibility = (CheckEligibilityResponse)new GsonRepresentation<CheckEligibilityResponse>(resource.getResponseEntity(), CheckEligibilityResponse.class).getObject(); Gson gson = getGson(helper); if (helper.isDebugEnabled()) helper.debug("Eligibility: " + gson.toJson(eligibility)); helper.getAction().addOptionBuilder().setKey("wl-eligibility").setValue(gson.toJson(eligibility)); if (ResponseStatus.success != eligibility.status) throw new SectioningException(eligibility.message == null || eligibility.message.isEmpty() ? "Failed to check wait-list eligibility (" + eligibility.status + ")." : eligibility.message); if (eligibility.data != null && eligibility.data.eligible != null && eligibility.data.eligible.booleanValue()) { check.setFlag(EligibilityFlag.WAIT_LIST_VALIDATION, true); } if (eligibility.data != null && eligibility.data.eligibilityProblems != null) { String m = null; for (EligibilityProblem p: eligibility.data.eligibilityProblems) if (m == null) m = p.message; else m += "\n" + p.message; if (m != null) check.setMessage(MESSAGES.exceptionFailedEligibilityCheck(m)); } } catch (SectioningException e) { helper.getAction().setApiException(e.getMessage()); throw (SectioningException)e; } catch (Exception e) { helper.getAction().setApiException(e.getMessage() == null ? "Null" : e.getMessage()); sLog.error(e.getMessage(), e); throw new SectioningException(e.getMessage()); } finally { if (resource != null) { if (resource.getResponse() != null) resource.getResponse().release(); resource.release(); } } } protected boolean hasOverride(org.unitime.timetable.model.Student student) { if (student.getOverrideExternalId() != null) return true; if (student.getMaxCredit() == null) return true; for (CourseDemand cd: student.getCourseDemands()) { if (Boolean.TRUE.equals(cd.isWaitlist()) && Boolean.FALSE.equals(cd.isAlternative()) && !cd.isEnrolledExceptForWaitListSwap()) for (org.unitime.timetable.model.CourseRequest cr: cd.getCourseRequests()) { if (cr.getOverrideExternalId() != null) return true; } } if (student.getOverrideExternalId() != null && student.getMaxCreditOverrideIntent() == CourseRequestOverrideIntent.WAITLIST) return true; return false; } public boolean updateStudent(OnlineSectioningServer server, OnlineSectioningHelper helper, Student student, Builder action) throws SectioningException { // No pending overrides -> nothing to do if (student == null || !hasOverride(student)) return false; ClientResource resource = null; try { resource = new ClientResource(getSpecialRegistrationApiSiteCheckSpecialRegistrationStatus()); resource.setNext(iClient); AcademicSessionInfo session = (server == null ? new AcademicSessionInfo(student.getSession()) : server.getAcademicSession()); String term = getBannerTerm(session); String campus = getBannerCampus(session); resource.addQueryParameter("term", term); resource.addQueryParameter("campus", campus); resource.addQueryParameter("studentId", getBannerId(student)); resource.addQueryParameter("mode", getSpecialRegistrationApiMode().name()); action.addOptionBuilder().setKey("term").setValue(term); action.addOptionBuilder().setKey("campus").setValue(campus); action.addOptionBuilder().setKey("studentId").setValue(getBannerId(student)); resource.addQueryParameter("apiKey", getSpecialRegistrationApiKey()); long t0 = System.currentTimeMillis(); resource.get(MediaType.APPLICATION_JSON); action.setApiGetTime(System.currentTimeMillis() - t0); SpecialRegistrationStatusResponse status = (SpecialRegistrationStatusResponse)new GsonRepresentation<SpecialRegistrationStatusResponse>(resource.getResponseEntity(), SpecialRegistrationStatusResponse.class).getObject(); Gson gson = getGson(helper); if (helper.isDebugEnabled()) helper.debug("Status: " + gson.toJson(status)); action.addOptionBuilder().setKey("wl-status").setValue(gson.toJson(status)); boolean changed = false; for (CourseDemand cd: student.getCourseDemands()) { if (Boolean.TRUE.equals(cd.isWaitlist()) && Boolean.FALSE.equals(cd.isAlternative()) && !cd.isEnrolledExceptForWaitListSwap()) for (org.unitime.timetable.model.CourseRequest cr: cd.getCourseRequests()) { if (cr.getOverrideExternalId() != null && !"TBD".equals(cr.getOverrideExternalId())) { SpecialRegistration req = null; for (SpecialRegistration r: status.data.requests) { if (cr.getOverrideExternalId().equals(r.regRequestId)) { req = r; break; } } if (req == null) { if (cr.getCourseRequestOverrideStatus() != CourseRequestOverrideStatus.CANCELLED) { cr.setCourseRequestOverrideStatus(CourseRequestOverrideStatus.CANCELLED); helper.getHibSession().update(cr); changed = true; } } else { Integer oldStatus = cr.getOverrideStatus(); switch (status(req, false)) { case OVERRIDE_REJECTED: cr.setCourseRequestOverrideStatus(CourseRequestOverrideStatus.REJECTED); break; case OVERRIDE_APPROVED: cr.setCourseRequestOverrideStatus(CourseRequestOverrideStatus.APPROVED); break; case OVERRIDE_CANCELLED: cr.setCourseRequestOverrideStatus(CourseRequestOverrideStatus.CANCELLED); break; case OVERRIDE_PENDING: cr.setCourseRequestOverrideStatus(CourseRequestOverrideStatus.PENDING); break; } if (oldStatus == null || !oldStatus.equals(cr.getOverrideStatus())) { helper.getHibSession().update(cr); changed = true; } } } } } boolean studentChanged = false; if (status.data.maxCredit != null && !status.data.maxCredit.equals(student.getMaxCredit())) { student.setMaxCredit(status.data.maxCredit); studentChanged = true; } if (student.getOverrideExternalId() != null) { SpecialRegistration req = null; for (SpecialRegistration r: status.data.requests) { if (student.getOverrideExternalId().equals(r.regRequestId)) { req = r; break; } } if (req == null && student.getMaxCreditOverrideIntent() == CourseRequestOverrideIntent.WAITLIST) { student.setOverrideExternalId(null); student.setOverrideMaxCredit(null); student.setOverrideStatus(null); student.setOverrideTimeStamp(null); student.setOverrideIntent(null); studentChanged = true; } else if (req != null) { Integer oldStatus = student.getOverrideStatus(); switch (status(req, true)) { case OVERRIDE_REJECTED: student.setMaxCreditOverrideStatus(CourseRequestOverrideStatus.REJECTED); break; case OVERRIDE_APPROVED: student.setMaxCreditOverrideStatus(CourseRequestOverrideStatus.APPROVED); break; case OVERRIDE_CANCELLED: student.setMaxCreditOverrideStatus(CourseRequestOverrideStatus.CANCELLED); break; case OVERRIDE_PENDING: student.setMaxCreditOverrideStatus(CourseRequestOverrideStatus.PENDING); break; } if (oldStatus == null || !oldStatus.equals(student.getOverrideStatus())) studentChanged = true; } } if (studentChanged) helper.getHibSession().update(student); if (changed || studentChanged) helper.getHibSession().flush(); return changed || studentChanged; } catch (SectioningException e) { action.setApiException(e.getMessage()); throw (SectioningException)e; } catch (Exception e) { action.setApiException(e.getMessage() == null ? "Null" : e.getMessage()); sLog.error(e.getMessage(), e); throw new SectioningException(e.getMessage()); } finally { if (resource != null) { if (resource.getResponse() != null) resource.getResponse().release(); resource.release(); } } } protected boolean hasNotApprovedCourseRequestOverride(org.unitime.timetable.model.Student student) { for (CourseDemand cd: student.getCourseDemands()) { if (Boolean.TRUE.equals(cd.isWaitlist()) && Boolean.FALSE.equals(cd.isAlternative()) && !cd.isEnrolledExceptForWaitListSwap()) { for (org.unitime.timetable.model.CourseRequest cr: cd.getCourseRequests()) { if (cr.getOverrideExternalId() != null && cr.getCourseRequestOverrideStatus() != CourseRequestOverrideStatus.APPROVED) return true; } } } if (student.getOverrideExternalId() != null && student.getMaxCreditOverrideIntent() == CourseRequestOverrideIntent.WAITLIST && student.getMaxCreditOverrideStatus() != CourseRequestOverrideStatus.APPROVED) return true; return false; } @Override public boolean revalidateStudent(OnlineSectioningServer server, OnlineSectioningHelper helper, Student student, Builder action) throws SectioningException { // Do not re-validate when validation is disabled if (!isValidationEnabled(student)) return false; // When there is a pending override, try to update student first boolean studentUpdated = false; if (hasOverride(student)) studentUpdated = updateStudent(server, helper, student, action); // All course requests are approved -> nothing to do if (!hasNotApprovedCourseRequestOverride(student) && !"true".equalsIgnoreCase(ApplicationProperties.getProperty("purdue.specreg.forceRevalidation", "false"))) return false; XStudent original = server.getStudent(student.getUniqueId()); if (original == null) return false; boolean changed = false; SpecialRegistrationRequest submitRequest = new SpecialRegistrationRequest(); submitRequest.studentId = getBannerId(original); submitRequest.term = getBannerTerm(server.getAcademicSession()); submitRequest.campus = getBannerCampus(server.getAcademicSession()); submitRequest.mode = getSpecialRegistrationApiMode(); submitRequest.changes = new ArrayList<Change>(); if (helper.getUser() != null) { submitRequest.requestorId = getRequestorId(helper.getUser()); submitRequest.requestorRole = getRequestorType(helper.getUser(), original); } Float maxCredit = null; Float maxCreditNeeded = null; for (CourseDemand cd: student.getCourseDemands()) { XCourseId dropCourse = null; Set<String> dropCrns = null; if (cd.getWaitListSwapWithCourseOffering() != null) { dropCourse = new XCourseId(cd.getWaitListSwapWithCourseOffering()); dropCrns = new TreeSet<String>(); for (StudentClassEnrollment enrl: student.getClassEnrollments()) { if (cd.getWaitListSwapWithCourseOffering().equals(enrl.getCourseOffering())) { dropCrns.add(enrl.getClazz().getExternalId(cd.getWaitListSwapWithCourseOffering())); } } } if (Boolean.TRUE.equals(cd.isWaitlist()) && Boolean.FALSE.equals(cd.isAlternative()) && !cd.isEnrolledExceptForWaitListSwap()) { XCourseId enrolledCourse = null; Integer enrolledOrder = null; if (dropCourse != null && !dropCrns.isEmpty()) { for (org.unitime.timetable.model.CourseRequest cr: cd.getCourseRequests()) if (cr.getCourseOffering().getUniqueId().equals(dropCourse.getCourseId())) { enrolledCourse = dropCourse; enrolledOrder = cr.getOrder(); } } for (org.unitime.timetable.model.CourseRequest cr: cd.getCourseRequests()) { // skip courses that cannot be wait-listed if (!cr.getCourseOffering().getInstructionalOffering().effectiveWaitList()) continue; // skip cases where the wait-list request was cancelled if ("TBD".equals(cr.getOverrideExternalId())) continue; // when enrolled (section swap), check if active if (enrolledCourse != null) { if (cr.getOrder() > enrolledOrder) continue; if (cr.getOrder() == enrolledOrder) { XCourseRequest rq = original.getRequestForCourse(enrolledCourse.getCourseId()); XOffering offering = server.getOffering(enrolledCourse.getOfferingId()); // when enrolled, skip the enrolled course if the enrollment matches the requirements if (rq != null && rq.getEnrollment() != null && offering != null && rq.isRequired(rq.getEnrollment(), offering)) continue; } } // get possible enrollments into the course Assignment<Request, Enrollment> assignment = new AssignmentMap<Request, Enrollment>(); CourseRequest courseRequest = SectioningRequest.convert(assignment, new XCourseRequest(cr, helper, null), dropCourse, server, WaitListMode.WaitList); Collection<Enrollment> enrls = courseRequest.getEnrollmentsSkipSameTime(assignment); // get a test enrollment (preferably a non-conflicting one) Enrollment testEnrollment = null; for (Iterator<Enrollment> e = enrls.iterator(); e.hasNext();) { testEnrollment = e.next(); boolean overlaps = false; for (Request q: testEnrollment.getStudent().getRequests()) { if (q.equals(courseRequest)) continue; Enrollment x = assignment.getValue(q); if (x == null || x.getAssignments() == null || x.getAssignments().isEmpty()) continue; for (Iterator<SctAssignment> i = x.getAssignments().iterator(); i.hasNext();) { SctAssignment a = i.next(); if (a.isOverlapping(testEnrollment.getAssignments())) { overlaps = true; } } } if (!overlaps) break; } // no test enrollment, take first possible enrollment if (testEnrollment == null) { Course c = courseRequest.getCourses().get(0); for (Config config: c.getOffering().getConfigs()) { if (courseRequest.isNotAllowed(c, config)) continue; testEnrollment = firstEnrollment(courseRequest, assignment, c, config, new HashSet<Section>(), 0); } } // still no test enrollment -> ignore if (testEnrollment == null) continue; // create request CheckRestrictionsRequest req = new CheckRestrictionsRequest(); req.studentId = getBannerId(original); req.term = getBannerTerm(server.getAcademicSession()); req.campus = getBannerCampus(server.getAcademicSession()); req.mode = getSpecialRegistrationApiMode(); Set<String> crns = new HashSet<String>(); Set<String> keep = new HashSet<String>(); for (Section section: testEnrollment.getSections()) { String crn = getCRN(section, testEnrollment.getCourse()); if (dropCrns != null && dropCrns.contains(crn)) { keep.add(crn); } else { SpecialRegistrationHelper.addWaitListCrn(req, crn); crns.add(crn); } } if (dropCrns != null) for (String crn: dropCrns) { if (!keep.contains(crn)) { SpecialRegistrationHelper.dropWaitListCrn(req, crn); crns.add(crn); } } // no CRNs to check -> continue if (crns.isEmpty()) continue; // call validation CheckRestrictionsResponse validation = null; ClientResource resource = null; try { resource = new ClientResource(getSpecialRegistrationApiValidationSite()); resource.setNext(iClient); resource.addQueryParameter("apiKey", getSpecialRegistrationApiKey()); Gson gson = getGson(helper); if (helper.isDebugEnabled()) helper.debug("Request: " + gson.toJson(req)); action.addOptionBuilder().setKey("wl-req-" + testEnrollment.getCourse().getName().replace(" ", "").toLowerCase()).setValue(gson.toJson(req)); long t1 = System.currentTimeMillis(); resource.post(new GsonRepresentation<CheckRestrictionsRequest>(req)); action.setApiPostTime( (action.hasApiPostTime() ? action.getApiPostTime() : 0) + System.currentTimeMillis() - t1); validation = (CheckRestrictionsResponse)new GsonRepresentation<CheckRestrictionsResponse>(resource.getResponseEntity(), CheckRestrictionsResponse.class).getObject(); if (helper.isDebugEnabled()) helper.debug("Response: " + gson.toJson(validation)); action.addOptionBuilder().setKey("wl-resp-" + testEnrollment.getCourse().getName().replace(" ", "").toLowerCase()).setValue(gson.toJson(validation)); if (ResponseStatus.success != validation.status) throw new SectioningException(validation.message == null || validation.message.isEmpty() ? "Failed to check student eligibility (" + validation.status + ")." : validation.message); } catch (SectioningException e) { action.setApiException(e.getMessage()); throw (SectioningException)e; } catch (Exception e) { action.setApiException(e.getMessage()); sLog.error(e.getMessage(), e); throw new SectioningException(e.getMessage()); } finally { if (resource != null) { if (resource.getResponse() != null) resource.getResponse().release(); resource.release(); } } if (validation.outJson != null && validation.outJson.problems != null) problems: for (Problem problem: validation.outJson.problems) { if ("HOLD".equals(problem.code)) continue; if ("DUPL".equals(problem.code)) continue; if ("MAXI".equals(problem.code)) continue; if ("CLOS".equals(problem.code)) continue; if ("TIME".equals(problem.code)) continue; if (!crns.contains(problem.crn)) continue; Change change = null; for (Change ch: submitRequest.changes) { if (ch.subject.equals(cr.getCourseOffering().getSubjectAreaAbbv()) && ch.courseNbr.equals(cr.getCourseOffering().getCourseNbr())) { change = ch; break; } } if (change == null) { change = new Change(); change.setCourse(cr.getCourseOffering().getSubjectAreaAbbv(), cr.getCourseOffering().getCourseNbr(), iExternalTermProvider, server.getAcademicSession()); change.crn = ""; change.errors = new ArrayList<ChangeError>(); change.operation = ChangeOperation.ADD; submitRequest.changes.add(change); } else { for (ChangeError err: change.errors) if (problem.code.equals(err.code)) continue problems; } ChangeError err = new ChangeError(); err.code = problem.code; err.message = problem.message; if (err.message != null && err.message.indexOf("this section") >= 0) err.message = err.message.replace("this section", cr.getCourseOffering().getCourseName()); if (err.message != null && err.message.indexOf(" (CRN ") >= 0) err.message = err.message.replaceFirst(" \\(CRN [0-9][0-9][0-9][0-9][0-9]\\) ", " "); change.errors.add(err); } if (maxCredit == null && validation.maxCredit != null) maxCredit = validation.maxCredit; if (validation.outJson.maxHoursCalc != null) { if (maxCreditNeeded == null || maxCreditNeeded < validation.outJson.maxHoursCalc) maxCreditNeeded = validation.outJson.maxHoursCalc; } } } } if (maxCredit == null) maxCredit = Float.parseFloat(ApplicationProperties.getProperty("purdue.specreg.maxCreditDefault", "18")); if (maxCreditNeeded != null && maxCreditNeeded > maxCredit) submitRequest.maxCredit = maxCreditNeeded; submitRequest.courseCreditHrs = new ArrayList<CourseCredit>(); for (XRequest r: original.getRequests()) { CourseCredit cc = null; if (r instanceof XCourseRequest) { XCourseRequest cr = (XCourseRequest)r; if (!cr.isWaitlist() || cr.getEnrollment() != null) continue; for (XCourseId cid: cr.getCourseIds()) { XCourse course = (cid instanceof XCourse ? (XCourse)cid : server.getCourse(cid.getCourseId())); if (course == null) continue; if (cc == null) { cc = new CourseCredit(); cc.setCourse(course.getSubjectArea(), course.getCourseNumber(), iExternalTermProvider, server.getAcademicSession()); cc.title = course.getTitle(); cc.creditHrs = (course.hasCredit() ? course.getMinCredit() : 0f); } else { if (cc.alternatives == null) cc.alternatives = new ArrayList<CourseCredit>(); CourseCredit acc = new CourseCredit(); acc.setCourse(course.getSubjectArea(), course.getCourseNumber(), iExternalTermProvider, server.getAcademicSession()); acc.title = course.getTitle(); acc.creditHrs = (course.hasCredit() ? course.getMinCredit() : 0f); cc.alternatives.add(acc); } } } if (cc != null) submitRequest.courseCreditHrs.add(cc); } SpecialRegistrationResponseList response = null; ClientResource resource = null; try { resource = new ClientResource(getSpecialRegistrationApiSiteSubmitRegistration()); resource.setNext(iClient); resource.addQueryParameter("apiKey", getSpecialRegistrationApiKey()); Gson gson = getGson(helper); if (helper.isDebugEnabled()) helper.debug("Submit Request: " + gson.toJson(submitRequest)); action.addOptionBuilder().setKey("wl-request").setValue(gson.toJson(submitRequest)); long t1 = System.currentTimeMillis(); resource.post(new GsonRepresentation<SpecialRegistrationRequest>(submitRequest)); action.setApiPostTime(action.getApiPostTime() + System.currentTimeMillis() - t1); response = (SpecialRegistrationResponseList)new GsonRepresentation<SpecialRegistrationResponseList>(resource.getResponseEntity(), SpecialRegistrationResponseList.class).getObject(); if (helper.isDebugEnabled()) helper.debug("Submit Response: " + gson.toJson(response)); action.addOptionBuilder().setKey("wl-response").setValue(gson.toJson(response)); if (ResponseStatus.success != response.status) throw new SectioningException(response.message == null || response.message.isEmpty() ? "Failed to request overrides (" + response.status + ")." : response.message); } catch (SectioningException e) { action.setApiException(e.getMessage()); throw (SectioningException)e; } catch (Exception e) { action.setApiException(e.getMessage()); sLog.error(e.getMessage(), e); throw new SectioningException(e.getMessage()); } finally { if (resource != null) { if (resource.getResponse() != null) resource.getResponse().release(); resource.release(); } } for (CourseDemand cd: student.getCourseDemands()) { if (Boolean.TRUE.equals(cd.isWaitlist()) && Boolean.FALSE.equals(cd.isAlternative()) && !cd.isEnrolledExceptForWaitListSwap()) cr: for (org.unitime.timetable.model.CourseRequest cr: cd.getCourseRequests()) { if (response != null && response.data != null) { for (SpecialRegistration r: response.data) if (r.changes != null) for (Change ch: r.changes) { if (cr.getCourseOffering().getSubjectAreaAbbv().equals(ch.subject) && cr.getCourseOffering().getCourseNbr().equals(ch.courseNbr)) { Integer oldStatus = cr.getOverrideStatus(); switch (status(r, false)) { case OVERRIDE_REJECTED: cr.setCourseRequestOverrideStatus(CourseRequestOverrideStatus.REJECTED); break; case OVERRIDE_APPROVED: cr.setCourseRequestOverrideStatus(CourseRequestOverrideStatus.APPROVED); break; case OVERRIDE_CANCELLED: cr.setCourseRequestOverrideStatus(CourseRequestOverrideStatus.CANCELLED); break; case OVERRIDE_PENDING: cr.setCourseRequestOverrideStatus(CourseRequestOverrideStatus.PENDING); break; } if (oldStatus == null || !oldStatus.equals(cr.getOverrideStatus())) changed = true; if (cr.getOverrideExternalId() == null || !cr.getOverrideExternalId().equals(r.regRequestId)) changed = true; cr.setOverrideExternalId(r.regRequestId); cr.setOverrideTimeStamp(r.dateCreated == null ? null : r.dateCreated.toDate()); cr.setCourseRequestOverrideIntent(CourseRequestOverrideIntent.WAITLIST); helper.getHibSession().update(cr); continue cr; } } } if (!"TBD".equals(cr.getOverrideExternalId()) && (cr.getOverrideExternalId() != null || cr.getOverrideStatus() != null)) { cr.setOverrideExternalId(null); cr.setOverrideStatus(null); cr.setOverrideTimeStamp(null); cr.setOverrideIntent(null); helper.getHibSession().update(cr); changed = true; } } } boolean studentChanged = false; if (submitRequest.maxCredit != null) { for (SpecialRegistration r: response.data) { if (r.maxCredit != null) { Integer oldStatus = student.getOverrideStatus(); switch (status(r, true)) { case OVERRIDE_REJECTED: student.setMaxCreditOverrideStatus(CourseRequestOverrideStatus.REJECTED); break; case OVERRIDE_APPROVED: student.setMaxCreditOverrideStatus(CourseRequestOverrideStatus.APPROVED); break; case OVERRIDE_CANCELLED: student.setMaxCreditOverrideStatus(CourseRequestOverrideStatus.CANCELLED); break; case OVERRIDE_PENDING: student.setMaxCreditOverrideStatus(CourseRequestOverrideStatus.PENDING); break; } if (oldStatus == null || !oldStatus.equals(student.getOverrideStatus())) studentChanged = true; if (student.getOverrideMaxCredit() == null || !student.getOverrideMaxCredit().equals(r.maxCredit)) studentChanged = true; student.setOverrideMaxCredit(r.maxCredit); if (student.getOverrideExternalId() == null || !student.getOverrideExternalId().equals(r.regRequestId)) studentChanged = true; student.setOverrideExternalId(r.regRequestId); student.setOverrideTimeStamp(r.dateCreated == null ? null : r.dateCreated.toDate()); student.setMaxCreditOverrideIntent(CourseRequestOverrideIntent.WAITLIST); break; } } } else if (student.getMaxCreditOverrideIntent() == CourseRequestOverrideIntent.WAITLIST) { student.setOverrideExternalId(null); student.setOverrideMaxCredit(null); student.setOverrideStatus(null); student.setOverrideTimeStamp(null); student.setOverrideIntent(null); studentChanged = true; } if (studentChanged) helper.getHibSession().update(student); if (changed) helper.getHibSession().flush(); if (changed || studentChanged) helper.getHibSession().flush(); return changed || studentChanged || studentUpdated; } @Override public void dispose() { try { iClient.stop(); } catch (Exception e) { sLog.error(e.getMessage(), e); } } @Override public Collection<Long> updateStudents(OnlineSectioningServer server, OnlineSectioningHelper helper, List<Student> students) throws SectioningException { Map<String, org.unitime.timetable.model.Student> id2student = new HashMap<String, org.unitime.timetable.model.Student>(); List<Long> reloadIds = new ArrayList<Long>(); int batchNumber = 1; for (int i = 0; i < students.size(); i++) { org.unitime.timetable.model.Student student = students.get(i); if (student == null || !hasOverride(student)) continue; if (!isValidationEnabled(student)) continue; String id = getBannerId(student); id2student.put(id, student); if (id2student.size() >= 100) { checkStudentStatuses(server, helper, id2student, reloadIds, batchNumber++); id2student.clear(); } } if (!id2student.isEmpty()) checkStudentStatuses(server, helper, id2student, reloadIds, batchNumber++); if (!reloadIds.isEmpty()) helper.getHibSession().flush(); if (!reloadIds.isEmpty() && server != null && !(server instanceof DatabaseServer)) server.execute(server.createAction(ReloadStudent.class).forStudents(reloadIds), helper.getUser()); return reloadIds; } protected void checkStudentStatuses(OnlineSectioningServer server, OnlineSectioningHelper helper, Map<String, org.unitime.timetable.model.Student> id2student, List<Long> reloadIds, int batchNumber) throws SectioningException { ClientResource resource = null; try { resource = new ClientResource(getSpecialRegistrationApiSiteCheckAllSpecialRegistrationStatus()); resource.setNext(iClient); AcademicSessionInfo session = (server == null ? null : server.getAcademicSession()); String studentIds = null; List<String> ids = new ArrayList<String>(); for (Map.Entry<String, org.unitime.timetable.model.Student> e: id2student.entrySet()) { if (session == null) session = new AcademicSessionInfo(e.getValue().getSession()); if (studentIds == null) studentIds = e.getKey(); else studentIds += "," + e.getKey(); ids.add(e.getKey()); } String term = getBannerTerm(session); String campus = getBannerCampus(session); resource.addQueryParameter("term", term); resource.addQueryParameter("campus", campus); resource.addQueryParameter("studentIds", studentIds); resource.addQueryParameter("mode", getSpecialRegistrationApiMode().name()); resource.addQueryParameter("apiKey", getSpecialRegistrationApiKey()); OnlineSectioningLog.Action.Builder action = helper.getAction(); if (action != null) { action.addOptionBuilder().setKey("term").setValue(term); action.addOptionBuilder().setKey("campus").setValue(campus); action.addOptionBuilder().setKey("studentIds-" + batchNumber).setValue(studentIds); } long t0 = System.currentTimeMillis(); resource.get(MediaType.APPLICATION_JSON); if (action != null) action.setApiGetTime(action.getApiGetTime() + System.currentTimeMillis() - t0); SpecialRegistrationMultipleStatusResponse response = (SpecialRegistrationMultipleStatusResponse)new GsonRepresentation<SpecialRegistrationMultipleStatusResponse>(resource.getResponseEntity(), SpecialRegistrationMultipleStatusResponse.class).getObject(); Gson gson = getGson(helper); if (helper.isDebugEnabled()) helper.debug("Response: " + gson.toJson(response)); if (action != null) action.addOptionBuilder().setKey("wl-response-" + batchNumber).setValue(gson.toJson(response)); if (ResponseStatus.success != response.status) throw new SectioningException(response.message == null || response.message.isEmpty() ? "Failed to check student statuses (" + response.status + ")." : response.message); if (response.data != null && response.data.students != null) { int index = 0; for (SpecialRegistrationStatus status: response.data.students) { String studentId = status.studentId; if (studentId == null && status.requests != null) for (SpecialRegistration req: status.requests) { if (req.studentId != null) { studentId = req.studentId; break; } } if (studentId == null) studentId = ids.get(index); index++; org.unitime.timetable.model.Student student = id2student.get(studentId); if (student == null) continue; boolean changed = false; for (CourseDemand cd: student.getCourseDemands()) { if (Boolean.TRUE.equals(cd.isWaitlist()) && Boolean.FALSE.equals(cd.isAlternative()) && !cd.isEnrolledExceptForWaitListSwap()) for (org.unitime.timetable.model.CourseRequest cr: cd.getCourseRequests()) { if (cr.getOverrideExternalId() != null) { SpecialRegistration req = null; for (SpecialRegistration r: status.requests) { if (cr.getOverrideExternalId().equals(r.regRequestId)) { req = r; break; } } if (req == null) { if (cr.getCourseRequestOverrideStatus() != CourseRequestOverrideStatus.CANCELLED) { cr.setCourseRequestOverrideStatus(CourseRequestOverrideStatus.CANCELLED); helper.getHibSession().update(cr); changed = true; } } else { Integer oldStatus = cr.getOverrideStatus(); switch (status(req, false)) { case OVERRIDE_REJECTED: cr.setCourseRequestOverrideStatus(CourseRequestOverrideStatus.REJECTED); break; case OVERRIDE_APPROVED: cr.setCourseRequestOverrideStatus(CourseRequestOverrideStatus.APPROVED); break; case OVERRIDE_CANCELLED: cr.setCourseRequestOverrideStatus(CourseRequestOverrideStatus.CANCELLED); break; case OVERRIDE_PENDING: cr.setCourseRequestOverrideStatus(CourseRequestOverrideStatus.PENDING); break; } if (oldStatus == null || !oldStatus.equals(cr.getOverrideStatus())) { helper.getHibSession().update(cr); changed = true; } } } } } boolean studentChanged = false; if (status.maxCredit != null && !status.maxCredit.equals(student.getMaxCredit())) { student.setMaxCredit(status.maxCredit); studentChanged = true; } if (student.getOverrideExternalId() != null) { SpecialRegistration req = null; for (SpecialRegistration r: status.requests) { if (student.getOverrideExternalId().equals(r.regRequestId)) { req = r; break; } } if (req == null && student.getMaxCreditOverrideIntent() == CourseRequestOverrideIntent.WAITLIST) { student.setOverrideExternalId(null); student.setOverrideMaxCredit(null); student.setOverrideStatus(null); student.setOverrideTimeStamp(null); student.setOverrideIntent(null); studentChanged = true; } else if (req != null) { Integer oldStatus = student.getOverrideStatus(); switch (status(req, true)) { case OVERRIDE_REJECTED: student.setMaxCreditOverrideStatus(CourseRequestOverrideStatus.REJECTED); break; case OVERRIDE_APPROVED: student.setMaxCreditOverrideStatus(CourseRequestOverrideStatus.APPROVED); break; case OVERRIDE_CANCELLED: student.setMaxCreditOverrideStatus(CourseRequestOverrideStatus.CANCELLED); break; case OVERRIDE_PENDING: student.setMaxCreditOverrideStatus(CourseRequestOverrideStatus.PENDING); break; } if (oldStatus == null || !oldStatus.equals(student.getOverrideStatus())) studentChanged = true; } } if (studentChanged) helper.getHibSession().update(student); if (changed || studentChanged) reloadIds.add(student.getUniqueId()); } } } catch (SectioningException e) { throw (SectioningException)e; } catch (Exception e) { sLog.error(e.getMessage(), e); throw new SectioningException(e.getMessage()); } finally { if (resource != null) { if (resource.getResponse() != null) resource.getResponse().release(); resource.release(); } } } @Override public boolean updateStudent(OnlineSectioningServer server, OnlineSectioningHelper helper, XStudent student, Builder action) throws SectioningException { // No pending overrides -> nothing to do if (student == null) return false; ClientResource resource = null; try { resource = new ClientResource(getSpecialRegistrationApiSiteCheckSpecialRegistrationStatus()); resource.setNext(iClient); AcademicSessionInfo session = server.getAcademicSession(); String term = getBannerTerm(session); String campus = getBannerCampus(session); resource.addQueryParameter("term", term); resource.addQueryParameter("campus", campus); resource.addQueryParameter("studentId", getBannerId(student)); resource.addQueryParameter("mode", getSpecialRegistrationApiMode().name()); action.addOptionBuilder().setKey("term").setValue(term); action.addOptionBuilder().setKey("campus").setValue(campus); action.addOptionBuilder().setKey("studentId").setValue(getBannerId(student)); resource.addQueryParameter("apiKey", getSpecialRegistrationApiKey()); long t0 = System.currentTimeMillis(); resource.get(MediaType.APPLICATION_JSON); action.setApiGetTime(System.currentTimeMillis() - t0); SpecialRegistrationStatusResponse status = (SpecialRegistrationStatusResponse)new GsonRepresentation<SpecialRegistrationStatusResponse>(resource.getResponseEntity(), SpecialRegistrationStatusResponse.class).getObject(); Gson gson = getGson(helper); if (helper.isDebugEnabled()) helper.debug("Status: " + gson.toJson(status)); action.addOptionBuilder().setKey("wl-status").setValue(gson.toJson(status)); boolean studentChanged = false; for (XRequest r: student.getRequests()) { if (r instanceof XCourseRequest) { XCourseRequest cr = (XCourseRequest)r; if (cr.isWaitlist() && !cr.isAlternative() && cr.getEnrollment() == null && cr.hasOverrides()) { for (Map.Entry<XCourseId, XOverride> e: cr.getOverrides().entrySet()) { XCourseId course = e.getKey(); XOverride override = e.getValue(); if ("TBD".equals(override.getExternalId())) continue; SpecialRegistration req = null; for (SpecialRegistration q: status.data.requests) { if (override.getExternalId().equals(q.regRequestId)) { req = q; break; } } if (req == null) { if (override.getStatus() != CourseRequestOverrideStatus.CANCELLED.ordinal()) { override.setStatus(CourseRequestOverrideStatus.CANCELLED.ordinal()); CourseDemand dbCourseDemand = CourseDemandDAO.getInstance().get(cr.getRequestId(), helper.getHibSession()); if (dbCourseDemand != null) { for (org.unitime.timetable.model.CourseRequest dbCourseRequest: dbCourseDemand.getCourseRequests()) { if (dbCourseRequest.getCourseOffering().getUniqueId().equals(course.getCourseId())) { dbCourseRequest.setOverrideStatus(CourseRequestOverrideStatus.CANCELLED.ordinal()); helper.getHibSession().update(dbCourseRequest); } } } studentChanged = true; } } else { Integer oldStatus = override.getStatus(); Integer newStatus = null; switch (status(req, false)) { case OVERRIDE_REJECTED: newStatus = CourseRequestOverrideStatus.REJECTED.ordinal(); break; case OVERRIDE_APPROVED: newStatus = CourseRequestOverrideStatus.APPROVED.ordinal(); break; case OVERRIDE_CANCELLED: newStatus = CourseRequestOverrideStatus.CANCELLED.ordinal(); break; case OVERRIDE_PENDING: newStatus = CourseRequestOverrideStatus.PENDING.ordinal(); break; } if (newStatus != null && !newStatus.equals(oldStatus)) { override.setStatus(newStatus); CourseDemand dbCourseDemand = CourseDemandDAO.getInstance().get(cr.getRequestId(), helper.getHibSession()); if (dbCourseDemand != null) { for (org.unitime.timetable.model.CourseRequest dbCourseRequest: dbCourseDemand.getCourseRequests()) { if (dbCourseRequest.getCourseOffering().getUniqueId().equals(course.getCourseId())) { dbCourseRequest.setOverrideStatus(newStatus); helper.getHibSession().update(dbCourseRequest); } } } studentChanged = true; } } } } } } if (status.data.maxCredit != null && !status.data.maxCredit.equals(student.getMaxCredit())) { student.setMaxCredit(status.data.maxCredit); Student dbStudent = StudentDAO.getInstance().get(student.getStudentId(), helper.getHibSession()); if (dbStudent != null) { dbStudent.setMaxCredit(status.data.maxCredit); helper.getHibSession().update(dbStudent); } studentChanged = true; } if (student.getMaxCreditOverride() != null) { SpecialRegistration req = null; for (SpecialRegistration r: status.data.requests) { if (r.regRequestId != null && r.regRequestId.equals(student.getMaxCreditOverride().getExternalId())) { req = r; break; } } if (req != null) { Integer oldStatus = student.getMaxCreditOverride().getStatus(); Integer newStatus = null; switch (status(req, true)) { case OVERRIDE_REJECTED: newStatus = CourseRequestOverrideStatus.REJECTED.ordinal(); break; case OVERRIDE_APPROVED: newStatus = CourseRequestOverrideStatus.APPROVED.ordinal(); break; case OVERRIDE_CANCELLED: newStatus = CourseRequestOverrideStatus.CANCELLED.ordinal(); break; case OVERRIDE_PENDING: newStatus = CourseRequestOverrideStatus.PENDING.ordinal(); break; } if (newStatus == null || !newStatus.equals(oldStatus)) { student.getMaxCreditOverride().setStatus(newStatus); Student dbStudent = StudentDAO.getInstance().get(student.getStudentId(), helper.getHibSession()); if (dbStudent != null) { dbStudent.setOverrideStatus(newStatus); helper.getHibSession().update(dbStudent); } studentChanged = true; } } } if (studentChanged) { server.update(student, false); helper.getHibSession().flush(); } if (studentChanged) helper.getHibSession().flush(); return studentChanged; } catch (SectioningException e) { action.setApiException(e.getMessage()); throw (SectioningException)e; } catch (Exception e) { action.setApiException(e.getMessage() == null ? "Null" : e.getMessage()); sLog.error(e.getMessage(), e); throw new SectioningException(e.getMessage()); } finally { if (resource != null) { if (resource.getResponse() != null) resource.getResponse().release(); resource.release(); } } } }
JavaSource/org/unitime/timetable/onlinesectioning/custom/purdue/PurdueWaitListValidationProvider.java
/* urse * Licensed to The Apereo Foundation under one or more contributor license * agreements. See the NOTICE file distributed with this work for * additional information regarding copyright ownership. * * The Apereo Foundation licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except in * compliance with the License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * * See the License for the specific language governing permissions and * limitations under the License. * */ package org.unitime.timetable.onlinesectioning.custom.purdue; import java.lang.reflect.Type; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Collection; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeSet; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.cpsolver.ifs.assignment.Assignment; import org.cpsolver.ifs.assignment.AssignmentMap; import org.cpsolver.studentsct.model.Config; import org.cpsolver.studentsct.model.Course; import org.cpsolver.studentsct.model.CourseRequest; import org.cpsolver.studentsct.model.Enrollment; import org.cpsolver.studentsct.model.Request; import org.cpsolver.studentsct.model.SctAssignment; import org.cpsolver.studentsct.model.Section; import org.cpsolver.studentsct.model.Subpart; import org.joda.time.DateTime; import org.joda.time.DateTimeZone; import org.restlet.Client; import org.restlet.Context; import org.restlet.data.MediaType; import org.restlet.data.Protocol; import org.restlet.resource.ClientResource; import org.unitime.localization.impl.Localization; import org.unitime.timetable.ApplicationProperties; import org.unitime.timetable.defaults.ApplicationProperty; import org.unitime.timetable.gwt.resources.StudentSectioningConstants; import org.unitime.timetable.gwt.resources.StudentSectioningMessages; import org.unitime.timetable.gwt.shared.CourseRequestInterface; import org.unitime.timetable.gwt.shared.PageAccessException; import org.unitime.timetable.gwt.shared.SectioningException; import org.unitime.timetable.gwt.shared.CourseRequestInterface.CheckCoursesResponse; import org.unitime.timetable.gwt.shared.CourseRequestInterface.CourseMessage; import org.unitime.timetable.gwt.shared.CourseRequestInterface.RequestedCourse; import org.unitime.timetable.gwt.shared.CourseRequestInterface.RequestedCourseStatus; import org.unitime.timetable.gwt.shared.OnlineSectioningInterface.EligibilityCheck; import org.unitime.timetable.gwt.shared.OnlineSectioningInterface.EligibilityCheck.EligibilityFlag; import org.unitime.timetable.gwt.shared.OnlineSectioningInterface.WaitListMode; import org.unitime.timetable.model.CourseDemand; import org.unitime.timetable.model.Student; import org.unitime.timetable.model.StudentClassEnrollment; import org.unitime.timetable.model.StudentSectioningStatus; import org.unitime.timetable.model.dao.CourseDemandDAO; import org.unitime.timetable.model.dao.StudentDAO; import org.unitime.timetable.model.CourseRequest.CourseRequestOverrideIntent; import org.unitime.timetable.model.CourseRequest.CourseRequestOverrideStatus; import org.unitime.timetable.onlinesectioning.AcademicSessionInfo; import org.unitime.timetable.onlinesectioning.OnlineSectioningHelper; import org.unitime.timetable.onlinesectioning.OnlineSectioningLog; import org.unitime.timetable.onlinesectioning.OnlineSectioningLog.Action.Builder; import org.unitime.timetable.onlinesectioning.OnlineSectioningServer; import org.unitime.timetable.onlinesectioning.custom.ExternalTermProvider; import org.unitime.timetable.onlinesectioning.custom.WaitListValidationProvider; import org.unitime.timetable.onlinesectioning.custom.purdue.SpecialRegistrationInterface.ApiMode; import org.unitime.timetable.onlinesectioning.custom.purdue.SpecialRegistrationInterface.Change; import org.unitime.timetable.onlinesectioning.custom.purdue.SpecialRegistrationInterface.ChangeError; import org.unitime.timetable.onlinesectioning.custom.purdue.SpecialRegistrationInterface.ChangeOperation; import org.unitime.timetable.onlinesectioning.custom.purdue.SpecialRegistrationInterface.ChangeStatus; import org.unitime.timetable.onlinesectioning.custom.purdue.SpecialRegistrationInterface.CheckEligibilityResponse; import org.unitime.timetable.onlinesectioning.custom.purdue.SpecialRegistrationInterface.CheckRestrictionsRequest; import org.unitime.timetable.onlinesectioning.custom.purdue.SpecialRegistrationInterface.CheckRestrictionsResponse; import org.unitime.timetable.onlinesectioning.custom.purdue.SpecialRegistrationInterface.CourseCredit; import org.unitime.timetable.onlinesectioning.custom.purdue.SpecialRegistrationInterface.DeniedMaxCredit; import org.unitime.timetable.onlinesectioning.custom.purdue.SpecialRegistrationInterface.DeniedRequest; import org.unitime.timetable.onlinesectioning.custom.purdue.SpecialRegistrationInterface.EligibilityProblem; import org.unitime.timetable.onlinesectioning.custom.purdue.SpecialRegistrationInterface.Problem; import org.unitime.timetable.onlinesectioning.custom.purdue.SpecialRegistrationInterface.RequestorRole; import org.unitime.timetable.onlinesectioning.custom.purdue.SpecialRegistrationInterface.ResponseStatus; import org.unitime.timetable.onlinesectioning.custom.purdue.SpecialRegistrationInterface.SpecialRegistration; import org.unitime.timetable.onlinesectioning.custom.purdue.SpecialRegistrationInterface.SpecialRegistrationMultipleStatusResponse; import org.unitime.timetable.onlinesectioning.custom.purdue.SpecialRegistrationInterface.SpecialRegistrationRequest; import org.unitime.timetable.onlinesectioning.custom.purdue.SpecialRegistrationInterface.SpecialRegistrationResponseList; import org.unitime.timetable.onlinesectioning.custom.purdue.SpecialRegistrationInterface.SpecialRegistrationStatus; import org.unitime.timetable.onlinesectioning.custom.purdue.SpecialRegistrationInterface.SpecialRegistrationStatusResponse; import org.unitime.timetable.onlinesectioning.model.XCourse; import org.unitime.timetable.onlinesectioning.model.XCourseId; import org.unitime.timetable.onlinesectioning.model.XCourseRequest; import org.unitime.timetable.onlinesectioning.model.XEnrollment; import org.unitime.timetable.onlinesectioning.model.XOffering; import org.unitime.timetable.onlinesectioning.model.XOverride; import org.unitime.timetable.onlinesectioning.model.XRequest; import org.unitime.timetable.onlinesectioning.model.XSection; import org.unitime.timetable.onlinesectioning.model.XStudent; import org.unitime.timetable.onlinesectioning.server.DatabaseServer; import org.unitime.timetable.onlinesectioning.solver.SectioningRequest; import org.unitime.timetable.onlinesectioning.updates.ReloadStudent; import org.unitime.timetable.util.Formats; import org.unitime.timetable.util.Formats.Format; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonDeserializationContext; import com.google.gson.JsonDeserializer; import com.google.gson.JsonElement; import com.google.gson.JsonParseException; import com.google.gson.JsonPrimitive; import com.google.gson.JsonSerializationContext; import com.google.gson.JsonSerializer; /** * @author Tomas Muller */ public class PurdueWaitListValidationProvider implements WaitListValidationProvider { private static Log sLog = LogFactory.getLog(PurdueWaitListValidationProvider.class); protected static final StudentSectioningMessages MESSAGES = Localization.create(StudentSectioningMessages.class); protected static final StudentSectioningConstants CONSTANTS = Localization.create(StudentSectioningConstants.class); protected static Format<Number> sCreditFormat = Formats.getNumberFormat("0.##"); private Client iClient; private ExternalTermProvider iExternalTermProvider; public PurdueWaitListValidationProvider() { List<Protocol> protocols = new ArrayList<Protocol>(); protocols.add(Protocol.HTTP); protocols.add(Protocol.HTTPS); iClient = new Client(protocols); Context cx = new Context(); cx.getParameters().add("readTimeout", getSpecialRegistrationApiReadTimeout()); iClient.setContext(cx); try { String clazz = ApplicationProperty.CustomizationExternalTerm.value(); if (clazz == null || clazz.isEmpty()) iExternalTermProvider = new BannerTermProvider(); else iExternalTermProvider = (ExternalTermProvider)Class.forName(clazz).getConstructor().newInstance(); } catch (Exception e) { sLog.error("Failed to create external term provider, using the default one instead.", e); iExternalTermProvider = new BannerTermProvider(); } } protected String getSpecialRegistrationApiReadTimeout() { return ApplicationProperties.getProperty("purdue.specreg.readTimeout", "60000"); } protected String getSpecialRegistrationApiSite() { return ApplicationProperties.getProperty("purdue.specreg.site"); } protected String getSpecialRegistrationApiSiteCheckEligibility() { return ApplicationProperties.getProperty("purdue.specreg.site.checkEligibility", getSpecialRegistrationApiSite() + "/checkEligibility"); } protected String getSpecialRegistrationApiValidationSite() { return ApplicationProperties.getProperty("purdue.specreg.site.validation", getSpecialRegistrationApiSite() + "/checkRestrictions"); } protected String getSpecialRegistrationApiSiteSubmitRegistration() { return ApplicationProperties.getProperty("purdue.specreg.site.submitRegistration", getSpecialRegistrationApiSite() + "/submitRegistration"); } protected String getSpecialRegistrationApiSiteCheckSpecialRegistrationStatus() { return ApplicationProperties.getProperty("purdue.specreg.site.checkSpecialRegistrationStatus", getSpecialRegistrationApiSite() + "/checkSpecialRegistrationStatus"); } protected String getSpecialRegistrationApiSiteCheckAllSpecialRegistrationStatus() { return ApplicationProperties.getProperty("purdue.specreg.site.checkAllSpecialRegistrationStatus", getSpecialRegistrationApiSite() + "/checkAllSpecialRegistrationStatus"); } protected String getSpecialRegistrationApiKey() { return ApplicationProperties.getProperty("purdue.specreg.apiKey"); } protected ApiMode getSpecialRegistrationApiMode() { return ApiMode.valueOf(ApplicationProperties.getProperty("purdue.specreg.mode.waitlist", "WAITL")); } protected String getBannerId(org.unitime.timetable.model.Student student) { String id = student.getExternalUniqueId(); while (id.length() < 9) id = "0" + id; return id; } protected String getBannerId(XStudent student) { String id = student.getExternalId(); while (id.length() < 9) id = "0" + id; return id; } protected String getBannerTerm(AcademicSessionInfo session) { return iExternalTermProvider.getExternalTerm(session); } protected String getBannerCampus(AcademicSessionInfo session) { return iExternalTermProvider.getExternalCampus(session); } protected String getRequestorId(OnlineSectioningLog.Entity user) { if (user == null || user.getExternalId() == null) return null; String id = user.getExternalId(); while (id.length() < 9) id = "0" + id; return id; } protected RequestorRole getRequestorType(OnlineSectioningLog.Entity user, XStudent student) { if (user == null || user.getExternalId() == null) return null; if (student != null) return (user.getExternalId().equals(student.getExternalId()) ? RequestorRole.STUDENT : RequestorRole.MANAGER); if (user.hasType()) { switch (user.getType()) { case MANAGER: return RequestorRole.MANAGER; case STUDENT: return RequestorRole.STUDENT; default: return RequestorRole.MANAGER; } } return null; } protected Gson getGson(OnlineSectioningHelper helper) { GsonBuilder builder = new GsonBuilder() .registerTypeAdapter(DateTime.class, new JsonSerializer<DateTime>() { @Override public JsonElement serialize(DateTime src, Type typeOfSrc, JsonSerializationContext context) { return new JsonPrimitive(src.toString("yyyy-MM-dd'T'HH:mm:ss'Z'")); } }) .registerTypeAdapter(DateTime.class, new JsonDeserializer<DateTime>() { @Override public DateTime deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { return new DateTime(json.getAsJsonPrimitive().getAsString(), DateTimeZone.UTC); } }) .registerTypeAdapter(Date.class, new JsonSerializer<Date>() { @Override public JsonElement serialize(Date src, Type typeOfSrc, JsonSerializationContext context) { return new JsonPrimitive(new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'").format(src)); } }) .registerTypeAdapter(Date.class, new JsonDeserializer<Date>() { @Override public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { try { return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(json.getAsJsonPrimitive().getAsString()); } catch (ParseException e) { throw new JsonParseException(e.getMessage(), e); } } }); if (helper.isDebugEnabled()) builder.setPrettyPrinting(); return builder.create(); } protected String getCRN(Section section, Course course) { String name = section.getName(course.getId()); if (name != null && name.indexOf('-') >= 0) return name.substring(0, name.indexOf('-')); return name; } protected boolean isValidationEnabled(org.unitime.timetable.model.Student student) { if (student == null) return false; StudentSectioningStatus status = student.getEffectiveStatus(); return status != null && status.hasOption(StudentSectioningStatus.Option.waitlist) && status.hasOption(StudentSectioningStatus.Option.specreg); } protected boolean isValidationEnabled(OnlineSectioningServer server, OnlineSectioningHelper helper, XStudent student) { String status = student.getStatus(); if (status == null) status = server.getAcademicSession().getDefaultSectioningStatus(); if (status == null) return true; StudentSectioningStatus dbStatus = StudentSectioningStatus.getPresentStatus(status, server.getAcademicSession().getUniqueId(), helper.getHibSession()); return dbStatus != null && dbStatus.hasOption(StudentSectioningStatus.Option.waitlist) && dbStatus.hasOption(StudentSectioningStatus.Option.specreg); } protected Enrollment firstEnrollment(CourseRequest request, Assignment<Request, Enrollment> assignment, Course course, Config config, HashSet<Section> sections, int idx) { if (config.getSubparts().size() == idx) { Enrollment e = new Enrollment(request, request.getCourses().indexOf(course), null, config, new HashSet<SctAssignment>(sections), null); if (request.isNotAllowed(e)) return null; return e; } else { Subpart subpart = config.getSubparts().get(idx); List<Section> sectionsThisSubpart = subpart.getSections(); List<Section> matchingSectionsThisSubpart = new ArrayList<Section>(subpart.getSections().size()); for (Section section : sectionsThisSubpart) { if (section.isCancelled()) continue; if (section.getParent() != null && !sections.contains(section.getParent())) continue; if (section.isOverlapping(sections)) continue; if (request.isNotAllowed(course, section)) continue; matchingSectionsThisSubpart.add(section); } for (Section section: matchingSectionsThisSubpart) { sections.add(section); Enrollment e = firstEnrollment(request, assignment, course, config, sections, idx + 1); if (e != null) return e; sections.remove(section); } } return null; } protected RequestedCourseStatus status(ChangeStatus status) { if (status == null) return RequestedCourseStatus.OVERRIDE_PENDING; switch (status) { case denied: return RequestedCourseStatus.OVERRIDE_REJECTED; case approved: return RequestedCourseStatus.OVERRIDE_APPROVED; case cancelled: return RequestedCourseStatus.OVERRIDE_CANCELLED; default: return RequestedCourseStatus.OVERRIDE_PENDING; } } protected RequestedCourseStatus combine(RequestedCourseStatus s1, RequestedCourseStatus s2) { if (s1 == null) return s2; if (s2 == null) return s1; if (s1 == s2) return s1; if (s1 == RequestedCourseStatus.OVERRIDE_REJECTED || s2 == RequestedCourseStatus.OVERRIDE_REJECTED) return RequestedCourseStatus.OVERRIDE_REJECTED; if (s1 == RequestedCourseStatus.OVERRIDE_PENDING || s2 == RequestedCourseStatus.OVERRIDE_PENDING) return RequestedCourseStatus.OVERRIDE_PENDING; if (s1 == RequestedCourseStatus.OVERRIDE_APPROVED || s2 == RequestedCourseStatus.OVERRIDE_APPROVED) return RequestedCourseStatus.OVERRIDE_APPROVED; if (s1 == RequestedCourseStatus.OVERRIDE_CANCELLED || s2 == RequestedCourseStatus.OVERRIDE_CANCELLED) return RequestedCourseStatus.OVERRIDE_CANCELLED; return s1; } protected RequestedCourseStatus status(SpecialRegistration request, boolean credit) { RequestedCourseStatus ret = null; if (request.changes != null) for (Change ch: request.changes) { if (ch.status == null) continue; if (credit && ch.subject == null && ch.courseNbr == null) ret = combine(ret, status(ch.status)); if (!credit && ch.subject != null && ch.courseNbr != null) ret = combine(ret, status(ch.status)); } if (ret != null) return ret; if (request.completionStatus != null) switch (request.completionStatus) { case completed: return RequestedCourseStatus.OVERRIDE_APPROVED; case cancelled: return RequestedCourseStatus.OVERRIDE_CANCELLED; case inProgress: return RequestedCourseStatus.OVERRIDE_PENDING; } return RequestedCourseStatus.OVERRIDE_PENDING; } public void validate(OnlineSectioningServer server, OnlineSectioningHelper helper, CourseRequestInterface request, CheckCoursesResponse response) throws SectioningException { XStudent original = (request.getStudentId() == null ? null : server.getStudent(request.getStudentId())); if (original == null) throw new PageAccessException(MESSAGES.exceptionEnrollNotStudent(server.getAcademicSession().toString())); // Do not validate when validation is disabled if (!isValidationEnabled(server, helper, original)) return; Integer CONF_NONE = null; Integer CONF_BANNER = 1; String creditError = null; Float maxCreditNeeded = null; for (CourseRequestInterface.Request line: request.getCourses()) { // only for wait-listed course requests if (line.isWaitList() && line.hasRequestedCourse()) { // skip enrolled courses XEnrollment enrolled = null; for (RequestedCourse rc: line.getRequestedCourse()) { if (rc.hasCourseId()) { XCourseRequest cr = original.getRequestForCourse(rc.getCourseId()); if (cr != null && cr.getEnrollment() != null) { enrolled = cr.getEnrollment(); break; } } } // when enrolled, only continue when swap for enrolled course is enabled (section wait-list) if (enrolled != null && !enrolled.getCourseId().equals(line.getWaitListSwapWithCourseOfferingId())) continue; XCourse dropCourse = null; Set<String> dropCrns = null; if (line.hasWaitListSwapWithCourseOfferingId()) { dropCourse = server.getCourse(line.getWaitListSwapWithCourseOfferingId()); XCourseRequest cr = original.getRequestForCourse(line.getWaitListSwapWithCourseOfferingId()); if (cr != null && cr.getEnrollment() != null && cr.getEnrollment().getCourseId().equals(line.getWaitListSwapWithCourseOfferingId())) { dropCrns = new TreeSet<String>(); XOffering dropOffering = server.getOffering(dropCourse.getOfferingId()); for (XSection section: dropOffering.getSections(cr.getEnrollment())) { dropCrns.add(section.getExternalId(line.getWaitListSwapWithCourseOfferingId())); } } } for (RequestedCourse rc: line.getRequestedCourse()) { if (rc.hasCourseId()) { XCourse xcourse = server.getCourse(rc.getCourseId()); if (xcourse == null) continue; // when enrolled, skip courses of lower choice than the enrollment if (enrolled != null && line.getIndex(rc.getCourseId()) > line.getIndex(enrolled.getCourseId())) continue; // skip offerings that cannot be wait-listed XOffering offering = server.getOffering(xcourse.getOfferingId()); if (offering == null || !offering.isWaitList()) continue; // when enrolled, skip the enrolled course if the enrollment matches the requirements if (enrolled != null && enrolled.getCourseId().equals(rc.getCourseId()) && enrolled.isRequired(rc, offering)) continue; // get possible enrollments into the course Assignment<Request, Enrollment> assignment = new AssignmentMap<Request, Enrollment>(); CourseRequest courseRequest = SectioningRequest.convert(assignment, new XCourseRequest(original, xcourse, rc), dropCourse, server, WaitListMode.WaitList); Collection<Enrollment> enrls = courseRequest.getEnrollmentsSkipSameTime(assignment); // get a test enrollment (preferably a non-conflicting one) Enrollment testEnrollment = null; for (Iterator<Enrollment> e = enrls.iterator(); e.hasNext();) { testEnrollment = e.next(); boolean overlaps = false; for (Request q: testEnrollment.getStudent().getRequests()) { if (q.equals(courseRequest)) continue; Enrollment x = assignment.getValue(q); if (x == null || x.getAssignments() == null || x.getAssignments().isEmpty()) continue; for (Iterator<SctAssignment> i = x.getAssignments().iterator(); i.hasNext();) { SctAssignment a = i.next(); if (a.isOverlapping(testEnrollment.getAssignments())) { overlaps = true; } } } if (!overlaps) break; } // no test enrollment, take first possible enrollment if (testEnrollment == null) { Course c = courseRequest.getCourses().get(0); for (Config config: c.getOffering().getConfigs()) { if (courseRequest.isNotAllowed(c, config)) continue; testEnrollment = firstEnrollment(courseRequest, assignment, c, config, new HashSet<Section>(), 0); } } // still no test enrollment -> ignore if (testEnrollment == null) continue; // create request CheckRestrictionsRequest req = new CheckRestrictionsRequest(); req.studentId = getBannerId(original); req.term = getBannerTerm(server.getAcademicSession()); req.campus = getBannerCampus(server.getAcademicSession()); req.mode = getSpecialRegistrationApiMode(); Set<String> crns = new HashSet<String>(); Set<String> keep = new HashSet<String>(); for (Section section: testEnrollment.getSections()) { String crn = getCRN(section, testEnrollment.getCourse()); if (dropCrns != null && dropCrns.contains(crn)) { keep.add(crn); } else { SpecialRegistrationHelper.addWaitListCrn(req, crn); crns.add(crn); } } if (dropCrns != null) for (String crn: dropCrns) { if (!keep.contains(crn)) { SpecialRegistrationHelper.dropWaitListCrn(req, crn); crns.add(crn); } } // no CRNs to check -> continue if (crns.isEmpty()) continue; // call validation CheckRestrictionsResponse resp = null; ClientResource resource = null; try { resource = new ClientResource(getSpecialRegistrationApiValidationSite()); resource.setNext(iClient); resource.addQueryParameter("apiKey", getSpecialRegistrationApiKey()); Gson gson = getGson(helper); if (helper.isDebugEnabled()) helper.debug("Request: " + gson.toJson(req)); helper.getAction().addOptionBuilder().setKey("wl-req-" + testEnrollment.getCourse().getName().replace(" ", "").toLowerCase()).setValue(gson.toJson(req)); long t1 = System.currentTimeMillis(); resource.post(new GsonRepresentation<CheckRestrictionsRequest>(req)); helper.getAction().setApiPostTime( (helper.getAction().hasApiPostTime() ? helper.getAction().getApiPostTime() : 0) + System.currentTimeMillis() - t1); resp = (CheckRestrictionsResponse)new GsonRepresentation<CheckRestrictionsResponse>(resource.getResponseEntity(), CheckRestrictionsResponse.class).getObject(); if (helper.isDebugEnabled()) helper.debug("Response: " + gson.toJson(resp)); helper.getAction().addOptionBuilder().setKey("wl-resp-" + testEnrollment.getCourse().getName().replace(" ", "").toLowerCase()).setValue(gson.toJson(resp)); if (ResponseStatus.success != resp.status) throw new SectioningException(resp.message == null || resp.message.isEmpty() ? "Failed to check student eligibility (" + resp.status + ")." : resp.message); } catch (SectioningException e) { helper.getAction().setApiException(e.getMessage()); throw (SectioningException)e; } catch (Exception e) { helper.getAction().setApiException(e.getMessage()); sLog.error(e.getMessage(), e); throw new SectioningException(e.getMessage()); } finally { if (resource != null) { if (resource.getResponse() != null) resource.getResponse().release(); resource.release(); } } // student max credit Float maxCredit = resp.maxCredit; if (maxCredit == null) maxCredit = Float.parseFloat(ApplicationProperties.getProperty("purdue.specreg.maxCreditDefault", "18")); Float maxCreditDenied = null; if (resp.deniedMaxCreditRequests != null) { for (DeniedMaxCredit r: resp.deniedMaxCreditRequests) { if (r.maxCredit != null && r.maxCredit > maxCredit && (maxCreditDenied == null || maxCreditDenied > r.maxCredit)) maxCreditDenied = r.maxCredit; } } Map<String, Map<String, RequestedCourseStatus>> overrides = new HashMap<String, Map<String, RequestedCourseStatus>>(); Float maxCreditOverride = null; RequestedCourseStatus maxCreditOverrideStatus = null; if (resp.cancelRegistrationRequests != null) for (SpecialRegistration r: resp.cancelRegistrationRequests) { if (r.changes == null || r.changes.isEmpty()) continue; for (Change ch: r.changes) { if (ch.status == ChangeStatus.cancelled || ch.status == ChangeStatus.denied) continue; if (ch.subject != null && ch.courseNbr != null) { String course = ch.subject + " " + ch.courseNbr; Map<String, RequestedCourseStatus> problems = overrides.get(course); if (problems == null) { problems = new HashMap<String, RequestedCourseStatus>(); overrides.put(course, problems); } if (ch.errors != null) for (ChangeError err: ch.errors) { if (err.code != null) problems.put(err.code, status(ch.status)); } } else if (r.maxCredit != null && (maxCreditOverride == null || maxCreditOverride < r.maxCredit)) { maxCreditOverride = r.maxCredit; maxCreditOverrideStatus = status(ch.status); } } } Float neededCredit = null; if (resp.outJson != null && resp.outJson.maxHoursCalc != null) neededCredit = resp.outJson.maxHoursCalc; if (neededCredit != null) { if (maxCreditNeeded == null || maxCreditNeeded < neededCredit) maxCreditNeeded = neededCredit; } if (maxCreditDenied != null && neededCredit != null && neededCredit >= maxCreditDenied) { response.addMessage(rc.getCourseId(), rc.getCourseName(), "WL-CREDIT", ApplicationProperties.getProperty("purdue.specreg.messages.maxCredit", "Maximum of {max} credit hours exceeded.").replace("{max}", sCreditFormat.format(maxCredit)).replace("{credit}", sCreditFormat.format(neededCredit)) , CONF_NONE); response.setCreditWarning(ApplicationProperties.getProperty("purdue.specreg.messages.maxCredit", "Maximum of {max} credit hours exceeded.") .replace("{max}", sCreditFormat.format(maxCredit)).replace("{credit}", sCreditFormat.format(neededCredit)).replace("{maxCreditDenied}", sCreditFormat.format(maxCreditDenied)) ); response.setMaxCreditOverrideStatus(RequestedCourseStatus.OVERRIDE_REJECTED); creditError = ApplicationProperties.getProperty("purdue.specreg.messages.maxCreditDeniedError", "Maximum of {max} credit hours exceeded.\nThe request to increase the maximum credit hours to {maxCreditDenied} has been denied.\nYou may not be able to get a full schedule.") .replace("{max}", sCreditFormat.format(maxCredit)).replace("{credit}", sCreditFormat.format(neededCredit)).replace("{maxCreditDenied}", sCreditFormat.format(maxCreditDenied)); response.setMaxCreditNeeded(maxCreditNeeded); } if (creditError == null && neededCredit != null && maxCredit < neededCredit) { response.addMessage(rc.getCourseId(), rc.getCourseName(), "WL-CREDIT", ApplicationProperties.getProperty("purdue.specreg.messages.maxCredit", "Maximum of {max} credit hours exceeded.").replace("{max}", sCreditFormat.format(maxCredit)).replace("{credit}", sCreditFormat.format(neededCredit)), maxCreditOverride == null || maxCreditOverride < neededCredit ? CONF_BANNER : CONF_NONE); response.setCreditWarning(ApplicationProperties.getProperty("purdue.specreg.messages.maxCredit", "Maximum of {max} credit hours exceeded.").replace("{max}", sCreditFormat.format(maxCredit)).replace("{credit}", sCreditFormat.format(neededCredit))); response.setMaxCreditOverrideStatus(maxCreditOverrideStatus == null || maxCreditOverride < neededCredit ? RequestedCourseStatus.OVERRIDE_NEEDED : maxCreditOverrideStatus); response.setMaxCreditNeeded(maxCreditNeeded); } Map<String, Set<String>> deniedOverrides = new HashMap<String, Set<String>>(); if (resp.deniedRequests != null) for (DeniedRequest r: resp.deniedRequests) { if (r.mode != req.mode) continue; String course = r.subject + " " + r.courseNbr; Set<String> problems = deniedOverrides.get(course); if (problems == null) { problems = new TreeSet<String>(); deniedOverrides.put(course, problems); } problems.add(r.code); } if (resp.outJson != null && resp.outJson.message != null && resp.outJson.status != null && resp.outJson.status != ResponseStatus.success) { response.addError(null, null, "Failure", resp.outJson.message); response.setErrorMessage(resp.outJson.message); } if (resp.outJson != null && resp.outJson.problems != null) for (Problem problem: resp.outJson.problems) { if ("HOLD".equals(problem.code)) { response.addError(null, null, problem.code, problem.message); response.setErrorMessage(ApplicationProperties.getProperty("purdue.specreg.messages.holdError", problem.message)); //throw new SectioningException(problem.message); } if ("DUPL".equals(problem.code)) continue; if ("MAXI".equals(problem.code)) continue; if ("CLOS".equals(problem.code)) continue; if ("TIME".equals(problem.code)) continue; if (!crns.contains(problem.crn)) continue; String bc = xcourse.getSubjectArea() + " " + xcourse.getCourseNumber(); Map<String, RequestedCourseStatus> problems = (bc == null ? null : overrides.get(bc)); Set<String> denied = (bc == null ? null : deniedOverrides.get(bc)); if (denied != null && denied.contains(problem.code)) { response.addMessage(xcourse.getCourseId(), xcourse.getCourseName(), problem.code, "Denied " + problem.message, CONF_NONE).setStatus(RequestedCourseStatus.OVERRIDE_REJECTED); } else { RequestedCourseStatus status = (problems == null ? null : problems.get(problem.code)); if (status == null) { if (resp.overrides != null && !resp.overrides.contains(problem.code)) { response.addError(xcourse.getCourseId(), xcourse.getCourseName(), problem.code, "Not Allowed " + problem.message).setStatus(RequestedCourseStatus.OVERRIDE_REJECTED); response.setErrorMessage(ApplicationProperties.getProperty("purdue.specreg.messages.waitlist.deniedOverrideError", "One or more wait-listed courses require registration overrides which is not allowed.\nYou cannot wait-list these courses.")); continue; } else { if (!xcourse.isOverrideEnabled(problem.code)) { response.addError(xcourse.getCourseId(), xcourse.getCourseName(), problem.code, "Not Allowed " + problem.message).setStatus(RequestedCourseStatus.OVERRIDE_REJECTED); response.setErrorMessage(ApplicationProperties.getProperty("purdue.specreg.messages.waitlist.deniedOverrideError", "One or more wait-listed courses require registration overrides which is not allowed.\nYou cannot wait-list these courses.")); continue; } } } response.addMessage(xcourse.getCourseId(), xcourse.getCourseName(), problem.code, problem.message, status == null ? CONF_BANNER : CONF_NONE) .setStatus(status == null ? RequestedCourseStatus.OVERRIDE_NEEDED : status); } } if (response.hasMessages()) for (CourseMessage m: response.getMessages()) { if (m.getCourse() != null && m.getMessage().indexOf("this section") >= 0) m.setMessage(m.getMessage().replace("this section", m.getCourse())); if (m.getCourse() != null && m.getMessage().indexOf(" (CRN ") >= 0) m.setMessage(m.getMessage().replaceFirst(" \\(CRN [0-9][0-9][0-9][0-9][0-9]\\) ", " ")); } } } } } if (response.getConfirms().contains(CONF_BANNER)) { response.addConfirmation(ApplicationProperties.getProperty("purdue.specreg.messages.waitlist.bannerProblemsFound", "The following registration errors for the wait-listed courses have been detected:"), CONF_BANNER, -1); String note = ApplicationProperties.getProperty("purdue.specreg.messages.waitlist.courseRequestNote", "<b>Request Note:</b>"); int idx = 1; if (note != null && !note.isEmpty()) { response.addConfirmation(note, CONF_BANNER, idx++); CourseMessage cm = response.addConfirmation("", CONF_BANNER, idx++); cm.setCode("REQUEST_NOTE"); for (String suggestion: ApplicationProperties.getProperty("purdue.specreg.waitlist.requestorNoteSuggestions", "").split("[\r\n]+")) if (!suggestion.isEmpty()) cm.addSuggestion(suggestion); } response.addConfirmation( ApplicationProperties.getProperty("purdue.specreg.messages.waitlist.requestOverrides", "\nIf you have already discussed these courses with your advisor and were advised to request " + "registration in them please select Request Overrides. If you aren’t sure, click Cancel Submit and " + "consult with your advisor before wait-listing these courses."), CONF_BANNER, idx++); } Set<Integer> conf = response.getConfirms(); if (conf.contains(CONF_BANNER)) { response.setConfirmation(CONF_BANNER, ApplicationProperties.getProperty("purdue.specreg.confirm.waitlist.bannerDialogName", "Request Wait-List Overrides"), ApplicationProperties.getProperty("purdue.specreg.confirm.waitlist.bannerYesButton", "Request Overrides"), ApplicationProperties.getProperty("purdue.specreg.confirm.waitlist.bannerNoButton", "Cancel Submit"), ApplicationProperties.getProperty("purdue.specreg.confirm.waitlist.bannerYesButtonTitle", "Request overrides for the above registration errors"), ApplicationProperties.getProperty("purdue.specreg.confirm.waitlist.bannerNoButtonTitle", "Go back to Scheduling Assistant")); } } @Override public void submit(OnlineSectioningServer server, OnlineSectioningHelper helper, CourseRequestInterface request, Float neededCredit) throws SectioningException { XStudent original = (request.getStudentId() == null ? null : server.getStudent(request.getStudentId())); if (original == null) return; // Do not submit when validation is disabled if (!isValidationEnabled(server, helper, original)) return; request.setMaxCreditOverrideStatus(RequestedCourseStatus.SAVED); ClientResource resource = null; Map<String, Set<String>> overrides = new HashMap<String, Set<String>>(); Float maxCredit = null; Float oldCredit = null; try { resource = new ClientResource(getSpecialRegistrationApiSiteCheckSpecialRegistrationStatus()); resource.setNext(iClient); AcademicSessionInfo session = server.getAcademicSession(); String term = getBannerTerm(session); String campus = getBannerCampus(session); resource.addQueryParameter("term", term); resource.addQueryParameter("campus", campus); resource.addQueryParameter("studentId", getBannerId(original)); resource.addQueryParameter("mode", getSpecialRegistrationApiMode().name()); helper.getAction().addOptionBuilder().setKey("term").setValue(term); helper.getAction().addOptionBuilder().setKey("campus").setValue(campus); helper.getAction().addOptionBuilder().setKey("studentId").setValue(getBannerId(original)); resource.addQueryParameter("apiKey", getSpecialRegistrationApiKey()); long t1 = System.currentTimeMillis(); resource.get(MediaType.APPLICATION_JSON); helper.getAction().setApiGetTime(System.currentTimeMillis() - t1); SpecialRegistrationStatusResponse status = (SpecialRegistrationStatusResponse)new GsonRepresentation<SpecialRegistrationStatusResponse>(resource.getResponseEntity(), SpecialRegistrationStatusResponse.class).getObject(); Gson gson = getGson(helper); if (helper.isDebugEnabled()) helper.debug("Status: " + gson.toJson(status)); helper.getAction().addOptionBuilder().setKey("wl-status").setValue(gson.toJson(status)); if (status != null && status.data != null) { maxCredit = status.data.maxCredit; request.setMaxCredit(status.data.maxCredit); } if (maxCredit == null) maxCredit = Float.parseFloat(ApplicationProperties.getProperty("purdue.specreg.maxCreditDefault", "18")); if (status != null && status.data != null && status.data.requests != null) { for (SpecialRegistration r: status.data.requests) { if (r.changes != null) for (Change ch: r.changes) { if (status(ch.status) == RequestedCourseStatus.OVERRIDE_PENDING && ch.subject != null && ch.courseNbr != null) { String course = ch.subject + " " + ch.courseNbr; Set<String> problems = overrides.get(course); if (problems == null) { problems = new TreeSet<String>(); overrides.put(course, problems); } if (ch.errors != null) for (ChangeError err: ch.errors) { if (err.code != null) problems.add(err.code); } } else if (status(ch.status) == RequestedCourseStatus.OVERRIDE_PENDING && r.maxCredit != null) { oldCredit = r.maxCredit; } } } } } catch (SectioningException e) { helper.getAction().setApiException(e.getMessage()); throw (SectioningException)e; } catch (Exception e) { helper.getAction().setApiException(e.getMessage()); sLog.error(e.getMessage(), e); throw new SectioningException(e.getMessage()); } finally { if (resource != null) { if (resource.getResponse() != null) resource.getResponse().release(); resource.release(); } } SpecialRegistrationRequest req = new SpecialRegistrationRequest(); req.studentId = getBannerId(original); req.term = getBannerTerm(server.getAcademicSession()); req.campus = getBannerCampus(server.getAcademicSession()); req.mode = getSpecialRegistrationApiMode(); req.changes = new ArrayList<Change>(); if (helper.getUser() != null) { req.requestorId = getRequestorId(helper.getUser()); req.requestorRole = getRequestorType(helper.getUser(), original); } if (request.hasConfirmations()) { for (CourseMessage m: request.getConfirmations()) { if ("REQUEST_NOTE".equals(m.getCode()) && m.getMessage() != null && !m.getMessage().isEmpty()) { req.requestorNotes = m.getMessage(); } } for (CourseRequestInterface.Request c: request.getCourses()) if (c.hasRequestedCourse() && c.isWaitList()) { for (CourseRequestInterface.RequestedCourse rc: c.getRequestedCourse()) { XCourseId cid = server.getCourse(rc.getCourseId(), rc.getCourseName()); if (cid == null) continue; XCourse course = (cid instanceof XCourse ? (XCourse)cid : server.getCourse(cid.getCourseId())); if (course == null) continue; String subject = course.getSubjectArea(); String courseNbr = course.getCourseNumber(); List<ChangeError> errors = new ArrayList<ChangeError>(); for (CourseMessage m: request.getConfirmations()) { if ("WL-CREDIT".equals(m.getCode())) continue; if ("NO_ALT".equals(m.getCode())) continue; if ("DROP_CRIT".equals(m.getCode())) continue; if ("WL-OVERLAP".equals(m.getCode())) continue; if ("NOT-ONLINE".equals(m.getCode())) continue; if ("NOT-RESIDENTIAL".equals(m.getCode())) continue; if (!m.hasCourse()) continue; if (!m.isError() && (course.getCourseId().equals(m.getCourseId()) || course.getCourseName().equals(m.getCourse()))) { ChangeError e = new ChangeError(); e.code = m.getCode(); e.message = m.getMessage(); errors.add(e); } } if (!errors.isEmpty()) { Change ch = new Change(); ch.setCourse(subject, courseNbr, iExternalTermProvider, server.getAcademicSession()); ch.crn = ""; ch.errors = errors; ch.operation = ChangeOperation.ADD; req.changes.add(ch); overrides.remove(subject + " " + courseNbr); } } } } req.courseCreditHrs = new ArrayList<CourseCredit>(); Float wlCredit = null; for (CourseRequestInterface.Request r: request.getCourses()) { if (r.hasRequestedCourse() && r.isWaitList()) { CourseCredit cc = null; Float credit = null; for (RequestedCourse rc: r.getRequestedCourse()) { XCourseId cid = server.getCourse(rc.getCourseId(), rc.getCourseName()); if (cid == null) continue; XCourse course = (cid instanceof XCourse ? (XCourse)cid : server.getCourse(cid.getCourseId())); if (course == null) continue; if (cc == null) { cc = new CourseCredit(); cc.setCourse(course.getSubjectArea(), course.getCourseNumber(), iExternalTermProvider, server.getAcademicSession()); cc.title = course.getTitle(); cc.creditHrs = (course.hasCredit() ? course.getMinCredit() : 0f); } else { if (cc.alternatives == null) cc.alternatives = new ArrayList<CourseCredit>(); CourseCredit acc = new CourseCredit(); acc.setCourse(course.getSubjectArea(), course.getCourseNumber(), iExternalTermProvider, server.getAcademicSession()); acc.title = course.getTitle(); acc.creditHrs = (course.hasCredit() ? course.getMinCredit() : 0f); cc.alternatives.add(acc); } if (rc.hasCredit() && (credit == null || credit < rc.getCreditMin())) credit = rc.getCreditMin(); } if (cc != null) req.courseCreditHrs.add(cc); if (credit != null && (wlCredit == null || wlCredit < credit)) wlCredit = credit; } } if (neededCredit != null && maxCredit < neededCredit) { req.maxCredit = neededCredit; } if (!req.changes.isEmpty() || !overrides.isEmpty() || req.maxCredit != null || oldCredit != null) { resource = null; try { resource = new ClientResource(getSpecialRegistrationApiSiteSubmitRegistration()); resource.setNext(iClient); resource.addQueryParameter("apiKey", getSpecialRegistrationApiKey()); Gson gson = getGson(helper); if (helper.isDebugEnabled()) helper.debug("Request: " + gson.toJson(req)); helper.getAction().addOptionBuilder().setKey("wl-request").setValue(gson.toJson(req)); long t1 = System.currentTimeMillis(); resource.post(new GsonRepresentation<SpecialRegistrationRequest>(req)); helper.getAction().setApiPostTime(System.currentTimeMillis() - t1); SpecialRegistrationResponseList response = (SpecialRegistrationResponseList)new GsonRepresentation<SpecialRegistrationResponseList>(resource.getResponseEntity(), SpecialRegistrationResponseList.class).getObject(); if (helper.isDebugEnabled()) helper.debug("Response: " + gson.toJson(response)); helper.getAction().addOptionBuilder().setKey("wl-response").setValue(gson.toJson(response)); if (ResponseStatus.success != response.status) throw new SectioningException(response.message == null || response.message.isEmpty() ? "Failed to request overrides (" + response.status + ")." : response.message); if (response.data != null) { for (CourseRequestInterface.Request c: request.getCourses()) if (c.hasRequestedCourse()) { for (CourseRequestInterface.RequestedCourse rc: c.getRequestedCourse()) { if (rc.getStatus() != null && rc.getStatus() != RequestedCourseStatus.OVERRIDE_REJECTED) { rc.setStatus(null); rc.setOverrideExternalId(null); rc.setOverrideTimeStamp(null); } XCourseId cid = server.getCourse(rc.getCourseId(), rc.getCourseName()); if (cid == null) continue; XCourse course = (cid instanceof XCourse ? (XCourse)cid : server.getCourse(cid.getCourseId())); if (course == null) continue; String subject = course.getSubjectArea(); String courseNbr = course.getCourseNumber(); for (SpecialRegistration r: response.data) { if (r.changes != null) for (Change ch: r.changes) { if (subject.equals(ch.subject) && courseNbr.equals(ch.courseNbr)) { rc.setOverrideTimeStamp(r.dateCreated == null ? null : r.dateCreated.toDate()); rc.setOverrideExternalId(r.regRequestId); rc.setStatus(status(r, false)); rc.setStatusNote(SpecialRegistrationHelper.note(r, false)); rc.setRequestId(r.regRequestId); rc.setRequestorNote(r.requestorNotes); break; } } } } } for (CourseRequestInterface.Request c: request.getAlternatives()) if (c.hasRequestedCourse()) { for (CourseRequestInterface.RequestedCourse rc: c.getRequestedCourse()) { if (rc.getStatus() != null && rc.getStatus() != RequestedCourseStatus.OVERRIDE_REJECTED) { rc.setStatus(null); rc.setOverrideExternalId(null); rc.setOverrideTimeStamp(null); } XCourseId cid = server.getCourse(rc.getCourseId(), rc.getCourseName()); if (cid == null) continue; XCourse course = (cid instanceof XCourse ? (XCourse)cid : server.getCourse(cid.getCourseId())); if (course == null) continue; String subject = course.getSubjectArea(); String courseNbr = course.getCourseNumber(); for (SpecialRegistration r: response.data) if (r.changes != null) for (Change ch: r.changes) { if (subject.equals(ch.subject) && courseNbr.equals(ch.courseNbr)) { rc.setOverrideTimeStamp(r.dateCreated == null ? null : r.dateCreated.toDate()); rc.setOverrideExternalId(r.regRequestId); rc.setStatus(status(r, false)); rc.setStatusNote(SpecialRegistrationHelper.note(r, false)); break; } } } } if (req.maxCredit != null) { for (SpecialRegistration r: response.data) { if (r.maxCredit != null) { request.setMaxCreditOverride(r.maxCredit); request.setMaxCreditOverrideExternalId(r.regRequestId); request.setMaxCreditOverrideTimeStamp(r.dateCreated == null ? null : r.dateCreated.toDate()); request.setMaxCreditOverrideStatus(status(r, true)); request.setCreditWarning( ApplicationProperties.getProperty("purdue.specreg.messages.maxCredit", "Maximum of {max} credit hours exceeded.") .replace("{max}", sCreditFormat.format(maxCredit)).replace("{credit}", sCreditFormat.format(req.maxCredit)) ); request.setCreditNote(SpecialRegistrationHelper.note(r, true)); request.setRequestorNote(r.requestorNotes); request.setRequestId(r.regRequestId); break; } } } else { request.setMaxCreditOverrideStatus(RequestedCourseStatus.SAVED); } } if (request.hasConfirmations()) { for (CourseMessage message: request.getConfirmations()) { if (message.getStatus() == RequestedCourseStatus.OVERRIDE_NEEDED) message.setStatus(RequestedCourseStatus.OVERRIDE_PENDING); } } } catch (SectioningException e) { helper.getAction().setApiException(e.getMessage()); throw (SectioningException)e; } catch (Exception e) { helper.getAction().setApiException(e.getMessage()); sLog.error(e.getMessage(), e); throw new SectioningException(e.getMessage()); } finally { if (resource != null) { if (resource.getResponse() != null) resource.getResponse().release(); resource.release(); } } } else { for (CourseRequestInterface.Request c: request.getCourses()) if (c.hasRequestedCourse()) { for (CourseRequestInterface.RequestedCourse rc: c.getRequestedCourse()) { if (rc.getStatus() != null && rc.getStatus() != RequestedCourseStatus.OVERRIDE_REJECTED) { rc.setStatus(null); rc.setOverrideExternalId(null); rc.setOverrideTimeStamp(null); } } } for (CourseRequestInterface.Request c: request.getAlternatives()) if (c.hasRequestedCourse()) { for (CourseRequestInterface.RequestedCourse rc: c.getRequestedCourse()) { if (rc.getStatus() != null && rc.getStatus() != RequestedCourseStatus.OVERRIDE_REJECTED) { rc.setStatus(null); rc.setOverrideExternalId(null); rc.setOverrideTimeStamp(null); } } } } } @Override public void check(OnlineSectioningServer server, OnlineSectioningHelper helper, CourseRequestInterface request) throws SectioningException { XStudent original = (request.getStudentId() == null ? null : server.getStudent(request.getStudentId())); if (original == null) return; // Do not check when validation is disabled if (!isValidationEnabled(server, helper, original)) return; Map<String, RequestedCourse> rcs = new HashMap<String, RequestedCourse>(); for (CourseRequestInterface.Request r: request.getCourses()) { if (r.hasRequestedCourse() && r.isWaitList()) for (RequestedCourse rc: r.getRequestedCourse()) { if (rc.getOverrideExternalId() != null) rcs.put(rc.getOverrideExternalId(), rc); rcs.put(rc.getCourseName(), rc); if (rc.getStatus() == RequestedCourseStatus.OVERRIDE_NEEDED && "TBD".equals(rc.getOverrideExternalId())) { request.addConfirmationMessage( rc.getCourseId(), rc.getCourseName(), "NOT_REQUESTED", ApplicationProperties.getProperty("purdue.specreg.messages.waitlist.notRequested", "Overrides not requested, wait-list inactive."), RequestedCourseStatus.OVERRIDE_NEEDED, 1 ); } } } if (request.getMaxCreditOverrideStatus() == null) { request.setMaxCreditOverrideStatus(RequestedCourseStatus.SAVED); } if (rcs.isEmpty() && !request.hasMaxCreditOverride()) return; Integer ORD_BANNER = 1; ClientResource resource = null; try { resource = new ClientResource(getSpecialRegistrationApiSiteCheckSpecialRegistrationStatus()); resource.setNext(iClient); AcademicSessionInfo session = server.getAcademicSession(); String term = getBannerTerm(session); String campus = getBannerCampus(session); resource.addQueryParameter("term", term); resource.addQueryParameter("campus", campus); resource.addQueryParameter("studentId", getBannerId(original)); resource.addQueryParameter("mode", getSpecialRegistrationApiMode().name()); helper.getAction().addOptionBuilder().setKey("term").setValue(term); helper.getAction().addOptionBuilder().setKey("campus").setValue(campus); helper.getAction().addOptionBuilder().setKey("studentId").setValue(getBannerId(original)); resource.addQueryParameter("apiKey", getSpecialRegistrationApiKey()); long t0 = System.currentTimeMillis(); resource.get(MediaType.APPLICATION_JSON); helper.getAction().setApiGetTime(System.currentTimeMillis() - t0); SpecialRegistrationStatusResponse status = (SpecialRegistrationStatusResponse)new GsonRepresentation<SpecialRegistrationStatusResponse>(resource.getResponseEntity(), SpecialRegistrationStatusResponse.class).getObject(); Gson gson = getGson(helper); if (helper.isDebugEnabled()) helper.debug("Status: " + gson.toJson(status)); helper.getAction().addOptionBuilder().setKey("wl-status").setValue(gson.toJson(status)); Float maxCredit = null; if (status != null && status.data != null) { maxCredit = status.data.maxCredit; request.setMaxCredit(status.data.maxCredit); } if (maxCredit == null) maxCredit = Float.parseFloat(ApplicationProperties.getProperty("purdue.specreg.maxCreditDefault", "18")); if (status != null && status.data != null && status.data.requests != null) { // Retrieve max credit request SpecialRegistration maxCreditReq = null; // Try matching request first if (request.getMaxCreditOverrideExternalId() != null) for (SpecialRegistration r: status.data.requests) { if (r.maxCredit != null && request.getMaxCreditOverrideExternalId().equals(r.regRequestId)) { maxCreditReq = r; break; } } // Get latest not-cancelled max credit override request otherwise if (maxCreditReq == null) for (SpecialRegistration r: status.data.requests) { if (r.maxCredit != null && status(r, true) != RequestedCourseStatus.OVERRIDE_CANCELLED && (maxCreditReq == null || r.dateCreated.isAfter(maxCreditReq.dateCreated))) { maxCreditReq = r; } } if (maxCreditReq != null) { request.setMaxCreditOverrideExternalId(maxCreditReq.regRequestId); request.setMaxCreditOverrideStatus(status(maxCreditReq, true)); request.setMaxCreditOverride(maxCreditReq.maxCredit); request.setMaxCreditOverrideTimeStamp(maxCreditReq.dateCreated == null ? null : maxCreditReq.dateCreated.toDate()); request.setCreditNote(SpecialRegistrationHelper.note(maxCreditReq, true)); String warning = null; if (maxCreditReq.changes != null) for (Change ch: maxCreditReq.changes) if (ch.subject == null && ch.courseNbr == null) if (ch.errors != null) for (ChangeError er: ch.errors) if ("MAXI".equals(er.code) && er.message != null) warning = (warning == null ? "" : warning + "\n") + er.message; request.setCreditWarning(warning); request.setRequestorNote(maxCreditReq.requestorNotes); request.setRequestId(maxCreditReq.regRequestId); for (String suggestion: ApplicationProperties.getProperty("purdue.specreg.waitlist.requestorNoteSuggestions", "").split("[\r\n]+")) if (!suggestion.isEmpty()) request.addRequestorNoteSuggestion(suggestion); } for (SpecialRegistration r: status.data.requests) { if (r.regRequestId == null) continue; RequestedCourse rc = rcs.get(r.regRequestId); if (rc == null) { if (r.changes != null) for (Change ch: r.changes) if (ch.status == ChangeStatus.approved) { rc = rcs.get(ch.subject + " " + ch.courseNbr); if (rc != null) { for (ChangeError er: ch.errors) request.addConfirmationMessage(rc.getCourseId(), rc.getCourseName(), er.code, "Approved " + er.message, status(ch.status), ORD_BANNER); if (rc.getRequestId() == null) { rc.setStatusNote(SpecialRegistrationHelper.note(r, false)); rc.setRequestorNote(r.requestorNotes); if (rc.getStatus() != RequestedCourseStatus.ENROLLED) rc.setStatus(RequestedCourseStatus.OVERRIDE_APPROVED); } } } continue; } if (rc.getStatus() != RequestedCourseStatus.ENROLLED) { rc.setStatus(status(r, false)); } if (r.changes != null) for (Change ch: r.changes) if (ch.errors != null && ch.courseNbr != null && ch.subject != null && ch.status != null) for (ChangeError er: ch.errors) { if (ch.status == ChangeStatus.denied) { request.addConfirmationError(rc.getCourseId(), rc.getCourseName(), er.code, "Denied " + er.message, status(ch.status), ORD_BANNER); request.setErrorMessage(ApplicationProperties.getProperty("purdue.specreg.messages.waitlist.deniedOverrideError", "One or more wait-listed courses require registration overrides which have been denied.\nYou cannot wait-list these courses.")); } else if (ch.status == ChangeStatus.approved) { request.addConfirmationMessage(rc.getCourseId(), rc.getCourseName(), er.code, "Approved " + er.message, status(ch.status), ORD_BANNER); } else { request.addConfirmationMessage(rc.getCourseId(), rc.getCourseName(), er.code, er.message, status(ch.status), ORD_BANNER); } } rc.setStatusNote(SpecialRegistrationHelper.note(r, false)); rc.setRequestorNote(r.requestorNotes); rc.setRequestId(r.regRequestId); for (String suggestion: ApplicationProperties.getProperty("purdue.specreg.waitlist.requestorNoteSuggestions", "").split("[\r\n]+")) if (!suggestion.isEmpty()) rc.addRequestorNoteSuggestion(suggestion); } } } catch (SectioningException e) { helper.getAction().setApiException(e.getMessage()); throw (SectioningException)e; } catch (Exception e) { helper.getAction().setApiException(e.getMessage() == null ? "Null" : e.getMessage()); sLog.error(e.getMessage(), e); throw new SectioningException(e.getMessage()); } finally { if (resource != null) { if (resource.getResponse() != null) resource.getResponse().release(); resource.release(); } } } @Override public void checkEligibility(OnlineSectioningServer server, OnlineSectioningHelper helper, EligibilityCheck check, XStudent student) throws SectioningException { if (student == null) return; // Do not check eligibility when validation is disabled if (!isValidationEnabled(server, helper, student)) return; if (!check.hasFlag(EligibilityCheck.EligibilityFlag.CAN_ENROLL)) return; ClientResource resource = null; try { resource = new ClientResource(getSpecialRegistrationApiSiteCheckEligibility()); resource.setNext(iClient); AcademicSessionInfo session = server.getAcademicSession(); String term = getBannerTerm(session); String campus = getBannerCampus(session); resource.addQueryParameter("term", term); resource.addQueryParameter("campus", campus); resource.addQueryParameter("studentId", getBannerId(student)); resource.addQueryParameter("mode", getSpecialRegistrationApiMode().name()); helper.getAction().addOptionBuilder().setKey("term").setValue(term); helper.getAction().addOptionBuilder().setKey("campus").setValue(campus); helper.getAction().addOptionBuilder().setKey("studentId").setValue(getBannerId(student)); resource.addQueryParameter("apiKey", getSpecialRegistrationApiKey()); long t0 = System.currentTimeMillis(); resource.get(MediaType.APPLICATION_JSON); helper.getAction().setApiGetTime( (helper.getAction().hasApiGetTime() ? helper.getAction().getApiGetTime() : 0l) + System.currentTimeMillis() - t0); CheckEligibilityResponse eligibility = (CheckEligibilityResponse)new GsonRepresentation<CheckEligibilityResponse>(resource.getResponseEntity(), CheckEligibilityResponse.class).getObject(); Gson gson = getGson(helper); if (helper.isDebugEnabled()) helper.debug("Eligibility: " + gson.toJson(eligibility)); helper.getAction().addOptionBuilder().setKey("wl-eligibility").setValue(gson.toJson(eligibility)); if (ResponseStatus.success != eligibility.status) throw new SectioningException(eligibility.message == null || eligibility.message.isEmpty() ? "Failed to check wait-list eligibility (" + eligibility.status + ")." : eligibility.message); if (eligibility.data != null && eligibility.data.eligible != null && eligibility.data.eligible.booleanValue()) { check.setFlag(EligibilityFlag.WAIT_LIST_VALIDATION, true); } if (eligibility.data != null && eligibility.data.eligibilityProblems != null) { String m = null; for (EligibilityProblem p: eligibility.data.eligibilityProblems) if (m == null) m = p.message; else m += "\n" + p.message; if (m != null) check.setMessage(MESSAGES.exceptionFailedEligibilityCheck(m)); } } catch (SectioningException e) { helper.getAction().setApiException(e.getMessage()); throw (SectioningException)e; } catch (Exception e) { helper.getAction().setApiException(e.getMessage() == null ? "Null" : e.getMessage()); sLog.error(e.getMessage(), e); throw new SectioningException(e.getMessage()); } finally { if (resource != null) { if (resource.getResponse() != null) resource.getResponse().release(); resource.release(); } } } protected boolean hasOverride(org.unitime.timetable.model.Student student) { if (student.getOverrideExternalId() != null) return true; if (student.getMaxCredit() == null) return true; for (CourseDemand cd: student.getCourseDemands()) { if (Boolean.TRUE.equals(cd.isWaitlist()) && Boolean.FALSE.equals(cd.isAlternative()) && !cd.isEnrolledExceptForWaitListSwap()) for (org.unitime.timetable.model.CourseRequest cr: cd.getCourseRequests()) { if (cr.getOverrideExternalId() != null) return true; } } if (student.getOverrideExternalId() != null && student.getMaxCreditOverrideIntent() == CourseRequestOverrideIntent.WAITLIST) return true; return false; } public boolean updateStudent(OnlineSectioningServer server, OnlineSectioningHelper helper, Student student, Builder action) throws SectioningException { // No pending overrides -> nothing to do if (student == null || !hasOverride(student)) return false; ClientResource resource = null; try { resource = new ClientResource(getSpecialRegistrationApiSiteCheckSpecialRegistrationStatus()); resource.setNext(iClient); AcademicSessionInfo session = (server == null ? new AcademicSessionInfo(student.getSession()) : server.getAcademicSession()); String term = getBannerTerm(session); String campus = getBannerCampus(session); resource.addQueryParameter("term", term); resource.addQueryParameter("campus", campus); resource.addQueryParameter("studentId", getBannerId(student)); resource.addQueryParameter("mode", getSpecialRegistrationApiMode().name()); action.addOptionBuilder().setKey("term").setValue(term); action.addOptionBuilder().setKey("campus").setValue(campus); action.addOptionBuilder().setKey("studentId").setValue(getBannerId(student)); resource.addQueryParameter("apiKey", getSpecialRegistrationApiKey()); long t0 = System.currentTimeMillis(); resource.get(MediaType.APPLICATION_JSON); action.setApiGetTime(System.currentTimeMillis() - t0); SpecialRegistrationStatusResponse status = (SpecialRegistrationStatusResponse)new GsonRepresentation<SpecialRegistrationStatusResponse>(resource.getResponseEntity(), SpecialRegistrationStatusResponse.class).getObject(); Gson gson = getGson(helper); if (helper.isDebugEnabled()) helper.debug("Status: " + gson.toJson(status)); action.addOptionBuilder().setKey("wl-status").setValue(gson.toJson(status)); boolean changed = false; for (CourseDemand cd: student.getCourseDemands()) { if (Boolean.TRUE.equals(cd.isWaitlist()) && Boolean.FALSE.equals(cd.isAlternative()) && !cd.isEnrolledExceptForWaitListSwap()) for (org.unitime.timetable.model.CourseRequest cr: cd.getCourseRequests()) { if (cr.getOverrideExternalId() != null && !"TBD".equals(cr.getOverrideExternalId())) { SpecialRegistration req = null; for (SpecialRegistration r: status.data.requests) { if (cr.getOverrideExternalId().equals(r.regRequestId)) { req = r; break; } } if (req == null) { if (cr.getCourseRequestOverrideStatus() != CourseRequestOverrideStatus.CANCELLED) { cr.setCourseRequestOverrideStatus(CourseRequestOverrideStatus.CANCELLED); helper.getHibSession().update(cr); changed = true; } } else { Integer oldStatus = cr.getOverrideStatus(); switch (status(req, false)) { case OVERRIDE_REJECTED: cr.setCourseRequestOverrideStatus(CourseRequestOverrideStatus.REJECTED); break; case OVERRIDE_APPROVED: cr.setCourseRequestOverrideStatus(CourseRequestOverrideStatus.APPROVED); break; case OVERRIDE_CANCELLED: cr.setCourseRequestOverrideStatus(CourseRequestOverrideStatus.CANCELLED); break; case OVERRIDE_PENDING: cr.setCourseRequestOverrideStatus(CourseRequestOverrideStatus.PENDING); break; } if (oldStatus == null || !oldStatus.equals(cr.getOverrideStatus())) { helper.getHibSession().update(cr); changed = true; } } } } } boolean studentChanged = false; if (status.data.maxCredit != null && !status.data.maxCredit.equals(student.getMaxCredit())) { student.setMaxCredit(status.data.maxCredit); studentChanged = true; } if (student.getOverrideExternalId() != null) { SpecialRegistration req = null; for (SpecialRegistration r: status.data.requests) { if (student.getOverrideExternalId().equals(r.regRequestId)) { req = r; break; } } if (req == null && student.getMaxCreditOverrideIntent() == CourseRequestOverrideIntent.WAITLIST) { student.setOverrideExternalId(null); student.setOverrideMaxCredit(null); student.setOverrideStatus(null); student.setOverrideTimeStamp(null); student.setOverrideIntent(null); studentChanged = true; } else if (req != null) { Integer oldStatus = student.getOverrideStatus(); switch (status(req, true)) { case OVERRIDE_REJECTED: student.setMaxCreditOverrideStatus(CourseRequestOverrideStatus.REJECTED); break; case OVERRIDE_APPROVED: student.setMaxCreditOverrideStatus(CourseRequestOverrideStatus.APPROVED); break; case OVERRIDE_CANCELLED: student.setMaxCreditOverrideStatus(CourseRequestOverrideStatus.CANCELLED); break; case OVERRIDE_PENDING: student.setMaxCreditOverrideStatus(CourseRequestOverrideStatus.PENDING); break; } if (oldStatus == null || !oldStatus.equals(student.getOverrideStatus())) studentChanged = true; } } if (studentChanged) helper.getHibSession().update(student); if (changed || studentChanged) helper.getHibSession().flush(); return changed || studentChanged; } catch (SectioningException e) { action.setApiException(e.getMessage()); throw (SectioningException)e; } catch (Exception e) { action.setApiException(e.getMessage() == null ? "Null" : e.getMessage()); sLog.error(e.getMessage(), e); throw new SectioningException(e.getMessage()); } finally { if (resource != null) { if (resource.getResponse() != null) resource.getResponse().release(); resource.release(); } } } protected boolean hasNotApprovedCourseRequestOverride(org.unitime.timetable.model.Student student) { for (CourseDemand cd: student.getCourseDemands()) { if (Boolean.TRUE.equals(cd.isWaitlist()) && Boolean.FALSE.equals(cd.isAlternative()) && !cd.isEnrolledExceptForWaitListSwap()) { for (org.unitime.timetable.model.CourseRequest cr: cd.getCourseRequests()) { if (cr.getOverrideExternalId() != null && cr.getCourseRequestOverrideStatus() != CourseRequestOverrideStatus.APPROVED) return true; } } } if (student.getOverrideExternalId() != null && student.getMaxCreditOverrideIntent() == CourseRequestOverrideIntent.WAITLIST && student.getMaxCreditOverrideStatus() != CourseRequestOverrideStatus.APPROVED) return true; return false; } @Override public boolean revalidateStudent(OnlineSectioningServer server, OnlineSectioningHelper helper, Student student, Builder action) throws SectioningException { // Do not re-validate when validation is disabled if (!isValidationEnabled(student)) return false; // When there is a pending override, try to update student first boolean studentUpdated = false; if (hasOverride(student)) studentUpdated = updateStudent(server, helper, student, action); // All course requests are approved -> nothing to do if (!hasNotApprovedCourseRequestOverride(student) && !"true".equalsIgnoreCase(ApplicationProperties.getProperty("purdue.specreg.forceRevalidation", "false"))) return false; XStudent original = server.getStudent(student.getUniqueId()); if (original == null) return false; boolean changed = false; SpecialRegistrationRequest submitRequest = new SpecialRegistrationRequest(); submitRequest.studentId = getBannerId(original); submitRequest.term = getBannerTerm(server.getAcademicSession()); submitRequest.campus = getBannerCampus(server.getAcademicSession()); submitRequest.mode = getSpecialRegistrationApiMode(); submitRequest.changes = new ArrayList<Change>(); if (helper.getUser() != null) { submitRequest.requestorId = getRequestorId(helper.getUser()); submitRequest.requestorRole = getRequestorType(helper.getUser(), original); } Float maxCredit = null; Float maxCreditNeeded = null; for (CourseDemand cd: student.getCourseDemands()) { XCourseId dropCourse = null; Set<String> dropCrns = null; if (cd.getWaitListSwapWithCourseOffering() != null) { dropCourse = new XCourseId(cd.getWaitListSwapWithCourseOffering()); dropCrns = new TreeSet<String>(); for (StudentClassEnrollment enrl: student.getClassEnrollments()) { if (cd.getWaitListSwapWithCourseOffering().equals(enrl.getCourseOffering())) { dropCrns.add(enrl.getClazz().getExternalId(cd.getWaitListSwapWithCourseOffering())); } } } if (Boolean.TRUE.equals(cd.isWaitlist()) && Boolean.FALSE.equals(cd.isAlternative()) && !cd.isEnrolledExceptForWaitListSwap()) { XCourseId enrolledCourse = null; Integer enrolledOrder = null; if (dropCourse != null && !dropCrns.isEmpty()) { for (org.unitime.timetable.model.CourseRequest cr: cd.getCourseRequests()) if (cr.getCourseOffering().getUniqueId().equals(dropCourse.getCourseId())) { enrolledCourse = dropCourse; enrolledOrder = cr.getOrder(); } } for (org.unitime.timetable.model.CourseRequest cr: cd.getCourseRequests()) { // skip courses that cannot be wait-listed if (!cr.getCourseOffering().getInstructionalOffering().effectiveWaitList()) continue; // skip cases where the wait-list request was cancelled if ("TBD".equals(cr.getOverrideExternalId())) continue; // when enrolled (section swap), check if active if (enrolledCourse != null) { if (cr.getOrder() > enrolledOrder) continue; if (cr.getOrder() == enrolledOrder) { XCourseRequest rq = original.getRequestForCourse(enrolledCourse.getCourseId()); XOffering offering = server.getOffering(enrolledCourse.getOfferingId()); // when enrolled, skip the enrolled course if the enrollment matches the requirements if (rq != null && rq.getEnrollment() != null && offering != null && rq.isRequired(rq.getEnrollment(), offering)) continue; } } // get possible enrollments into the course Assignment<Request, Enrollment> assignment = new AssignmentMap<Request, Enrollment>(); CourseRequest courseRequest = SectioningRequest.convert(assignment, new XCourseRequest(cr, helper, null), dropCourse, server, WaitListMode.WaitList); Collection<Enrollment> enrls = courseRequest.getEnrollmentsSkipSameTime(assignment); // get a test enrollment (preferably a non-conflicting one) Enrollment testEnrollment = null; for (Iterator<Enrollment> e = enrls.iterator(); e.hasNext();) { testEnrollment = e.next(); boolean overlaps = false; for (Request q: testEnrollment.getStudent().getRequests()) { if (q.equals(courseRequest)) continue; Enrollment x = assignment.getValue(q); if (x == null || x.getAssignments() == null || x.getAssignments().isEmpty()) continue; for (Iterator<SctAssignment> i = x.getAssignments().iterator(); i.hasNext();) { SctAssignment a = i.next(); if (a.isOverlapping(testEnrollment.getAssignments())) { overlaps = true; } } } if (!overlaps) break; } // no test enrollment, take first possible enrollment if (testEnrollment == null) { Course c = courseRequest.getCourses().get(0); for (Config config: c.getOffering().getConfigs()) { if (courseRequest.isNotAllowed(c, config)) continue; testEnrollment = firstEnrollment(courseRequest, assignment, c, config, new HashSet<Section>(), 0); } } // still no test enrollment -> ignore if (testEnrollment == null) continue; // create request CheckRestrictionsRequest req = new CheckRestrictionsRequest(); req.studentId = getBannerId(original); req.term = getBannerTerm(server.getAcademicSession()); req.campus = getBannerCampus(server.getAcademicSession()); req.mode = getSpecialRegistrationApiMode(); Set<String> crns = new HashSet<String>(); Set<String> keep = new HashSet<String>(); for (Section section: testEnrollment.getSections()) { String crn = getCRN(section, testEnrollment.getCourse()); if (dropCrns != null && dropCrns.contains(crn)) { keep.add(crn); } else { SpecialRegistrationHelper.addWaitListCrn(req, crn); crns.add(crn); } } if (dropCrns != null) for (String crn: dropCrns) { if (!keep.contains(crn)) { SpecialRegistrationHelper.dropWaitListCrn(req, crn); crns.add(crn); } } // no CRNs to check -> continue if (crns.isEmpty()) continue; // call validation CheckRestrictionsResponse validation = null; ClientResource resource = null; try { resource = new ClientResource(getSpecialRegistrationApiValidationSite()); resource.setNext(iClient); resource.addQueryParameter("apiKey", getSpecialRegistrationApiKey()); Gson gson = getGson(helper); if (helper.isDebugEnabled()) helper.debug("Request: " + gson.toJson(req)); action.addOptionBuilder().setKey("wl-req-" + testEnrollment.getCourse().getName().replace(" ", "").toLowerCase()).setValue(gson.toJson(req)); long t1 = System.currentTimeMillis(); resource.post(new GsonRepresentation<CheckRestrictionsRequest>(req)); action.setApiPostTime( (action.hasApiPostTime() ? action.getApiPostTime() : 0) + System.currentTimeMillis() - t1); validation = (CheckRestrictionsResponse)new GsonRepresentation<CheckRestrictionsResponse>(resource.getResponseEntity(), CheckRestrictionsResponse.class).getObject(); if (helper.isDebugEnabled()) helper.debug("Response: " + gson.toJson(validation)); action.addOptionBuilder().setKey("wl-resp-" + testEnrollment.getCourse().getName().replace(" ", "").toLowerCase()).setValue(gson.toJson(validation)); if (ResponseStatus.success != validation.status) throw new SectioningException(validation.message == null || validation.message.isEmpty() ? "Failed to check student eligibility (" + validation.status + ")." : validation.message); } catch (SectioningException e) { action.setApiException(e.getMessage()); throw (SectioningException)e; } catch (Exception e) { action.setApiException(e.getMessage()); sLog.error(e.getMessage(), e); throw new SectioningException(e.getMessage()); } finally { if (resource != null) { if (resource.getResponse() != null) resource.getResponse().release(); resource.release(); } } if (validation.outJson != null && validation.outJson.problems != null) problems: for (Problem problem: validation.outJson.problems) { if ("HOLD".equals(problem.code)) continue; if ("DUPL".equals(problem.code)) continue; if ("MAXI".equals(problem.code)) continue; if ("CLOS".equals(problem.code)) continue; if ("TIME".equals(problem.code)) continue; if (!crns.contains(problem.crn)) continue; Change change = null; for (Change ch: submitRequest.changes) { if (ch.subject.equals(cr.getCourseOffering().getSubjectAreaAbbv()) && ch.courseNbr.equals(cr.getCourseOffering().getCourseNbr())) { change = ch; break; } } if (change == null) { change = new Change(); change.setCourse(cr.getCourseOffering().getSubjectAreaAbbv(), cr.getCourseOffering().getCourseNbr(), iExternalTermProvider, server.getAcademicSession()); change.crn = ""; change.errors = new ArrayList<ChangeError>(); change.operation = ChangeOperation.ADD; submitRequest.changes.add(change); } else { for (ChangeError err: change.errors) if (problem.code.equals(err.code)) continue problems; } ChangeError err = new ChangeError(); err.code = problem.code; err.message = problem.message; if (err.message != null && err.message.indexOf("this section") >= 0) err.message = err.message.replace("this section", cr.getCourseOffering().getCourseName()); if (err.message != null && err.message.indexOf(" (CRN ") >= 0) err.message = err.message.replaceFirst(" \\(CRN [0-9][0-9][0-9][0-9][0-9]\\) ", " "); change.errors.add(err); } if (maxCredit == null && validation.maxCredit != null) maxCredit = validation.maxCredit; if (validation.outJson.maxHoursCalc != null) { if (maxCreditNeeded == null || maxCreditNeeded < validation.outJson.maxHoursCalc) maxCreditNeeded = validation.outJson.maxHoursCalc; } } } } if (maxCredit == null) maxCredit = Float.parseFloat(ApplicationProperties.getProperty("purdue.specreg.maxCreditDefault", "18")); if (maxCreditNeeded != null && maxCreditNeeded > maxCredit) submitRequest.maxCredit = maxCreditNeeded; submitRequest.courseCreditHrs = new ArrayList<CourseCredit>(); for (XRequest r: original.getRequests()) { CourseCredit cc = null; if (r instanceof XCourseRequest) { XCourseRequest cr = (XCourseRequest)r; if (!cr.isWaitlist() || cr.getEnrollment() != null) continue; for (XCourseId cid: cr.getCourseIds()) { XCourse course = (cid instanceof XCourse ? (XCourse)cid : server.getCourse(cid.getCourseId())); if (course == null) continue; if (cc == null) { cc = new CourseCredit(); cc.setCourse(course.getSubjectArea(), course.getCourseNumber(), iExternalTermProvider, server.getAcademicSession()); cc.title = course.getTitle(); cc.creditHrs = (course.hasCredit() ? course.getMinCredit() : 0f); } else { if (cc.alternatives == null) cc.alternatives = new ArrayList<CourseCredit>(); CourseCredit acc = new CourseCredit(); acc.setCourse(course.getSubjectArea(), course.getCourseNumber(), iExternalTermProvider, server.getAcademicSession()); acc.title = course.getTitle(); acc.creditHrs = (course.hasCredit() ? course.getMinCredit() : 0f); cc.alternatives.add(acc); } } } if (cc != null) submitRequest.courseCreditHrs.add(cc); } SpecialRegistrationResponseList response = null; ClientResource resource = null; try { resource = new ClientResource(getSpecialRegistrationApiSiteSubmitRegistration()); resource.setNext(iClient); resource.addQueryParameter("apiKey", getSpecialRegistrationApiKey()); Gson gson = getGson(helper); if (helper.isDebugEnabled()) helper.debug("Submit Request: " + gson.toJson(submitRequest)); action.addOptionBuilder().setKey("wl-request").setValue(gson.toJson(submitRequest)); long t1 = System.currentTimeMillis(); resource.post(new GsonRepresentation<SpecialRegistrationRequest>(submitRequest)); action.setApiPostTime(action.getApiPostTime() + System.currentTimeMillis() - t1); response = (SpecialRegistrationResponseList)new GsonRepresentation<SpecialRegistrationResponseList>(resource.getResponseEntity(), SpecialRegistrationResponseList.class).getObject(); if (helper.isDebugEnabled()) helper.debug("Submit Response: " + gson.toJson(response)); action.addOptionBuilder().setKey("wl-response").setValue(gson.toJson(response)); if (ResponseStatus.success != response.status) throw new SectioningException(response.message == null || response.message.isEmpty() ? "Failed to request overrides (" + response.status + ")." : response.message); } catch (SectioningException e) { action.setApiException(e.getMessage()); throw (SectioningException)e; } catch (Exception e) { action.setApiException(e.getMessage()); sLog.error(e.getMessage(), e); throw new SectioningException(e.getMessage()); } finally { if (resource != null) { if (resource.getResponse() != null) resource.getResponse().release(); resource.release(); } } for (CourseDemand cd: student.getCourseDemands()) { if (Boolean.TRUE.equals(cd.isWaitlist()) && Boolean.FALSE.equals(cd.isAlternative()) && !cd.isEnrolledExceptForWaitListSwap()) cr: for (org.unitime.timetable.model.CourseRequest cr: cd.getCourseRequests()) { if (response != null && response.data != null) { for (SpecialRegistration r: response.data) if (r.changes != null) for (Change ch: r.changes) { if (cr.getCourseOffering().getSubjectAreaAbbv().equals(ch.subject) && cr.getCourseOffering().getCourseNbr().equals(ch.courseNbr)) { Integer oldStatus = cr.getOverrideStatus(); switch (status(r, false)) { case OVERRIDE_REJECTED: cr.setCourseRequestOverrideStatus(CourseRequestOverrideStatus.REJECTED); break; case OVERRIDE_APPROVED: cr.setCourseRequestOverrideStatus(CourseRequestOverrideStatus.APPROVED); break; case OVERRIDE_CANCELLED: cr.setCourseRequestOverrideStatus(CourseRequestOverrideStatus.CANCELLED); break; case OVERRIDE_PENDING: cr.setCourseRequestOverrideStatus(CourseRequestOverrideStatus.PENDING); break; } if (oldStatus == null || !oldStatus.equals(cr.getOverrideStatus())) changed = true; if (cr.getOverrideExternalId() == null || !cr.getOverrideExternalId().equals(r.regRequestId)) changed = true; cr.setOverrideExternalId(r.regRequestId); cr.setOverrideTimeStamp(r.dateCreated == null ? null : r.dateCreated.toDate()); cr.setCourseRequestOverrideIntent(CourseRequestOverrideIntent.WAITLIST); helper.getHibSession().update(cr); continue cr; } } } if (!"TBD".equals(cr.getOverrideExternalId()) && (cr.getOverrideExternalId() != null || cr.getOverrideStatus() != null)) { cr.setOverrideExternalId(null); cr.setOverrideStatus(null); cr.setOverrideTimeStamp(null); cr.setOverrideIntent(null); helper.getHibSession().update(cr); changed = true; } } } boolean studentChanged = false; if (submitRequest.maxCredit != null) { for (SpecialRegistration r: response.data) { if (r.maxCredit != null) { Integer oldStatus = student.getOverrideStatus(); switch (status(r, true)) { case OVERRIDE_REJECTED: student.setMaxCreditOverrideStatus(CourseRequestOverrideStatus.REJECTED); break; case OVERRIDE_APPROVED: student.setMaxCreditOverrideStatus(CourseRequestOverrideStatus.APPROVED); break; case OVERRIDE_CANCELLED: student.setMaxCreditOverrideStatus(CourseRequestOverrideStatus.CANCELLED); break; case OVERRIDE_PENDING: student.setMaxCreditOverrideStatus(CourseRequestOverrideStatus.PENDING); break; } if (oldStatus == null || !oldStatus.equals(student.getOverrideStatus())) studentChanged = true; if (student.getOverrideMaxCredit() == null || !student.getOverrideMaxCredit().equals(r.maxCredit)) studentChanged = true; student.setOverrideMaxCredit(r.maxCredit); if (student.getOverrideExternalId() == null || !student.getOverrideExternalId().equals(r.regRequestId)) studentChanged = true; student.setOverrideExternalId(r.regRequestId); student.setOverrideTimeStamp(r.dateCreated == null ? null : r.dateCreated.toDate()); student.setMaxCreditOverrideIntent(CourseRequestOverrideIntent.WAITLIST); break; } } } else if (student.getMaxCreditOverrideIntent() == CourseRequestOverrideIntent.WAITLIST) { student.setOverrideExternalId(null); student.setOverrideMaxCredit(null); student.setOverrideStatus(null); student.setOverrideTimeStamp(null); student.setOverrideIntent(null); studentChanged = true; } if (studentChanged) helper.getHibSession().update(student); if (changed) helper.getHibSession().flush(); if (changed || studentChanged) helper.getHibSession().flush(); return changed || studentChanged || studentUpdated; } @Override public void dispose() { try { iClient.stop(); } catch (Exception e) { sLog.error(e.getMessage(), e); } } @Override public Collection<Long> updateStudents(OnlineSectioningServer server, OnlineSectioningHelper helper, List<Student> students) throws SectioningException { Map<String, org.unitime.timetable.model.Student> id2student = new HashMap<String, org.unitime.timetable.model.Student>(); List<Long> reloadIds = new ArrayList<Long>(); int batchNumber = 1; for (int i = 0; i < students.size(); i++) { org.unitime.timetable.model.Student student = students.get(i); if (student == null || !hasOverride(student)) continue; if (!isValidationEnabled(student)) continue; String id = getBannerId(student); id2student.put(id, student); if (id2student.size() >= 100) { checkStudentStatuses(server, helper, id2student, reloadIds, batchNumber++); id2student.clear(); } } if (!id2student.isEmpty()) checkStudentStatuses(server, helper, id2student, reloadIds, batchNumber++); if (!reloadIds.isEmpty()) helper.getHibSession().flush(); if (!reloadIds.isEmpty() && server != null && !(server instanceof DatabaseServer)) server.execute(server.createAction(ReloadStudent.class).forStudents(reloadIds), helper.getUser()); return reloadIds; } protected void checkStudentStatuses(OnlineSectioningServer server, OnlineSectioningHelper helper, Map<String, org.unitime.timetable.model.Student> id2student, List<Long> reloadIds, int batchNumber) throws SectioningException { ClientResource resource = null; try { resource = new ClientResource(getSpecialRegistrationApiSiteCheckAllSpecialRegistrationStatus()); resource.setNext(iClient); AcademicSessionInfo session = (server == null ? null : server.getAcademicSession()); String studentIds = null; List<String> ids = new ArrayList<String>(); for (Map.Entry<String, org.unitime.timetable.model.Student> e: id2student.entrySet()) { if (session == null) session = new AcademicSessionInfo(e.getValue().getSession()); if (studentIds == null) studentIds = e.getKey(); else studentIds += "," + e.getKey(); ids.add(e.getKey()); } String term = getBannerTerm(session); String campus = getBannerCampus(session); resource.addQueryParameter("term", term); resource.addQueryParameter("campus", campus); resource.addQueryParameter("studentIds", studentIds); resource.addQueryParameter("mode", getSpecialRegistrationApiMode().name()); resource.addQueryParameter("apiKey", getSpecialRegistrationApiKey()); OnlineSectioningLog.Action.Builder action = helper.getAction(); if (action != null) { action.addOptionBuilder().setKey("term").setValue(term); action.addOptionBuilder().setKey("campus").setValue(campus); action.addOptionBuilder().setKey("studentIds-" + batchNumber).setValue(studentIds); } long t0 = System.currentTimeMillis(); resource.get(MediaType.APPLICATION_JSON); if (action != null) action.setApiGetTime(action.getApiGetTime() + System.currentTimeMillis() - t0); SpecialRegistrationMultipleStatusResponse response = (SpecialRegistrationMultipleStatusResponse)new GsonRepresentation<SpecialRegistrationMultipleStatusResponse>(resource.getResponseEntity(), SpecialRegistrationMultipleStatusResponse.class).getObject(); Gson gson = getGson(helper); if (helper.isDebugEnabled()) helper.debug("Response: " + gson.toJson(response)); if (action != null) action.addOptionBuilder().setKey("wl-response-" + batchNumber).setValue(gson.toJson(response)); if (ResponseStatus.success != response.status) throw new SectioningException(response.message == null || response.message.isEmpty() ? "Failed to check student statuses (" + response.status + ")." : response.message); if (response.data != null && response.data.students != null) { int index = 0; for (SpecialRegistrationStatus status: response.data.students) { String studentId = status.studentId; if (studentId == null && status.requests != null) for (SpecialRegistration req: status.requests) { if (req.studentId != null) { studentId = req.studentId; break; } } if (studentId == null) studentId = ids.get(index); index++; org.unitime.timetable.model.Student student = id2student.get(studentId); if (student == null) continue; boolean changed = false; for (CourseDemand cd: student.getCourseDemands()) { if (Boolean.TRUE.equals(cd.isWaitlist()) && Boolean.FALSE.equals(cd.isAlternative()) && !cd.isEnrolledExceptForWaitListSwap()) for (org.unitime.timetable.model.CourseRequest cr: cd.getCourseRequests()) { if (cr.getOverrideExternalId() != null) { SpecialRegistration req = null; for (SpecialRegistration r: status.requests) { if (cr.getOverrideExternalId().equals(r.regRequestId)) { req = r; break; } } if (req == null) { if (cr.getCourseRequestOverrideStatus() != CourseRequestOverrideStatus.CANCELLED) { cr.setCourseRequestOverrideStatus(CourseRequestOverrideStatus.CANCELLED); helper.getHibSession().update(cr); changed = true; } } else { Integer oldStatus = cr.getOverrideStatus(); switch (status(req, false)) { case OVERRIDE_REJECTED: cr.setCourseRequestOverrideStatus(CourseRequestOverrideStatus.REJECTED); break; case OVERRIDE_APPROVED: cr.setCourseRequestOverrideStatus(CourseRequestOverrideStatus.APPROVED); break; case OVERRIDE_CANCELLED: cr.setCourseRequestOverrideStatus(CourseRequestOverrideStatus.CANCELLED); break; case OVERRIDE_PENDING: cr.setCourseRequestOverrideStatus(CourseRequestOverrideStatus.PENDING); break; } if (oldStatus == null || !oldStatus.equals(cr.getOverrideStatus())) { helper.getHibSession().update(cr); changed = true; } } } } } boolean studentChanged = false; if (status.maxCredit != null && !status.maxCredit.equals(student.getMaxCredit())) { student.setMaxCredit(status.maxCredit); studentChanged = true; } if (student.getOverrideExternalId() != null) { SpecialRegistration req = null; for (SpecialRegistration r: status.requests) { if (student.getOverrideExternalId().equals(r.regRequestId)) { req = r; break; } } if (req == null && student.getMaxCreditOverrideIntent() == CourseRequestOverrideIntent.WAITLIST) { student.setOverrideExternalId(null); student.setOverrideMaxCredit(null); student.setOverrideStatus(null); student.setOverrideTimeStamp(null); student.setOverrideIntent(null); studentChanged = true; } else if (req != null) { Integer oldStatus = student.getOverrideStatus(); switch (status(req, true)) { case OVERRIDE_REJECTED: student.setMaxCreditOverrideStatus(CourseRequestOverrideStatus.REJECTED); break; case OVERRIDE_APPROVED: student.setMaxCreditOverrideStatus(CourseRequestOverrideStatus.APPROVED); break; case OVERRIDE_CANCELLED: student.setMaxCreditOverrideStatus(CourseRequestOverrideStatus.CANCELLED); break; case OVERRIDE_PENDING: student.setMaxCreditOverrideStatus(CourseRequestOverrideStatus.PENDING); break; } if (oldStatus == null || !oldStatus.equals(student.getOverrideStatus())) studentChanged = true; } } if (studentChanged) helper.getHibSession().update(student); if (changed || studentChanged) reloadIds.add(student.getUniqueId()); } } } catch (SectioningException e) { throw (SectioningException)e; } catch (Exception e) { sLog.error(e.getMessage(), e); throw new SectioningException(e.getMessage()); } finally { if (resource != null) { if (resource.getResponse() != null) resource.getResponse().release(); resource.release(); } } } @Override public boolean updateStudent(OnlineSectioningServer server, OnlineSectioningHelper helper, XStudent student, Builder action) throws SectioningException { // No pending overrides -> nothing to do if (student == null) return false; ClientResource resource = null; try { resource = new ClientResource(getSpecialRegistrationApiSiteCheckSpecialRegistrationStatus()); resource.setNext(iClient); AcademicSessionInfo session = server.getAcademicSession(); String term = getBannerTerm(session); String campus = getBannerCampus(session); resource.addQueryParameter("term", term); resource.addQueryParameter("campus", campus); resource.addQueryParameter("studentId", getBannerId(student)); resource.addQueryParameter("mode", getSpecialRegistrationApiMode().name()); action.addOptionBuilder().setKey("term").setValue(term); action.addOptionBuilder().setKey("campus").setValue(campus); action.addOptionBuilder().setKey("studentId").setValue(getBannerId(student)); resource.addQueryParameter("apiKey", getSpecialRegistrationApiKey()); long t0 = System.currentTimeMillis(); resource.get(MediaType.APPLICATION_JSON); action.setApiGetTime(System.currentTimeMillis() - t0); SpecialRegistrationStatusResponse status = (SpecialRegistrationStatusResponse)new GsonRepresentation<SpecialRegistrationStatusResponse>(resource.getResponseEntity(), SpecialRegistrationStatusResponse.class).getObject(); Gson gson = getGson(helper); if (helper.isDebugEnabled()) helper.debug("Status: " + gson.toJson(status)); action.addOptionBuilder().setKey("wl-status").setValue(gson.toJson(status)); boolean studentChanged = false; for (XRequest r: student.getRequests()) { if (r instanceof XCourseRequest) { XCourseRequest cr = (XCourseRequest)r; if (cr.isWaitlist() && !cr.isAlternative() && cr.getEnrollment() == null && cr.hasOverrides()) { for (Map.Entry<XCourseId, XOverride> e: cr.getOverrides().entrySet()) { XCourseId course = e.getKey(); XOverride override = e.getValue(); if ("TBD".equals(override.getExternalId())) continue; SpecialRegistration req = null; for (SpecialRegistration q: status.data.requests) { if (override.getExternalId().equals(q.regRequestId)) { req = q; break; } } if (req == null) { if (override.getStatus() != CourseRequestOverrideStatus.CANCELLED.ordinal()) { override.setStatus(CourseRequestOverrideStatus.CANCELLED.ordinal()); CourseDemand dbCourseDemand = CourseDemandDAO.getInstance().get(cr.getRequestId(), helper.getHibSession()); if (dbCourseDemand != null) { for (org.unitime.timetable.model.CourseRequest dbCourseRequest: dbCourseDemand.getCourseRequests()) { if (dbCourseRequest.getCourseOffering().getUniqueId().equals(course.getCourseId())) { dbCourseRequest.setOverrideStatus(CourseRequestOverrideStatus.CANCELLED.ordinal()); helper.getHibSession().update(dbCourseRequest); } } } studentChanged = true; } } else { Integer oldStatus = override.getStatus(); Integer newStatus = null; switch (status(req, false)) { case OVERRIDE_REJECTED: newStatus = CourseRequestOverrideStatus.REJECTED.ordinal(); break; case OVERRIDE_APPROVED: newStatus = CourseRequestOverrideStatus.APPROVED.ordinal(); break; case OVERRIDE_CANCELLED: newStatus = CourseRequestOverrideStatus.CANCELLED.ordinal(); break; case OVERRIDE_PENDING: newStatus = CourseRequestOverrideStatus.PENDING.ordinal(); break; } if (newStatus != null && !newStatus.equals(oldStatus)) { override.setStatus(newStatus); CourseDemand dbCourseDemand = CourseDemandDAO.getInstance().get(cr.getRequestId(), helper.getHibSession()); if (dbCourseDemand != null) { for (org.unitime.timetable.model.CourseRequest dbCourseRequest: dbCourseDemand.getCourseRequests()) { if (dbCourseRequest.getCourseOffering().getUniqueId().equals(course.getCourseId())) { dbCourseRequest.setOverrideStatus(newStatus); helper.getHibSession().update(dbCourseRequest); } } } studentChanged = true; } } } } } } if (status.data.maxCredit != null && !status.data.maxCredit.equals(student.getMaxCredit())) { student.setMaxCredit(status.data.maxCredit); Student dbStudent = StudentDAO.getInstance().get(student.getStudentId(), helper.getHibSession()); if (dbStudent != null) { dbStudent.setMaxCredit(status.data.maxCredit); helper.getHibSession().update(dbStudent); } studentChanged = true; } if (student.getMaxCreditOverride() != null) { SpecialRegistration req = null; for (SpecialRegistration r: status.data.requests) { if (r.regRequestId != null && r.regRequestId.equals(student.getMaxCreditOverride().getExternalId())) { req = r; break; } } if (req != null) { Integer oldStatus = student.getMaxCreditOverride().getStatus(); Integer newStatus = null; switch (status(req, true)) { case OVERRIDE_REJECTED: newStatus = CourseRequestOverrideStatus.REJECTED.ordinal(); break; case OVERRIDE_APPROVED: newStatus = CourseRequestOverrideStatus.APPROVED.ordinal(); break; case OVERRIDE_CANCELLED: newStatus = CourseRequestOverrideStatus.CANCELLED.ordinal(); break; case OVERRIDE_PENDING: newStatus = CourseRequestOverrideStatus.PENDING.ordinal(); break; } if (newStatus == null || !newStatus.equals(oldStatus)) { student.getMaxCreditOverride().setStatus(newStatus); Student dbStudent = StudentDAO.getInstance().get(student.getStudentId(), helper.getHibSession()); if (dbStudent != null) { dbStudent.setOverrideStatus(newStatus); helper.getHibSession().update(dbStudent); } studentChanged = true; } } } if (studentChanged) { server.update(student, false); helper.getHibSession().flush(); } if (studentChanged) helper.getHibSession().flush(); return studentChanged; } catch (SectioningException e) { action.setApiException(e.getMessage()); throw (SectioningException)e; } catch (Exception e) { action.setApiException(e.getMessage() == null ? "Null" : e.getMessage()); sLog.error(e.getMessage(), e); throw new SectioningException(e.getMessage()); } finally { if (resource != null) { if (resource.getResponse() != null) resource.getResponse().release(); resource.release(); } } } }
Wait-Listing: Custom Validation Submit - do not reset wait-list inactive statuses
JavaSource/org/unitime/timetable/onlinesectioning/custom/purdue/PurdueWaitListValidationProvider.java
Wait-Listing: Custom Validation Submit
<ide><path>avaSource/org/unitime/timetable/onlinesectioning/custom/purdue/PurdueWaitListValidationProvider.java <ide> for (CourseRequestInterface.Request c: request.getCourses()) <ide> if (c.hasRequestedCourse()) { <ide> for (CourseRequestInterface.RequestedCourse rc: c.getRequestedCourse()) { <del> if (rc.getStatus() != null && rc.getStatus() != RequestedCourseStatus.OVERRIDE_REJECTED) { <add> if (rc.getStatus() != null && rc.getStatus() != RequestedCourseStatus.OVERRIDE_REJECTED && rc.getStatus() != RequestedCourseStatus.WAITLIST_INACTIVE) { <ide> rc.setStatus(null); <ide> rc.setOverrideExternalId(null); <ide> rc.setOverrideTimeStamp(null); <ide> for (CourseRequestInterface.Request c: request.getAlternatives()) <ide> if (c.hasRequestedCourse()) { <ide> for (CourseRequestInterface.RequestedCourse rc: c.getRequestedCourse()) { <del> if (rc.getStatus() != null && rc.getStatus() != RequestedCourseStatus.OVERRIDE_REJECTED) { <add> if (rc.getStatus() != null && rc.getStatus() != RequestedCourseStatus.OVERRIDE_REJECTED && rc.getStatus() != RequestedCourseStatus.WAITLIST_INACTIVE) { <ide> rc.setStatus(null); <ide> rc.setOverrideExternalId(null); <ide> rc.setOverrideTimeStamp(null); <ide> for (CourseRequestInterface.Request c: request.getCourses()) <ide> if (c.hasRequestedCourse()) { <ide> for (CourseRequestInterface.RequestedCourse rc: c.getRequestedCourse()) { <del> if (rc.getStatus() != null && rc.getStatus() != RequestedCourseStatus.OVERRIDE_REJECTED) { <add> if (rc.getStatus() != null && rc.getStatus() != RequestedCourseStatus.OVERRIDE_REJECTED && rc.getStatus() != RequestedCourseStatus.WAITLIST_INACTIVE) { <ide> rc.setStatus(null); <ide> rc.setOverrideExternalId(null); <ide> rc.setOverrideTimeStamp(null); <ide> for (CourseRequestInterface.Request c: request.getAlternatives()) <ide> if (c.hasRequestedCourse()) { <ide> for (CourseRequestInterface.RequestedCourse rc: c.getRequestedCourse()) { <del> if (rc.getStatus() != null && rc.getStatus() != RequestedCourseStatus.OVERRIDE_REJECTED) { <add> if (rc.getStatus() != null && rc.getStatus() != RequestedCourseStatus.OVERRIDE_REJECTED && rc.getStatus() != RequestedCourseStatus.WAITLIST_INACTIVE) { <ide> rc.setStatus(null); <ide> rc.setOverrideExternalId(null); <ide> rc.setOverrideTimeStamp(null);
Java
mit
bc5f0249049819f258d9c189497a0146cda5f1d5
0
kmizu/jcombinator
package com.github.kmizu.jcombinator; import com.github.kmizu.jcombinator.datatype.Tuple2; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import static org.junit.Assert.*; import static com.github.kmizu.jcombinator.Parser.*; import static com.github.kmizu.jcombinator.TestHelper.*; import static com.github.kmizu.jcombinator.Functions.*; @RunWith(JUnit4.class) public class PrimitiveTest { @Test public void testStringParser() { Parser<String> helloWorld = string("Hello, World"); helloWorld.invoke("Hello, World").fold( (success) -> { assertEquals("Hello, World", success.value()); assertEquals("", success.next()); }, (failure) -> { assertTrue(false); } ); } @Test public void testManyParser() { let(string("a").many(), ax -> { ax.invoke("aaaaa").fold( (success) -> { assertEquals(listOf("a", "a", "a", "a", "a"), success.value()); assertEquals("", success.next()); }, (failure) -> { assertTrue(false); } ); }); } @Test public void testCat() { let(string("a").cat(string("b")), ab -> { ab.invoke("ab").fold( (success) -> { assertEquals(new Tuple2<>("a", "b"), success.value()); assertEquals("", success.next()); }, (failure) -> { assertTrue(false); } ); }); } }
src/test/java/com/github/kmizu/jcombinator/PrimitiveTest.java
package com.github.kmizu.jcombinator; import com.github.kmizu.jcombinator.datatype.Tuple2; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import static org.junit.Assert.*; import static com.github.kmizu.jcombinator.Parser.*; import static com.github.kmizu.jcombinator.TestHelper.*; import static com.github.kmizu.jcombinator.Functions.*; @RunWith(JUnit4.class) public class PrimitiveTest { @Test public void testStringParser() { Parser<String> helloWorld = string("Hello, World"); helloWorld.invoke("Hello, World").fold( (success) -> { assertEquals("Hello, World", success.value()); assertEquals("", success.next()); return null; }, (failure) -> { assertTrue(false); return null; } ); } @Test public void testManyParser() { let(string("a").many(), ax -> { ax.invoke("aaaaa").fold( (success) -> { assertEquals(listOf("a", "a", "a", "a", "a"), success.value()); assertEquals("", success.next()); return null; }, (failure) -> { assertTrue(false); return null; } ); }); } @Test public void testCat() { let(string("a").cat(string("b")), ab -> { ab.invoke("ab").fold( (success) -> { assertEquals(new Tuple2<>("a", "b"), success.value()); assertEquals("", success.next()); return null; }, (failure) -> { assertTrue(false); return null; } ); }); } }
Remove extra 'return null'
src/test/java/com/github/kmizu/jcombinator/PrimitiveTest.java
Remove extra 'return null'
<ide><path>rc/test/java/com/github/kmizu/jcombinator/PrimitiveTest.java <ide> (success) -> { <ide> assertEquals("Hello, World", success.value()); <ide> assertEquals("", success.next()); <del> return null; <ide> }, <ide> (failure) -> { <ide> assertTrue(false); <del> return null; <ide> } <ide> ); <ide> } <ide> (success) -> { <ide> assertEquals(listOf("a", "a", "a", "a", "a"), success.value()); <ide> assertEquals("", success.next()); <del> return null; <ide> }, <ide> (failure) -> { <ide> assertTrue(false); <del> return null; <ide> } <ide> ); <ide> }); <ide> (success) -> { <ide> assertEquals(new Tuple2<>("a", "b"), success.value()); <ide> assertEquals("", success.next()); <del> return null; <ide> }, <ide> (failure) -> { <ide> assertTrue(false); <del> return null; <ide> } <ide> ); <ide>
Java
lgpl-2.1
132434e8f20f825bb93647b966265b5a4ae31d7d
0
fpuna-cia/karaku,roskoff/karaku,fpuna-cia/karaku,roskoff/karaku,fpuna-cia/karaku,roskoff/karaku,roskoff/karaku,fpuna-cia/karaku,roskoff/karaku,fpuna-cia/karaku
/** * @I18nHelper 1.0 25/03/13. Sistema Integral de Gestion Hospitalaria */ package py.una.med.base.util; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Locale; import java.util.ResourceBundle; import java.util.Scanner; import javax.faces.context.FacesContext; import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.Resource; import org.springframework.stereotype.Component; import py.una.med.base.configuration.SIGHConfiguration; import py.una.med.base.exception.KeyNotFoundException; import py.una.med.base.model.DisplayName; /** * Clase que sirve como punto de acceso unico para la internacionalizacion * * @author Arturo Volpe */ @Component public class I18nHelper { private static ArrayList<ResourceBundle> bundles; private static List<String> getBundlesLocation() { Resource resource = new ClassPathResource( SIGHConfiguration.CONFIG_LOCATION); Scanner sc; try { sc = new Scanner(resource.getInputStream()); } catch (IOException e) { throw new RuntimeException(e); } String line = ""; while (sc.hasNextLine()) { line = sc.nextLine(); if (line.startsWith("language_bundles")) { break; } } sc.close(); if (!line.contains("=")) { throw new RuntimeException( "Archivo de configuraicon no contiene ubicacion de archivos de idiomas"); } String value = line.split("=")[1]; return Arrays.asList(value.split(" ")); } private static List<ResourceBundle> getBundles() { if (bundles != null) return bundles; bundles = new ArrayList<ResourceBundle>(); List<String> bundlesLocation = getBundlesLocation(); for (String bundle : bundlesLocation) { if (bundle.equals("")) continue; FacesContext facesContext = FacesContext.getCurrentInstance(); Locale locale = facesContext.getViewRoot().getLocale(); ResourceBundle toAdd = ResourceBundle.getBundle(bundle, locale); bundles.add(toAdd); } return bundles; } private static String findInBundles(String key) throws KeyNotFoundException { for (ResourceBundle bundle : getBundles()) { try { if (bundle.getString(key) != null) return bundle.getString(key); } catch (Exception e) { } } throw new KeyNotFoundException(key); } public String getString(String key) { return findInBundles(key); } public static String getMessage(String key) { return findInBundles(key); } public static List<String> convertStrings(String ... strings) { ArrayList<String> convert = new ArrayList<String>(strings.length); for (String s : strings) { convert.add(getMessage(s)); } return convert; } public static boolean compare(String key, String value) { return getMessage(key).equals(value); } public static String getName(DisplayName displayName) { if ("".equals(displayName.toString())) return ""; return getMessage(displayName.key().substring(1, displayName.key().length() - 1)); } }
src/main/java/py/una/med/base/util/I18nHelper.java
/** * @I18nHelper 1.0 25/03/13. Sistema Integral de Gestion Hospitalaria */ package py.una.med.base.util; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Locale; import java.util.ResourceBundle; import java.util.Scanner; import javax.faces.context.FacesContext; import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.Resource; import org.springframework.stereotype.Component; import py.una.med.base.configuration.SIGHConfiguration; import py.una.med.base.exception.KeyNotFoundException; import py.una.med.base.model.DisplayName; /** * Clase que sirve como punto de acceso unico para la internacionalizacion * * @author Arturo Volpe */ @Component public class I18nHelper { private static ArrayList<ResourceBundle> bundles; private static List<String> getBundlesLocation() { Resource resource = new ClassPathResource( SIGHConfiguration.CONFIG_LOCATION); Scanner sc; try { sc = new Scanner(resource.getInputStream()); } catch (IOException e) { throw new RuntimeException(e); } String line = ""; while (sc.hasNextLine()) { line = sc.nextLine(); if (line.startsWith("language_bundles")) { break; } } sc.close(); if (!line.contains("=")) { throw new RuntimeException( "Archivo de configuraicon no contiene ubicacion de archivos de idiomas"); } String value = line.split("=")[1]; return Arrays.asList(value.split(" ")); } private static List<ResourceBundle> getBundles() { if (bundles != null) return bundles; bundles = new ArrayList<ResourceBundle>(); List<String> bundlesLocation = getBundlesLocation(); for (String bundle : bundlesLocation) { if (bundle.equals("")) continue; FacesContext facesContext = FacesContext.getCurrentInstance(); Locale locale = facesContext.getViewRoot().getLocale(); ResourceBundle toAdd = ResourceBundle.getBundle(bundle, locale); bundles.add(toAdd); } return bundles; } private static String findInBundles(String key) throws KeyNotFoundException { for (ResourceBundle bundle : getBundles()) { try { if (bundle.getString(key) != null) return bundle.getString(key); } catch (Exception e) { } } throw new KeyNotFoundException(key); } public String getString(String key) { return findInBundles(key); } public static String getMessage(String key) { return findInBundles(key); } public static List<String> convertStrings(String ... strings) { ArrayList<String> convert = new ArrayList<String>(strings.length); for (String s : strings) { convert.add(getMessage(s)); } return convert; } public static boolean compare(String key, String value) { return getMessage(key).equals(value); } public static String getName(DisplayName displayName) { if ("".equals(displayName)) return ""; return getMessage(displayName.key().substring(1, displayName.key().length() - 1)); } }
Evitar el uso de equals entre clases e interfaces no relacionadas Equals entre clases e interfaces no relacionadas debe siempre retornar false. Teniendo en cuenta esto se corrige el metodo getName de I18nHelper. refs #2648 Signed-off-by: Uriel Gonzalez <[email protected]>
src/main/java/py/una/med/base/util/I18nHelper.java
Evitar el uso de equals entre clases e interfaces no relacionadas
<ide><path>rc/main/java/py/una/med/base/util/I18nHelper.java <ide> <ide> public static String getName(DisplayName displayName) { <ide> <del> if ("".equals(displayName)) <add> if ("".equals(displayName.toString())) <ide> return ""; <ide> return getMessage(displayName.key().substring(1, <ide> displayName.key().length() - 1));
Java
apache-2.0
12c44f219ddf7473835ca7085de3fcbf9af9d37a
0
IWSDevelopers/iws,IWSDevelopers/iws
/* * ============================================================================= * Copyright 1998-2014, IAESTE Internet Development Team. All rights reserved. * ---------------------------------------------------------------------------- * Project: IntraWeb Services (iws-ejb) - net.iaeste.iws.ejb.notifications.NotificationManager * ----------------------------------------------------------------------------- * This software is provided by the members of the IAESTE Internet Development * Team (IDT) to IAESTE A.s.b.l. It is for internal use only and may not be * redistributed. IAESTE A.s.b.l. is not permitted to sell this software. * * This software is provided "as is"; the IDT or individuals within the IDT * cannot be held legally responsible for any problems the software may cause. * ============================================================================= */ package net.iaeste.iws.ejb.notifications; import net.iaeste.iws.api.exceptions.IWSException; import net.iaeste.iws.common.configuration.Settings; import net.iaeste.iws.common.notification.Notifiable; import net.iaeste.iws.common.notification.NotificationField; import net.iaeste.iws.common.notification.NotificationType; import net.iaeste.iws.common.utils.Observer; import net.iaeste.iws.core.notifications.Notifications; import net.iaeste.iws.persistence.Authentication; import net.iaeste.iws.persistence.NotificationDao; import net.iaeste.iws.persistence.entities.UserEntity; import net.iaeste.iws.persistence.entities.notifications.NotificationConsumerEntity; import net.iaeste.iws.persistence.entities.notifications.NotificationJobEntity; import net.iaeste.iws.persistence.entities.notifications.NotificationJobTaskEntity; import net.iaeste.iws.persistence.jpa.NotificationJpaDao; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.ejb.TransactionAttribute; import javax.ejb.TransactionAttributeType; import javax.ejb.TransactionManagement; import javax.ejb.TransactionManagementType; import javax.persistence.EntityManager; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectOutputStream; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Map; /** * Notes; It is good to see the notification system evolving. There is just a * couple of things that has to be clarified. One is that the actual handling * of sending, should be done in different ways. If users request that * information is send at specific intervals, daily, weekly, etc. then the * handling should be done via a "cron" job. That is a Timer job in EJB, or * perhaps via an external queuing system like Quartz. * * @author Pavel Fiala / last $Author:$ * @version $Revision:$ / $Date:$ * @since IWS 1.0 */ @TransactionAttribute(TransactionAttributeType.REQUIRED) @TransactionManagement(TransactionManagementType.CONTAINER) public class NotificationManager implements Notifications { private static final Logger log = LoggerFactory.getLogger(NotificationManager.class); private final EntityManager iwsEntityManager; private final EntityManager mailingEntityManager; private final Settings settings; private final NotificationDao dao; private final NotificationMessageGenerator messageGenerator; private final List<Observer> observers = new ArrayList<>(10); private final boolean hostedInBean; public NotificationManager(final EntityManager iwsEntityManager, final EntityManager mailingEntityManager, final Settings settings, final NotificationMessageGenerator messageGenerator, final boolean hostedInBean) { this.iwsEntityManager = iwsEntityManager; this.mailingEntityManager = mailingEntityManager; this.settings = settings; this.messageGenerator = messageGenerator; this.hostedInBean = hostedInBean; dao = new NotificationJpaDao(iwsEntityManager); } /** * Startup notification manager - load from DB registered notification consumers and subcribe them to the manager */ public void startupConsumers() { final List<NotificationConsumerEntity> consumers = dao.findActiveNotificationConsumers(); final NotificationConsumerClassLoader classLoader = new NotificationConsumerClassLoader(); for (final NotificationConsumerEntity consumer : consumers) { final Observer observer = classLoader.findConsumerClass(consumer.getClassName(), iwsEntityManager, mailingEntityManager, settings); observer.setId(consumer.getId()); addObserver(observer); } } /** * {@inheritDoc} */ @Override @TransactionAttribute(TransactionAttributeType.REQUIRED) public void processJobs() { final Date now = new Date(); final List<NotificationJobEntity> unprocessedJobs = dao.findUnprocessedNotificationJobs(now); if (!unprocessedJobs.isEmpty()) { for (final NotificationJobEntity job : unprocessedJobs) { prepareJobTasks(job); job.setNotified(true); job.setModified(new Date()); dao.persist(job); } // notifyObservers(); } //TODO call observers even there is no new job. however, there is probably some tasks in the db... can be removed once the db (transaction?) issue is solved notifyObservers(); } private void prepareJobTasks(final NotificationJobEntity job) { for (final Observer observer : observers) { final NotificationConsumerEntity consumer = dao.findNotificationConsumerById(observer.getId()); final NotificationJobTaskEntity task = new NotificationJobTaskEntity(job, consumer); dao.persist(task); } } /** * {@inheritDoc} */ @Override public void notify(final Authentication authentication, final Notifiable obj, final NotificationType type) { // Save the general information about the Object to be notified. // final List<UserEntity> users = getRecipients(obj, type); // final Map<String, String> messageTexts = messageGenerator.generateFromTemplate(obj, type); // for (final UserEntity user : users) { //get user settings //TODO user should have permanent entry in the notification setting to receive messages about NotificationSubject.USER immediately // final UserNotificationEntity userNotification = dao.findUserNotificationSetting(user, type); // // if (userNotification != null) { // final NotificationMessageEntity message = new NotificationMessageEntity(); // message.setUser(user); // message.setStatus(NotificationMessageStatus.NEW); // message.setProcessAfter(getNotificationTime(userNotification.getFrequency())); // only immediate messages for now // message.setProcessAfter(new Date().toDate()); // message.setNotificationDeliveryMode(NotificationDeliveryMode.EMAIL); // message.setMessage(messageTexts.get("body")); // message.setMessageTitle(messageTexts.get("title")); // // dao.persist(message); // } // } // notifyObservers(); log.info("New '" + type + "' notification request at NotificationManager"); if (obj != null) { try { final ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); final ObjectOutputStream objectStream = new ObjectOutputStream(outputStream); final Map<NotificationField, String> fields = obj.prepareNotifiableFields(type); objectStream.writeObject(fields); final byte[] bytes = outputStream.toByteArray(); final NotificationJobEntity job = new NotificationJobEntity(type, bytes); dao.persist(job); log.info("New notification job for '" + type + "' created"); if (!hostedInBean) { processJobs(); } } catch (IWSException e) { log.error("Preparing notification job failed", e); } catch (IOException ignored) { //TODO write to log and skip the task or throw an exception? // LOG.warn("Serializing of Notifiable instance for NotificationType " + type + " failed", ignored); log.warn("Serializing of Notifiable instance for NotificationType " + type + " failed"); } } } /** * {@inheritDoc} */ @Override public void notify(final UserEntity user) { // final List<UserEntity> users = getRecipients(user, NotificationType.RESET_PASSWORD); // if(users.size()==1) { // final Map<String, String> messageTexts = messageGenerator.generateFromTemplate(user, NotificationType.RESET_PASSWORD); // final NotificationMessageEntity message = new NotificationMessageEntity(); // message.setStatus(NotificationMessageStatus.NEW); // message.setProcessAfter(getNotificationTime(userNotification.getFrequency())); //only immediate messages for now // message.setProcessAfter(new Date().toDate()); // // message.setMessage(messageTexts.get("body")); // message.setMessageTitle(messageTexts.get("title")); // // dao.persist(message); // notifyObservers(); // } else { //write to log? // } log.info("New 'user' notification request at NotificationManager"); if (user != null) { try { final ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); final ObjectOutputStream objectStream = new ObjectOutputStream(outputStream); final Map<NotificationField, String> fields = user.prepareNotifiableFields(NotificationType.RESET_PASSWORD); objectStream.writeObject(fields); final byte[] bytes = outputStream.toByteArray(); final NotificationJobEntity job = new NotificationJobEntity(NotificationType.RESET_PASSWORD, bytes); dao.persist(job); log.info("New notification job for '" + NotificationType.RESET_PASSWORD + "' created"); if (!hostedInBean) { processJobs(); } } catch (IWSException e) { log.error("Preparing notification job failed", e); } catch (IOException ignored) { //TODO write to log and skip the task or throw an exception? // LOG.warn("Serializing of Notifiable instance for NotificationType " + type + " failed", ignored); log.warn("Serializing of Notifiable instance for NotificationType.RESET_PASSWORD failed"); } } } @Override public void addObserver(final Observer observer) { observers.add(observer); } @Override public void deleteObserver(final Observer observer) { observers.remove(observer); } @Override public void notifyObservers() { for (final Observer observer : observers) { observer.update(this); } } public int getObserversCount() { return observers.size(); } }
iws-ejb/src/main/java/net/iaeste/iws/ejb/notifications/NotificationManager.java
/* * ============================================================================= * Copyright 1998-2014, IAESTE Internet Development Team. All rights reserved. * ---------------------------------------------------------------------------- * Project: IntraWeb Services (iws-ejb) - net.iaeste.iws.ejb.notifications.NotificationManager * ----------------------------------------------------------------------------- * This software is provided by the members of the IAESTE Internet Development * Team (IDT) to IAESTE A.s.b.l. It is for internal use only and may not be * redistributed. IAESTE A.s.b.l. is not permitted to sell this software. * * This software is provided "as is"; the IDT or individuals within the IDT * cannot be held legally responsible for any problems the software may cause. * ============================================================================= */ package net.iaeste.iws.ejb.notifications; import net.iaeste.iws.api.exceptions.IWSException; import net.iaeste.iws.common.configuration.Settings; import net.iaeste.iws.common.notification.Notifiable; import net.iaeste.iws.common.notification.NotificationField; import net.iaeste.iws.common.notification.NotificationType; import net.iaeste.iws.common.utils.Observer; import net.iaeste.iws.core.notifications.Notifications; import net.iaeste.iws.persistence.Authentication; import net.iaeste.iws.persistence.NotificationDao; import net.iaeste.iws.persistence.entities.UserEntity; import net.iaeste.iws.persistence.entities.notifications.NotificationConsumerEntity; import net.iaeste.iws.persistence.entities.notifications.NotificationJobEntity; import net.iaeste.iws.persistence.entities.notifications.NotificationJobTaskEntity; import net.iaeste.iws.persistence.jpa.NotificationJpaDao; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.persistence.EntityManager; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectOutputStream; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Map; /** * Notes; It is good to see the notification system evolving. There is just a * couple of things that has to be clarified. One is that the actual handling * of sending, should be done in different ways. If users request that * information is send at specific intervals, daily, weekly, etc. then the * handling should be done via a "cron" job. That is a Timer job in EJB, or * perhaps via an external queuing system like Quartz. * * @author Pavel Fiala / last $Author:$ * @version $Revision:$ / $Date:$ * @since IWS 1.0 */ public final class NotificationManager implements Notifications { private static final Logger log = LoggerFactory.getLogger(NotificationManager.class); private final EntityManager iwsEntityManager; private final EntityManager mailingEntityManager; private final Settings settings; private final NotificationDao dao; private final NotificationMessageGenerator messageGenerator; private final List<Observer> observers = new ArrayList<>(10); private final boolean hostedInBean; public NotificationManager(final EntityManager iwsEntityManager, final EntityManager mailingEntityManager, final Settings settings, final NotificationMessageGenerator messageGenerator, final boolean hostedInBean) { this.iwsEntityManager = iwsEntityManager; this.mailingEntityManager = mailingEntityManager; this.settings = settings; this.messageGenerator = messageGenerator; this.hostedInBean = hostedInBean; dao = new NotificationJpaDao(iwsEntityManager); } /** * Startup notification manager - load from DB registered notification consumers and subcribe them to the manager */ public void startupConsumers() { final List<NotificationConsumerEntity> consumers = dao.findActiveNotificationConsumers(); final NotificationConsumerClassLoader classLoader = new NotificationConsumerClassLoader(); for (final NotificationConsumerEntity consumer : consumers) { final Observer observer = classLoader.findConsumerClass(consumer.getClassName(), iwsEntityManager, mailingEntityManager, settings); observer.setId(consumer.getId()); addObserver(observer); } } /** * {@inheritDoc} */ @Override public void processJobs() { final Date now = new Date(); final List<NotificationJobEntity> unprocessedJobs = dao.findUnprocessedNotificationJobs(now); if (!unprocessedJobs.isEmpty()) { for (final NotificationJobEntity job : unprocessedJobs) { prepareJobTasks(job); job.setNotified(true); job.setModified(new Date()); dao.persist(job); } // notifyObservers(); } //TODO call observers even there is no new job. however, there is probably some tasks in the db... can be removed once the db (transaction?) issue is solved notifyObservers(); } private void prepareJobTasks(final NotificationJobEntity job) { for (final Observer observer : observers) { final NotificationConsumerEntity consumer = dao.findNotificationConsumerById(observer.getId()); final NotificationJobTaskEntity task = new NotificationJobTaskEntity(job, consumer); dao.persist(task); } } /** * {@inheritDoc} */ @Override public void notify(final Authentication authentication, final Notifiable obj, final NotificationType type) { // Save the general information about the Object to be notified. // final List<UserEntity> users = getRecipients(obj, type); // final Map<String, String> messageTexts = messageGenerator.generateFromTemplate(obj, type); // for (final UserEntity user : users) { //get user settings //TODO user should have permanent entry in the notification setting to receive messages about NotificationSubject.USER immediately // final UserNotificationEntity userNotification = dao.findUserNotificationSetting(user, type); // // if (userNotification != null) { // final NotificationMessageEntity message = new NotificationMessageEntity(); // message.setUser(user); // message.setStatus(NotificationMessageStatus.NEW); // message.setProcessAfter(getNotificationTime(userNotification.getFrequency())); // only immediate messages for now // message.setProcessAfter(new Date().toDate()); // message.setNotificationDeliveryMode(NotificationDeliveryMode.EMAIL); // message.setMessage(messageTexts.get("body")); // message.setMessageTitle(messageTexts.get("title")); // // dao.persist(message); // } // } // notifyObservers(); log.info("New '" + type + "' notification request at NotificationManager"); if (obj != null) { try { final ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); final ObjectOutputStream objectStream = new ObjectOutputStream(outputStream); final Map<NotificationField, String> fields = obj.prepareNotifiableFields(type); objectStream.writeObject(fields); final byte[] bytes = outputStream.toByteArray(); final NotificationJobEntity job = new NotificationJobEntity(type, bytes); dao.persist(job); log.info("New notification job for '" + type + "' created"); if (!hostedInBean) { processJobs(); } } catch (IWSException e) { log.error("Preparing notification job failed", e); } catch (IOException ignored) { //TODO write to log and skip the task or throw an exception? // LOG.warn("Serializing of Notifiable instance for NotificationType " + type + " failed", ignored); log.warn("Serializing of Notifiable instance for NotificationType " + type + " failed"); } } } /** * {@inheritDoc} */ @Override public void notify(final UserEntity user) { // final List<UserEntity> users = getRecipients(user, NotificationType.RESET_PASSWORD); // if(users.size()==1) { // final Map<String, String> messageTexts = messageGenerator.generateFromTemplate(user, NotificationType.RESET_PASSWORD); // final NotificationMessageEntity message = new NotificationMessageEntity(); // message.setStatus(NotificationMessageStatus.NEW); // message.setProcessAfter(getNotificationTime(userNotification.getFrequency())); //only immediate messages for now // message.setProcessAfter(new Date().toDate()); // // message.setMessage(messageTexts.get("body")); // message.setMessageTitle(messageTexts.get("title")); // // dao.persist(message); // notifyObservers(); // } else { //write to log? // } log.info("New 'user' notification request at NotificationManager"); if (user != null) { try { final ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); final ObjectOutputStream objectStream = new ObjectOutputStream(outputStream); final Map<NotificationField, String> fields = user.prepareNotifiableFields(NotificationType.RESET_PASSWORD); objectStream.writeObject(fields); final byte[] bytes = outputStream.toByteArray(); final NotificationJobEntity job = new NotificationJobEntity(NotificationType.RESET_PASSWORD, bytes); dao.persist(job); log.info("New notification job for '" + NotificationType.RESET_PASSWORD + "' created"); if (!hostedInBean) { processJobs(); } } catch (IWSException e) { log.error("Preparing notification job failed", e); } catch (IOException ignored) { //TODO write to log and skip the task or throw an exception? // LOG.warn("Serializing of Notifiable instance for NotificationType " + type + " failed", ignored); log.warn("Serializing of Notifiable instance for NotificationType.RESET_PASSWORD failed"); } } } @Override public void addObserver(final Observer observer) { observers.add(observer); } @Override public void deleteObserver(final Observer observer) { observers.remove(observer); } @Override public void notifyObservers() { for (final Observer observer : observers) { observer.update(this); } } public int getObserversCount() { return observers.size(); } }
Added Transaction Control to Job Processing. The problem we have had with the Database being unable to create multiple new Prepared Statements, may be related to the missing Transactional Control added to the Notification Manager Class. It is another attempt at trying to resolve our problems with the timer performing a rollback and killing all changes. Thus eventually killing itself.
iws-ejb/src/main/java/net/iaeste/iws/ejb/notifications/NotificationManager.java
Added Transaction Control to Job Processing.
<ide><path>ws-ejb/src/main/java/net/iaeste/iws/ejb/notifications/NotificationManager.java <ide> import org.slf4j.Logger; <ide> import org.slf4j.LoggerFactory; <ide> <add>import javax.ejb.TransactionAttribute; <add>import javax.ejb.TransactionAttributeType; <add>import javax.ejb.TransactionManagement; <add>import javax.ejb.TransactionManagementType; <ide> import javax.persistence.EntityManager; <ide> import java.io.ByteArrayOutputStream; <ide> import java.io.IOException; <ide> * @version $Revision:$ / $Date:$ <ide> * @since IWS 1.0 <ide> */ <del>public final class NotificationManager implements Notifications { <add>@TransactionAttribute(TransactionAttributeType.REQUIRED) <add>@TransactionManagement(TransactionManagementType.CONTAINER) <add>public class NotificationManager implements Notifications { <ide> <ide> private static final Logger log = LoggerFactory.getLogger(NotificationManager.class); <ide> <ide> * {@inheritDoc} <ide> */ <ide> @Override <add> @TransactionAttribute(TransactionAttributeType.REQUIRED) <ide> public void processJobs() { <ide> final Date now = new Date(); <ide> final List<NotificationJobEntity> unprocessedJobs = dao.findUnprocessedNotificationJobs(now);
Java
bsd-3-clause
bb3dae046ecff80ca458d273035f97ed84ab457d
0
agmip/translator-dssat,MengZhang/translator-dssat
package org.agmip.translators.dssat; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import static org.agmip.translators.dssat.DssatCommonInput.copyItem; import static org.agmip.util.MapUtil.*; /** * DSSAT Experiment Data I/O API Class * * @author Meng Zhang * @version 1.0 */ public class DssatXFileOutput extends DssatCommonOutput { public static final DssatCRIDHelper crHelper = new DssatCRIDHelper(); /** * DSSAT Experiment Data Output method * * @param arg0 file output path * @param result data holder object */ @Override public void writeFile(String arg0, Map result) { // Initial variables HashMap expData = (HashMap) result; HashMap soilData = getObjectOr(result, "soil", new HashMap()); HashMap wthData = getObjectOr(result, "weather", new HashMap()); BufferedWriter bwX; // output object StringBuilder sbGenData = new StringBuilder(); // construct the data info in the output StringBuilder sbNotesData = new StringBuilder(); // construct the data info in the output StringBuilder sbData = new StringBuilder(); // construct the data info in the output StringBuilder eventPart2 = new StringBuilder(); // output string for second part of event data HashMap secData; ArrayList subDataArr; // Arraylist for event data holder HashMap subData; ArrayList secDataArr; // Arraylist for section data holder HashMap sqData; ArrayList<HashMap> evtArr; // Arraylist for section data holder HashMap evtData; // int trmnNum; // total numbers of treatment in the data holder int cuNum; // total numbers of cultivars in the data holder int flNum; // total numbers of fields in the data holder int saNum; // total numbers of soil analysis in the data holder int icNum; // total numbers of initial conditions in the data holder int mpNum; // total numbers of plaintings in the data holder int miNum; // total numbers of irrigations in the data holder int mfNum; // total numbers of fertilizers in the data holder int mrNum; // total numbers of residues in the data holder int mcNum; // total numbers of chemical in the data holder int mtNum; // total numbers of tillage in the data holder int meNum; // total numbers of enveronment modification in the data holder int mhNum; // total numbers of harvest in the data holder int smNum; // total numbers of simulation controll record ArrayList<HashMap> sqArr; // array for treatment record ArrayList cuArr = new ArrayList(); // array for cultivars record ArrayList flArr = new ArrayList(); // array for fields record ArrayList saArr = new ArrayList(); // array for soil analysis record ArrayList icArr = new ArrayList(); // array for initial conditions record ArrayList mpArr = new ArrayList(); // array for plaintings record ArrayList miArr = new ArrayList(); // array for irrigations record ArrayList mfArr = new ArrayList(); // array for fertilizers record ArrayList mrArr = new ArrayList(); // array for residues record ArrayList mcArr = new ArrayList(); // array for chemical record ArrayList mtArr = new ArrayList(); // array for tillage record ArrayList<HashMap> meArr; // array for enveronment modification record ArrayList mhArr = new ArrayList(); // array for harvest record ArrayList<HashMap> smArr; // array for simulation control record String exName; try { // Set default value for missing data if (expData == null || expData.isEmpty()) { return; } // decompressData((HashMap) result); setDefVal(); // Initial BufferedWriter String fileName = getFileName(result, "X"); arg0 = revisePath(arg0); outputFile = new File(arg0 + fileName); bwX = new BufferedWriter(new FileWriter(outputFile)); // Output XFile // EXP.DETAILS Section sbGenData.append(String.format("*EXP.DETAILS: %1$-10s %2$s\r\n\r\n", getExName(result), getObjectOr(expData, "local_name", defValBlank).toString())); // GENERAL Section sbGenData.append("*GENERAL\r\n"); // People if (!getObjectOr(expData, "people", "").equals("")) { sbGenData.append(String.format("@PEOPLE\r\n %1$s\r\n", getObjectOr(expData, "people", defValBlank).toString())); } // Address if (getObjectOr(expData, "institution", "").equals("")) { if (!getObjectOr(expData, "fl_loc_1", "").equals("") && getObjectOr(expData, "fl_loc_2", "").equals("") && getObjectOr(expData, "fl_loc_3", "").equals("")) { sbGenData.append(String.format("@ADDRESS\r\n %3$s, %2$s, %1$s\r\n", getObjectOr(expData, "fl_loc_1", defValBlank).toString(), getObjectOr(expData, "fl_loc_2", defValBlank).toString(), getObjectOr(expData, "fl_loc_3", defValBlank).toString())); } } else { sbGenData.append(String.format("@ADDRESS\r\n %1$s\r\n", getObjectOr(expData, "institution", defValBlank).toString())); } // Site if (!getObjectOr(expData, "site", "").equals("")) { sbGenData.append(String.format("@SITE\r\n %1$s\r\n", getObjectOr(expData, "site", defValBlank).toString())); } // Plot Info if (isPlotInfoExist(expData)) { sbGenData.append("@ PAREA PRNO PLEN PLDR PLSP PLAY HAREA HRNO HLEN HARM.........\r\n"); sbGenData.append(String.format(" %1$6s %2$5s %3$5s %4$5s %5$5s %6$-5s %7$5s %8$5s %9$5s %10$-15s\r\n", formatNumStr(6, expData, "plta", defValR), formatNumStr(5, expData, "pltr#", defValI), formatNumStr(5, expData, "pltln", defValR), formatNumStr(5, expData, "pldr", defValI), formatNumStr(5, expData, "pltsp", defValI), getObjectOr(expData, "plot_layout", defValC).toString(), formatNumStr(5, expData, "pltha", defValR), formatNumStr(5, expData, "plth#", defValI), formatNumStr(5, expData, "plthl", defValR), getObjectOr(expData, "plthm", defValC).toString())); } // Notes if (!getObjectOr(expData, "tr_notes", "").equals("")) { sbNotesData.append("@NOTES\r\n"); String notes = getObjectOr(expData, "tr_notes", defValC).toString(); notes = notes.replaceAll("\\\\r\\\\n", "\r\n"); // If notes contain newline code, then write directly if (notes.indexOf("\r\n") >= 0) { // sbData.append(String.format(" %1$s\r\n", notes)); sbNotesData.append(notes); } // Otherwise, add newline for every 75-bits charactors else { while (notes.length() > 75) { sbNotesData.append(" ").append(notes.substring(0, 75)).append("\r\n"); notes = notes.substring(75); } sbNotesData.append(" ").append(notes).append("\r\n"); } } sbData.append("\r\n"); // TREATMENT Section sqArr = getDataList(expData, "dssat_sequence", "data"); evtArr = getDataList(expData, "management", "events"); meArr = getDataList(expData, "dssat_environment_modification", "data"); smArr = getDataList(expData, "dssat_simulation_control", "data"); boolean isSmExist = !smArr.isEmpty(); String seqId; String em; String sm; sbData.append("*TREATMENTS -------------FACTOR LEVELS------------\r\n"); sbData.append("@N R O C TNAME.................... CU FL SA IC MP MI MF MR MC MT ME MH SM\r\n"); // if there is no sequence info, create dummy data if (sqArr.isEmpty()) { sqArr.add(new HashMap()); } // Set field info HashMap flData = new HashMap(); copyItem(flData, expData, "id_field"); if (wthData.isEmpty()) { // copyItem(flData, expData, "wst_id"); flData.put("wst_id", getWthFileName(expData)); } else { flData.put("wst_id", getWthFileName(wthData)); } copyItem(flData, expData, "flsl"); copyItem(flData, expData, "flob"); copyItem(flData, expData, "fl_drntype"); copyItem(flData, expData, "fldrd"); copyItem(flData, expData, "fldrs"); copyItem(flData, expData, "flst"); copyItem(flData, soilData, "sltx"); copyItem(flData, soilData, "sldp"); copyItem(flData, expData, "soil_id"); copyItem(flData, expData, "fl_name"); copyItem(flData, expData, "fl_lat"); copyItem(flData, expData, "fl_long"); copyItem(flData, expData, "flele"); copyItem(flData, expData, "farea"); copyItem(flData, expData, "fllwr"); copyItem(flData, expData, "flsla"); copyItem(flData, getObjectOr(expData, "dssat_info", new HashMap()), "flhst"); copyItem(flData, getObjectOr(expData, "dssat_info", new HashMap()), "fhdur"); // remove the "_trno" in the soil_id when soil analysis is available String soilId = getValueOr(flData, "soil_id", ""); if (soilId.length() > 10 && soilId.matches("\\w+_\\d+")) { flData.put("soil_id", soilId.replaceAll("_\\d+$", "")); } flNum = setSecDataArr(flData, flArr); // Set initial condition info icNum = setSecDataArr(getObjectOr(expData, "initial_conditions", new HashMap()), icArr); // Set soil analysis info // ArrayList<HashMap> icSubArr = getDataList(expData, "initial_condition", "soilLayer"); ArrayList<HashMap> soilLarys = getDataList(expData, "soil", "soilLayer"); // // If it is stored in the initial condition block // if (isSoilAnalysisExist(icSubArr)) { // HashMap saData = new HashMap(); // ArrayList<HashMap> saSubArr = new ArrayList<HashMap>(); // HashMap saSubData; // for (int i = 0; i < icSubArr.size(); i++) { // saSubData = new HashMap(); // copyItem(saSubData, icSubArr.get(i), "sabl", "icbl", false); // copyItem(saSubData, icSubArr.get(i), "sasc", "slsc", false); // saSubArr.add(saSubData); // } // copyItem(saData, soilData, "sadat"); // saData.put("soilLayer", saSubArr); // saNum = setSecDataArr(saData, saArr); // } else // If it is stored in the soil block if (isSoilAnalysisExist(soilLarys)) { HashMap saData = new HashMap(); ArrayList<HashMap> saSubArr = new ArrayList<HashMap>(); HashMap saSubData; for (int i = 0; i < soilLarys.size(); i++) { saSubData = new HashMap(); copyItem(saSubData, soilLarys.get(i), "sabl", "sllb", false); copyItem(saSubData, soilLarys.get(i), "sasc", "slsc", false); saSubArr.add(saSubData); } copyItem(saData, soilData, "sadat"); saData.put("soilLayer", saSubArr); saNum = setSecDataArr(saData, saArr); } else { saNum = 0; } // Set sequence related block info for (int i = 0; i < sqArr.size(); i++) { sqData = sqArr.get(i); seqId = getValueOr(sqData, "seqid", defValBlank); em = getValueOr(sqData, "em", defValBlank); sm = getValueOr(sqData, "sm", defValBlank); HashMap cuData = new HashMap(); HashMap mpData = new HashMap(); ArrayList<HashMap> miSubArr = new ArrayList<HashMap>(); ArrayList<HashMap> mfSubArr = new ArrayList<HashMap>(); ArrayList<HashMap> mrSubArr = new ArrayList<HashMap>(); ArrayList<HashMap> mcSubArr = new ArrayList<HashMap>(); ArrayList<HashMap> mtSubArr = new ArrayList<HashMap>(); // ArrayList<HashMap> meSubArr = new ArrayList<HashMap>(); ArrayList<HashMap> mhSubArr = new ArrayList<HashMap>(); HashMap smData = new HashMap(); // Set environment modification info // meSubArr = getObjectOr(sqData, "em_data", meSubArr); String meNumStr = ""; meNum = 0; for (int j = 0, cnt = 0; j < meArr.size(); j++) { if (!meNumStr.equals(meArr.get(j).get("em"))) { meNumStr = (String) meArr.get(j).get("em"); cnt++; if (em.equals(meNumStr)) { meNum = cnt; break; } } } // Set simulation control info smNum = 0; if (isSmExist) { for (int j = 0; j < smArr.size(); j++) { if (sm.equals(smArr.get(j).get("sm"))) { smNum = j + 1; break; } } } if (smNum == 0) { smData.put("fertilizer", mfSubArr); smData.put("irrigation", miSubArr); smData.put("planting", mpData); smNum = setSecDataArr(smData, smArr); } // if (!getValueOr(sqData, "sm_general", "").equals("")) { // smData.put("sm_general", getValueOr(sqData, "sm_general", defValBlank)); // smData.put("sm_options", getValueOr(sqData, "sm_options", defValBlank)); // smData.put("sm_methods", getValueOr(sqData, "sm_methods", defValBlank)); // smData.put("sm_management", getValueOr(sqData, "sm_management", defValBlank)); // smData.put("sm_outputs", getValueOr(sqData, "sm_outputs", defValBlank)); // smData.put("sm_planting", getValueOr(sqData, "sm_planting", defValBlank)); // smData.put("sm_irrigation", getValueOr(sqData, "sm_irrigation", defValBlank)); // smData.put("sm_nitrogen", getValueOr(sqData, "sm_nitrogen", defValBlank)); // smData.put("sm_residues", getValueOr(sqData, "sm_residues", defValBlank)); // smData.put("sm_harvests", getValueOr(sqData, "sm_harvests", defValBlank)); // } else { // smData.put("fertilizer", mfSubArr); // smData.put("irrigation", miSubArr); // smData.put("planting", mpData); // } // Loop all event data for (int j = 0; j < evtArr.size(); j++) { evtData = new HashMap(); evtData.putAll(evtArr.get(j)); // Check if it has same sequence number if (getValueOr(evtData, "seqid", defValBlank).equals(seqId)) { evtData.remove("seqid"); // Planting event if (getValueOr(evtData, "event", defValBlank).equals("planting")) { // Set cultivals info copyItem(cuData, evtData, "cul_name"); copyItem(cuData, evtData, "crid"); copyItem(cuData, evtData, "cul_id", "dssat_cul_id", false); copyItem(cuData, evtData, "rm"); copyItem(cuData, evtData, "cul_notes"); translateTo2BitCrid(cuData); // Set planting info mpData.putAll(evtData); mpData.remove("cul_name"); } // irrigation event else if (getValueOr(evtData, "event", "").equals("irrigation")) { miSubArr.add(evtData); } // fertilizer event else if (getValueOr(evtData, "event", "").equals("fertilizer")) { mfSubArr.add(evtData); } // organic_matter event else if (getValueOr(evtData, "event", "").equals("organic_matter")) { // P.S. change event name to organic-materials; Back to organic_matter again. mrSubArr.add(evtData); } // chemical event else if (getValueOr(evtData, "event", "").equals("chemical")) { mcSubArr.add(evtData); } // tillage event else if (getValueOr(evtData, "event", "").equals("tillage")) { mtSubArr.add(evtData); // } // environment_modification event // else if (getValueOr(evtData, "event", "").equals("environment_modification")) { // meSubArr.add(evtData); } // harvest event else if (getValueOr(evtData, "event", "").equals("harvest")) { mhSubArr.add(evtData); } else { } } else { } } // If alternative fields are avaiable for fertilizer data if (mfSubArr.isEmpty()) { if (!getObjectOr(result, "fen_tot", "").equals("") || !getObjectOr(result, "fep_tot", "").equals("") || !getObjectOr(result, "fek_tot", "").equals("")) { mfSubArr.add(new HashMap()); } } cuNum = setSecDataArr(cuData, cuArr); mpNum = setSecDataArr(mpData, mpArr); miNum = setSecDataArr(miSubArr, miArr); mfNum = setSecDataArr(mfSubArr, mfArr); mrNum = setSecDataArr(mrSubArr, mrArr); mcNum = setSecDataArr(mcSubArr, mcArr); mtNum = setSecDataArr(mtSubArr, mtArr); // meNum = setSecDataArr(meSubArr, meArr); mhNum = setSecDataArr(mhSubArr, mhArr); // smNum = setSecDataArr(smData, smArr); // if (smArr.isEmpty()) { // smNum = 1; // } sbData.append(String.format("%1$2s %2$1s %3$1s %4$1s %5$-25s %6$2s %7$2s %8$2s %9$2s %10$2s %11$2s %12$2s %13$2s %14$2s %15$2s %16$2s %17$2s %18$2s\r\n", getValueOr(sqData, "trno", "1").toString(), getValueOr(sqData, "sq", "1").toString(), // P.S. default value here is based on document DSSAT vol2.pdf getValueOr(sqData, "op", "1").toString(), getValueOr(sqData, "co", "0").toString(), getValueOr(sqData, "tr_name", getValueOr(expData, "tr_name", defValC)).toString(), cuNum, //getObjectOr(data, "ge", defValI).toString(), flNum, //getObjectOr(data, "fl", defValI).toString(), saNum, //getObjectOr(data, "sa", defValI).toString(), icNum, //getObjectOr(data, "ic", defValI).toString(), mpNum, //getObjectOr(data, "pl", defValI).toString(), miNum, //getObjectOr(data, "ir", defValI).toString(), mfNum, //getObjectOr(data, "fe", defValI).toString(), mrNum, //getObjectOr(data, "om", defValI).toString(), mcNum, //getObjectOr(data, "ch", defValI).toString(), mtNum, //getObjectOr(data, "ti", defValI).toString(), meNum, //getObjectOr(data, "em", defValI).toString(), mhNum, //getObjectOr(data, "ha", defValI).toString(), smNum)); // 1 } sbData.append("\r\n"); // CULTIVARS Section if (!cuArr.isEmpty()) { sbData.append("*CULTIVARS\r\n"); sbData.append("@C CR INGENO CNAME\r\n"); for (int idx = 0; idx < cuArr.size(); idx++) { secData = (HashMap) cuArr.get(idx); // String cul_id = defValC; String crid = getObjectOr(secData, "crid", ""); // Checl if necessary data is missing if (crid.equals("")) { sbError.append("! Warning: Incompleted record because missing data : [crid]\r\n"); // } else { // // Set cultivar id a default value deponds on the crop id // if (crid.equals("MZ")) { // cul_id = "990002"; // } else { // cul_id = "999999"; // } // } // if (getObjectOr(secData, "cul_id", "").equals("")) { // sbError.append("! Warning: Incompleted record because missing data : [cul_id], and will use default value '").append(cul_id).append("'\r\n"); } sbData.append(String.format("%1$2s %2$-2s %3$-6s %4$s\r\n", idx + 1, //getObjectOr(secData, "ge", defValI).toString(), getObjectOr(secData, "crid", defValBlank).toString(), // P.S. if missing, default value use blank string getObjectOr(secData, "cul_id", defValC).toString(), // P.S. Set default value which is deponds on crid(Cancelled) getObjectOr(secData, "cul_name", defValC).toString())); if (!getObjectOr(secData, "rm", "").equals("") || !getObjectOr(secData, "cul_notes", "").equals("")) { if (sbNotesData.toString().equals("")) { sbNotesData.append("@NOTES\r\n"); } sbNotesData.append(" Cultivar Additional Info\r\n"); sbNotesData.append(" C RM CNAME CUL_NOTES\r\n"); sbNotesData.append(String.format("%1$2s %2$4s %3$s\r\n", idx + 1, //getObjectOr(secData, "ge", defValI).toString(), getObjectOr(secData, "rm", defValC).toString(), getObjectOr(secData, "cul_notes", defValC).toString())); } } sbData.append("\r\n"); } else { sbError.append("! Warning: There is no cultivar data in the experiment.\r\n"); } // FIELDS Section if (!flArr.isEmpty()) { sbData.append("*FIELDS\r\n"); sbData.append("@L ID_FIELD WSTA.... FLSA FLOB FLDT FLDD FLDS FLST SLTX SLDP ID_SOIL FLNAME\r\n"); eventPart2 = new StringBuilder(); eventPart2.append("@L ...........XCRD ...........YCRD .....ELEV .............AREA .SLEN .FLWR .SLAS FLHST FHDUR\r\n"); } else { sbError.append("! Warning: There is no field data in the experiment.\r\n"); } for (int idx = 0; idx < flArr.size(); idx++) { secData = (HashMap) flArr.get(idx); // Check if the necessary is missing if (getObjectOr(secData, "wst_id", "").equals("")) { sbError.append("! Warning: Incompleted record because missing data : [wst_id]\r\n"); } if (getObjectOr(secData, "soil_id", "").equals("")) { sbError.append("! Warning: Incompleted record because missing data : [soil_id]\r\n"); } sbData.append(String.format("%1$2s %2$-8s %3$-8s %4$5s %5$5s %6$-5s %7$5s %8$5s %9$-5s %10$-5s%11$5s %12$-10s %13$s\r\n", // P.S. change length definition to match current way idx + 1, //getObjectOr(secData, "fl", defValI).toString(), getObjectOr(secData, "id_field", defValC).toString(), getObjectOr(secData, "wst_id", defValC).toString(), getObjectOr(secData, "flsl", defValC).toString(), formatNumStr(5, secData, "flob", defValR), getObjectOr(secData, "fl_drntype", defValC).toString(), formatNumStr(5, secData, "fldrd", defValR), formatNumStr(5, secData, "fldrs", defValR), getObjectOr(secData, "flst", defValC).toString(), getObjectOr(secData, "sltx", defValC).toString(), formatNumStr(5, secData, "sldp", defValR), getObjectOr(secData, "soil_id", defValC).toString(), getObjectOr(secData, "fl_name", defValC).toString())); eventPart2.append(String.format("%1$2s %2$15s %3$15s %4$9s %5$17s %6$5s %7$5s %8$5s %9$5s %10$5s\r\n", idx + 1, //getObjectOr(secData, "fl", defValI).toString(), formatNumStr(15, secData, "fl_lat", defValR), formatNumStr(15, secData, "fl_long", defValR), formatNumStr(9, secData, "flele", defValR), formatNumStr(17, secData, "farea", defValR), "-99", // P.S. SLEN keeps -99 formatNumStr(5, secData, "fllwr", defValR), formatNumStr(5, secData, "flsla", defValR), getObjectOr(secData, "flhst", defValC).toString(), formatNumStr(5, secData, "fhdur", defValR))); } if (!flArr.isEmpty()) { sbData.append(eventPart2.toString()).append("\r\n"); } // SOIL ANALYSIS Section if (!saArr.isEmpty()) { sbData.append("*SOIL ANALYSIS\r\n"); for (int idx = 0; idx < saArr.size(); idx++) { secData = (HashMap) saArr.get(idx); sbData.append("@A SADAT SMHB SMPX SMKE SANAME\r\n"); sbData.append(String.format("%1$2s %2$5s %3$5s %4$5s %5$5s %6$s\r\n", idx + 1, //getObjectOr(secData, "sa", defValI).toString(), formatDateStr(getObjectOr(secData, "sadat", defValD).toString()), getObjectOr(secData, "samhb", defValC).toString(), getObjectOr(secData, "sampx", defValC).toString(), getObjectOr(secData, "samke", defValC).toString(), getObjectOr(secData, "sa_name", defValC).toString())); subDataArr = (ArrayList) getObjectOr(secData, "soilLayer", new ArrayList()); if (!subDataArr.isEmpty()) { sbData.append("@A SABL SADM SAOC SANI SAPHW SAPHB SAPX SAKE SASC\r\n"); } for (int j = 0; j < subDataArr.size(); j++) { subData = (HashMap) subDataArr.get(j); sbData.append(String.format("%1$2s %2$5s %3$5s %4$5s %5$5s %6$5s %7$5s %8$5s %9$5s %10$5s\r\n", idx + 1, //getObjectOr(subData, "sa", defValI).toString(), formatNumStr(5, subData, "sabl", defValR), formatNumStr(5, subData, "sabdm", defValR), formatNumStr(5, subData, "saoc", defValR), formatNumStr(5, subData, "sani", defValR), formatNumStr(5, subData, "saphw", defValR), formatNumStr(5, subData, "saphb", defValR), formatNumStr(5, subData, "sapx", defValR), formatNumStr(5, subData, "sake", defValR), formatNumStr(5, subData, "sasc", defValR))); } } sbData.append("\r\n"); } // INITIAL CONDITIONS Section if (!icArr.isEmpty()) { sbData.append("*INITIAL CONDITIONS\r\n"); for (int idx = 0; idx < icArr.size(); idx++) { secData = (HashMap) icArr.get(idx); translateTo2BitCrid(secData, "icpcr"); sbData.append("@C PCR ICDAT ICRT ICND ICRN ICRE ICWD ICRES ICREN ICREP ICRIP ICRID ICNAME\r\n"); sbData.append(String.format("%1$2s %2$5s %3$5s %4$5s %5$5s %6$5s %7$5s %8$5s %9$5s %10$5s %11$5s %12$5s %13$5s %14$s\r\n", idx + 1, //getObjectOr(secData, "ic", defValI).toString(), getObjectOr(secData, "icpcr", defValC).toString(), formatDateStr(getObjectOr(secData, "icdat", getPdate(result)).toString()), formatNumStr(5, secData, "icrt", defValR), formatNumStr(5, secData, "icnd", defValR), formatNumStr(5, secData, "icrz#", defValR), formatNumStr(5, secData, "icrze", defValR), formatNumStr(5, secData, "icwt", defValR), formatNumStr(5, secData, "icrag", defValR), formatNumStr(5, secData, "icrn", defValR), formatNumStr(5, secData, "icrp", defValR), formatNumStr(5, secData, "icrip", defValR), formatNumStr(5, secData, "icrdp", defValR), getObjectOr(secData, "ic_name", defValC).toString())); subDataArr = (ArrayList) getObjectOr(secData, "soilLayer", new ArrayList()); if (!subDataArr.isEmpty()) { sbData.append("@C ICBL SH2O SNH4 SNO3\r\n"); } for (int j = 0; j < subDataArr.size(); j++) { subData = (HashMap) subDataArr.get(j); sbData.append(String.format("%1$2s %2$5s %3$5s %4$5s %5$5s\r\n", idx + 1, //getObjectOr(subData, "ic", defValI).toString(), formatNumStr(5, subData, "icbl", defValR), formatNumStr(5, subData, "ich2o", defValR), formatNumStr(5, subData, "icnh4", defValR), formatNumStr(5, subData, "icno3", defValR))); } } sbData.append("\r\n"); } // PLANTING DETAILS Section if (!mpArr.isEmpty()) { sbData.append("*PLANTING DETAILS\r\n"); sbData.append("@P PDATE EDATE PPOP PPOE PLME PLDS PLRS PLRD PLDP PLWT PAGE PENV PLPH SPRL PLNAME\r\n"); for (int idx = 0; idx < mpArr.size(); idx++) { secData = (HashMap) mpArr.get(idx); // Check if necessary data is missing String pdate = getObjectOr(secData, "date", ""); if (pdate.equals("")) { sbError.append("! Warning: Incompleted record because missing data : [pdate]\r\n"); } else if (formatDateStr(pdate).equals(defValD)) { sbError.append("! Warning: Incompleted record because variable [pdate] with invalid value [").append(pdate).append("]\r\n"); } if (getObjectOr(secData, "plpop", getObjectOr(secData, "plpoe", "")).equals("")) { sbError.append("! Warning: Incompleted record because missing data : [plpop] and [plpoe]\r\n"); } if (getObjectOr(secData, "plrs", "").equals("")) { sbError.append("! Warning: Incompleted record because missing data : [plrs]\r\n"); } // if (getObjectOr(secData, "plma", "").equals("")) { // sbError.append("! Warning: missing data : [plma], and will automatically use default value 'S'\r\n"); // } // if (getObjectOr(secData, "plds", "").equals("")) { // sbError.append("! Warning: missing data : [plds], and will automatically use default value 'R'\r\n"); // } // if (getObjectOr(secData, "pldp", "").equals("")) { // sbError.append("! Warning: missing data : [pldp], and will automatically use default value '7'\r\n"); // } sbData.append(String.format("%1$2s %2$5s %3$5s %4$5s %5$5s %6$5s %7$5s %8$5s %9$5s %10$5s %11$5s %12$5s %13$5s %14$5s %15$5s %16$s\r\n", idx + 1, //getObjectOr(data, "pl", defValI).toString(), formatDateStr(getObjectOr(secData, "date", defValD).toString()), formatDateStr(getObjectOr(secData, "pldae", defValD).toString()), formatNumStr(5, secData, "plpop", getObjectOr(secData, "plpoe", defValR)), formatNumStr(5, secData, "plpoe", getObjectOr(secData, "plpop", defValR)), getObjectOr(secData, "plma", defValC).toString(), // P.S. Set default value as "S"(Cancelled) getObjectOr(secData, "plds", defValC).toString(), // P.S. Set default value as "R"(Cancelled) formatNumStr(5, secData, "plrs", defValR), formatNumStr(5, secData, "plrd", defValR), formatNumStr(5, secData, "pldp", defValR), // P.S. Set default value as "7"(Cancelled) formatNumStr(5, secData, "plmwt", defValR), formatNumStr(5, secData, "page", defValR), formatNumStr(5, secData, "penv", defValR), formatNumStr(5, secData, "plph", defValR), formatNumStr(5, secData, "plspl", defValR), getObjectOr(secData, "pl_name", defValC).toString())); } sbData.append("\r\n"); } else { sbError.append("! Warning: There is no plainting data in the experiment.\r\n"); } // IRRIGATION AND WATER MANAGEMENT Section if (!miArr.isEmpty()) { sbData.append("*IRRIGATION AND WATER MANAGEMENT\r\n"); for (int idx = 0; idx < miArr.size(); idx++) { // secData = (ArrayList) miArr.get(idx); subDataArr = (ArrayList) miArr.get(idx); if (!subDataArr.isEmpty()) { subData = (HashMap) subDataArr.get(0); } else { subData = new HashMap(); } sbData.append("@I EFIR IDEP ITHR IEPT IOFF IAME IAMT IRNAME\r\n"); sbData.append(String.format("%1$2s %2$5s %3$5s %4$5s %5$5s %6$5s %7$5s %8$5s %9$s\r\n", idx + 1, //getObjectOr(data, "ir", defValI).toString(), formatNumStr(5, subData, "ireff", defValR), formatNumStr(5, subData, "irmdp", defValR), formatNumStr(5, subData, "irthr", defValR), formatNumStr(5, subData, "irept", defValR), getObjectOr(subData, "irstg", defValC).toString(), getObjectOr(subData, "iame", defValC).toString(), formatNumStr(5, subData, "iamt", defValR), getObjectOr(subData, "ir_name", defValC).toString())); if (!subDataArr.isEmpty()) { sbData.append("@I IDATE IROP IRVAL\r\n"); } for (int j = 0; j < subDataArr.size(); j++) { subData = (HashMap) subDataArr.get(j); sbData.append(String.format("%1$2s %2$5s %3$-5s %4$5s\r\n", idx + 1, //getObjectOr(subData, "ir", defValI).toString(), formatDateStr(getObjectOr(subData, "date", defValD).toString()), // P.S. idate -> date getObjectOr(subData, "irop", defValC).toString(), formatNumStr(5, subData, "irval", defValR))); } } sbData.append("\r\n"); } // FERTILIZERS (INORGANIC) Section if (!mfArr.isEmpty()) { sbData.append("*FERTILIZERS (INORGANIC)\r\n"); sbData.append("@F FDATE FMCD FACD FDEP FAMN FAMP FAMK FAMC FAMO FOCD FERNAME\r\n"); // String fen_tot = getObjectOr(result, "fen_tot", defValR); // String fep_tot = getObjectOr(result, "fep_tot", defValR); // String fek_tot = getObjectOr(result, "fek_tot", defValR); // String pdate = getPdate(result); // if (pdate.equals("")) { // pdate = defValD; // } for (int idx = 0; idx < mfArr.size(); idx++) { secDataArr = (ArrayList) mfArr.get(idx); for (int i = 0; i < secDataArr.size(); i++) { secData = (HashMap) secDataArr.get(i); // if (getObjectOr(secData, "fdate", "").equals("")) { // sbError.append("! Warning: missing data : [fdate], and will automatically use planting value '").append(pdate).append("'\r\n"); // } // if (getObjectOr(secData, "fecd", "").equals("")) { // sbError.append("! Warning: missing data : [fecd], and will automatically use default value 'FE001'\r\n"); // } // if (getObjectOr(secData, "feacd", "").equals("")) { // sbError.append("! Warning: missing data : [feacd], and will automatically use default value 'AP002'\r\n"); // } // if (getObjectOr(secData, "fedep", "").equals("")) { // sbError.append("! Warning: missing data : [fedep], and will automatically use default value '10'\r\n"); // } // if (getObjectOr(secData, "feamn", "").equals("")) { // sbError.append("! Warning: missing data : [feamn], and will automatically use the value of FEN_TOT, '").append(fen_tot).append("'\r\n"); // } // if (getObjectOr(secData, "feamp", "").equals("")) { // sbError.append("! Warning: missing data : [feamp], and will automatically use the value of FEP_TOT, '").append(fep_tot).append("'\r\n"); // } // if (getObjectOr(secData, "feamk", "").equals("")) { // sbError.append("! Warning: missing data : [feamk], and will automatically use the value of FEK_TOT, '").append(fek_tot).append("'\r\n"); // } sbData.append(String.format("%1$2s %2$5s %3$5s %4$5s %5$5s %6$5s %7$5s %8$5s %9$5s %10$5s %11$5s %12$s\r\n", idx + 1, //getObjectOr(data, "fe", defValI).toString(), formatDateStr(getObjectOr(secData, "date", defValD).toString()), // P.S. fdate -> date getObjectOr(secData, "fecd", defValC).toString(), // P.S. Set default value as "FE005"(Cancelled) getObjectOr(secData, "feacd", defValC).toString(), // P.S. Set default value as "AP002"(Cancelled) formatNumStr(5, secData, "fedep", defValR), // P.S. Set default value as "10"(Cancelled) formatNumStr(5, secData, "feamn", defValR), // P.S. Set default value to use the value of FEN_TOT in meta data(Cancelled) formatNumStr(5, secData, "feamp", defValR), // P.S. Set default value to use the value of FEP_TOT in meta data(Cancelled) formatNumStr(5, secData, "feamk", defValR), // P.S. Set default value to use the value of FEK_TOT in meta data(Cancelled) formatNumStr(5, secData, "feamc", defValR), formatNumStr(5, secData, "feamo", defValR), getObjectOr(secData, "feocd", defValC).toString(), getObjectOr(secData, "fe_name", defValC).toString())); } } sbData.append("\r\n"); } // RESIDUES AND ORGANIC FERTILIZER Section if (!mrArr.isEmpty()) { sbData.append("*RESIDUES AND ORGANIC FERTILIZER\r\n"); sbData.append("@R RDATE RCOD RAMT RESN RESP RESK RINP RDEP RMET RENAME\r\n"); for (int idx = 0; idx < mrArr.size(); idx++) { secDataArr = (ArrayList) mrArr.get(idx); for (int i = 0; i < secDataArr.size(); i++) { secData = (HashMap) secDataArr.get(i); sbData.append(String.format("%1$2s %2$5s %3$-5s %4$5s %5$5s %6$5s %7$5s %8$5s %9$5s %10$5s %11$s\r\n", idx + 1, //getObjectOr(secData, "om", defValI).toString(), formatDateStr(getObjectOr(secData, "date", defValD).toString()), // P.S. omdat -> date getObjectOr(secData, "omcd", defValC).toString(), formatNumStr(5, secData, "omamt", defValR), formatNumStr(5, secData, "omn%", defValR), formatNumStr(5, secData, "omp%", defValR), formatNumStr(5, secData, "omk%", defValR), formatNumStr(5, secData, "ominp", defValR), formatNumStr(5, secData, "omdep", defValR), formatNumStr(5, secData, "omacd", defValR), getObjectOr(secData, "om_name", defValC).toString())); } } sbData.append("\r\n"); } // CHEMICAL APPLICATIONS Section if (!mcArr.isEmpty()) { sbData.append("*CHEMICAL APPLICATIONS\r\n"); sbData.append("@C CDATE CHCOD CHAMT CHME CHDEP CHT..CHNAME\r\n"); for (int idx = 0; idx < mcArr.size(); idx++) { secDataArr = (ArrayList) mcArr.get(idx); for (int i = 0; i < secDataArr.size(); i++) { secData = (HashMap) secDataArr.get(i); sbData.append(String.format("%1$2s %2$5s %3$5s %4$5s %5$5s %6$5s %7$5s %8$s\r\n", idx + 1, //getObjectOr(secData, "ch", defValI).toString(), formatDateStr(getObjectOr(secData, "date", defValD).toString()), // P.S. cdate -> date getObjectOr(secData, "chcd", defValC).toString(), formatNumStr(5, secData, "chamt", defValR), getObjectOr(secData, "chacd", defValC).toString(), getObjectOr(secData, "chdep", defValC).toString(), getObjectOr(secData, "ch_targets", defValC).toString(), getObjectOr(secData, "ch_name", defValC).toString())); } } sbData.append("\r\n"); } // TILLAGE Section if (!mtArr.isEmpty()) { sbData.append("*TILLAGE AND ROTATIONS\r\n"); sbData.append("@T TDATE TIMPL TDEP TNAME\r\n"); for (int idx = 0; idx < mtArr.size(); idx++) { secDataArr = (ArrayList) mtArr.get(idx); for (int i = 0; i < secDataArr.size(); i++) { secData = (HashMap) secDataArr.get(i); sbData.append(String.format("%1$2s %2$5s %3$5s %4$5s %5$s\r\n", idx + 1, //getObjectOr(secData, "ti", defValI).toString(), formatDateStr(getObjectOr(secData, "date", defValD).toString()), // P.S. tdate -> date getObjectOr(secData, "tiimp", defValC).toString(), formatNumStr(5, secData, "tidep", defValR), getObjectOr(secData, "ti_name", defValC).toString())); } } sbData.append("\r\n"); } // ENVIRONMENT MODIFICATIONS Section if (!meArr.isEmpty()) { sbData.append("*ENVIRONMENT MODIFICATIONS\r\n"); sbData.append("@E ODATE EDAY ERAD EMAX EMIN ERAIN ECO2 EDEW EWIND ENVNAME\r\n"); String emNumStr = ""; for (int idx = 0, cnt = 1; idx < meArr.size(); idx++) { // secDataArr = (ArrayList) meArr.get(idx); secData = meArr.get(idx); if (!emNumStr.equals(secData.get("em"))) { cnt++; emNumStr = (String) secData.get("em"); } sbData.append(String.format("%1$2s%2$s\r\n", cnt, secData.get("em_data"))); // for (int i = 0; i < secDataArr.size(); i++) { // sbData.append(String.format("%1$2s%2$s\r\n", // idx + 1, // (String) secDataArr.get(i))); // sbData.append(String.format("%1$2s %2$5s %3$-1s%4$4s %5$-1s%6$4s %7$-1s%8$4s %9$-1s%10$4s %11$-1s%12$4s %13$-1s%14$4s %15$-1s%16$4s %17$-1s%18$4s %19$s\r\n", // idx + 1, //getObjectOr(secData, "em", defValI).toString(), // formatDateStr(getObjectOr(secData, "date", defValD).toString()), // P.S. emday -> date // getObjectOr(secData, "ecdyl", defValBlank).toString(), // formatNumStr(4, getObjectOr(secData, "emdyl", defValR), // getObjectOr(secData, "ecrad", defValBlank).toString(), // formatNumStr(4, getObjectOr(secData, "emrad", defValR), // getObjectOr(secData, "ecmax", defValBlank).toString(), // formatNumStr(4, getObjectOr(secData, "emmax", defValR), // getObjectOr(secData, "ecmin", defValBlank).toString(), // formatNumStr(4, getObjectOr(secData, "emmin", defValR), // getObjectOr(secData, "ecrai", defValBlank).toString(), // formatNumStr(4, getObjectOr(secData, "emrai", defValR), // getObjectOr(secData, "ecco2", defValBlank).toString(), // formatNumStr(4, getObjectOr(secData, "emco2", defValR), // getObjectOr(secData, "ecdew", defValBlank).toString(), // formatNumStr(4, getObjectOr(secData, "emdew", defValR), // getObjectOr(secData, "ecwnd", defValBlank).toString(), // formatNumStr(4, getObjectOr(secData, "emwnd", defValR), // getObjectOr(secData, "em_name", defValC).toString())); // } } sbData.append("\r\n"); } // HARVEST DETAILS Section if (!mhArr.isEmpty()) { sbData.append("*HARVEST DETAILS\r\n"); sbData.append("@H HDATE HSTG HCOM HSIZE HPC HBPC HNAME\r\n"); for (int idx = 0; idx < mhArr.size(); idx++) { secDataArr = (ArrayList) mhArr.get(idx); for (int i = 0; i < secDataArr.size(); i++) { secData = (HashMap) secDataArr.get(i); sbData.append(String.format("%1$2s %2$5s %3$-5s %4$-5s %5$-5s %6$5s %7$5s %8$s\r\n", idx + 1, //getObjectOr(secData, "ha", defValI).toString(), formatDateStr(getObjectOr(secData, "date", defValD).toString()), // P.S. hdate -> date getObjectOr(secData, "hastg", defValC).toString(), getObjectOr(secData, "hacom", defValC).toString(), getObjectOr(secData, "hasiz", defValC).toString(), formatNumStr(5, secData, "hapc", defValR), formatNumStr(5, secData, "habpc", defValR), getObjectOr(secData, "ha_name", defValC).toString())); } } sbData.append("\r\n"); } // SIMULATION CONTROLS and AUTOMATIC MANAGEMENT Section if (!smArr.isEmpty()) { // Set Title list ArrayList smTitles = new ArrayList(); smTitles.add("@N GENERAL NYERS NREPS START SDATE RSEED SNAME.................... SMODEL\r\n"); smTitles.add("@N OPTIONS WATER NITRO SYMBI PHOSP POTAS DISES CHEM TILL CO2\r\n"); smTitles.add("@N METHODS WTHER INCON LIGHT EVAPO INFIL PHOTO HYDRO NSWIT MESOM MESEV MESOL\r\n"); smTitles.add("@N MANAGEMENT PLANT IRRIG FERTI RESID HARVS\r\n"); smTitles.add("@N OUTPUTS FNAME OVVEW SUMRY FROPT GROUT CAOUT WAOUT NIOUT MIOUT DIOUT VBOSE CHOUT OPOUT\r\n"); smTitles.add("@ AUTOMATIC MANAGEMENT\r\n@N PLANTING PFRST PLAST PH2OL PH2OU PH2OD PSTMX PSTMN\r\n"); smTitles.add("@N IRRIGATION IMDEP ITHRL ITHRU IROFF IMETH IRAMT IREFF\r\n"); smTitles.add("@N NITROGEN NMDEP NMTHR NAMNT NCODE NAOFF\r\n"); smTitles.add("@N RESIDUES RIPCN RTIME RIDEP\r\n"); smTitles.add("@N HARVEST HFRST HLAST HPCNP HPCNR\r\n"); String[] keys = new String[10]; keys[0] = "sm_general"; keys[1] = "sm_options"; keys[2] = "sm_methods"; keys[3] = "sm_management"; keys[4] = "sm_outputs"; keys[5] = "sm_planting"; keys[6] = "sm_irrigation"; keys[7] = "sm_nitrogen"; keys[8] = "sm_residues"; keys[9] = "sm_harvests"; // Loop all the simulation control records for (int idx = 0; idx < smArr.size(); idx++) { secData = (HashMap) smArr.get(idx); if (secData.containsKey("sm_general")) { sbData.append("*SIMULATION CONTROLS\r\n"); secData.remove("sm"); // Object[] keys = secData.keySet().toArray(); for (int i = 0; i < keys.length; i++) { sbData.append(smTitles.get(i)); sbData.append(String.format("%2s ", idx + 1)).append(((String) secData.get(keys[i]))).append("\r\n"); if (i == 4) { sbData.append("\r\n"); } } } else { sbData.append(createSMMAStr(idx + 1, expData, secData)); } } } else { sbData.append(createSMMAStr(1, expData, new HashMap())); } // Output finish bwX.write(sbError.toString()); bwX.write(sbGenData.toString()); bwX.write(sbNotesData.toString()); bwX.write(sbData.toString()); bwX.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } /** * Create string of Simulation Control and Automatic Management Section * * @param smid simulation index number * @param expData date holder for experiment data * @param trData date holder for one treatment data * @return date string with format of "yyddd" */ private String createSMMAStr(int smid, HashMap expData, HashMap trData) { StringBuilder sb = new StringBuilder(); String nitro = "Y"; String water = "Y"; String sdate; String sm = String.format("%2d", smid); ArrayList<HashMap> dataArr; HashMap subData; // // Check if the meta data of fertilizer is not "N" ("Y" or null) // if (!getValueOr(expData, "fertilizer", "").equals("N")) { // // // Check if necessary data is missing in all the event records // // P.S. rule changed since all the necessary data has a default value for it // dataArr = (ArrayList) getObjectOr(trData, "fertilizer", new ArrayList()); // if (dataArr.isEmpty()) { // nitro = "N"; // } //// for (int i = 0; i < dataArr.size(); i++) { //// subData = dataArr.get(i); //// if (getValueOr(subData, "date", "").equals("") //// || getValueOr(subData, "fecd", "").equals("") //// || getValueOr(subData, "feacd", "").equals("") //// || getValueOr(subData, "feamn", "").equals("")) { //// nitro = "N"; //// break; //// } //// } // } // // Check if the meta data of irrigation is not "N" ("Y" or null) // if (!getValueOr(expData, "irrigation", "").equals("N")) { // // // Check if necessary data is missing in all the event records // dataArr = (ArrayList) getObjectOr(trData, "irrigation", new ArrayList()); // for (int i = 0; i < dataArr.size(); i++) { // subData = dataArr.get(i); // if (getValueOr(subData, "date", "").equals("") // || getValueOr(subData, "irval", "").equals("")) { // water = "N"; // break; // } // } // } sdate = getObjectOr(expData, "sdat", "").toString(); if (sdate.equals("")) { subData = (HashMap) getObjectOr(trData, "planting", new HashMap()); sdate = getValueOr(subData, "date", defValD); } sdate = formatDateStr(sdate); sb.append("*SIMULATION CONTROLS\r\n"); sb.append("@N GENERAL NYERS NREPS START SDATE RSEED SNAME....................\r\n"); sb.append(sm).append(" GE 1 1 S ").append(sdate).append(" 2150 DEFAULT SIMULATION CONTROL\r\n"); sb.append("@N OPTIONS WATER NITRO SYMBI PHOSP POTAS DISES CHEM TILL CO2\r\n"); sb.append(sm).append(" OP ").append(water).append(" ").append(nitro).append(" Y N N N N Y M\r\n"); sb.append("@N METHODS WTHER INCON LIGHT EVAPO INFIL PHOTO HYDRO NSWIT MESOM MESEV MESOL\r\n"); sb.append(sm).append(" ME M M E R S L R 1 P S 2\r\n"); // P.S. 2012/09/02 MESOM "G" -> "P" sb.append("@N MANAGEMENT PLANT IRRIG FERTI RESID HARVS\r\n"); sb.append(sm).append(" MA R R R R M\r\n"); sb.append("@N OUTPUTS FNAME OVVEW SUMRY FROPT GROUT CAOUT WAOUT NIOUT MIOUT DIOUT VBOSE CHOUT OPOUT\r\n"); sb.append(sm).append(" OU N Y Y 1 Y Y N N N N N N N\r\n\r\n"); sb.append("@ AUTOMATIC MANAGEMENT\r\n"); sb.append("@N PLANTING PFRST PLAST PH2OL PH2OU PH2OD PSTMX PSTMN\r\n"); sb.append(sm).append(" PL 82050 82064 40 100 30 40 10\r\n"); sb.append("@N IRRIGATION IMDEP ITHRL ITHRU IROFF IMETH IRAMT IREFF\r\n"); sb.append(sm).append(" IR 30 50 100 GS000 IR001 10 1.00\r\n"); sb.append("@N NITROGEN NMDEP NMTHR NAMNT NCODE NAOFF\r\n"); sb.append(sm).append(" NI 30 50 25 FE001 GS000\r\n"); sb.append("@N RESIDUES RIPCN RTIME RIDEP\r\n"); sb.append(sm).append(" RE 100 1 20\r\n"); sb.append("@N HARVEST HFRST HLAST HPCNP HPCNR\r\n"); sb.append(sm).append(" HA 0 83057 100 0\r\n"); return sb.toString(); } /** * Get index value of the record and set new id value in the array * * @param m sub data * @param arr array of sub data * @return current index value of the sub data */ private int setSecDataArr(HashMap m, ArrayList arr) { if (!m.isEmpty()) { for (int j = 0; j < arr.size(); j++) { if (arr.get(j).equals(m)) { return j + 1; } } arr.add(m); return arr.size(); } else { return 0; } } /** * Get index value of the record and set new id value in the array * * @param inArr sub array of data * @param outArr array of sub data * @return current index value of the sub data */ private int setSecDataArr(ArrayList inArr, ArrayList outArr) { if (!inArr.isEmpty()) { for (int j = 0; j < outArr.size(); j++) { if (outArr.get(j).equals(inArr)) { return j + 1; } } outArr.add(inArr); return outArr.size(); } else { return 0; } } /** * To check if there is plot info data existed in the experiment * * @param expData experiment data holder * @return the boolean value for if plot info exists */ private boolean isPlotInfoExist(Map expData) { String[] plotIds = {"plta", "pltr#", "pltln", "pldr", "pltsp", "plot_layout", "pltha", "plth#", "plthl", "plthm"}; for (int i = 0; i < plotIds.length; i++) { if (!getValueOr(expData, plotIds[i], "").equals("")) { return true; } } return false; } /** * To check if there is soil analysis info data existed in the experiment * * @param expData initial condition layer data array * @return the boolean value for if soil analysis info exists */ private boolean isSoilAnalysisExist(ArrayList<HashMap> icSubArr) { for (int i = 0; i < icSubArr.size(); i++) { if (!getValueOr(icSubArr.get(i), "slsc", "").equals("")) { return true; } } return false; } /** * Get sub data array from experiment data object * * @param expData experiment data holder * @param blockName top level block name * @param dataListName sub array name * @return sub data array */ private ArrayList<HashMap> getDataList(Map expData, String blockName, String dataListName) { HashMap dataBlock = getObjectOr(expData, blockName, new HashMap()); return getObjectOr(dataBlock, dataListName, new ArrayList<HashMap>()); } /** * Try to translate 3-bit crid to 2-bit version stored in the map * * @param cuData the cultivar data record * @param id the field id for contain crop id info */ private void translateTo2BitCrid(HashMap cuData, String id) { String crid = getObjectOr(cuData, id, ""); if (!crid.equals("")) { DssatCRIDHelper crids = new DssatCRIDHelper(); cuData.put(id, crids.get2BitCrid(crid)); } } /** * Try to translate 3-bit crid to 2-bit version stored in the map * * @param cuData the cultivar data record */ private void translateTo2BitCrid(HashMap cuData) { translateTo2BitCrid(cuData, "crid"); } }
src/main/java/org/agmip/translators/dssat/DssatXFileOutput.java
package org.agmip.translators.dssat; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import static org.agmip.translators.dssat.DssatCommonInput.copyItem; import static org.agmip.util.MapUtil.*; /** * DSSAT Experiment Data I/O API Class * * @author Meng Zhang * @version 1.0 */ public class DssatXFileOutput extends DssatCommonOutput { public static final DssatCRIDHelper crHelper = new DssatCRIDHelper(); /** * DSSAT Experiment Data Output method * * @param arg0 file output path * @param result data holder object */ @Override public void writeFile(String arg0, Map result) { // Initial variables HashMap expData = (HashMap) result; HashMap soilData = getObjectOr(result, "soil", new HashMap()); HashMap wthData = getObjectOr(result, "weather", new HashMap()); BufferedWriter bwX; // output object StringBuilder sbGenData = new StringBuilder(); // construct the data info in the output StringBuilder sbNotesData = new StringBuilder(); // construct the data info in the output StringBuilder sbData = new StringBuilder(); // construct the data info in the output StringBuilder eventPart2 = new StringBuilder(); // output string for second part of event data HashMap secData; ArrayList subDataArr; // Arraylist for event data holder HashMap subData; ArrayList secDataArr; // Arraylist for section data holder HashMap sqData; ArrayList<HashMap> evtArr; // Arraylist for section data holder HashMap evtData; // int trmnNum; // total numbers of treatment in the data holder int cuNum; // total numbers of cultivars in the data holder int flNum; // total numbers of fields in the data holder int saNum; // total numbers of soil analysis in the data holder int icNum; // total numbers of initial conditions in the data holder int mpNum; // total numbers of plaintings in the data holder int miNum; // total numbers of irrigations in the data holder int mfNum; // total numbers of fertilizers in the data holder int mrNum; // total numbers of residues in the data holder int mcNum; // total numbers of chemical in the data holder int mtNum; // total numbers of tillage in the data holder int meNum; // total numbers of enveronment modification in the data holder int mhNum; // total numbers of harvest in the data holder int smNum; // total numbers of simulation controll record ArrayList<HashMap> sqArr; // array for treatment record ArrayList cuArr = new ArrayList(); // array for cultivars record ArrayList flArr = new ArrayList(); // array for fields record ArrayList saArr = new ArrayList(); // array for soil analysis record ArrayList icArr = new ArrayList(); // array for initial conditions record ArrayList mpArr = new ArrayList(); // array for plaintings record ArrayList miArr = new ArrayList(); // array for irrigations record ArrayList mfArr = new ArrayList(); // array for fertilizers record ArrayList mrArr = new ArrayList(); // array for residues record ArrayList mcArr = new ArrayList(); // array for chemical record ArrayList mtArr = new ArrayList(); // array for tillage record ArrayList<HashMap> meArr; // array for enveronment modification record ArrayList mhArr = new ArrayList(); // array for harvest record ArrayList<HashMap> smArr; // array for simulation control record String exName; try { // Set default value for missing data if (expData == null || expData.isEmpty()) { return; } // decompressData((HashMap) result); setDefVal(); // Initial BufferedWriter String fileName = getFileName(result, "X"); arg0 = revisePath(arg0); outputFile = new File(arg0 + fileName); bwX = new BufferedWriter(new FileWriter(outputFile)); // Output XFile // EXP.DETAILS Section sbGenData.append(String.format("*EXP.DETAILS: %1$-10s %2$s\r\n\r\n", getExName(result), getObjectOr(expData, "local_name", defValBlank).toString())); // GENERAL Section sbGenData.append("*GENERAL\r\n"); // People if (!getObjectOr(expData, "people", "").equals("")) { sbGenData.append(String.format("@PEOPLE\r\n %1$s\r\n", getObjectOr(expData, "people", defValBlank).toString())); } // Address if (getObjectOr(expData, "institution", "").equals("")) { if (!getObjectOr(expData, "fl_loc_1", "").equals("") && getObjectOr(expData, "fl_loc_2", "").equals("") && getObjectOr(expData, "fl_loc_3", "").equals("")) { sbGenData.append(String.format("@ADDRESS\r\n %3$s, %2$s, %1$s\r\n", getObjectOr(expData, "fl_loc_1", defValBlank).toString(), getObjectOr(expData, "fl_loc_2", defValBlank).toString(), getObjectOr(expData, "fl_loc_3", defValBlank).toString())); } } else { sbGenData.append(String.format("@ADDRESS\r\n %1$s\r\n", getObjectOr(expData, "institution", defValBlank).toString())); } // Site if (!getObjectOr(expData, "site", "").equals("")) { sbGenData.append(String.format("@SITE\r\n %1$s\r\n", getObjectOr(expData, "site", defValBlank).toString())); } // Plot Info if (isPlotInfoExist(expData)) { sbGenData.append("@ PAREA PRNO PLEN PLDR PLSP PLAY HAREA HRNO HLEN HARM.........\r\n"); sbGenData.append(String.format(" %1$6s %2$5s %3$5s %4$5s %5$5s %6$-5s %7$5s %8$5s %9$5s %10$-15s\r\n", formatNumStr(6, expData, "plta", defValR), formatNumStr(5, expData, "pltr#", defValI), formatNumStr(5, expData, "pltln", defValR), formatNumStr(5, expData, "pldr", defValI), formatNumStr(5, expData, "pltsp", defValI), getObjectOr(expData, "plot_layout", defValC).toString(), formatNumStr(5, expData, "pltha", defValR), formatNumStr(5, expData, "plth#", defValI), formatNumStr(5, expData, "plthl", defValR), getObjectOr(expData, "plthm", defValC).toString())); } // Notes if (!getObjectOr(expData, "tr_notes", "").equals("")) { sbNotesData.append("@NOTES\r\n"); String notes = getObjectOr(expData, "tr_notes", defValC).toString(); notes = notes.replaceAll("\\\\r\\\\n", "\r\n"); // If notes contain newline code, then write directly if (notes.indexOf("\r\n") >= 0) { // sbData.append(String.format(" %1$s\r\n", notes)); sbNotesData.append(notes); } // Otherwise, add newline for every 75-bits charactors else { while (notes.length() > 75) { sbNotesData.append(" ").append(notes.substring(0, 75)).append("\r\n"); notes = notes.substring(75); } sbNotesData.append(" ").append(notes).append("\r\n"); } } sbData.append("\r\n"); // TREATMENT Section sqArr = getDataList(expData, "dssat_sequence", "data"); evtArr = getDataList(expData, "management", "events"); meArr = getDataList(expData, "dssat_environment_modification", "data"); smArr = getDataList(expData, "dssat_simulation_control", "data"); boolean isSmExist = !smArr.isEmpty(); String seqId; String em; String sm; sbData.append("*TREATMENTS -------------FACTOR LEVELS------------\r\n"); sbData.append("@N R O C TNAME.................... CU FL SA IC MP MI MF MR MC MT ME MH SM\r\n"); // if there is no sequence info, create dummy data if (sqArr.isEmpty()) { sqArr.add(new HashMap()); } // Set field info HashMap flData = new HashMap(); copyItem(flData, expData, "id_field"); if (wthData.isEmpty()) { // copyItem(flData, expData, "wst_id"); flData.put("wst_id", getWthFileName(expData)); } else { flData.put("wst_id", getWthFileName(wthData)); } copyItem(flData, expData, "flsl"); copyItem(flData, expData, "flob"); copyItem(flData, expData, "fl_drntype"); copyItem(flData, expData, "fldrd"); copyItem(flData, expData, "fldrs"); copyItem(flData, expData, "flst"); copyItem(flData, soilData, "sltx"); copyItem(flData, soilData, "sldp"); copyItem(flData, expData, "soil_id"); copyItem(flData, expData, "fl_name"); copyItem(flData, expData, "fl_lat"); copyItem(flData, expData, "fl_long"); copyItem(flData, expData, "flele"); copyItem(flData, expData, "farea"); copyItem(flData, expData, "fllwr"); copyItem(flData, expData, "flsla"); copyItem(flData, getObjectOr(expData, "dssat_info", new HashMap()), "flhst"); copyItem(flData, getObjectOr(expData, "dssat_info", new HashMap()), "fhdur"); // remove the "_trno" in the soil_id when soil analysis is available String soilId = getValueOr(flData, "soil_id", ""); if (soilId.length() > 10 && soilId.matches("\\w+_\\d+")) { flData.put("soil_id", soilId.replaceAll("_\\d+$", "")); } flNum = setSecDataArr(flData, flArr); // Set initial condition info icNum = setSecDataArr(getObjectOr(expData, "initial_conditions", new HashMap()), icArr); // Set soil analysis info // ArrayList<HashMap> icSubArr = getDataList(expData, "initial_condition", "soilLayer"); ArrayList<HashMap> soilLarys = getDataList(expData, "soil", "soilLayer"); // // If it is stored in the initial condition block // if (isSoilAnalysisExist(icSubArr)) { // HashMap saData = new HashMap(); // ArrayList<HashMap> saSubArr = new ArrayList<HashMap>(); // HashMap saSubData; // for (int i = 0; i < icSubArr.size(); i++) { // saSubData = new HashMap(); // copyItem(saSubData, icSubArr.get(i), "sabl", "icbl", false); // copyItem(saSubData, icSubArr.get(i), "sasc", "slsc", false); // saSubArr.add(saSubData); // } // copyItem(saData, soilData, "sadat"); // saData.put("soilLayer", saSubArr); // saNum = setSecDataArr(saData, saArr); // } else // If it is stored in the soil block if (isSoilAnalysisExist(soilLarys)) { HashMap saData = new HashMap(); ArrayList<HashMap> saSubArr = new ArrayList<HashMap>(); HashMap saSubData; for (int i = 0; i < soilLarys.size(); i++) { saSubData = new HashMap(); copyItem(saSubData, soilLarys.get(i), "sabl", "sllb", false); copyItem(saSubData, soilLarys.get(i), "sasc", "slsc", false); saSubArr.add(saSubData); } copyItem(saData, soilData, "sadat"); saData.put("soilLayer", saSubArr); saNum = setSecDataArr(saData, saArr); } else { saNum = 0; } // Set sequence related block info for (int i = 0; i < sqArr.size(); i++) { sqData = sqArr.get(i); seqId = getValueOr(sqData, "seqid", defValBlank); em = getValueOr(sqData, "em", defValBlank); sm = getValueOr(sqData, "sm", defValBlank); HashMap cuData = new HashMap(); HashMap mpData = new HashMap(); ArrayList<HashMap> miSubArr = new ArrayList<HashMap>(); ArrayList<HashMap> mfSubArr = new ArrayList<HashMap>(); ArrayList<HashMap> mrSubArr = new ArrayList<HashMap>(); ArrayList<HashMap> mcSubArr = new ArrayList<HashMap>(); ArrayList<HashMap> mtSubArr = new ArrayList<HashMap>(); // ArrayList<HashMap> meSubArr = new ArrayList<HashMap>(); ArrayList<HashMap> mhSubArr = new ArrayList<HashMap>(); HashMap smData = new HashMap(); // Set environment modification info // meSubArr = getObjectOr(sqData, "em_data", meSubArr); String meNumStr = ""; meNum = 0; for (int j = 0, cnt = 0; j < meArr.size(); j++) { if (!meNumStr.equals(meArr.get(j).get("em"))) { meNumStr = (String) meArr.get(j).get("em"); cnt++; if (em.equals(meNumStr)) { meNum = cnt; break; } } } // Set simulation control info smNum = 0; if (isSmExist) { for (int j = 0; j < smArr.size(); j++) { if (sm.equals(smArr.get(j).get("sm"))) { smNum = j + 1; break; } } } if (smNum == 0) { smData.put("fertilizer", mfSubArr); smData.put("irrigation", miSubArr); smData.put("planting", mpData); smNum = setSecDataArr(smData, smArr); } // if (!getValueOr(sqData, "sm_general", "").equals("")) { // smData.put("sm_general", getValueOr(sqData, "sm_general", defValBlank)); // smData.put("sm_options", getValueOr(sqData, "sm_options", defValBlank)); // smData.put("sm_methods", getValueOr(sqData, "sm_methods", defValBlank)); // smData.put("sm_management", getValueOr(sqData, "sm_management", defValBlank)); // smData.put("sm_outputs", getValueOr(sqData, "sm_outputs", defValBlank)); // smData.put("sm_planting", getValueOr(sqData, "sm_planting", defValBlank)); // smData.put("sm_irrigation", getValueOr(sqData, "sm_irrigation", defValBlank)); // smData.put("sm_nitrogen", getValueOr(sqData, "sm_nitrogen", defValBlank)); // smData.put("sm_residues", getValueOr(sqData, "sm_residues", defValBlank)); // smData.put("sm_harvests", getValueOr(sqData, "sm_harvests", defValBlank)); // } else { // smData.put("fertilizer", mfSubArr); // smData.put("irrigation", miSubArr); // smData.put("planting", mpData); // } // Loop all event data for (int j = 0; j < evtArr.size(); j++) { evtData = new HashMap(); evtData.putAll(evtArr.get(j)); // Check if it has same sequence number if (getValueOr(evtData, "seqid", defValBlank).equals(seqId)) { evtData.remove("seqid"); // Planting event if (getValueOr(evtData, "event", defValBlank).equals("planting")) { // Set cultivals info copyItem(cuData, evtData, "cul_name"); copyItem(cuData, evtData, "crid"); copyItem(cuData, evtData, "cul_id"); copyItem(cuData, evtData, "rm"); copyItem(cuData, evtData, "cul_notes"); translateTo2BitCrid(cuData); // Set planting info mpData.putAll(evtData); mpData.remove("cul_name"); } // irrigation event else if (getValueOr(evtData, "event", "").equals("irrigation")) { miSubArr.add(evtData); } // fertilizer event else if (getValueOr(evtData, "event", "").equals("fertilizer")) { mfSubArr.add(evtData); } // organic_matter event else if (getValueOr(evtData, "event", "").equals("organic_matter")) { // P.S. change event name to organic-materials; Back to organic_matter again. mrSubArr.add(evtData); } // chemical event else if (getValueOr(evtData, "event", "").equals("chemical")) { mcSubArr.add(evtData); } // tillage event else if (getValueOr(evtData, "event", "").equals("tillage")) { mtSubArr.add(evtData); // } // environment_modification event // else if (getValueOr(evtData, "event", "").equals("environment_modification")) { // meSubArr.add(evtData); } // harvest event else if (getValueOr(evtData, "event", "").equals("harvest")) { mhSubArr.add(evtData); } else { } } else { } } // If alternative fields are avaiable for fertilizer data if (mfSubArr.isEmpty()) { if (!getObjectOr(result, "fen_tot", "").equals("") || !getObjectOr(result, "fep_tot", "").equals("") || !getObjectOr(result, "fek_tot", "").equals("")) { mfSubArr.add(new HashMap()); } } cuNum = setSecDataArr(cuData, cuArr); mpNum = setSecDataArr(mpData, mpArr); miNum = setSecDataArr(miSubArr, miArr); mfNum = setSecDataArr(mfSubArr, mfArr); mrNum = setSecDataArr(mrSubArr, mrArr); mcNum = setSecDataArr(mcSubArr, mcArr); mtNum = setSecDataArr(mtSubArr, mtArr); // meNum = setSecDataArr(meSubArr, meArr); mhNum = setSecDataArr(mhSubArr, mhArr); // smNum = setSecDataArr(smData, smArr); // if (smArr.isEmpty()) { // smNum = 1; // } sbData.append(String.format("%1$2s %2$1s %3$1s %4$1s %5$-25s %6$2s %7$2s %8$2s %9$2s %10$2s %11$2s %12$2s %13$2s %14$2s %15$2s %16$2s %17$2s %18$2s\r\n", getValueOr(sqData, "trno", "1").toString(), getValueOr(sqData, "sq", "1").toString(), // P.S. default value here is based on document DSSAT vol2.pdf getValueOr(sqData, "op", "1").toString(), getValueOr(sqData, "co", "0").toString(), getValueOr(sqData, "tr_name", getValueOr(expData, "tr_name", defValC)).toString(), cuNum, //getObjectOr(data, "ge", defValI).toString(), flNum, //getObjectOr(data, "fl", defValI).toString(), saNum, //getObjectOr(data, "sa", defValI).toString(), icNum, //getObjectOr(data, "ic", defValI).toString(), mpNum, //getObjectOr(data, "pl", defValI).toString(), miNum, //getObjectOr(data, "ir", defValI).toString(), mfNum, //getObjectOr(data, "fe", defValI).toString(), mrNum, //getObjectOr(data, "om", defValI).toString(), mcNum, //getObjectOr(data, "ch", defValI).toString(), mtNum, //getObjectOr(data, "ti", defValI).toString(), meNum, //getObjectOr(data, "em", defValI).toString(), mhNum, //getObjectOr(data, "ha", defValI).toString(), smNum)); // 1 } sbData.append("\r\n"); // CULTIVARS Section if (!cuArr.isEmpty()) { sbData.append("*CULTIVARS\r\n"); sbData.append("@C CR INGENO CNAME\r\n"); for (int idx = 0; idx < cuArr.size(); idx++) { secData = (HashMap) cuArr.get(idx); // String cul_id = defValC; String crid = getObjectOr(secData, "crid", ""); // Checl if necessary data is missing if (crid.equals("")) { sbError.append("! Warning: Incompleted record because missing data : [crid]\r\n"); // } else { // // Set cultivar id a default value deponds on the crop id // if (crid.equals("MZ")) { // cul_id = "990002"; // } else { // cul_id = "999999"; // } // } // if (getObjectOr(secData, "cul_id", "").equals("")) { // sbError.append("! Warning: Incompleted record because missing data : [cul_id], and will use default value '").append(cul_id).append("'\r\n"); } sbData.append(String.format("%1$2s %2$-2s %3$-6s %4$s\r\n", idx + 1, //getObjectOr(secData, "ge", defValI).toString(), getObjectOr(secData, "crid", defValBlank).toString(), // P.S. if missing, default value use blank string getObjectOr(secData, "cul_id", defValC).toString(), // P.S. Set default value which is deponds on crid(Cancelled) getObjectOr(secData, "cul_name", defValC).toString())); if (!getObjectOr(secData, "rm", "").equals("") || !getObjectOr(secData, "cul_notes", "").equals("")) { if (sbNotesData.toString().equals("")) { sbNotesData.append("@NOTES\r\n"); } sbNotesData.append(" Cultivar Additional Info\r\n"); sbNotesData.append(" C RM CNAME CUL_NOTES\r\n"); sbNotesData.append(String.format("%1$2s %2$4s %3$s\r\n", idx + 1, //getObjectOr(secData, "ge", defValI).toString(), getObjectOr(secData, "rm", defValC).toString(), getObjectOr(secData, "cul_notes", defValC).toString())); } } sbData.append("\r\n"); } else { sbError.append("! Warning: There is no cultivar data in the experiment.\r\n"); } // FIELDS Section if (!flArr.isEmpty()) { sbData.append("*FIELDS\r\n"); sbData.append("@L ID_FIELD WSTA.... FLSA FLOB FLDT FLDD FLDS FLST SLTX SLDP ID_SOIL FLNAME\r\n"); eventPart2 = new StringBuilder(); eventPart2.append("@L ...........XCRD ...........YCRD .....ELEV .............AREA .SLEN .FLWR .SLAS FLHST FHDUR\r\n"); } else { sbError.append("! Warning: There is no field data in the experiment.\r\n"); } for (int idx = 0; idx < flArr.size(); idx++) { secData = (HashMap) flArr.get(idx); // Check if the necessary is missing if (getObjectOr(secData, "wst_id", "").equals("")) { sbError.append("! Warning: Incompleted record because missing data : [wst_id]\r\n"); } if (getObjectOr(secData, "soil_id", "").equals("")) { sbError.append("! Warning: Incompleted record because missing data : [soil_id]\r\n"); } sbData.append(String.format("%1$2s %2$-8s %3$-8s %4$5s %5$5s %6$-5s %7$5s %8$5s %9$-5s %10$-5s%11$5s %12$-10s %13$s\r\n", // P.S. change length definition to match current way idx + 1, //getObjectOr(secData, "fl", defValI).toString(), getObjectOr(secData, "id_field", defValC).toString(), getObjectOr(secData, "wst_id", defValC).toString(), getObjectOr(secData, "flsl", defValC).toString(), formatNumStr(5, secData, "flob", defValR), getObjectOr(secData, "fl_drntype", defValC).toString(), formatNumStr(5, secData, "fldrd", defValR), formatNumStr(5, secData, "fldrs", defValR), getObjectOr(secData, "flst", defValC).toString(), getObjectOr(secData, "sltx", defValC).toString(), formatNumStr(5, secData, "sldp", defValR), getObjectOr(secData, "soil_id", defValC).toString(), getObjectOr(secData, "fl_name", defValC).toString())); eventPart2.append(String.format("%1$2s %2$15s %3$15s %4$9s %5$17s %6$5s %7$5s %8$5s %9$5s %10$5s\r\n", idx + 1, //getObjectOr(secData, "fl", defValI).toString(), formatNumStr(15, secData, "fl_lat", defValR), formatNumStr(15, secData, "fl_long", defValR), formatNumStr(9, secData, "flele", defValR), formatNumStr(17, secData, "farea", defValR), "-99", // P.S. SLEN keeps -99 formatNumStr(5, secData, "fllwr", defValR), formatNumStr(5, secData, "flsla", defValR), getObjectOr(secData, "flhst", defValC).toString(), formatNumStr(5, secData, "fhdur", defValR))); } if (!flArr.isEmpty()) { sbData.append(eventPart2.toString()).append("\r\n"); } // SOIL ANALYSIS Section if (!saArr.isEmpty()) { sbData.append("*SOIL ANALYSIS\r\n"); for (int idx = 0; idx < saArr.size(); idx++) { secData = (HashMap) saArr.get(idx); sbData.append("@A SADAT SMHB SMPX SMKE SANAME\r\n"); sbData.append(String.format("%1$2s %2$5s %3$5s %4$5s %5$5s %6$s\r\n", idx + 1, //getObjectOr(secData, "sa", defValI).toString(), formatDateStr(getObjectOr(secData, "sadat", defValD).toString()), getObjectOr(secData, "samhb", defValC).toString(), getObjectOr(secData, "sampx", defValC).toString(), getObjectOr(secData, "samke", defValC).toString(), getObjectOr(secData, "sa_name", defValC).toString())); subDataArr = (ArrayList) getObjectOr(secData, "soilLayer", new ArrayList()); if (!subDataArr.isEmpty()) { sbData.append("@A SABL SADM SAOC SANI SAPHW SAPHB SAPX SAKE SASC\r\n"); } for (int j = 0; j < subDataArr.size(); j++) { subData = (HashMap) subDataArr.get(j); sbData.append(String.format("%1$2s %2$5s %3$5s %4$5s %5$5s %6$5s %7$5s %8$5s %9$5s %10$5s\r\n", idx + 1, //getObjectOr(subData, "sa", defValI).toString(), formatNumStr(5, subData, "sabl", defValR), formatNumStr(5, subData, "sabdm", defValR), formatNumStr(5, subData, "saoc", defValR), formatNumStr(5, subData, "sani", defValR), formatNumStr(5, subData, "saphw", defValR), formatNumStr(5, subData, "saphb", defValR), formatNumStr(5, subData, "sapx", defValR), formatNumStr(5, subData, "sake", defValR), formatNumStr(5, subData, "sasc", defValR))); } } sbData.append("\r\n"); } // INITIAL CONDITIONS Section if (!icArr.isEmpty()) { sbData.append("*INITIAL CONDITIONS\r\n"); for (int idx = 0; idx < icArr.size(); idx++) { secData = (HashMap) icArr.get(idx); translateTo2BitCrid(secData, "icpcr"); sbData.append("@C PCR ICDAT ICRT ICND ICRN ICRE ICWD ICRES ICREN ICREP ICRIP ICRID ICNAME\r\n"); sbData.append(String.format("%1$2s %2$5s %3$5s %4$5s %5$5s %6$5s %7$5s %8$5s %9$5s %10$5s %11$5s %12$5s %13$5s %14$s\r\n", idx + 1, //getObjectOr(secData, "ic", defValI).toString(), getObjectOr(secData, "icpcr", defValC).toString(), formatDateStr(getObjectOr(secData, "icdat", getPdate(result)).toString()), formatNumStr(5, secData, "icrt", defValR), formatNumStr(5, secData, "icnd", defValR), formatNumStr(5, secData, "icrz#", defValR), formatNumStr(5, secData, "icrze", defValR), formatNumStr(5, secData, "icwt", defValR), formatNumStr(5, secData, "icrag", defValR), formatNumStr(5, secData, "icrn", defValR), formatNumStr(5, secData, "icrp", defValR), formatNumStr(5, secData, "icrip", defValR), formatNumStr(5, secData, "icrdp", defValR), getObjectOr(secData, "ic_name", defValC).toString())); subDataArr = (ArrayList) getObjectOr(secData, "soilLayer", new ArrayList()); if (!subDataArr.isEmpty()) { sbData.append("@C ICBL SH2O SNH4 SNO3\r\n"); } for (int j = 0; j < subDataArr.size(); j++) { subData = (HashMap) subDataArr.get(j); sbData.append(String.format("%1$2s %2$5s %3$5s %4$5s %5$5s\r\n", idx + 1, //getObjectOr(subData, "ic", defValI).toString(), formatNumStr(5, subData, "icbl", defValR), formatNumStr(5, subData, "ich2o", defValR), formatNumStr(5, subData, "icnh4", defValR), formatNumStr(5, subData, "icno3", defValR))); } } sbData.append("\r\n"); } // PLANTING DETAILS Section if (!mpArr.isEmpty()) { sbData.append("*PLANTING DETAILS\r\n"); sbData.append("@P PDATE EDATE PPOP PPOE PLME PLDS PLRS PLRD PLDP PLWT PAGE PENV PLPH SPRL PLNAME\r\n"); for (int idx = 0; idx < mpArr.size(); idx++) { secData = (HashMap) mpArr.get(idx); // Check if necessary data is missing String pdate = getObjectOr(secData, "date", ""); if (pdate.equals("")) { sbError.append("! Warning: Incompleted record because missing data : [pdate]\r\n"); } else if (formatDateStr(pdate).equals(defValD)) { sbError.append("! Warning: Incompleted record because variable [pdate] with invalid value [").append(pdate).append("]\r\n"); } if (getObjectOr(secData, "plpop", getObjectOr(secData, "plpoe", "")).equals("")) { sbError.append("! Warning: Incompleted record because missing data : [plpop] and [plpoe]\r\n"); } if (getObjectOr(secData, "plrs", "").equals("")) { sbError.append("! Warning: Incompleted record because missing data : [plrs]\r\n"); } // if (getObjectOr(secData, "plma", "").equals("")) { // sbError.append("! Warning: missing data : [plma], and will automatically use default value 'S'\r\n"); // } // if (getObjectOr(secData, "plds", "").equals("")) { // sbError.append("! Warning: missing data : [plds], and will automatically use default value 'R'\r\n"); // } // if (getObjectOr(secData, "pldp", "").equals("")) { // sbError.append("! Warning: missing data : [pldp], and will automatically use default value '7'\r\n"); // } sbData.append(String.format("%1$2s %2$5s %3$5s %4$5s %5$5s %6$5s %7$5s %8$5s %9$5s %10$5s %11$5s %12$5s %13$5s %14$5s %15$5s %16$s\r\n", idx + 1, //getObjectOr(data, "pl", defValI).toString(), formatDateStr(getObjectOr(secData, "date", defValD).toString()), formatDateStr(getObjectOr(secData, "pldae", defValD).toString()), formatNumStr(5, secData, "plpop", getObjectOr(secData, "plpoe", defValR)), formatNumStr(5, secData, "plpoe", getObjectOr(secData, "plpop", defValR)), getObjectOr(secData, "plma", defValC).toString(), // P.S. Set default value as "S"(Cancelled) getObjectOr(secData, "plds", defValC).toString(), // P.S. Set default value as "R"(Cancelled) formatNumStr(5, secData, "plrs", defValR), formatNumStr(5, secData, "plrd", defValR), formatNumStr(5, secData, "pldp", defValR), // P.S. Set default value as "7"(Cancelled) formatNumStr(5, secData, "plmwt", defValR), formatNumStr(5, secData, "page", defValR), formatNumStr(5, secData, "penv", defValR), formatNumStr(5, secData, "plph", defValR), formatNumStr(5, secData, "plspl", defValR), getObjectOr(secData, "pl_name", defValC).toString())); } sbData.append("\r\n"); } else { sbError.append("! Warning: There is no plainting data in the experiment.\r\n"); } // IRRIGATION AND WATER MANAGEMENT Section if (!miArr.isEmpty()) { sbData.append("*IRRIGATION AND WATER MANAGEMENT\r\n"); for (int idx = 0; idx < miArr.size(); idx++) { // secData = (ArrayList) miArr.get(idx); subDataArr = (ArrayList) miArr.get(idx); if (!subDataArr.isEmpty()) { subData = (HashMap) subDataArr.get(0); } else { subData = new HashMap(); } sbData.append("@I EFIR IDEP ITHR IEPT IOFF IAME IAMT IRNAME\r\n"); sbData.append(String.format("%1$2s %2$5s %3$5s %4$5s %5$5s %6$5s %7$5s %8$5s %9$s\r\n", idx + 1, //getObjectOr(data, "ir", defValI).toString(), formatNumStr(5, subData, "ireff", defValR), formatNumStr(5, subData, "irmdp", defValR), formatNumStr(5, subData, "irthr", defValR), formatNumStr(5, subData, "irept", defValR), getObjectOr(subData, "irstg", defValC).toString(), getObjectOr(subData, "iame", defValC).toString(), formatNumStr(5, subData, "iamt", defValR), getObjectOr(subData, "ir_name", defValC).toString())); if (!subDataArr.isEmpty()) { sbData.append("@I IDATE IROP IRVAL\r\n"); } for (int j = 0; j < subDataArr.size(); j++) { subData = (HashMap) subDataArr.get(j); sbData.append(String.format("%1$2s %2$5s %3$-5s %4$5s\r\n", idx + 1, //getObjectOr(subData, "ir", defValI).toString(), formatDateStr(getObjectOr(subData, "date", defValD).toString()), // P.S. idate -> date getObjectOr(subData, "irop", defValC).toString(), formatNumStr(5, subData, "irval", defValR))); } } sbData.append("\r\n"); } // FERTILIZERS (INORGANIC) Section if (!mfArr.isEmpty()) { sbData.append("*FERTILIZERS (INORGANIC)\r\n"); sbData.append("@F FDATE FMCD FACD FDEP FAMN FAMP FAMK FAMC FAMO FOCD FERNAME\r\n"); // String fen_tot = getObjectOr(result, "fen_tot", defValR); // String fep_tot = getObjectOr(result, "fep_tot", defValR); // String fek_tot = getObjectOr(result, "fek_tot", defValR); // String pdate = getPdate(result); // if (pdate.equals("")) { // pdate = defValD; // } for (int idx = 0; idx < mfArr.size(); idx++) { secDataArr = (ArrayList) mfArr.get(idx); for (int i = 0; i < secDataArr.size(); i++) { secData = (HashMap) secDataArr.get(i); // if (getObjectOr(secData, "fdate", "").equals("")) { // sbError.append("! Warning: missing data : [fdate], and will automatically use planting value '").append(pdate).append("'\r\n"); // } // if (getObjectOr(secData, "fecd", "").equals("")) { // sbError.append("! Warning: missing data : [fecd], and will automatically use default value 'FE001'\r\n"); // } // if (getObjectOr(secData, "feacd", "").equals("")) { // sbError.append("! Warning: missing data : [feacd], and will automatically use default value 'AP002'\r\n"); // } // if (getObjectOr(secData, "fedep", "").equals("")) { // sbError.append("! Warning: missing data : [fedep], and will automatically use default value '10'\r\n"); // } // if (getObjectOr(secData, "feamn", "").equals("")) { // sbError.append("! Warning: missing data : [feamn], and will automatically use the value of FEN_TOT, '").append(fen_tot).append("'\r\n"); // } // if (getObjectOr(secData, "feamp", "").equals("")) { // sbError.append("! Warning: missing data : [feamp], and will automatically use the value of FEP_TOT, '").append(fep_tot).append("'\r\n"); // } // if (getObjectOr(secData, "feamk", "").equals("")) { // sbError.append("! Warning: missing data : [feamk], and will automatically use the value of FEK_TOT, '").append(fek_tot).append("'\r\n"); // } sbData.append(String.format("%1$2s %2$5s %3$5s %4$5s %5$5s %6$5s %7$5s %8$5s %9$5s %10$5s %11$5s %12$s\r\n", idx + 1, //getObjectOr(data, "fe", defValI).toString(), formatDateStr(getObjectOr(secData, "date", defValD).toString()), // P.S. fdate -> date getObjectOr(secData, "fecd", defValC).toString(), // P.S. Set default value as "FE005"(Cancelled) getObjectOr(secData, "feacd", defValC).toString(), // P.S. Set default value as "AP002"(Cancelled) formatNumStr(5, secData, "fedep", defValR), // P.S. Set default value as "10"(Cancelled) formatNumStr(5, secData, "feamn", defValR), // P.S. Set default value to use the value of FEN_TOT in meta data(Cancelled) formatNumStr(5, secData, "feamp", defValR), // P.S. Set default value to use the value of FEP_TOT in meta data(Cancelled) formatNumStr(5, secData, "feamk", defValR), // P.S. Set default value to use the value of FEK_TOT in meta data(Cancelled) formatNumStr(5, secData, "feamc", defValR), formatNumStr(5, secData, "feamo", defValR), getObjectOr(secData, "feocd", defValC).toString(), getObjectOr(secData, "fe_name", defValC).toString())); } } sbData.append("\r\n"); } // RESIDUES AND ORGANIC FERTILIZER Section if (!mrArr.isEmpty()) { sbData.append("*RESIDUES AND ORGANIC FERTILIZER\r\n"); sbData.append("@R RDATE RCOD RAMT RESN RESP RESK RINP RDEP RMET RENAME\r\n"); for (int idx = 0; idx < mrArr.size(); idx++) { secDataArr = (ArrayList) mrArr.get(idx); for (int i = 0; i < secDataArr.size(); i++) { secData = (HashMap) secDataArr.get(i); sbData.append(String.format("%1$2s %2$5s %3$-5s %4$5s %5$5s %6$5s %7$5s %8$5s %9$5s %10$5s %11$s\r\n", idx + 1, //getObjectOr(secData, "om", defValI).toString(), formatDateStr(getObjectOr(secData, "date", defValD).toString()), // P.S. omdat -> date getObjectOr(secData, "omcd", defValC).toString(), formatNumStr(5, secData, "omamt", defValR), formatNumStr(5, secData, "omn%", defValR), formatNumStr(5, secData, "omp%", defValR), formatNumStr(5, secData, "omk%", defValR), formatNumStr(5, secData, "ominp", defValR), formatNumStr(5, secData, "omdep", defValR), formatNumStr(5, secData, "omacd", defValR), getObjectOr(secData, "om_name", defValC).toString())); } } sbData.append("\r\n"); } // CHEMICAL APPLICATIONS Section if (!mcArr.isEmpty()) { sbData.append("*CHEMICAL APPLICATIONS\r\n"); sbData.append("@C CDATE CHCOD CHAMT CHME CHDEP CHT..CHNAME\r\n"); for (int idx = 0; idx < mcArr.size(); idx++) { secDataArr = (ArrayList) mcArr.get(idx); for (int i = 0; i < secDataArr.size(); i++) { secData = (HashMap) secDataArr.get(i); sbData.append(String.format("%1$2s %2$5s %3$5s %4$5s %5$5s %6$5s %7$5s %8$s\r\n", idx + 1, //getObjectOr(secData, "ch", defValI).toString(), formatDateStr(getObjectOr(secData, "date", defValD).toString()), // P.S. cdate -> date getObjectOr(secData, "chcd", defValC).toString(), formatNumStr(5, secData, "chamt", defValR), getObjectOr(secData, "chacd", defValC).toString(), getObjectOr(secData, "chdep", defValC).toString(), getObjectOr(secData, "ch_targets", defValC).toString(), getObjectOr(secData, "ch_name", defValC).toString())); } } sbData.append("\r\n"); } // TILLAGE Section if (!mtArr.isEmpty()) { sbData.append("*TILLAGE AND ROTATIONS\r\n"); sbData.append("@T TDATE TIMPL TDEP TNAME\r\n"); for (int idx = 0; idx < mtArr.size(); idx++) { secDataArr = (ArrayList) mtArr.get(idx); for (int i = 0; i < secDataArr.size(); i++) { secData = (HashMap) secDataArr.get(i); sbData.append(String.format("%1$2s %2$5s %3$5s %4$5s %5$s\r\n", idx + 1, //getObjectOr(secData, "ti", defValI).toString(), formatDateStr(getObjectOr(secData, "date", defValD).toString()), // P.S. tdate -> date getObjectOr(secData, "tiimp", defValC).toString(), formatNumStr(5, secData, "tidep", defValR), getObjectOr(secData, "ti_name", defValC).toString())); } } sbData.append("\r\n"); } // ENVIRONMENT MODIFICATIONS Section if (!meArr.isEmpty()) { sbData.append("*ENVIRONMENT MODIFICATIONS\r\n"); sbData.append("@E ODATE EDAY ERAD EMAX EMIN ERAIN ECO2 EDEW EWIND ENVNAME\r\n"); String emNumStr = ""; for (int idx = 0, cnt = 1; idx < meArr.size(); idx++) { // secDataArr = (ArrayList) meArr.get(idx); secData = meArr.get(idx); if (!emNumStr.equals(secData.get("em"))) { cnt++; emNumStr = (String) secData.get("em"); } sbData.append(String.format("%1$2s%2$s\r\n", cnt, secData.get("em_data"))); // for (int i = 0; i < secDataArr.size(); i++) { // sbData.append(String.format("%1$2s%2$s\r\n", // idx + 1, // (String) secDataArr.get(i))); // sbData.append(String.format("%1$2s %2$5s %3$-1s%4$4s %5$-1s%6$4s %7$-1s%8$4s %9$-1s%10$4s %11$-1s%12$4s %13$-1s%14$4s %15$-1s%16$4s %17$-1s%18$4s %19$s\r\n", // idx + 1, //getObjectOr(secData, "em", defValI).toString(), // formatDateStr(getObjectOr(secData, "date", defValD).toString()), // P.S. emday -> date // getObjectOr(secData, "ecdyl", defValBlank).toString(), // formatNumStr(4, getObjectOr(secData, "emdyl", defValR), // getObjectOr(secData, "ecrad", defValBlank).toString(), // formatNumStr(4, getObjectOr(secData, "emrad", defValR), // getObjectOr(secData, "ecmax", defValBlank).toString(), // formatNumStr(4, getObjectOr(secData, "emmax", defValR), // getObjectOr(secData, "ecmin", defValBlank).toString(), // formatNumStr(4, getObjectOr(secData, "emmin", defValR), // getObjectOr(secData, "ecrai", defValBlank).toString(), // formatNumStr(4, getObjectOr(secData, "emrai", defValR), // getObjectOr(secData, "ecco2", defValBlank).toString(), // formatNumStr(4, getObjectOr(secData, "emco2", defValR), // getObjectOr(secData, "ecdew", defValBlank).toString(), // formatNumStr(4, getObjectOr(secData, "emdew", defValR), // getObjectOr(secData, "ecwnd", defValBlank).toString(), // formatNumStr(4, getObjectOr(secData, "emwnd", defValR), // getObjectOr(secData, "em_name", defValC).toString())); // } } sbData.append("\r\n"); } // HARVEST DETAILS Section if (!mhArr.isEmpty()) { sbData.append("*HARVEST DETAILS\r\n"); sbData.append("@H HDATE HSTG HCOM HSIZE HPC HBPC HNAME\r\n"); for (int idx = 0; idx < mhArr.size(); idx++) { secDataArr = (ArrayList) mhArr.get(idx); for (int i = 0; i < secDataArr.size(); i++) { secData = (HashMap) secDataArr.get(i); sbData.append(String.format("%1$2s %2$5s %3$-5s %4$-5s %5$-5s %6$5s %7$5s %8$s\r\n", idx + 1, //getObjectOr(secData, "ha", defValI).toString(), formatDateStr(getObjectOr(secData, "date", defValD).toString()), // P.S. hdate -> date getObjectOr(secData, "hastg", defValC).toString(), getObjectOr(secData, "hacom", defValC).toString(), getObjectOr(secData, "hasiz", defValC).toString(), formatNumStr(5, secData, "hapc", defValR), formatNumStr(5, secData, "habpc", defValR), getObjectOr(secData, "ha_name", defValC).toString())); } } sbData.append("\r\n"); } // SIMULATION CONTROLS and AUTOMATIC MANAGEMENT Section if (!smArr.isEmpty()) { // Set Title list ArrayList smTitles = new ArrayList(); smTitles.add("@N GENERAL NYERS NREPS START SDATE RSEED SNAME.................... SMODEL\r\n"); smTitles.add("@N OPTIONS WATER NITRO SYMBI PHOSP POTAS DISES CHEM TILL CO2\r\n"); smTitles.add("@N METHODS WTHER INCON LIGHT EVAPO INFIL PHOTO HYDRO NSWIT MESOM MESEV MESOL\r\n"); smTitles.add("@N MANAGEMENT PLANT IRRIG FERTI RESID HARVS\r\n"); smTitles.add("@N OUTPUTS FNAME OVVEW SUMRY FROPT GROUT CAOUT WAOUT NIOUT MIOUT DIOUT VBOSE CHOUT OPOUT\r\n"); smTitles.add("@ AUTOMATIC MANAGEMENT\r\n@N PLANTING PFRST PLAST PH2OL PH2OU PH2OD PSTMX PSTMN\r\n"); smTitles.add("@N IRRIGATION IMDEP ITHRL ITHRU IROFF IMETH IRAMT IREFF\r\n"); smTitles.add("@N NITROGEN NMDEP NMTHR NAMNT NCODE NAOFF\r\n"); smTitles.add("@N RESIDUES RIPCN RTIME RIDEP\r\n"); smTitles.add("@N HARVEST HFRST HLAST HPCNP HPCNR\r\n"); String[] keys = new String[10]; keys[0] = "sm_general"; keys[1] = "sm_options"; keys[2] = "sm_methods"; keys[3] = "sm_management"; keys[4] = "sm_outputs"; keys[5] = "sm_planting"; keys[6] = "sm_irrigation"; keys[7] = "sm_nitrogen"; keys[8] = "sm_residues"; keys[9] = "sm_harvests"; // Loop all the simulation control records for (int idx = 0; idx < smArr.size(); idx++) { secData = (HashMap) smArr.get(idx); if (secData.containsKey("sm_general")) { sbData.append("*SIMULATION CONTROLS\r\n"); secData.remove("sm"); // Object[] keys = secData.keySet().toArray(); for (int i = 0; i < keys.length; i++) { sbData.append(smTitles.get(i)); sbData.append(String.format("%2s ", idx + 1)).append(((String) secData.get(keys[i]))).append("\r\n"); if (i == 4) { sbData.append("\r\n"); } } } else { sbData.append(createSMMAStr(idx + 1, expData, secData)); } } } else { sbData.append(createSMMAStr(1, expData, new HashMap())); } // Output finish bwX.write(sbError.toString()); bwX.write(sbGenData.toString()); bwX.write(sbNotesData.toString()); bwX.write(sbData.toString()); bwX.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } /** * Create string of Simulation Control and Automatic Management Section * * @param smid simulation index number * @param expData date holder for experiment data * @param trData date holder for one treatment data * @return date string with format of "yyddd" */ private String createSMMAStr(int smid, HashMap expData, HashMap trData) { StringBuilder sb = new StringBuilder(); String nitro = "Y"; String water = "Y"; String sdate; String sm = String.format("%2d", smid); ArrayList<HashMap> dataArr; HashMap subData; // // Check if the meta data of fertilizer is not "N" ("Y" or null) // if (!getValueOr(expData, "fertilizer", "").equals("N")) { // // // Check if necessary data is missing in all the event records // // P.S. rule changed since all the necessary data has a default value for it // dataArr = (ArrayList) getObjectOr(trData, "fertilizer", new ArrayList()); // if (dataArr.isEmpty()) { // nitro = "N"; // } //// for (int i = 0; i < dataArr.size(); i++) { //// subData = dataArr.get(i); //// if (getValueOr(subData, "date", "").equals("") //// || getValueOr(subData, "fecd", "").equals("") //// || getValueOr(subData, "feacd", "").equals("") //// || getValueOr(subData, "feamn", "").equals("")) { //// nitro = "N"; //// break; //// } //// } // } // // Check if the meta data of irrigation is not "N" ("Y" or null) // if (!getValueOr(expData, "irrigation", "").equals("N")) { // // // Check if necessary data is missing in all the event records // dataArr = (ArrayList) getObjectOr(trData, "irrigation", new ArrayList()); // for (int i = 0; i < dataArr.size(); i++) { // subData = dataArr.get(i); // if (getValueOr(subData, "date", "").equals("") // || getValueOr(subData, "irval", "").equals("")) { // water = "N"; // break; // } // } // } sdate = getObjectOr(expData, "sdat", "").toString(); if (sdate.equals("")) { subData = (HashMap) getObjectOr(trData, "planting", new HashMap()); sdate = getValueOr(subData, "date", defValD); } sdate = formatDateStr(sdate); sb.append("*SIMULATION CONTROLS\r\n"); sb.append("@N GENERAL NYERS NREPS START SDATE RSEED SNAME....................\r\n"); sb.append(sm).append(" GE 1 1 S ").append(sdate).append(" 2150 DEFAULT SIMULATION CONTROL\r\n"); sb.append("@N OPTIONS WATER NITRO SYMBI PHOSP POTAS DISES CHEM TILL CO2\r\n"); sb.append(sm).append(" OP ").append(water).append(" ").append(nitro).append(" Y N N N N Y M\r\n"); sb.append("@N METHODS WTHER INCON LIGHT EVAPO INFIL PHOTO HYDRO NSWIT MESOM MESEV MESOL\r\n"); sb.append(sm).append(" ME M M E R S L R 1 P S 2\r\n"); // P.S. 2012/09/02 MESOM "G" -> "P" sb.append("@N MANAGEMENT PLANT IRRIG FERTI RESID HARVS\r\n"); sb.append(sm).append(" MA R R R R M\r\n"); sb.append("@N OUTPUTS FNAME OVVEW SUMRY FROPT GROUT CAOUT WAOUT NIOUT MIOUT DIOUT VBOSE CHOUT OPOUT\r\n"); sb.append(sm).append(" OU N Y Y 1 Y Y N N N N N N N\r\n\r\n"); sb.append("@ AUTOMATIC MANAGEMENT\r\n"); sb.append("@N PLANTING PFRST PLAST PH2OL PH2OU PH2OD PSTMX PSTMN\r\n"); sb.append(sm).append(" PL 82050 82064 40 100 30 40 10\r\n"); sb.append("@N IRRIGATION IMDEP ITHRL ITHRU IROFF IMETH IRAMT IREFF\r\n"); sb.append(sm).append(" IR 30 50 100 GS000 IR001 10 1.00\r\n"); sb.append("@N NITROGEN NMDEP NMTHR NAMNT NCODE NAOFF\r\n"); sb.append(sm).append(" NI 30 50 25 FE001 GS000\r\n"); sb.append("@N RESIDUES RIPCN RTIME RIDEP\r\n"); sb.append(sm).append(" RE 100 1 20\r\n"); sb.append("@N HARVEST HFRST HLAST HPCNP HPCNR\r\n"); sb.append(sm).append(" HA 0 83057 100 0\r\n"); return sb.toString(); } /** * Get index value of the record and set new id value in the array * * @param m sub data * @param arr array of sub data * @return current index value of the sub data */ private int setSecDataArr(HashMap m, ArrayList arr) { if (!m.isEmpty()) { for (int j = 0; j < arr.size(); j++) { if (arr.get(j).equals(m)) { return j + 1; } } arr.add(m); return arr.size(); } else { return 0; } } /** * Get index value of the record and set new id value in the array * * @param inArr sub array of data * @param outArr array of sub data * @return current index value of the sub data */ private int setSecDataArr(ArrayList inArr, ArrayList outArr) { if (!inArr.isEmpty()) { for (int j = 0; j < outArr.size(); j++) { if (outArr.get(j).equals(inArr)) { return j + 1; } } outArr.add(inArr); return outArr.size(); } else { return 0; } } /** * To check if there is plot info data existed in the experiment * * @param expData experiment data holder * @return the boolean value for if plot info exists */ private boolean isPlotInfoExist(Map expData) { String[] plotIds = {"plta", "pltr#", "pltln", "pldr", "pltsp", "plot_layout", "pltha", "plth#", "plthl", "plthm"}; for (int i = 0; i < plotIds.length; i++) { if (!getValueOr(expData, plotIds[i], "").equals("")) { return true; } } return false; } /** * To check if there is soil analysis info data existed in the experiment * * @param expData initial condition layer data array * @return the boolean value for if soil analysis info exists */ private boolean isSoilAnalysisExist(ArrayList<HashMap> icSubArr) { for (int i = 0; i < icSubArr.size(); i++) { if (!getValueOr(icSubArr.get(i), "slsc", "").equals("")) { return true; } } return false; } /** * Get sub data array from experiment data object * * @param expData experiment data holder * @param blockName top level block name * @param dataListName sub array name * @return sub data array */ private ArrayList<HashMap> getDataList(Map expData, String blockName, String dataListName) { HashMap dataBlock = getObjectOr(expData, blockName, new HashMap()); return getObjectOr(dataBlock, dataListName, new ArrayList<HashMap>()); } /** * Try to translate 3-bit crid to 2-bit version stored in the map * * @param cuData the cultivar data record * @param id the field id for contain crop id info */ private void translateTo2BitCrid(HashMap cuData, String id) { String crid = getObjectOr(cuData, id, ""); if (!crid.equals("")) { DssatCRIDHelper crids = new DssatCRIDHelper(); cuData.put(id, crids.get2BitCrid(crid)); } } /** * Try to translate 3-bit crid to 2-bit version stored in the map * * @param cuData the cultivar data record */ private void translateTo2BitCrid(HashMap cuData) { translateTo2BitCrid(cuData, "crid"); } }
1. Fix #28
src/main/java/org/agmip/translators/dssat/DssatXFileOutput.java
1. Fix #28
<ide><path>rc/main/java/org/agmip/translators/dssat/DssatXFileOutput.java <ide> // Set cultivals info <ide> copyItem(cuData, evtData, "cul_name"); <ide> copyItem(cuData, evtData, "crid"); <del> copyItem(cuData, evtData, "cul_id"); <add> copyItem(cuData, evtData, "cul_id", "dssat_cul_id", false); <ide> copyItem(cuData, evtData, "rm"); <ide> copyItem(cuData, evtData, "cul_notes"); <ide> translateTo2BitCrid(cuData);
Java
mit
ccb4f63fd3ee31020125fdec8eb804221213c1a6
0
OreCruncher/ThermalRecycling
/* * This file is part of ThermalRecycling, licensed under the MIT License (MIT). * * Copyright (c) OreCruncher * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.blockartistry.mod.ThermalRecycling.data; import java.util.HashSet; import java.util.List; import java.util.Set; import org.blockartistry.mod.ThermalRecycling.ModLog; import org.blockartistry.mod.ThermalRecycling.data.registry.ItemData; import org.blockartistry.mod.ThermalRecycling.data.registry.ItemRegistry; import org.blockartistry.mod.ThermalRecycling.data.registry.RecipeData; import org.blockartistry.mod.ThermalRecycling.util.ItemStackHelper; import net.minecraft.item.ItemStack; public final class AutoDetect { private static boolean EXECUTE = false; private AutoDetect() { } private static float detect(final ItemData data, final Set<ItemStack> recursionList) { if (data.auto == null) { // ModLog.debug("detect: %s (%s)", data.getName(), // data.getInternalName()); final RecipeData recipe = ItemRegistry.getRecipe(data.stack); if (data.isBlockedFromScrapping || recipe == null || !recipe.hasOutput()) { data.auto = data.value; data.score = data.auto.score; } else { if(!recursionList.add(data.stack)) { ModLog.info("Recursion detected on item : " + ItemStackHelper.resolveInternalName(data.stack)); data.auto = data.value; data.score = data.value.score; return data.score; } float score = 0; final List<ItemStack> output = recipe.getOutput(); for (final ItemStack stack : output) { final ItemData child = ItemRegistry.get(stack); score += detect(child, recursionList) * stack.stackSize; } score = score / (float) recipe.getMinimumInputQuantityRequired(); data.auto = ScrapValue.determineValue(score); data.score = score; if (data.value != data.auto) { final StringBuilder builder = new StringBuilder(); builder.append("MISMATCH: ").append(data.getInternalName()); builder.append(" value: ").append(data.value.name()); builder.append(" auto: ").append(data.auto.name()); ModLog.info(builder.toString()); } recursionList.remove(data.stack); } } return data.score; } public static void detect() { if(!EXECUTE) return; // Score the buggers for (final ItemData data : ItemRegistry.getItemDataList()) try { final Set<ItemStack> recursion = new HashSet<ItemStack>(); detect(data, recursion); } catch (final Exception ex) { ModLog.warn("autoDetect() blew a gasket: %s (%s)", data.getName(), data.getInternalName()); } } }
src/main/java/org/blockartistry/mod/ThermalRecycling/data/AutoDetect.java
/* * This file is part of ThermalRecycling, licensed under the MIT License (MIT). * * Copyright (c) OreCruncher * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.blockartistry.mod.ThermalRecycling.data; import java.util.HashSet; import java.util.List; import java.util.Set; import org.blockartistry.mod.ThermalRecycling.ModLog; import org.blockartistry.mod.ThermalRecycling.data.registry.ItemData; import org.blockartistry.mod.ThermalRecycling.data.registry.ItemRegistry; import org.blockartistry.mod.ThermalRecycling.data.registry.RecipeData; import org.blockartistry.mod.ThermalRecycling.util.ItemStackHelper; import net.minecraft.item.ItemStack; public final class AutoDetect { private static boolean EXECUTE = true; private AutoDetect() { } private static float detect(final ItemData data, final Set<ItemStack> recursionList) { if (data.auto == null) { // ModLog.debug("detect: %s (%s)", data.getName(), // data.getInternalName()); final RecipeData recipe = ItemRegistry.getRecipe(data.stack); if (data.isBlockedFromScrapping || recipe == null || !recipe.hasOutput()) { data.auto = data.value; data.score = data.auto.score; } else { if(!recursionList.add(data.stack)) { ModLog.info("Recursion detected on item : " + ItemStackHelper.resolveInternalName(data.stack)); data.auto = data.value; data.score = data.value.score; return data.score; } float score = 0; final List<ItemStack> output = recipe.getOutput(); for (final ItemStack stack : output) { final ItemData child = ItemRegistry.get(stack); score += detect(child, recursionList) * stack.stackSize; } score = score / (float) recipe.getMinimumInputQuantityRequired(); data.auto = ScrapValue.determineValue(score); data.score = score; if (data.value != data.auto) { final StringBuilder builder = new StringBuilder(); builder.append("MISMATCH: ").append(data.getInternalName()); builder.append(" value: ").append(data.value.name()); builder.append(" auto: ").append(data.auto.name()); ModLog.info(builder.toString()); } recursionList.remove(data.stack); } } return data.score; } public static void detect() { if(!EXECUTE) return; // Score the buggers for (final ItemData data : ItemRegistry.getItemDataList()) try { final Set<ItemStack> recursion = new HashSet<ItemStack>(); detect(data, recursion); } catch (final Exception ex) { ModLog.warn("autoDetect() blew a gasket: %s (%s)", data.getName(), data.getInternalName()); } } }
Turn off scrap value profiling
src/main/java/org/blockartistry/mod/ThermalRecycling/data/AutoDetect.java
Turn off scrap value profiling
<ide><path>rc/main/java/org/blockartistry/mod/ThermalRecycling/data/AutoDetect.java <ide> <ide> public final class AutoDetect { <ide> <del> private static boolean EXECUTE = true; <add> private static boolean EXECUTE = false; <ide> <ide> private AutoDetect() { <ide> }
Java
apache-2.0
7f14dfcbbb1fd1f094030ccb6fec705279fb8466
0
akexorcist/Android-SleepingForLess
package com.akexorcist.sleepingforless.view.post; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.akexorcist.sleepingforless.R; import com.akexorcist.sleepingforless.view.post.constant.PostType; import com.akexorcist.sleepingforless.view.post.holder.CodePostViewHolder; import com.akexorcist.sleepingforless.view.post.holder.HeaderPostViewHolder; import com.akexorcist.sleepingforless.view.post.holder.ImagePostViewHolder; import com.akexorcist.sleepingforless.view.post.holder.PlainTextPostViewHolder; import com.akexorcist.sleepingforless.view.post.holder.VideoPostViewHolder; import com.akexorcist.sleepingforless.view.post.model.BasePost; import com.akexorcist.sleepingforless.view.post.model.CodePost; import com.akexorcist.sleepingforless.view.post.model.HeaderPost; import com.akexorcist.sleepingforless.view.post.model.ImagePost; import com.akexorcist.sleepingforless.view.post.model.PlainTextPost; import com.akexorcist.sleepingforless.view.post.model.VideoPost; import java.util.ArrayList; import java.util.List; /** * Created by Akexorcist on 3/10/2016 AD. */ public class PostAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> { private PostClickListener postClickListener; private List<BasePost> postList; public PostAdapter() { this.postList = new ArrayList<>(); } public PostAdapter(List<BasePost> postList) { this.postList = postList; } public void setPostClickListener(PostClickListener postClickListener) { this.postClickListener = postClickListener; } @Override public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { if (viewType == PostType.CODE) { return new CodePostViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.view_post_content_code, parent, false)); } else if (viewType == PostType.IMAGE) { return new ImagePostViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.view_post_content_image, parent, false)); } else if (viewType == PostType.VIDEO) { return new VideoPostViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.view_post_content_video, parent, false)); } else if (viewType == PostType.HEADER) { return new HeaderPostViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.view_post_content_header, parent, false)); } else if (viewType == PostType.PLAIN_TEXT) { return new PlainTextPostViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.view_post_content_plain_text, parent, false)); } else if (viewType == PostType.BLANK) { return new PlainTextPostViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.view_post_content_blank, parent, false)); } return null; } @Override public int getItemViewType(int position) { return position < postList.size() ? postList.get(position).getType() : PostType.BLANK; } @Override public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) { int viewType = getItemViewType(position); if (position < postList.size()) { BasePost basePost = postList.get(position); if (viewType == PostType.PLAIN_TEXT) { addPlainTextContent(holder, basePost); } else if (viewType == PostType.HEADER) { addHeaderContent(holder, basePost); } else if (viewType == PostType.IMAGE) { addImageContent(holder, basePost); } else if (viewType == PostType.CODE) { addCodeContent(holder, basePost); } else if (viewType == PostType.VIDEO) { addVideoContent(holder, basePost); } } } @Override public int getItemCount() { return postList.size() > 0 ? postList.size() + 1 : 0; } // Plain Text private void addPlainTextContent(RecyclerView.ViewHolder holder, BasePost basePost) { PlainTextPost post = (PlainTextPost) basePost; PlainTextPostViewHolder postViewHolder = (PlainTextPostViewHolder) holder; postViewHolder.setText(post); postViewHolder.setLinkClickListener(new LinkClickable.LinkClickListener() { @Override public void onLinkClick(String url) { if (postClickListener != null) { postClickListener.onLinkClickListener(url); } } }); } // Header private void addHeaderContent(RecyclerView.ViewHolder holder, BasePost basePost) { HeaderPost post = (HeaderPost) basePost; HeaderPostViewHolder postViewHolder = (HeaderPostViewHolder) holder; postViewHolder.setHeaderText(post.getText()); postViewHolder.setHeaderSize(post.getSize()); } // Code Text private void addCodeContent(RecyclerView.ViewHolder holder, BasePost basePost) { CodePost post = (CodePost) basePost; CodePostViewHolder postViewHolder = (CodePostViewHolder) holder; postViewHolder.setCode(post.getCode()); } // Image private void addImageContent(RecyclerView.ViewHolder holder, BasePost basePost) { final ImagePost post = (ImagePost) basePost; ImagePostViewHolder postViewHolder = (ImagePostViewHolder) holder; postViewHolder.load(post.getPostUrl()); postViewHolder.setImageClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (postClickListener != null) { postClickListener.onImageClickListener(post.getFullSizeUrl()); } } }); postViewHolder.setImageLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { if (postClickListener != null) { postClickListener.onImageLongClickListener(post.getFullSizeUrl()); } return true; } }); } // Video private void addVideoContent(RecyclerView.ViewHolder holder, BasePost basePost) { final VideoPost post = (VideoPost) basePost; final VideoPostViewHolder videoPostViewHolder = (VideoPostViewHolder) holder; videoPostViewHolder.setButtonPlayClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (postClickListener != null) { postClickListener.onVideoClickListener(post.getUrl()); } } }); videoPostViewHolder.setVideoUrl(post.getUrl()); } public interface PostClickListener { void onImageClickListener(String fullUrl); void onImageLongClickListener(String fullUrl); void onLinkClickListener(String url); void onVideoClickListener(String url); } }
app/src/main/java/com/akexorcist/sleepingforless/view/post/PostAdapter.java
package com.akexorcist.sleepingforless.view.post; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.akexorcist.sleepingforless.R; import com.akexorcist.sleepingforless.view.post.constant.PostType; import com.akexorcist.sleepingforless.view.post.holder.CodePostViewHolder; import com.akexorcist.sleepingforless.view.post.holder.HeaderPostViewHolder; import com.akexorcist.sleepingforless.view.post.holder.ImagePostViewHolder; import com.akexorcist.sleepingforless.view.post.holder.PlainTextPostViewHolder; import com.akexorcist.sleepingforless.view.post.holder.VideoPostViewHolder; import com.akexorcist.sleepingforless.view.post.model.BasePost; import com.akexorcist.sleepingforless.view.post.model.CodePost; import com.akexorcist.sleepingforless.view.post.model.HeaderPost; import com.akexorcist.sleepingforless.view.post.model.ImagePost; import com.akexorcist.sleepingforless.view.post.model.PlainTextPost; import com.akexorcist.sleepingforless.view.post.model.VideoPost; import java.util.ArrayList; import java.util.List; /** * Created by Akexorcist on 3/10/2016 AD. */ public class PostAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> { private PostClickListener postClickListener; private List<BasePost> postList; public PostAdapter() { this.postList = new ArrayList<>(); } public PostAdapter(List<BasePost> postList) { this.postList = postList; } public void setPostClickListener(PostClickListener postClickListener) { this.postClickListener = postClickListener; } @Override public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { if (viewType == PostType.CODE) { return new CodePostViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.view_post_content_code, parent, false)); } else if (viewType == PostType.IMAGE) { return new ImagePostViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.view_post_content_image, parent, false)); } else if (viewType == PostType.VIDEO) { return new VideoPostViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.view_post_content_video, parent, false)); } else if (viewType == PostType.HEADER) { return new HeaderPostViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.view_post_content_header, parent, false)); } else if (viewType == PostType.PLAIN_TEXT) { return new PlainTextPostViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.view_post_content_plain_text, parent, false)); } else if (viewType == PostType.BLANK) { return new PlainTextPostViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.view_post_content_blank, parent, false)); } return null; } @Override public int getItemViewType(int position) { return position < postList.size() - 1 ? postList.get(position).getType() : PostType.BLANK; } @Override public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) { int viewType = getItemViewType(position); if (position < postList.size() - 1) { BasePost basePost = postList.get(position); if (viewType == PostType.PLAIN_TEXT) { addPlainTextContent(holder, basePost); } else if (viewType == PostType.HEADER) { addHeaderContent(holder, basePost); } else if (viewType == PostType.IMAGE) { addImageContent(holder, basePost); } else if (viewType == PostType.CODE) { addCodeContent(holder, basePost); } else if (viewType == PostType.VIDEO) { addVideoContent(holder, basePost); } } } @Override public int getItemCount() { return postList.size() > 0 ? postList.size() + 1 : 0; } // Plain Text private void addPlainTextContent(RecyclerView.ViewHolder holder, BasePost basePost) { PlainTextPost post = (PlainTextPost) basePost; PlainTextPostViewHolder postViewHolder = (PlainTextPostViewHolder) holder; postViewHolder.setText(post); postViewHolder.setLinkClickListener(new LinkClickable.LinkClickListener() { @Override public void onLinkClick(String url) { if (postClickListener != null) { postClickListener.onLinkClickListener(url); } } }); } // Header private void addHeaderContent(RecyclerView.ViewHolder holder, BasePost basePost) { HeaderPost post = (HeaderPost) basePost; HeaderPostViewHolder postViewHolder = (HeaderPostViewHolder) holder; postViewHolder.setHeaderText(post.getText()); postViewHolder.setHeaderSize(post.getSize()); } // Code Text private void addCodeContent(RecyclerView.ViewHolder holder, BasePost basePost) { CodePost post = (CodePost) basePost; CodePostViewHolder postViewHolder = (CodePostViewHolder) holder; postViewHolder.setCode(post.getCode()); } // Image private void addImageContent(RecyclerView.ViewHolder holder, BasePost basePost) { final ImagePost post = (ImagePost) basePost; ImagePostViewHolder postViewHolder = (ImagePostViewHolder) holder; postViewHolder.load(post.getPostUrl()); postViewHolder.setImageClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (postClickListener != null) { postClickListener.onImageClickListener(post.getFullSizeUrl()); } } }); postViewHolder.setImageLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { if (postClickListener != null) { postClickListener.onImageLongClickListener(post.getFullSizeUrl()); } return true; } }); } // Video private void addVideoContent(RecyclerView.ViewHolder holder, BasePost basePost) { final VideoPost post = (VideoPost) basePost; final VideoPostViewHolder videoPostViewHolder = (VideoPostViewHolder) holder; videoPostViewHolder.setButtonPlayClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (postClickListener != null) { postClickListener.onVideoClickListener(post.getUrl()); } } }); videoPostViewHolder.setVideoUrl(post.getUrl()); } public interface PostClickListener { void onImageClickListener(String fullUrl); void onImageLongClickListener(String fullUrl); void onLinkClickListener(String url); void onVideoClickListener(String url); } }
Fix content item last row disappear
app/src/main/java/com/akexorcist/sleepingforless/view/post/PostAdapter.java
Fix content item last row disappear
<ide><path>pp/src/main/java/com/akexorcist/sleepingforless/view/post/PostAdapter.java <ide> <ide> @Override <ide> public int getItemViewType(int position) { <del> return position < postList.size() - 1 ? postList.get(position).getType() : PostType.BLANK; <add> return position < postList.size() ? postList.get(position).getType() : PostType.BLANK; <ide> } <ide> <ide> @Override <ide> public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) { <ide> int viewType = getItemViewType(position); <del> if (position < postList.size() - 1) { <add> if (position < postList.size()) { <ide> BasePost basePost = postList.get(position); <ide> if (viewType == PostType.PLAIN_TEXT) { <ide> addPlainTextContent(holder, basePost);
Java
apache-2.0
d5d2d32226b112a6fbf8f3579605563b8108ffd4
0
daradurvs/ignite,voipp/ignite,shroman/ignite,xtern/ignite,ascherbakoff/ignite,vladisav/ignite,shroman/ignite,samaitra/ignite,psadusumilli/ignite,irudyak/ignite,StalkXT/ignite,chandresh-pancholi/ignite,sk0x50/ignite,NSAmelchev/ignite,amirakhmedov/ignite,alexzaitzev/ignite,samaitra/ignite,daradurvs/ignite,daradurvs/ignite,andrey-kuznetsov/ignite,voipp/ignite,amirakhmedov/ignite,voipp/ignite,chandresh-pancholi/ignite,psadusumilli/ignite,endian675/ignite,StalkXT/ignite,psadusumilli/ignite,BiryukovVA/ignite,xtern/ignite,shroman/ignite,irudyak/ignite,psadusumilli/ignite,ptupitsyn/ignite,xtern/ignite,voipp/ignite,apache/ignite,NSAmelchev/ignite,vladisav/ignite,shroman/ignite,sk0x50/ignite,andrey-kuznetsov/ignite,irudyak/ignite,andrey-kuznetsov/ignite,ptupitsyn/ignite,voipp/ignite,samaitra/ignite,chandresh-pancholi/ignite,endian675/ignite,chandresh-pancholi/ignite,ptupitsyn/ignite,wmz7year/ignite,StalkXT/ignite,voipp/ignite,endian675/ignite,NSAmelchev/ignite,nizhikov/ignite,apache/ignite,xtern/ignite,WilliamDo/ignite,BiryukovVA/ignite,andrey-kuznetsov/ignite,shroman/ignite,amirakhmedov/ignite,wmz7year/ignite,apache/ignite,daradurvs/ignite,andrey-kuznetsov/ignite,WilliamDo/ignite,chandresh-pancholi/ignite,amirakhmedov/ignite,samaitra/ignite,BiryukovVA/ignite,andrey-kuznetsov/ignite,apache/ignite,nizhikov/ignite,ascherbakoff/ignite,SharplEr/ignite,daradurvs/ignite,irudyak/ignite,wmz7year/ignite,apache/ignite,endian675/ignite,vladisav/ignite,irudyak/ignite,alexzaitzev/ignite,amirakhmedov/ignite,BiryukovVA/ignite,xtern/ignite,alexzaitzev/ignite,StalkXT/ignite,psadusumilli/ignite,ilantukh/ignite,daradurvs/ignite,WilliamDo/ignite,samaitra/ignite,ascherbakoff/ignite,ilantukh/ignite,ilantukh/ignite,nizhikov/ignite,sk0x50/ignite,ascherbakoff/ignite,endian675/ignite,SharplEr/ignite,SomeFire/ignite,andrey-kuznetsov/ignite,sk0x50/ignite,StalkXT/ignite,ilantukh/ignite,apache/ignite,amirakhmedov/ignite,BiryukovVA/ignite,SharplEr/ignite,wmz7year/ignite,wmz7year/ignite,daradurvs/ignite,ptupitsyn/ignite,shroman/ignite,wmz7year/ignite,nizhikov/ignite,SomeFire/ignite,NSAmelchev/ignite,SharplEr/ignite,sk0x50/ignite,chandresh-pancholi/ignite,ascherbakoff/ignite,BiryukovVA/ignite,SomeFire/ignite,SomeFire/ignite,WilliamDo/ignite,sk0x50/ignite,StalkXT/ignite,ascherbakoff/ignite,SomeFire/ignite,wmz7year/ignite,ptupitsyn/ignite,SharplEr/ignite,daradurvs/ignite,SomeFire/ignite,vladisav/ignite,wmz7year/ignite,SharplEr/ignite,daradurvs/ignite,nizhikov/ignite,alexzaitzev/ignite,nizhikov/ignite,nizhikov/ignite,samaitra/ignite,alexzaitzev/ignite,endian675/ignite,chandresh-pancholi/ignite,irudyak/ignite,SomeFire/ignite,WilliamDo/ignite,irudyak/ignite,StalkXT/ignite,NSAmelchev/ignite,SomeFire/ignite,voipp/ignite,WilliamDo/ignite,alexzaitzev/ignite,samaitra/ignite,apache/ignite,andrey-kuznetsov/ignite,SharplEr/ignite,shroman/ignite,NSAmelchev/ignite,sk0x50/ignite,amirakhmedov/ignite,xtern/ignite,alexzaitzev/ignite,NSAmelchev/ignite,shroman/ignite,samaitra/ignite,vladisav/ignite,WilliamDo/ignite,endian675/ignite,StalkXT/ignite,ascherbakoff/ignite,ascherbakoff/ignite,samaitra/ignite,alexzaitzev/ignite,SharplEr/ignite,NSAmelchev/ignite,endian675/ignite,andrey-kuznetsov/ignite,xtern/ignite,ilantukh/ignite,ilantukh/ignite,irudyak/ignite,WilliamDo/ignite,BiryukovVA/ignite,ptupitsyn/ignite,irudyak/ignite,NSAmelchev/ignite,SharplEr/ignite,samaitra/ignite,apache/ignite,BiryukovVA/ignite,apache/ignite,xtern/ignite,ptupitsyn/ignite,psadusumilli/ignite,sk0x50/ignite,vladisav/ignite,chandresh-pancholi/ignite,shroman/ignite,sk0x50/ignite,amirakhmedov/ignite,vladisav/ignite,ascherbakoff/ignite,SomeFire/ignite,ilantukh/ignite,nizhikov/ignite,ilantukh/ignite,ptupitsyn/ignite,alexzaitzev/ignite,StalkXT/ignite,shroman/ignite,chandresh-pancholi/ignite,BiryukovVA/ignite,vladisav/ignite,nizhikov/ignite,amirakhmedov/ignite,ptupitsyn/ignite,SomeFire/ignite,ptupitsyn/ignite,BiryukovVA/ignite,psadusumilli/ignite,xtern/ignite,psadusumilli/ignite,andrey-kuznetsov/ignite,voipp/ignite,ilantukh/ignite,voipp/ignite,ilantukh/ignite,daradurvs/ignite
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.ignite.cache.eviction; import javax.cache.configuration.Factory; import org.apache.ignite.internal.util.typedef.internal.A; import static org.apache.ignite.configuration.CacheConfiguration.DFLT_CACHE_SIZE; /** * Common functionality implementation for eviction policies factories. */ public abstract class AbstractEvictionPolicyFactory<T> implements Factory<T> { /** */ private int maxSize = DFLT_CACHE_SIZE; /** */ private int batchSize = 1; /** */ private long maxMemSize; /** * Sets maximum allowed size of cache before entry will start getting evicted. * * @param max Maximum allowed size of cache before entry will start getting evicted. * @return {@code this} for chaining. */ public AbstractEvictionPolicyFactory setMaxSize(int max) { A.ensure(max >= 0, "max >= 0"); this.maxSize = max; return this; } /** * Gets maximum allowed size of cache before entry will start getting evicted. * * @return Maximum allowed size of cache before entry will start getting evicted. */ public int getMaxSize() { return maxSize; } /** * Sets batch size. * * @param batchSize Batch size. * @return {@code this} for chaining. */ public AbstractEvictionPolicyFactory setBatchSize(int batchSize) { A.ensure(batchSize > 0, "batchSize > 0"); this.batchSize = batchSize; return this; } /** * Gets batch size. * * @return batch size. */ public int getBatchSize() { return batchSize; } /** * Sets maximum allowed cache size in bytes. * * @return {@code this} for chaining. */ public AbstractEvictionPolicyFactory setMaxMemorySize(long maxMemSize) { A.ensure(maxMemSize >= 0, "maxMemSize >= 0"); this.maxMemSize = maxMemSize; return this; } /** * Gets maximum allowed cache size in bytes. * * @return maximum allowed cache size in bytes. */ public long getMaxMemorySize() { return maxMemSize; } }
modules/core/src/main/java/org/apache/ignite/cache/eviction/AbstractEvictionPolicyFactory.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.ignite.cache.eviction; import javax.cache.configuration.Factory; import org.apache.ignite.internal.util.typedef.internal.A; /** * Common functionality implementation for eviction policies factories. */ public abstract class AbstractEvictionPolicyFactory<T> implements Factory<T> { /** */ private int maxSize; /** */ private int batchSize = 1; /** */ private long maxMemSize; /** * Sets maximum allowed size of cache before entry will start getting evicted. * * @param max Maximum allowed size of cache before entry will start getting evicted. * @return {@code this} for chaining. */ public AbstractEvictionPolicyFactory setMaxSize(int max) { A.ensure(max >= 0, "max >= 0"); this.maxSize = max; return this; } /** * Gets maximum allowed size of cache before entry will start getting evicted. * * @return Maximum allowed size of cache before entry will start getting evicted. */ public int getMaxSize() { return maxSize; } /** * Sets batch size. * * @param batchSize Batch size. * @return {@code this} for chaining. */ public AbstractEvictionPolicyFactory setBatchSize(int batchSize) { A.ensure(batchSize > 0, "batchSize > 0"); this.batchSize = batchSize; return this; } /** * Gets batch size. * * @return batch size. */ public int getBatchSize() { return batchSize; } /** * Sets maximum allowed cache size in bytes. * * @return {@code this} for chaining. */ public AbstractEvictionPolicyFactory setMaxMemorySize(long maxMemSize) { A.ensure(maxMemSize >= 0, "maxMemSize >= 0"); this.maxMemSize = maxMemSize; return this; } /** * Gets maximum allowed cache size in bytes. * * @return maximum allowed cache size in bytes. */ public long getMaxMemorySize() { return maxMemSize; } }
Fixed IGNITE-6838. Restore EvictionPolicy 'maxSize' field default value.
modules/core/src/main/java/org/apache/ignite/cache/eviction/AbstractEvictionPolicyFactory.java
Fixed IGNITE-6838. Restore EvictionPolicy 'maxSize' field default value.
<ide><path>odules/core/src/main/java/org/apache/ignite/cache/eviction/AbstractEvictionPolicyFactory.java <ide> import javax.cache.configuration.Factory; <ide> import org.apache.ignite.internal.util.typedef.internal.A; <ide> <add>import static org.apache.ignite.configuration.CacheConfiguration.DFLT_CACHE_SIZE; <add> <ide> /** <ide> * Common functionality implementation for eviction policies factories. <ide> */ <ide> public abstract class AbstractEvictionPolicyFactory<T> implements Factory<T> { <ide> /** */ <del> private int maxSize; <add> private int maxSize = DFLT_CACHE_SIZE; <ide> <ide> /** */ <ide> private int batchSize = 1;
Java
apache-2.0
74bc6cb98556bf9172c4a77a4eec336fb0863311
0
thammegowda/incubator-joshua,fhieber/incubator-joshua,fhieber/incubator-joshua,lukeorland/joshua,fhieber/incubator-joshua,thammegowda/incubator-joshua,fhieber/incubator-joshua,thammegowda/incubator-joshua,thammegowda/incubator-joshua,lukeorland/joshua,thammegowda/incubator-joshua,lukeorland/joshua,thammegowda/incubator-joshua,thammegowda/incubator-joshua,lukeorland/joshua,fhieber/incubator-joshua,thammegowda/incubator-joshua,thammegowda/incubator-joshua,fhieber/incubator-joshua,fhieber/incubator-joshua,lukeorland/joshua,fhieber/incubator-joshua,thammegowda/incubator-joshua,lukeorland/joshua,fhieber/incubator-joshua,lukeorland/joshua,lukeorland/joshua,lukeorland/joshua
package joshua.decoder.ff; import java.util.List; import joshua.decoder.ff.state_maintenance.DPState; import joshua.decoder.ff.tm.Rule; import joshua.decoder.hypergraph.HGNode; import joshua.corpus.Vocabulary; import joshua.decoder.chart_parser.SourcePath; /** * This feature is fired when an out-of-vocabulary word (with respect to the translation model) is * entered into the chart. OOVs work in the following manner: for each word in the input that is OOV * with respect to the translation model, we create a rule that pushes that word through * untranslated (the suffix "_OOV" can optionally be appended according to the runtime parameter * "mark-oovs") . These rules are all stored in a grammar whose owner is "oov". The OOV feature * function template then fires the "OOVPenalty" feature whenever it is asked to score an OOV rule. * * @author Matt Post <[email protected]> */ public class OOVFF extends StatelessFF { private int ownerID = -1; public OOVFF(FeatureVector weights) { super(weights, "OOVPenalty"); ownerID = Vocabulary.id("oov"); } /** * OOV rules cover exactly one word, and such rules belong to a grammar whose owner is "oov". Each * OOV fires the OOVPenalty feature with a value of 1, so the cost is simply the weight, which was * cached when the feature was created. */ @Override public DPState compute(Rule rule, List<HGNode> tailNodes, int i, int j, SourcePath sourcePath, int sentID, Accumulator acc) { if (rule != null && this.ownerID == rule.getOwner()) acc.add(name, 1.0f); return null; } /** * It's important for the OOV feature to contribute to the rule's estimated cost, so that OOV * rules (which are added for all words, not just ones without translation options) get sorted * to the bottom during cube pruning. */ @Override public float estimateCost(Rule rule, int sentID) { if (rule != null && this.ownerID == rule.getOwner()) return weights.get(name); return 0.0f; } }
src/joshua/decoder/ff/OOVFF.java
package joshua.decoder.ff; import java.util.List; import joshua.decoder.ff.state_maintenance.DPState; import joshua.decoder.ff.tm.Rule; import joshua.decoder.hypergraph.HGNode; import joshua.corpus.Vocabulary; import joshua.decoder.chart_parser.SourcePath; /** * This feature is fired when an out-of-vocabulary word (with respect to the translation model) is * entered into the chart. OOVs work in the following manner: for each word in the input that is OOV * with respect to the translation model, we create a rule that pushes that word through * untranslated (the suffix "_OOV" can optionally be appended according to the runtime parameter * "mark-oovs") . These rules are all stored in a grammar whose owner is "oov". The OOV feature * function template then fires the "OOVPenalty" feature whenever it is asked to score an OOV rule. * * @author Matt Post <[email protected]> */ public class OOVFF extends StatelessFF { private int ownerID = -1; public OOVFF(FeatureVector weights) { super(weights, "OOVPenalty"); ownerID = Vocabulary.id("oov"); } /** * OOV rules cover exactly one word, and such rules belong to a grammar whose owner is "oov". Each * OOV fires the OOVPenalty feature with a value of 1, so the cost is simply the weight, which was * cached when the feature was created. */ @Override public DPState compute(Rule rule, List<HGNode> tailNodes, int i, int j, SourcePath sourcePath, int sentID, Accumulator acc) { if (rule != null && this.ownerID == rule.getOwner()) acc.add(name, 1.0f); return null; } }
BUGFIX: The OOV penalty was not contributing to the rule's estimated cost This is important because the estimated cost is used to sort rules during cube pruning. OOV rules were at the top prior to this.
src/joshua/decoder/ff/OOVFF.java
BUGFIX: The OOV penalty was not contributing to the rule's estimated cost
<ide><path>rc/joshua/decoder/ff/OOVFF.java <ide> <ide> return null; <ide> } <add> <add> /** <add> * It's important for the OOV feature to contribute to the rule's estimated cost, so that OOV <add> * rules (which are added for all words, not just ones without translation options) get sorted <add> * to the bottom during cube pruning. <add> */ <add> @Override <add> public float estimateCost(Rule rule, int sentID) { <add> if (rule != null && this.ownerID == rule.getOwner()) <add> return weights.get(name); <add> return 0.0f; <add> } <ide> }
Java
apache-2.0
66541573824c6bbd690921917ebcaf7b9af6428c
0
wmarshall484/streamsx.topology,wmarshall484/streamsx.topology,wmarshall484/streamsx.topology,IBMStreams/streamsx.topology,ddebrunner/streamsx.topology,IBMStreams/streamsx.topology,IBMStreams/streamsx.topology,ddebrunner/streamsx.topology,ddebrunner/streamsx.topology,wmarshall484/streamsx.topology,ddebrunner/streamsx.topology,IBMStreams/streamsx.topology,ddebrunner/streamsx.topology,wmarshall484/streamsx.topology,ddebrunner/streamsx.topology,IBMStreams/streamsx.topology,IBMStreams/streamsx.topology,wmarshall484/streamsx.topology,IBMStreams/streamsx.topology,ddebrunner/streamsx.topology,wmarshall484/streamsx.topology,wmarshall484/streamsx.topology
/* # Licensed Materials - Property of IBM # Copyright IBM Corp. 2015 */ package com.ibm.streamsx.topology.test.api; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotSame; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertSame; import static org.junit.Assert.assertTrue; import static org.junit.Assume.assumeTrue; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeMap; import java.util.concurrent.TimeUnit; import org.junit.Test; import com.ibm.streamsx.topology.TStream; import com.ibm.streamsx.topology.Topology; import com.ibm.streamsx.topology.context.StreamsContext.Type; import com.ibm.streamsx.topology.function.Function; import com.ibm.streamsx.topology.function.FunctionContainer; import com.ibm.streamsx.topology.function.FunctionContext; import com.ibm.streamsx.topology.function.Initializable; import com.ibm.streamsx.topology.function.Predicate; import com.ibm.streamsx.topology.function.ToIntFunction; import com.ibm.streamsx.topology.streams.BeaconStreams; import com.ibm.streamsx.topology.streams.CollectionStreams; import com.ibm.streamsx.topology.streams.StringStreams; import com.ibm.streamsx.topology.test.AllowAll; import com.ibm.streamsx.topology.test.TestTopology; import com.ibm.streamsx.topology.tester.Condition; import com.ibm.streamsx.topology.tester.Tester; public class StreamTest extends TestTopology { public static void assertStream(Topology f, TStream<?> stream) { TopologyTest.assertFlowElement(f, stream); } @Test public void testBasics() throws Exception { assumeTrue(isMainRun()); final Topology topology = new Topology("BasicStream"); assertEquals("BasicStream", topology.getName()); assertSame(topology, topology.topology()); TStream<String> source = topology.strings("a", "b", "c"); assertStream(topology, source); assertSame(String.class, source.getTupleClass()); assertSame(String.class, source.getTupleType()); assertNotSame(source, source.autonomous()); } @Test public void testStringFilter() throws Exception { final Topology f = newTopology("StringFilter"); TStream<String> source = f.strings("hello", "goodbye", "farewell"); assertStream(f, source); TStream<String> filtered = source.filter(lengthFilter(5)); completeAndValidate(filtered, 10, "goodbye", "farewell"); } @SuppressWarnings("serial") public static Predicate<String> lengthFilter(final int length) { return new Predicate<String>() { @Override public boolean test(String v1) { return v1.length() > length; } }; } @Test public void testTransform() throws Exception { final Topology f = newTopology("TransformStream"); TStream<String> source = f.strings("325", "457", "9325"); assertStream(f, source); TStream<Integer> i1 = source.transform(stringToInt()); TStream<Integer> i2 = i1.transform(add17()); completeAndValidate(i2, 10, "342", "474", "9342"); } @Test public void testTransformWithDrop() throws Exception { final Topology f = newTopology("TransformStream"); TStream<String> source = f.strings("93", "68", "221"); assertStream(f, source); TStream<Integer> i1 = source.transform(stringToIntExcept68()); TStream<Integer> i2 = i1.transform(add17()); completeAndValidate(i2, 10, "110", "238"); } @Test public void testMultiTransform() throws Exception { final Topology topology = newTopology("MultiTransformStream"); TStream<String> source = topology.strings("mary had a little lamb", "its fleece was white as snow"); assertStream(topology, source); TStream<String> words = source.multiTransform(splitWords()); completeAndValidate(words, 10, "mary", "had", "a", "little", "lamb", "its", "fleece", "was", "white", "as", "snow"); } @Test public void testUnionNops() throws Exception { assumeTrue(isMainRun()); final Topology f = newTopology("Union"); TStream<String> s1 = f.strings("A1", "B1", "C1", "D1"); Set<TStream<String>> empty = Collections.emptySet(); assertSame(s1, s1.union(s1)); assertSame(s1, s1.union(empty)); assertSame(s1, s1.union(Collections.singleton(s1))); } @Test public void testUnion() throws Exception { final Topology topology = newTopology("Union"); TStream<String> s1 = topology.strings("A1", "B1", "C1", "D1"); TStream<String> s2 = topology.strings("A2", "B2", "C2", "D2"); List<String> l3 = new ArrayList<>(); l3.add("A3"); l3.add("B3"); TStream<String> s3 = topology.constants(l3); List<String> l4 = new ArrayList<>(); l4.add("A4"); l4.add("B4"); TStream<String> s4 = topology.constants(l4); assertNotSame(s1, s2); TStream<String> su = s1.union(s2); assertNotSame(su, s1); assertNotSame(su, s2); // Merge with two different schema types // but the primary has the correct direct type. su = su.union(s3); assertEquals(String.class, su.getTupleClass()); assertEquals(String.class, su.getTupleType()); // Merge with two different schema types // but the primary has the generic type assertNull(s4.getTupleClass()); su = s4.union(su); assertEquals(String.class, su.getTupleClass()); assertEquals(String.class, su.getTupleType()); // TODO - testing doesn't work against union streams in embedded. su = su.filter(new AllowAll<String>()); Tester tester = topology.getTester(); Condition<Long> suCount = tester.tupleCount(su, 12); Condition<List<String>> suContents = tester.stringContentsUnordered(su, "A1", "B1", "C1", "D1", "A2", "B2", "C2", "D2", "A3", "B3", "A4", "B4"); //assertTrue(complete(tester, suCount, 10, TimeUnit.SECONDS)); complete(tester, suCount, 10, TimeUnit.SECONDS); assertTrue("SU:" + suContents, suContents.valid()); assertTrue("SU:" + suCount, suCount.valid()); } @Test public void testUnionSet() throws Exception { final Topology topology = newTopology("Union"); TStream<String> s1 = topology.strings("A1", "B1", "C1"); TStream<String> s2 = topology.strings("A2", "B2", "C2", "D2"); TStream<String> s3 = topology.strings("A3", "B3", "C3"); Set<TStream<String>> streams = new HashSet<TStream<String>>(); streams.add(s2); streams.add(s3); TStream<String> su = s1.union(streams); // TODO - testing doesn't work against union streams in embedded. su = su.filter(new AllowAll<String>()); Tester tester = topology.getTester(); Condition<Long> suCount = tester.tupleCount(su, 10); Condition<List<String>> suContents = tester.stringContentsUnordered(su, "A1", "B1", "C1", "A2", "B2", "C2", "D2", "A3", "B3", "C3"); assertTrue(complete(tester, suCount, 10, TimeUnit.SECONDS)); // assertTrue("SU:" + suContents, suContents.valid()); assertTrue("SU:" + suCount, suCount.valid()); assertTrue("SUContents:" + suContents, suContents.valid()); } @Test public void testSimpleParallel() throws Exception { final Topology topology = newTopology("EmbeddedParallel"); TStream<Number> s1 = topology.numbers(1, 2, 3, 94, 5, 6).parallel(6) .filter(new AllowAll<Number>()).endParallel(); TStream<String> sp = StringStreams.toString(s1); Tester tester = topology.getTester(); Condition<Long> spCount = tester.tupleCount(sp, 6); Condition<List<String>> spContents = tester.stringContentsUnordered(sp, "1", "2", "3", "94", "5", "6"); complete(tester, spCount, 60, TimeUnit.SECONDS); // assertTrue("SU:" + suContents, suContents.valid()); assertTrue("SP:" + spCount, spCount.valid()); assertTrue("SPContents:" + spContents, spContents.valid()); } @Test public void testSplit() throws Exception { final Topology topology = newTopology("testSplit"); TStream<String> s1 = topology.strings("ch0", "ch1", "ch2", "omit", "another-ch2", "another-ch1", "another-ch0", "another-omit"); List<TStream<String>> splits = s1.split(3, myStringSplitter()); assertEquals("list size", 3, splits.size()); Tester tester = topology.getTester(); List<Condition<List<String>>> contents = new ArrayList<>(); for(int i = 0; i < splits.size(); i++) { TStream<String> ch = splits.get(i); Condition<List<String>> chContents = tester.stringContents(ch, "ch"+i, "another-ch"+i); contents.add(chContents); } TStream<String> all = splits.get(0).union( new HashSet<>(splits.subList(1, splits.size()))); Condition<Long> uCount = tester.tupleCount(all, 6); complete(tester, uCount, 10, TimeUnit.SECONDS); for(int i = 0; i < splits.size(); i++) { assertTrue("chContents["+i+"]:" + contents.get(i), contents.get(i).valid()); } } /** * Partition strings based on the last character of the string. * If the last character is a digit return its value as an int, else return -1. * @return */ @SuppressWarnings("serial") private static ToIntFunction<String> myStringSplitter() { return new ToIntFunction<String>() { @Override public int applyAsInt(String s) { char ch = s.charAt(s.length() - 1); return Character.digit(ch, 10); } }; } @SuppressWarnings("serial") static Function<String, Integer> stringToInt() { return new Function<String, Integer>() { @Override public Integer apply(String v1) { return Integer.valueOf(v1); } }; } @SuppressWarnings("serial") static Function<String, Integer> stringToIntExcept68() { return new Function<String, Integer>() { @Override public Integer apply(String v1) { Integer i = Integer.valueOf(v1); return (i == 68) ? null : i; } }; } @SuppressWarnings("serial") static Function<Integer, Integer> add17() { return new Function<Integer, Integer>() { @Override public Integer apply(Integer v1) { return v1 + 17; } }; } @SuppressWarnings("serial") static Function<String, Iterable<String>> splitWords() { return new Function<String, Iterable<String>>() { @Override public Iterable<String> apply(String v1) { return Arrays.asList(v1.split(" ")); } }; } @Test public void testFunctionContextNonDistributed() throws Exception { assumeTrue(getTesterType() != Type.DISTRIBUTED_TESTER); Topology t = newTopology(); TStream<Map<String, Object>> values = BeaconStreams.single(t).transform(new ExtractFunctionContext()); TStream<String> strings = StringStreams.toString(CollectionStreams.flattenMap(values)); Tester tester = t.getTester(); Condition<Long> spCount = tester.tupleCount(strings, 9); Condition<List<String>> spContents = tester.stringContents(strings, "channel=-1", "domainId=" + System.getProperty("user.name"), "id=0", "instanceId=" + System.getProperty("user.name"), "jobId=0", "jobName=NOTNULL", "maxChannels=0", "noAppConfig={}", "relaunchCount=0" ); complete(tester, spCount, 60, TimeUnit.SECONDS); // assertTrue("SU:" + suContents, suContents.valid()); assertTrue("SP:" + spCount, spCount.valid()); assertTrue("SPContents:" + spContents, spContents.valid()); } public static class ExtractFunctionContext implements Function<Long,Map<String,Object>>, Initializable { private static final long serialVersionUID = 1L; private transient FunctionContext functionContext; @Override public Map<String, Object> apply(Long v) { Map<String,Object> values = new TreeMap<>(); values.put("channel", functionContext.getChannel()); values.put("maxChannels", functionContext.getMaxChannels()); FunctionContainer container = functionContext.getContainer(); values.put("id", container.getId()); values.put("jobId", container.getJobId()); values.put("relaunchCount", container.getRelaunchCount()); values.put("domainId", container.getDomainId()); values.put("instanceId", container.getInstanceId()); values.put("jobName", container.getJobName() == null ? "NULL" : "NOTNULL"); values.put("noAppConfig", container.getApplicationConfiguration("no_such_config")); return values; } @Override public void initialize(FunctionContext functionContext) throws Exception { this.functionContext = functionContext; } } }
test/java/src/com/ibm/streamsx/topology/test/api/StreamTest.java
/* # Licensed Materials - Property of IBM # Copyright IBM Corp. 2015 */ package com.ibm.streamsx.topology.test.api; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotSame; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertSame; import static org.junit.Assert.assertTrue; import static org.junit.Assume.assumeTrue; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeMap; import java.util.concurrent.TimeUnit; import org.junit.Test; import com.ibm.streamsx.topology.TStream; import com.ibm.streamsx.topology.Topology; import com.ibm.streamsx.topology.context.StreamsContext.Type; import com.ibm.streamsx.topology.function.Function; import com.ibm.streamsx.topology.function.FunctionContainer; import com.ibm.streamsx.topology.function.FunctionContext; import com.ibm.streamsx.topology.function.Initializable; import com.ibm.streamsx.topology.function.Predicate; import com.ibm.streamsx.topology.function.ToIntFunction; import com.ibm.streamsx.topology.streams.BeaconStreams; import com.ibm.streamsx.topology.streams.CollectionStreams; import com.ibm.streamsx.topology.streams.StringStreams; import com.ibm.streamsx.topology.test.AllowAll; import com.ibm.streamsx.topology.test.TestTopology; import com.ibm.streamsx.topology.tester.Condition; import com.ibm.streamsx.topology.tester.Tester; public class StreamTest extends TestTopology { public static void assertStream(Topology f, TStream<?> stream) { TopologyTest.assertFlowElement(f, stream); } @Test public void testBasics() throws Exception { assumeTrue(isMainRun()); final Topology topology = new Topology("BasicStream"); assertEquals("BasicStream", topology.getName()); assertSame(topology, topology.topology()); TStream<String> source = topology.strings("a", "b", "c"); assertStream(topology, source); assertSame(String.class, source.getTupleClass()); assertSame(String.class, source.getTupleType()); assertNotSame(source, source.autonomous()); } @Test public void testStringFilter() throws Exception { final Topology f = newTopology("StringFilter"); TStream<String> source = f.strings("hello", "goodbye", "farewell"); assertStream(f, source); TStream<String> filtered = source.filter(lengthFilter(5)); completeAndValidate(filtered, 10, "goodbye", "farewell"); } @SuppressWarnings("serial") public static Predicate<String> lengthFilter(final int length) { return new Predicate<String>() { @Override public boolean test(String v1) { return v1.length() > length; } }; } @Test public void testTransform() throws Exception { final Topology f = newTopology("TransformStream"); TStream<String> source = f.strings("325", "457", "9325"); assertStream(f, source); TStream<Integer> i1 = source.transform(stringToInt()); TStream<Integer> i2 = i1.transform(add17()); completeAndValidate(i2, 10, "342", "474", "9342"); } @Test public void testTransformWithDrop() throws Exception { final Topology f = newTopology("TransformStream"); TStream<String> source = f.strings("93", "68", "221"); assertStream(f, source); TStream<Integer> i1 = source.transform(stringToIntExcept68()); TStream<Integer> i2 = i1.transform(add17()); completeAndValidate(i2, 10, "110", "238"); } @Test public void testMultiTransform() throws Exception { final Topology topology = newTopology("MultiTransformStream"); TStream<String> source = topology.strings("mary had a little lamb", "its fleece was white as snow"); assertStream(topology, source); TStream<String> words = source.multiTransform(splitWords()); completeAndValidate(words, 10, "mary", "had", "a", "little", "lamb", "its", "fleece", "was", "white", "as", "snow"); } @Test public void testUnionNops() throws Exception { assumeTrue(isMainRun()); final Topology f = newTopology("Union"); TStream<String> s1 = f.strings("A1", "B1", "C1", "D1"); Set<TStream<String>> empty = Collections.emptySet(); assertSame(s1, s1.union(s1)); assertSame(s1, s1.union(empty)); assertSame(s1, s1.union(Collections.singleton(s1))); } @Test public void testUnion() throws Exception { final Topology topology = newTopology("Union"); TStream<String> s1 = topology.strings("A1", "B1", "C1", "D1"); TStream<String> s2 = topology.strings("A2", "B2", "C2", "D2"); List<String> l3 = new ArrayList<>(); l3.add("A3"); l3.add("B3"); TStream<String> s3 = topology.constants(l3); List<String> l4 = new ArrayList<>(); l4.add("A4"); l4.add("B4"); TStream<String> s4 = topology.constants(l4); assertNotSame(s1, s2); TStream<String> su = s1.union(s2); assertNotSame(su, s1); assertNotSame(su, s2); // Merge with two different schema types // but the primary has the correct direct type. su = su.union(s3); assertEquals(String.class, su.getTupleClass()); assertEquals(String.class, su.getTupleType()); // Merge with two different schema types // but the primary has the generic type assertNull(s4.getTupleClass()); su = s4.union(su); assertEquals(String.class, su.getTupleClass()); assertEquals(String.class, su.getTupleType()); // TODO - testing doesn't work against union streams in embedded. su = su.filter(new AllowAll<String>()); Tester tester = topology.getTester(); Condition<Long> suCount = tester.tupleCount(su, 12); Condition<List<String>> suContents = tester.stringContentsUnordered(su, "A1", "B1", "C1", "D1", "A2", "B2", "C2", "D2", "A3", "B3", "A4", "B4"); //assertTrue(complete(tester, suCount, 10, TimeUnit.SECONDS)); complete(tester, suCount, 10, TimeUnit.SECONDS); assertTrue("SU:" + suContents, suContents.valid()); assertTrue("SU:" + suCount, suCount.valid()); } @Test public void testUnionSet() throws Exception { final Topology topology = newTopology("Union"); TStream<String> s1 = topology.strings("A1", "B1", "C1"); TStream<String> s2 = topology.strings("A2", "B2", "C2", "D2"); TStream<String> s3 = topology.strings("A3", "B3", "C3"); Set<TStream<String>> streams = new HashSet<TStream<String>>(); streams.add(s2); streams.add(s3); TStream<String> su = s1.union(streams); // TODO - testing doesn't work against union streams in embedded. su = su.filter(new AllowAll<String>()); Tester tester = topology.getTester(); Condition<Long> suCount = tester.tupleCount(su, 10); Condition<List<String>> suContents = tester.stringContentsUnordered(su, "A1", "B1", "C1", "A2", "B2", "C2", "D2", "A3", "B3", "C3"); assertTrue(complete(tester, suCount, 10, TimeUnit.SECONDS)); // assertTrue("SU:" + suContents, suContents.valid()); assertTrue("SU:" + suCount, suCount.valid()); assertTrue("SUContents:" + suContents, suContents.valid()); } @Test public void testSimpleParallel() throws Exception { final Topology topology = newTopology("EmbeddedParallel"); TStream<Number> s1 = topology.numbers(1, 2, 3, 94, 5, 6).parallel(6) .filter(new AllowAll<Number>()).endParallel(); TStream<String> sp = StringStreams.toString(s1); Tester tester = topology.getTester(); Condition<Long> spCount = tester.tupleCount(sp, 6); Condition<List<String>> spContents = tester.stringContentsUnordered(sp, "1", "2", "3", "94", "5", "6"); complete(tester, spCount, 60, TimeUnit.SECONDS); // assertTrue("SU:" + suContents, suContents.valid()); assertTrue("SP:" + spCount, spCount.valid()); assertTrue("SPContents:" + spContents, spContents.valid()); } @Test public void testSplit() throws Exception { final Topology topology = newTopology("testSplit"); TStream<String> s1 = topology.strings("ch0", "ch1", "ch2", "omit", "another-ch2", "another-ch1", "another-ch0", "another-omit"); List<TStream<String>> splits = s1.split(3, myStringSplitter()); assertEquals("list size", 3, splits.size()); Tester tester = topology.getTester(); List<Condition<List<String>>> contents = new ArrayList<>(); for(int i = 0; i < splits.size(); i++) { TStream<String> ch = splits.get(i); Condition<List<String>> chContents = tester.stringContents(ch, "ch"+i, "another-ch"+i); contents.add(chContents); } TStream<String> all = splits.get(0).union( new HashSet<>(splits.subList(1, splits.size()))); Condition<Long> uCount = tester.tupleCount(all, 6); complete(tester, uCount, 10, TimeUnit.SECONDS); for(int i = 0; i < splits.size(); i++) { assertTrue("chContents["+i+"]:" + contents.get(i), contents.get(i).valid()); } } /** * Partition strings based on the last character of the string. * If the last character is a digit return its value as an int, else return -1. * @return */ @SuppressWarnings("serial") private static ToIntFunction<String> myStringSplitter() { return new ToIntFunction<String>() { @Override public int applyAsInt(String s) { char ch = s.charAt(s.length() - 1); return Character.digit(ch, 10); } }; } @SuppressWarnings("serial") static Function<String, Integer> stringToInt() { return new Function<String, Integer>() { @Override public Integer apply(String v1) { return Integer.valueOf(v1); } }; } @SuppressWarnings("serial") static Function<String, Integer> stringToIntExcept68() { return new Function<String, Integer>() { @Override public Integer apply(String v1) { Integer i = Integer.valueOf(v1); return (i == 68) ? null : i; } }; } @SuppressWarnings("serial") static Function<Integer, Integer> add17() { return new Function<Integer, Integer>() { @Override public Integer apply(Integer v1) { return v1 + 17; } }; } @SuppressWarnings("serial") static Function<String, Iterable<String>> splitWords() { return new Function<String, Iterable<String>>() { @Override public Iterable<String> apply(String v1) { return Arrays.asList(v1.split(" ")); } }; } @Test public void testFunctionContextNonDistributed() throws Exception { assumeTrue(getTesterType() != Type.DISTRIBUTED_TESTER); Topology t = newTopology(); TStream<Map<String, Object>> values = BeaconStreams.single(t).transform(new ExtractFunctionContext()); TStream<String> strings = StringStreams.toString(CollectionStreams.flattenMap(values)); Tester tester = t.getTester(); Condition<Long> spCount = tester.tupleCount(strings, 7); Condition<List<String>> spContents = tester.stringContents(strings, "channel=-1", "domainId=" + System.getProperty("user.name"), "id=0", "instanceId=" + System.getProperty("user.name"), "jobId=0", "maxChannels=0", "relaunchCount=0" ); complete(tester, spCount, 60, TimeUnit.SECONDS); // assertTrue("SU:" + suContents, suContents.valid()); assertTrue("SP:" + spCount, spCount.valid()); assertTrue("SPContents:" + spContents, spContents.valid()); } public static class ExtractFunctionContext implements Function<Long,Map<String,Object>>, Initializable { private static final long serialVersionUID = 1L; private FunctionContext functionContext; @Override public Map<String, Object> apply(Long v) { Map<String,Object> values = new TreeMap<>(); values.put("channel", functionContext.getChannel()); values.put("maxChannels", functionContext.getMaxChannels()); FunctionContainer container = functionContext.getContainer(); values.put("id", container.getId()); values.put("jobId", container.getJobId()); values.put("relaunchCount", container.getRelaunchCount()); values.put("domainId", container.getDomainId()); values.put("instanceId", container.getInstanceId()); return values; } @Override public void initialize(FunctionContext functionContext) throws Exception { this.functionContext = functionContext; } } }
Add basic test for new methods
test/java/src/com/ibm/streamsx/topology/test/api/StreamTest.java
Add basic test for new methods
<ide><path>est/java/src/com/ibm/streamsx/topology/test/api/StreamTest.java <ide> <ide> Tester tester = t.getTester(); <ide> <del> Condition<Long> spCount = tester.tupleCount(strings, 7); <add> Condition<Long> spCount = tester.tupleCount(strings, 9); <ide> Condition<List<String>> spContents = tester.stringContents(strings, <ide> "channel=-1", <ide> "domainId=" + System.getProperty("user.name"), <ide> "id=0", <ide> "instanceId=" + System.getProperty("user.name"), <ide> "jobId=0", <add> "jobName=NOTNULL", <ide> "maxChannels=0", <add> "noAppConfig={}", <ide> "relaunchCount=0" <ide> ); <ide> <ide> public static class ExtractFunctionContext <ide> implements Function<Long,Map<String,Object>>, Initializable { <ide> private static final long serialVersionUID = 1L; <del> private FunctionContext functionContext; <add> private transient FunctionContext functionContext; <ide> <ide> @Override <ide> public Map<String, Object> apply(Long v) { <ide> values.put("domainId", container.getDomainId()); <ide> values.put("instanceId", container.getInstanceId()); <ide> <add> values.put("jobName", container.getJobName() == null ? "NULL" : "NOTNULL"); <add> values.put("noAppConfig", container.getApplicationConfiguration("no_such_config")); <add> <ide> return values; <ide> } <ide>
Java
apache-2.0
78d969a034deb0c0f0d1ebdb95e49539a3990a8b
0
Orange-OpenSource/maven-plugins,mikkokar/maven-plugins,johnmccabe/maven-plugins,zigarn/maven-plugins,zigarn/maven-plugins,Orange-OpenSource/maven-plugins,kikinteractive/maven-plugins,Orange-OpenSource/maven-plugins,restlet/maven-plugins,hazendaz/maven-plugins,zigarn/maven-plugins,HubSpot/maven-plugins,ptahchiev/maven-plugins,lennartj/maven-plugins,sonatype/maven-plugins,mcculls/maven-plugins,hgschmie/apache-maven-plugins,mcculls/maven-plugins,apache/maven-plugins,dmlloyd/maven-plugins,dmlloyd/maven-plugins,kikinteractive/maven-plugins,restlet/maven-plugins,HubSpot/maven-plugins,hgschmie/apache-maven-plugins,mikkokar/maven-plugins,rkorpachyov/maven-plugins,hgschmie/apache-maven-plugins,johnmccabe/maven-plugins,omnidavesz/maven-plugins,jdcasey/maven-plugins-fixes,rkorpachyov/maven-plugins,HubSpot/maven-plugins,mcculls/maven-plugins,edwardmlyte/maven-plugins,mikkokar/maven-plugins,mcculls/maven-plugins,edwardmlyte/maven-plugins,krosenvold/maven-plugins,krosenvold/maven-plugins,johnmccabe/maven-plugins,dmlloyd/maven-plugins,krosenvold/maven-plugins,criteo-forks/maven-plugins,rkorpachyov/maven-plugins,sonatype/maven-plugins,lennartj/maven-plugins,apache/maven-plugins,johnmccabe/maven-plugins,PressAssociation/maven-plugins,kidaa/maven-plugins,zigarn/maven-plugins,hazendaz/maven-plugins,Orange-OpenSource/maven-plugins,apache/maven-plugins,edwardmlyte/maven-plugins,ptahchiev/maven-plugins,kidaa/maven-plugins,omnidavesz/maven-plugins,hazendaz/maven-plugins,apache/maven-plugins,mikkokar/maven-plugins,jdcasey/maven-plugins-fixes,criteo-forks/maven-plugins,sonatype/maven-plugins,rkorpachyov/maven-plugins,kikinteractive/maven-plugins,PressAssociation/maven-plugins,criteo-forks/maven-plugins,ptahchiev/maven-plugins,hazendaz/maven-plugins,PressAssociation/maven-plugins,criteo-forks/maven-plugins,krosenvold/maven-plugins,ptahchiev/maven-plugins,HubSpot/maven-plugins,kidaa/maven-plugins,PressAssociation/maven-plugins,omnidavesz/maven-plugins,hgschmie/apache-maven-plugins,apache/maven-plugins,lennartj/maven-plugins,jdcasey/maven-plugins-fixes,sonatype/maven-plugins,omnidavesz/maven-plugins,restlet/maven-plugins,rkorpachyov/maven-plugins,edwardmlyte/maven-plugins,hazendaz/maven-plugins,lennartj/maven-plugins,restlet/maven-plugins,kidaa/maven-plugins
package org.apache.maven.plugin; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import org.codehaus.plexus.compiler.util.scan.SimpleSourceInclusionScanner; import org.codehaus.plexus.compiler.util.scan.SourceInclusionScanner; import org.codehaus.plexus.compiler.util.scan.StaleSourceScanner; import java.io.File; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; /** * Compiles application test sources. * * @author <a href="mailto:[email protected]">Jason van Zyl</a> * @version $Id$ * @since 2.0 * @goal testCompile * @phase test-compile * @threadSafe * @requiresDependencyResolution test */ public class TestCompilerMojo extends AbstractCompilerMojo { /** * Set this to 'true' to bypass compilation of test sources. * Its use is NOT RECOMMENDED, but quite convenient on occasion. * * @parameter expression="${maven.test.skip}" */ private boolean skip; /** * The source directories containing the test-source to be compiled. * * @parameter default-value="${project.testCompileSourceRoots}" * @required * @readonly */ private List<String> compileSourceRoots; /** * Project test classpath. * * @parameter default-value="${project.testClasspathElements}" * @required * @readonly */ private List<String> classpathElements; /** * The directory where compiled test classes go. * * @parameter default-value="${project.build.testOutputDirectory}" * @required * @readonly */ private File outputDirectory; /** * A list of inclusion filters for the compiler. * * @parameter */ private Set<String> testIncludes = new HashSet<String>(); /** * A list of exclusion filters for the compiler. * * @parameter */ private Set<String> testExcludes = new HashSet<String>(); /** * The -source argument for the test Java compiler. * * @parameter expression="${maven.compiler.testSource}" * @since 2.1 */ private String testSource; /** * The -target argument for the test Java compiler. * * @parameter expression="${maven.compiler.testTarget}" * @since 2.1 */ private String testTarget; /** * <p> * Sets the arguments to be passed to test compiler (prepending a dash) if fork is set to true. * </p> * <p> * This is because the list of valid arguments passed to a Java compiler * varies based on the compiler version. * </p> * * @parameter * @since 2.1 */ private Map<String, String> testCompilerArguments; /** * <p> * Sets the unformatted argument string to be passed to test compiler if fork is set to true. * </p> * <p> * This is because the list of valid arguments passed to a Java compiler * varies based on the compiler version. * </p> * * @parameter * @since 2.1 */ private String testCompilerArgument; /** * <p> * Specify where to place generated source files created by annotation processing. * Only applies to JDK 1.6+ * </p> * @parameter default-value="${project.build.directory}/generated-sources/test-annotations" * @since 2.2 */ private File generatedTestSourcesDirectory; public void execute() throws MojoExecutionException, CompilationFailureException { if ( skip ) { getLog().info( "Not compiling test sources" ); } else { super.execute(); } } protected List<String> getCompileSourceRoots() { return compileSourceRoots; } protected List<String> getClasspathElements() { return classpathElements; } protected File getOutputDirectory() { return outputDirectory; } protected SourceInclusionScanner getSourceInclusionScanner( int staleMillis ) { SourceInclusionScanner scanner = null; if ( testIncludes.isEmpty() && testExcludes.isEmpty() ) { scanner = new StaleSourceScanner( staleMillis ); } else { if ( testIncludes.isEmpty() ) { testIncludes.add( "**/*.java" ); } scanner = new StaleSourceScanner( staleMillis, testIncludes, testExcludes ); } return scanner; } protected SourceInclusionScanner getSourceInclusionScanner( String inputFileEnding ) { SourceInclusionScanner scanner = null; if ( testIncludes.isEmpty() && testExcludes.isEmpty() ) { testIncludes = Collections.singleton( "**/*." + inputFileEnding ); scanner = new SimpleSourceInclusionScanner( testIncludes, Collections.EMPTY_SET ); } else { if ( testIncludes.isEmpty() ) { testIncludes.add( "**/*." + inputFileEnding ); } scanner = new SimpleSourceInclusionScanner( testIncludes, testExcludes ); } return scanner; } protected String getSource() { return testSource == null ? source : testSource; } protected String getTarget() { return testTarget == null ? target : testTarget; } protected String getCompilerArgument() { return testCompilerArgument == null ? compilerArgument : testCompilerArgument; } protected Map<String, String> getCompilerArguments() { return testCompilerArguments == null ? compilerArguments : testCompilerArguments; } protected File getGeneratedSourcesDirectory() { return generatedTestSourcesDirectory; } }
maven-compiler-plugin/src/main/java/org/apache/maven/plugin/TestCompilerMojo.java
package org.apache.maven.plugin; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import org.codehaus.plexus.compiler.util.scan.SimpleSourceInclusionScanner; import org.codehaus.plexus.compiler.util.scan.SourceInclusionScanner; import org.codehaus.plexus.compiler.util.scan.StaleSourceScanner; import java.io.File; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; /** * Compiles application test sources. * * @author <a href="mailto:[email protected]">Jason van Zyl</a> * @version $Id$ * @since 2.0 * @goal testCompile * @phase test-compile * @threadSafe * @requiresDependencyResolution test */ public class TestCompilerMojo extends AbstractCompilerMojo { /** * Set this to 'true' to bypass unit tests entirely. * Its use is NOT RECOMMENDED, but quite convenient on occasion. * * @parameter expression="${maven.test.skip}" */ private boolean skip; /** * The source directories containing the test-source to be compiled. * * @parameter default-value="${project.testCompileSourceRoots}" * @required * @readonly */ private List<String> compileSourceRoots; /** * Project test classpath. * * @parameter default-value="${project.testClasspathElements}" * @required * @readonly */ private List<String> classpathElements; /** * The directory where compiled test classes go. * * @parameter default-value="${project.build.testOutputDirectory}" * @required * @readonly */ private File outputDirectory; /** * A list of inclusion filters for the compiler. * * @parameter */ private Set<String> testIncludes = new HashSet<String>(); /** * A list of exclusion filters for the compiler. * * @parameter */ private Set<String> testExcludes = new HashSet<String>(); /** * The -source argument for the test Java compiler. * * @parameter expression="${maven.compiler.testSource}" * @since 2.1 */ private String testSource; /** * The -target argument for the test Java compiler. * * @parameter expression="${maven.compiler.testTarget}" * @since 2.1 */ private String testTarget; /** * <p> * Sets the arguments to be passed to test compiler (prepending a dash) if fork is set to true. * </p> * <p> * This is because the list of valid arguments passed to a Java compiler * varies based on the compiler version. * </p> * * @parameter * @since 2.1 */ private Map<String, String> testCompilerArguments; /** * <p> * Sets the unformatted argument string to be passed to test compiler if fork is set to true. * </p> * <p> * This is because the list of valid arguments passed to a Java compiler * varies based on the compiler version. * </p> * * @parameter * @since 2.1 */ private String testCompilerArgument; /** * <p> * Specify where to place generated source files created by annotation processing. * Only applies to JDK 1.6+ * </p> * @parameter default-value="${project.build.directory}/generated-sources/test-annotations" * @since 2.2 */ private File generatedTestSourcesDirectory; public void execute() throws MojoExecutionException, CompilationFailureException { if ( skip ) { getLog().info( "Not compiling test sources" ); } else { super.execute(); } } protected List<String> getCompileSourceRoots() { return compileSourceRoots; } protected List<String> getClasspathElements() { return classpathElements; } protected File getOutputDirectory() { return outputDirectory; } protected SourceInclusionScanner getSourceInclusionScanner( int staleMillis ) { SourceInclusionScanner scanner = null; if ( testIncludes.isEmpty() && testExcludes.isEmpty() ) { scanner = new StaleSourceScanner( staleMillis ); } else { if ( testIncludes.isEmpty() ) { testIncludes.add( "**/*.java" ); } scanner = new StaleSourceScanner( staleMillis, testIncludes, testExcludes ); } return scanner; } protected SourceInclusionScanner getSourceInclusionScanner( String inputFileEnding ) { SourceInclusionScanner scanner = null; if ( testIncludes.isEmpty() && testExcludes.isEmpty() ) { testIncludes = Collections.singleton( "**/*." + inputFileEnding ); scanner = new SimpleSourceInclusionScanner( testIncludes, Collections.EMPTY_SET ); } else { if ( testIncludes.isEmpty() ) { testIncludes.add( "**/*." + inputFileEnding ); } scanner = new SimpleSourceInclusionScanner( testIncludes, testExcludes ); } return scanner; } protected String getSource() { return testSource == null ? source : testSource; } protected String getTarget() { return testTarget == null ? target : testTarget; } protected String getCompilerArgument() { return testCompilerArgument == null ? compilerArgument : testCompilerArgument; } protected Map<String, String> getCompilerArguments() { return testCompilerArguments == null ? compilerArguments : testCompilerArguments; } protected File getGeneratedSourcesDirectory() { return generatedTestSourcesDirectory; } }
[MCOMPILER-136] The description of the skip parameter of the testCompile mojo is incorrect git-svn-id: 6038db50b076e48c7926ed71fd94f8e91be2fbc9@1026646 13f79535-47bb-0310-9956-ffa450edef68
maven-compiler-plugin/src/main/java/org/apache/maven/plugin/TestCompilerMojo.java
[MCOMPILER-136] The description of the skip parameter of the testCompile mojo is incorrect
<ide><path>aven-compiler-plugin/src/main/java/org/apache/maven/plugin/TestCompilerMojo.java <ide> extends AbstractCompilerMojo <ide> { <ide> /** <del> * Set this to 'true' to bypass unit tests entirely. <add> * Set this to 'true' to bypass compilation of test sources. <ide> * Its use is NOT RECOMMENDED, but quite convenient on occasion. <ide> * <ide> * @parameter expression="${maven.test.skip}"
Java
apache-2.0
f7cbb521b02b8eb9b3b3c1d7c45b184620f6ff6c
0
Gigaspaces/xap-openspaces,Gigaspaces/xap-openspaces,Gigaspaces/xap-openspaces
/* * Copyright 2006-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * Copyright 2006-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.openspaces.admin.pu; import java.util.Map; import java.util.concurrent.TimeUnit; import org.openspaces.admin.AdminAware; import org.openspaces.admin.StatisticsMonitor; import org.openspaces.admin.gsm.GridServiceManager; import org.openspaces.admin.pu.elastic.config.ScaleStrategyConfig; import org.openspaces.admin.pu.events.BackupGridServiceManagerChangedEventManager; import org.openspaces.admin.pu.events.ManagingGridServiceManagerChangedEventManager; import org.openspaces.admin.pu.events.ProcessingUnitInstanceAddedEventManager; import org.openspaces.admin.pu.events.ProcessingUnitInstanceLifecycleEventListener; import org.openspaces.admin.pu.events.ProcessingUnitInstanceRemovedEventManager; import org.openspaces.admin.pu.events.ProcessingUnitInstanceStatisticsChangedEventManager; import org.openspaces.admin.pu.events.ProcessingUnitSpaceCorrelatedEventManager; import org.openspaces.admin.pu.events.ProcessingUnitStatusChangedEventManager; import org.openspaces.admin.space.Space; import org.openspaces.core.properties.BeanLevelProperties; /** * A processing unit holds one or more {@link org.openspaces.admin.pu.ProcessingUnitInstance}s. * * @author kimchy * @author itaif */ public interface ProcessingUnit extends Iterable<ProcessingUnitInstance>, AdminAware, StatisticsMonitor { /** * Returns the handle to all the different processing units. */ ProcessingUnits getProcessingUnits(); /** * Returns the name of the processing unit. */ String getName(); /** * Returns the number of required instances as defined in the processing unit's SLA. * If there are backups, it will only return the number of primary instances and not the * number of backup. To get the total number of instances please use the method {@link #getTotalNumberOfInstances()}. * Note that this method does not count the number of running instances, but rather the number of planned * instances for the processing unit. To count the number of active processing unit instances please use the method * {@link #getInstances()}. */ int getNumberOfInstances(); /** * Returns the number of backups (if the topology is a backup one) per instance, as defined in the * processing unit's SLA. Note that this method does not return he number of running backup instances, but * rather the number of planned backup instances per primary. */ int getNumberOfBackups(); /** * Returns the total required number of instances as defined in the processing SLA. * If there are no backups, will return{@link #getNumberOfInstances()}. If there are backups, * will return {@link #getNumberOfInstances()} * ({@link #getNumberOfBackups()} + 1) * Note that this method does not count the number of running instances, but rather the total number of planned * instances for the processing unit. To count the number of active processing unit instances please use the method * {@link #getInstances()}. */ int getTotalNumberOfInstances(); /** * Returns the number of instnaces of this processing unit that can run within a VM. * * <p>In case of a partitioned with backup topology, it applies on a per partition level (meaning that a * primary and backup will not run on the same VM). * * <p>In case of a non backup based topology, it applies on the number of instances of the whole processing * unit that can run on the same VM). */ int getMaxInstancesPerVM(); /** * Returns the number of instnaces of this processing unit that can run within a Machine. * * <p>In case of a partitioned with backup topology, it applies on a per partition level (meaning that a * primary and backup will not run on the same Machine). * * <p>In case of a non backup based topology, it applies on the number of instances of the whole processing * unit that can run on the same Machine). */ int getMaxInstancesPerMachine(); /** * Returns a map containing the zone name and the maximum number of instances for that zone. */ Map<String, Integer> getMaxInstancesPerZone(); /** * Returns the list of zones this processing units are required to run on. If there is more than * one zone, the processing unit can run on either of the zones. */ String[] getRequiredZones(); /** * Returns the deployment status of the processing unit. */ DeploymentStatus getStatus(); /** * Return the deploy time properties of the processing unit. */ BeanLevelProperties getBeanLevelProperties(); /** * Returns the type of processing unit: stateless, stateful, mirror, web. * @since 8.0.3 */ ProcessingUnitType getProcessingUnitType(); /** * Waits till at least the provided number of Processing Unit Instances are up. */ boolean waitFor(int numberOfProcessingUnitInstances); /** * Waits till at least the provided number of Processing Unit Instances are up for the specified timeout. */ boolean waitFor(int numberOfProcessingUnitInstances, long timeout, TimeUnit timeUnit); /** * Waits till an embedded Space is correlated with the processing unit. */ Space waitForSpace(); /** * Waits till an embedded Space is correlated with the processing unit for the specified timeout. */ Space waitForSpace(long timeout, TimeUnit timeUnit); /** * Waits till there is a managing {@link org.openspaces.admin.gsm.GridServiceManager} for the processing unit. */ GridServiceManager waitForManaged(); /** * Waits till there is a managing {@link org.openspaces.admin.gsm.GridServiceManager} for the processing unit * for the specified timeout. */ GridServiceManager waitForManaged(long timeout, TimeUnit timeUnit); /** * Returns <code>true</code> if this processing unit allows to increment instances on it. */ boolean canIncrementInstance(); /** * Returns <code>true</code> if this processing unit allows to decrement instances on it. */ boolean canDecrementInstance(); /** * Will increment a processing unit instance. */ void incrementInstance(); /** * Will randomly decrement an instance from the processing units. For more fine * grained control see {@link ProcessingUnitInstance#decrement()}. */ void decrementInstance(); /** * Returns <code>true</code> if there is a managing GSM for it. */ boolean isManaged(); /** * Returns the managing (primary) GSM for the processing unit. */ GridServiceManager getManagingGridServiceManager(); /** * Returns the backup GSMs for the processing unit. */ GridServiceManager[] getBackupGridServiceManagers(); /** * Returns the backup GSM matching the provided UID. */ GridServiceManager getBackupGridServiceManager(String gridServiceManagerUID); /** * Undeploys the processing unit. */ void undeploy(); /** * Returns the (first) embedded space within a processing unit. Returns <code>null</code> if * no embedded space is defined within the processing unit or if no processing unit instance * has been added to the processing unit. */ Space getSpace(); /** * Returns all the embedded spaces within a processing unit. Returns an empty array if there * are no embedded spaces defined within the processing unit, or none has been associated with * the processing unit yet. */ Space[] getSpaces(); /** * Returns the processing unit instances currently discovered. */ ProcessingUnitInstance[] getInstances(); /** * Returns the processing unit partitions of this processing unit. */ ProcessingUnitPartition[] getPartitions(); /** * Returns a processing unit partition based on the specified partition id. */ ProcessingUnitPartition getPartition(int partitionId); /** * Returns an event manager allowing to register {@link org.openspaces.admin.pu.events.ProcessingUnitInstanceAddedEventListener}s. */ ProcessingUnitInstanceAddedEventManager getProcessingUnitInstanceAdded(); /** * Returns an event manager allowing to register {@link org.openspaces.admin.pu.events.ProcessingUnitInstanceRemovedEventListener}s. */ ProcessingUnitInstanceRemovedEventManager getProcessingUnitInstanceRemoved(); /** * Adds a {@link ProcessingUnitInstanceLifecycleEventListener}. */ void addLifecycleListener(ProcessingUnitInstanceLifecycleEventListener eventListener); /** * Removes a {@link ProcessingUnitInstanceLifecycleEventListener}. */ void removeLifecycleListener(ProcessingUnitInstanceLifecycleEventListener eventListener); /** * Returns an event manger allowing to listen for {@link org.openspaces.admin.pu.events.ManagingGridServiceManagerChangedEvent}s. */ ManagingGridServiceManagerChangedEventManager getManagingGridServiceManagerChanged(); /** * Returns an event manager allowing to listen for {@link org.openspaces.admin.pu.events.BackupGridServiceManagerChangedEvent}s. */ BackupGridServiceManagerChangedEventManager getBackupGridServiceManagerChanged(); /** * Returns an event manager allowing to listen for {@link org.openspaces.admin.pu.events.ProcessingUnitStatusChangedEvent}s. */ ProcessingUnitStatusChangedEventManager getProcessingUnitStatusChanged(); /** * Returns an event manager allowing to listen for {@link org.openspaces.admin.pu.events.ProcessingUnitSpaceCorrelatedEvent}s. */ ProcessingUnitSpaceCorrelatedEventManager getSpaceCorrelated(); /** * Returns a processing unit instance statistics change event manger allowing to register for * events of {@link org.openspaces.admin.pu.events.ProcessingUnitInstanceStatisticsChangedEvent}. * * <p>Note, in order to receive events, the virtual machines need to be in a "statistics" monitored * state. */ ProcessingUnitInstanceStatisticsChangedEventManager getProcessingUnitInstanceStatisticsChanged(); /** * Modifies the processing unit scalability strategy. * * This method is only available if the processing unit deployment is elastic * * @param strategyConfig * * @since 8.0 */ void scale(ScaleStrategyConfig strategyConfig); /** * Modifies the elastic configuration of this processing unit * * This method is only available if the processing unit deployment is elastic * * @param config * * @since 8.0 */ void setElasticProperties(Map<String,String> config); }
src/main/src/org/openspaces/admin/pu/ProcessingUnit.java
/* * Copyright 2006-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * Copyright 2006-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.openspaces.admin.pu; import java.util.Map; import java.util.concurrent.TimeUnit; import org.openspaces.admin.AdminAware; import org.openspaces.admin.StatisticsMonitor; import org.openspaces.admin.gsm.GridServiceManager; import org.openspaces.admin.pu.elastic.config.ScaleStrategyConfig; import org.openspaces.admin.pu.events.BackupGridServiceManagerChangedEventManager; import org.openspaces.admin.pu.events.ManagingGridServiceManagerChangedEventManager; import org.openspaces.admin.pu.events.ProcessingUnitInstanceAddedEventManager; import org.openspaces.admin.pu.events.ProcessingUnitInstanceLifecycleEventListener; import org.openspaces.admin.pu.events.ProcessingUnitInstanceRemovedEventManager; import org.openspaces.admin.pu.events.ProcessingUnitInstanceStatisticsChangedEventManager; import org.openspaces.admin.pu.events.ProcessingUnitSpaceCorrelatedEventManager; import org.openspaces.admin.pu.events.ProcessingUnitStatusChangedEventManager; import org.openspaces.admin.space.Space; import org.openspaces.core.properties.BeanLevelProperties; /** * A processing unit holds one or more {@link org.openspaces.admin.pu.ProcessingUnitInstance}s. * * @author kimchy * @author itaif */ public interface ProcessingUnit extends Iterable<ProcessingUnitInstance>, AdminAware, StatisticsMonitor { /** * Returns the handle to all the different processing units. */ ProcessingUnits getProcessingUnits(); /** * Returns the name of the processing unit. */ String getName(); /** * Returns the number of required instances as defined in the processing unit's SLA. * If there are backups, it will only return the number of primary instances and not the * number of backup. To get the total number of instances please use the method {@link #getTotalNumberOfInstances()}. * Note that this method does not count the number of running instances, but rather the number of planned * instances for the processing unit. To count the number of active processing unit instances please use the method * {@link #getInstances()}. */ int getNumberOfInstances(); /** * Returns the number of backups (if the topology is a backup one) per instance, as defined in the * processing unit's SLA. Note that this method does not return he number of running backup instances, but * rather the number of planned backup instances per primary. */ int getNumberOfBackups(); /** * Returns the total required number of instances as defined in the processing SLA. * If there are no backups, will return{@link #getNumberOfInstances()}. If there are backups, * will return {@link #getNumberOfInstances()} * ({@link #getNumberOfBackups()} + 1) * Note that this method does not count the number of running instances, but rather the total number of planned * instances for the processing unit. To count the number of active processing unit instances please use the method * {@link #getInstances()}. */ int getTotalNumberOfInstances(); /** * Returns the number of instnaces of this processing unit that can run within a VM. * * <p>In case of a partitioned with backup topology, it applies on a per partition level (meaning that a * primary and backup will not run on the same VM). * * <p>In case of a non backup based topology, it applies on the number of instances of the whole processing * unit that can run on the same VM). */ int getMaxInstancesPerVM(); /** * Returns the number of instnaces of this processing unit that can run within a Machine. * * <p>In case of a partitioned with backup topology, it applies on a per partition level (meaning that a * primary and backup will not run on the same Machine). * * <p>In case of a non backup based topology, it applies on the number of instances of the whole processing * unit that can run on the same Machine). */ int getMaxInstancesPerMachine(); /** * Returns a map containing the zone name and the maximum number of instances for that zone. */ Map<String, Integer> getMaxInstancesPerZone(); /** * Returns the list of zones this processing units are required to run on. If there is more than * one zone, the processing unit can run on either of the zones. */ String[] getRequiredZones(); /** * Returns the deployment status of the processing unit. */ DeploymentStatus getStatus(); /** * Return the deploy time properties of the processing unit. */ BeanLevelProperties getBeanLevelProperties(); /** * Returns the type of processing unit: stateless, stateful, mirror, web. */ ProcessingUnitType getProcessingUnitType(); /** * Waits till at least the provided number of Processing Unit Instances are up. */ boolean waitFor(int numberOfProcessingUnitInstances); /** * Waits till at least the provided number of Processing Unit Instances are up for the specified timeout. */ boolean waitFor(int numberOfProcessingUnitInstances, long timeout, TimeUnit timeUnit); /** * Waits till an embedded Space is correlated with the processing unit. */ Space waitForSpace(); /** * Waits till an embedded Space is correlated with the processing unit for the specified timeout. */ Space waitForSpace(long timeout, TimeUnit timeUnit); /** * Waits till there is a managing {@link org.openspaces.admin.gsm.GridServiceManager} for the processing unit. */ GridServiceManager waitForManaged(); /** * Waits till there is a managing {@link org.openspaces.admin.gsm.GridServiceManager} for the processing unit * for the specified timeout. */ GridServiceManager waitForManaged(long timeout, TimeUnit timeUnit); /** * Returns <code>true</code> if this processing unit allows to increment instances on it. */ boolean canIncrementInstance(); /** * Returns <code>true</code> if this processing unit allows to decrement instances on it. */ boolean canDecrementInstance(); /** * Will increment a processing unit instance. */ void incrementInstance(); /** * Will randomly decrement an instance from the processing units. For more fine * grained control see {@link ProcessingUnitInstance#decrement()}. */ void decrementInstance(); /** * Returns <code>true</code> if there is a managing GSM for it. */ boolean isManaged(); /** * Returns the managing (primary) GSM for the processing unit. */ GridServiceManager getManagingGridServiceManager(); /** * Returns the backup GSMs for the processing unit. */ GridServiceManager[] getBackupGridServiceManagers(); /** * Returns the backup GSM matching the provided UID. */ GridServiceManager getBackupGridServiceManager(String gridServiceManagerUID); /** * Undeploys the processing unit. */ void undeploy(); /** * Returns the (first) embedded space within a processing unit. Returns <code>null</code> if * no embedded space is defined within the processing unit or if no processing unit instance * has been added to the processing unit. */ Space getSpace(); /** * Returns all the embedded spaces within a processing unit. Returns an empty array if there * are no embedded spaces defined within the processing unit, or none has been associated with * the processing unit yet. */ Space[] getSpaces(); /** * Returns the processing unit instances currently discovered. */ ProcessingUnitInstance[] getInstances(); /** * Returns the processing unit partitions of this processing unit. */ ProcessingUnitPartition[] getPartitions(); /** * Returns a processing unit partition based on the specified partition id. */ ProcessingUnitPartition getPartition(int partitionId); /** * Returns an event manager allowing to register {@link org.openspaces.admin.pu.events.ProcessingUnitInstanceAddedEventListener}s. */ ProcessingUnitInstanceAddedEventManager getProcessingUnitInstanceAdded(); /** * Returns an event manager allowing to register {@link org.openspaces.admin.pu.events.ProcessingUnitInstanceRemovedEventListener}s. */ ProcessingUnitInstanceRemovedEventManager getProcessingUnitInstanceRemoved(); /** * Adds a {@link ProcessingUnitInstanceLifecycleEventListener}. */ void addLifecycleListener(ProcessingUnitInstanceLifecycleEventListener eventListener); /** * Removes a {@link ProcessingUnitInstanceLifecycleEventListener}. */ void removeLifecycleListener(ProcessingUnitInstanceLifecycleEventListener eventListener); /** * Returns an event manger allowing to listen for {@link org.openspaces.admin.pu.events.ManagingGridServiceManagerChangedEvent}s. */ ManagingGridServiceManagerChangedEventManager getManagingGridServiceManagerChanged(); /** * Returns an event manager allowing to listen for {@link org.openspaces.admin.pu.events.BackupGridServiceManagerChangedEvent}s. */ BackupGridServiceManagerChangedEventManager getBackupGridServiceManagerChanged(); /** * Returns an event manager allowing to listen for {@link org.openspaces.admin.pu.events.ProcessingUnitStatusChangedEvent}s. */ ProcessingUnitStatusChangedEventManager getProcessingUnitStatusChanged(); /** * Returns an event manager allowing to listen for {@link org.openspaces.admin.pu.events.ProcessingUnitSpaceCorrelatedEvent}s. */ ProcessingUnitSpaceCorrelatedEventManager getSpaceCorrelated(); /** * Returns a processing unit instance statistics change event manger allowing to register for * events of {@link org.openspaces.admin.pu.events.ProcessingUnitInstanceStatisticsChangedEvent}. * * <p>Note, in order to receive events, the virtual machines need to be in a "statistics" monitored * state. */ ProcessingUnitInstanceStatisticsChangedEventManager getProcessingUnitInstanceStatisticsChanged(); /** * Modifies the processing unit scalability strategy. * * This method is only available if the processing unit deployment is elastic * * @param strategyConfig * * @since 8.0 */ void scale(ScaleStrategyConfig strategyConfig); /** * Modifies the elastic configuration of this processing unit * * This method is only available if the processing unit deployment is elastic * * @param config * * @since 8.0 */ void setElasticProperties(Map<String,String> config); }
GS-8952: Expose processing unit type (stateless, stateful, mirror, web) in ProcessingUnit API add @since 8.0.3 svn path=/trunk/openspaces/; revision=88801 Former-commit-id: b883a94bf51c5faef2cb576d392f324332ec36c0
src/main/src/org/openspaces/admin/pu/ProcessingUnit.java
GS-8952: Expose processing unit type (stateless, stateful, mirror, web) in ProcessingUnit API add @since 8.0.3
<ide><path>rc/main/src/org/openspaces/admin/pu/ProcessingUnit.java <ide> <ide> /** <ide> * Returns the type of processing unit: stateless, stateful, mirror, web. <add> * @since 8.0.3 <ide> */ <ide> ProcessingUnitType getProcessingUnitType(); <ide>
Java
lgpl-2.1
e9b6628f571e10a989fd5d62ed78fb038e20110c
0
hal/core,hal/core,hal/core,hal/core,hal/core
/* * JBoss, Home of Professional Open Source * Copyright 2011 Red Hat Inc. and/or its affiliates and other contributors * as indicated by the @author tags. All rights reserved. * See the copyright.txt in the distribution for a * full listing of individual contributors. * * This copyrighted material is made available to anyone wishing to use, * modify, copy, or redistribute it subject to the terms and conditions * of the GNU Lesser General Public License, v. 2.1. * This program is distributed in the hope that it will be useful, but WITHOUT A * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A * PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. * You should have received a copy of the GNU Lesser General Public License, * v.2.1 along with this distribution; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ package org.jboss.as.console.client.shared.subsys.osgi.runtime; import com.google.gwt.event.shared.EventBus; import com.google.gwt.user.client.Timer; import com.google.gwt.user.client.ui.HTML; import com.google.inject.Inject; import com.gwtplatform.mvp.client.Presenter; import com.gwtplatform.mvp.client.View; import com.gwtplatform.mvp.client.annotations.NameToken; import com.gwtplatform.mvp.client.annotations.ProxyCodeSplit; import com.gwtplatform.mvp.client.proxy.Place; import com.gwtplatform.mvp.client.proxy.Proxy; import org.jboss.as.console.client.Console; import org.jboss.as.console.client.core.NameTokens; import org.jboss.as.console.client.domain.model.ServerInstance; import org.jboss.as.console.client.domain.model.SimpleCallback; import org.jboss.as.console.client.shared.dispatch.DispatchAsync; import org.jboss.as.console.client.shared.dispatch.impl.DMRAction; import org.jboss.as.console.client.shared.dispatch.impl.DMRResponse; import org.jboss.as.console.client.shared.general.MessageWindow; import org.jboss.as.console.client.shared.runtime.RuntimeBaseAddress; import org.jboss.as.console.client.shared.state.CurrentServerSelection; import org.jboss.as.console.client.shared.state.ServerSelectionEvent; import org.jboss.as.console.client.shared.subsys.RevealStrategy; import org.jboss.as.console.client.shared.subsys.osgi.runtime.model.OSGiBundle; import org.jboss.as.console.client.widgets.forms.AddressBinding; import org.jboss.as.console.client.widgets.forms.ApplicationMetaData; import org.jboss.as.console.client.widgets.forms.BeanMetaData; import org.jboss.ballroom.client.widgets.window.DefaultWindow; import org.jboss.dmr.client.ModelDescriptionConstants; import org.jboss.dmr.client.ModelNode; /** * @author David Bosschaert */ public class OSGiRuntimePresenter extends Presenter<OSGiRuntimePresenter.MyView, OSGiRuntimePresenter.MyProxy> implements ServerSelectionEvent.ServerSelectionListener { private final BeanMetaData bundleMetaData; private final DispatchAsync dispatcher; private final RevealStrategy revealStrategy; private CurrentServerSelection serverSelection; @ProxyCodeSplit @NameToken(NameTokens.OSGiRuntimePresenter) public interface MyProxy extends Proxy<OSGiRuntimePresenter>, Place { } public interface MyView extends View { void initialLoad(); void setPresenter(OSGiRuntimePresenter osGiRuntimePresenter); } @Inject public OSGiRuntimePresenter( EventBus eventBus, MyView view, MyProxy proxy, DispatchAsync dispatcher, ApplicationMetaData propertyMetaData, RevealStrategy revealStrategy, CurrentServerSelection serverSelection) { super(eventBus, view, proxy); this.dispatcher = dispatcher; this.revealStrategy = revealStrategy; this.bundleMetaData = propertyMetaData.getBeanMetaData(OSGiBundle.class); this.serverSelection = serverSelection; } @Override protected void onBind() { super.onBind(); getView().setPresenter(this); getEventBus().addHandler(ServerSelectionEvent.TYPE, this); } @Override protected void onReset() { super.onReset(); if(serverSelection.isActive()) getView().initialLoad(); } @Override public void onServerSelection(String hostName, ServerInstance server) { if(isVisible()) getView().initialLoad(); } @Override protected void revealInParent() { revealStrategy.revealInRuntimeParent(this); } void startBundle(OSGiBundle bundle) { bundleAction(bundle, "start"); } void stopBundle(OSGiBundle bundle) { bundleAction(bundle, "stop"); } private void bundleAction(OSGiBundle bundle, String operationName) { AddressBinding address = bundleMetaData.getAddress(); ModelNode operation = address.asResource(RuntimeBaseAddress.get(), bundle.getName()); operation.get(ModelDescriptionConstants.OP).set(operationName); dispatcher.execute(new DMRAction(operation), new SimpleCallback<DMRResponse>() { @Override public void onSuccess(DMRResponse result) { ModelNode response = result.get(); if(response.isFailure()) { Console.error(Console.MESSAGES.modificationFailed("OSGi Bundle"), response.getFailureDescription()); } else { Console.info(Console.MESSAGES.modified("OSGi Bundle")); } getView().initialLoad(); } }); } public void askToActivateSubsystem() { final DefaultWindow window = new DefaultWindow(Console.CONSTANTS.subsys_osgi()); window.setWidth(320); window.setHeight(140); window.setWidget(new MessageWindow(Console.MESSAGES.subsys_osgi_activate(), new MessageWindow.Result() { @Override public void result(boolean result) { window.hide(); if (result) activateSubsystem(); } }).asWidget()); window.setGlassEnabled(true); window.center(); } protected void activateSubsystem() { // Since it takes a few moments for the subsystem to activate we're showing a window indicating this final DefaultWindow window = new DefaultWindow(Console.CONSTANTS.subsys_osgi()); window.setWidth(320); window.setHeight(140); window.setWidget(new HTML(Console.MESSAGES.subsys_osgi_activating())); window.setGlassEnabled(true); window.center(); AddressBinding address = bundleMetaData.getAddress(); ModelNode operation = address.asSubresource(RuntimeBaseAddress.get()); // get an operation on the parent address... operation.get(ModelDescriptionConstants.OP).set("activate"); dispatcher.execute(new DMRAction(operation), new SimpleCallback<DMRResponse>() { @Override public void onSuccess(DMRResponse result) { Timer t = new Timer() { @Override public void run() { window.hide(); onReset(); } }; t.schedule(4000); } @Override public void onFailure(Throwable caught) { window.hide(); super.onFailure(caught); } }); } }
gui/src/main/java/org/jboss/as/console/client/shared/subsys/osgi/runtime/OSGiRuntimePresenter.java
/* * JBoss, Home of Professional Open Source * Copyright 2011 Red Hat Inc. and/or its affiliates and other contributors * as indicated by the @author tags. All rights reserved. * See the copyright.txt in the distribution for a * full listing of individual contributors. * * This copyrighted material is made available to anyone wishing to use, * modify, copy, or redistribute it subject to the terms and conditions * of the GNU Lesser General Public License, v. 2.1. * This program is distributed in the hope that it will be useful, but WITHOUT A * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A * PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. * You should have received a copy of the GNU Lesser General Public License, * v.2.1 along with this distribution; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ package org.jboss.as.console.client.shared.subsys.osgi.runtime; import com.google.gwt.event.shared.EventBus; import com.google.gwt.user.client.Timer; import com.google.gwt.user.client.ui.HTML; import com.google.inject.Inject; import com.gwtplatform.mvp.client.Presenter; import com.gwtplatform.mvp.client.View; import com.gwtplatform.mvp.client.annotations.NameToken; import com.gwtplatform.mvp.client.annotations.ProxyCodeSplit; import com.gwtplatform.mvp.client.proxy.Place; import com.gwtplatform.mvp.client.proxy.Proxy; import org.jboss.as.console.client.Console; import org.jboss.as.console.client.core.NameTokens; import org.jboss.as.console.client.domain.model.ServerInstance; import org.jboss.as.console.client.domain.model.SimpleCallback; import org.jboss.as.console.client.shared.dispatch.DispatchAsync; import org.jboss.as.console.client.shared.dispatch.impl.DMRAction; import org.jboss.as.console.client.shared.dispatch.impl.DMRResponse; import org.jboss.as.console.client.shared.general.MessageWindow; import org.jboss.as.console.client.shared.runtime.RuntimeBaseAddress; import org.jboss.as.console.client.shared.state.CurrentServerSelection; import org.jboss.as.console.client.shared.state.ServerSelectionEvent; import org.jboss.as.console.client.shared.subsys.RevealStrategy; import org.jboss.as.console.client.shared.subsys.osgi.runtime.model.OSGiBundle; import org.jboss.as.console.client.widgets.forms.AddressBinding; import org.jboss.as.console.client.widgets.forms.ApplicationMetaData; import org.jboss.as.console.client.widgets.forms.BeanMetaData; import org.jboss.ballroom.client.widgets.window.DefaultWindow; import org.jboss.dmr.client.ModelDescriptionConstants; import org.jboss.dmr.client.ModelNode; /** * @author David Bosschaert */ public class OSGiRuntimePresenter extends Presenter<OSGiRuntimePresenter.MyView, OSGiRuntimePresenter.MyProxy> implements ServerSelectionEvent.ServerSelectionListener { private final BeanMetaData bundleMetaData; private final DispatchAsync dispatcher; private final RevealStrategy revealStrategy; private CurrentServerSelection serverSelection; @ProxyCodeSplit @NameToken(NameTokens.OSGiRuntimePresenter) public interface MyProxy extends Proxy<OSGiRuntimePresenter>, Place { } public interface MyView extends View { void initialLoad(); void setPresenter(OSGiRuntimePresenter osGiRuntimePresenter); } @Inject public OSGiRuntimePresenter( EventBus eventBus, MyView view, MyProxy proxy, DispatchAsync dispatcher, ApplicationMetaData propertyMetaData, RevealStrategy revealStrategy, CurrentServerSelection serverSelection) { super(eventBus, view, proxy); this.dispatcher = dispatcher; this.revealStrategy = revealStrategy; this.bundleMetaData = propertyMetaData.getBeanMetaData(OSGiBundle.class); this.serverSelection = serverSelection; } @Override protected void onBind() { super.onBind(); getView().setPresenter(this); getEventBus().addHandler(ServerSelectionEvent.TYPE, this); } @Override protected void onReset() { super.onReset(); if(serverSelection.isSet()) getView().initialLoad(); } @Override public void onServerSelection(String hostName, ServerInstance server) { if(isVisible()) getView().initialLoad(); } @Override protected void revealInParent() { revealStrategy.revealInRuntimeParent(this); } void startBundle(OSGiBundle bundle) { bundleAction(bundle, "start"); } void stopBundle(OSGiBundle bundle) { bundleAction(bundle, "stop"); } private void bundleAction(OSGiBundle bundle, String operationName) { AddressBinding address = bundleMetaData.getAddress(); ModelNode operation = address.asResource(RuntimeBaseAddress.get(), bundle.getName()); operation.get(ModelDescriptionConstants.OP).set(operationName); dispatcher.execute(new DMRAction(operation), new SimpleCallback<DMRResponse>() { @Override public void onSuccess(DMRResponse result) { ModelNode response = result.get(); if(response.isFailure()) { Console.error(Console.MESSAGES.modificationFailed("OSGi Bundle"), response.getFailureDescription()); } else { Console.info(Console.MESSAGES.modified("OSGi Bundle")); } getView().initialLoad(); } }); } public void askToActivateSubsystem() { final DefaultWindow window = new DefaultWindow(Console.CONSTANTS.subsys_osgi()); window.setWidth(320); window.setHeight(140); window.setWidget(new MessageWindow(Console.MESSAGES.subsys_osgi_activate(), new MessageWindow.Result() { @Override public void result(boolean result) { window.hide(); if (result) activateSubsystem(); } }).asWidget()); window.setGlassEnabled(true); window.center(); } protected void activateSubsystem() { // Since it takes a few moments for the subsystem to activate we're showing a window indicating this final DefaultWindow window = new DefaultWindow(Console.CONSTANTS.subsys_osgi()); window.setWidth(320); window.setHeight(140); window.setWidget(new HTML(Console.MESSAGES.subsys_osgi_activating())); window.setGlassEnabled(true); window.center(); AddressBinding address = bundleMetaData.getAddress(); ModelNode operation = address.asSubresource(RuntimeBaseAddress.get()); // get an operation on the parent address... operation.get(ModelDescriptionConstants.OP).set("activate"); dispatcher.execute(new DMRAction(operation), new SimpleCallback<DMRResponse>() { @Override public void onSuccess(DMRResponse result) { Timer t = new Timer() { @Override public void run() { window.hide(); onReset(); } }; t.schedule(4000); } @Override public void onFailure(Throwable caught) { window.hide(); super.onFailure(caught); } }); } }
properly load osgi runtime data in standalone mode
gui/src/main/java/org/jboss/as/console/client/shared/subsys/osgi/runtime/OSGiRuntimePresenter.java
properly load osgi runtime data in standalone mode
<ide><path>ui/src/main/java/org/jboss/as/console/client/shared/subsys/osgi/runtime/OSGiRuntimePresenter.java <ide> protected void onReset() { <ide> super.onReset(); <ide> <del> if(serverSelection.isSet()) <add> if(serverSelection.isActive()) <ide> getView().initialLoad(); <ide> <ide> }
Java
apache-2.0
d167f7a5213f16d3588eb5688cf2e95b7f749391
0
nudelchef/libgdx,Heart2009/libgdx,FredGithub/libgdx,andyvand/libgdx,ztv/libgdx,MovingBlocks/libgdx,alireza-hosseini/libgdx,petugez/libgdx,thepullman/libgdx,Zonglin-Li6565/libgdx,saqsun/libgdx,309746069/libgdx,sjosegarcia/libgdx,antag99/libgdx,MovingBlocks/libgdx,Wisienkas/libgdx,GreenLightning/libgdx,djom20/libgdx,davebaol/libgdx,stickyd/libgdx,Gliby/libgdx,cypherdare/libgdx,czyzby/libgdx,xpenatan/libgdx-LWJGL3,stinsonga/libgdx,antag99/libgdx,del-sol/libgdx,snovak/libgdx,alireza-hosseini/libgdx,tommyettinger/libgdx,josephknight/libgdx,revo09/libgdx,luischavez/libgdx,MadcowD/libgdx,ricardorigodon/libgdx,alex-dorokhov/libgdx,noelsison2/libgdx,flaiker/libgdx,andyvand/libgdx,jberberick/libgdx,jberberick/libgdx,ttencate/libgdx,ricardorigodon/libgdx,samskivert/libgdx,junkdog/libgdx,djom20/libgdx,del-sol/libgdx,antag99/libgdx,anserran/libgdx,ninoalma/libgdx,stinsonga/libgdx,basherone/libgdxcn,josephknight/libgdx,gouessej/libgdx,JFixby/libgdx,hyvas/libgdx,MetSystem/libgdx,Senth/libgdx,nave966/libgdx,SidneyXu/libgdx,Senth/libgdx,alex-dorokhov/libgdx,ricardorigodon/libgdx,saltares/libgdx,codepoke/libgdx,MikkelTAndersen/libgdx,nudelchef/libgdx,codepoke/libgdx,ThiagoGarciaAlves/libgdx,MovingBlocks/libgdx,azakhary/libgdx,jasonwee/libgdx,309746069/libgdx,youprofit/libgdx,jsjolund/libgdx,toloudis/libgdx,ninoalma/libgdx,Heart2009/libgdx,davebaol/libgdx,xranby/libgdx,mumer92/libgdx,realitix/libgdx,nave966/libgdx,ya7lelkom/libgdx,Zomby2D/libgdx,gf11speed/libgdx,revo09/libgdx,zhimaijoy/libgdx,gouessej/libgdx,Badazdz/libgdx,titovmaxim/libgdx,MikkelTAndersen/libgdx,toloudis/libgdx,sinistersnare/libgdx,Xhanim/libgdx,bsmr-java/libgdx,collinsmith/libgdx,libgdx/libgdx,hyvas/libgdx,nooone/libgdx,bgroenks96/libgdx,MetSystem/libgdx,zhimaijoy/libgdx,junkdog/libgdx,azakhary/libgdx,nooone/libgdx,yangweigbh/libgdx,alireza-hosseini/libgdx,GreenLightning/libgdx,saltares/libgdx,kagehak/libgdx,MetSystem/libgdx,anserran/libgdx,ttencate/libgdx,SidneyXu/libgdx,UnluckyNinja/libgdx,andyvand/libgdx,stickyd/libgdx,srwonka/libGdx,anserran/libgdx,SidneyXu/libgdx,shiweihappy/libgdx,jberberick/libgdx,Dzamir/libgdx,fiesensee/libgdx,BlueRiverInteractive/libgdx,codepoke/libgdx,josephknight/libgdx,curtiszimmerman/libgdx,billgame/libgdx,Xhanim/libgdx,KrisLee/libgdx,Xhanim/libgdx,JDReutt/libgdx,1yvT0s/libgdx,bgroenks96/libgdx,MikkelTAndersen/libgdx,ya7lelkom/libgdx,andyvand/libgdx,designcrumble/libgdx,bladecoder/libgdx,antag99/libgdx,gdos/libgdx,realitix/libgdx,FyiurAmron/libgdx,gouessej/libgdx,kagehak/libgdx,katiepino/libgdx,firefly2442/libgdx,nooone/libgdx,ricardorigodon/libgdx,1yvT0s/libgdx,tommycli/libgdx,yangweigbh/libgdx,zommuter/libgdx,billgame/libgdx,Gliby/libgdx,Badazdz/libgdx,ninoalma/libgdx,petugez/libgdx,luischavez/libgdx,sarkanyi/libgdx,toloudis/libgdx,KrisLee/libgdx,FyiurAmron/libgdx,alex-dorokhov/libgdx,del-sol/libgdx,sarkanyi/libgdx,shiweihappy/libgdx,del-sol/libgdx,codepoke/libgdx,Deftwun/libgdx,thepullman/libgdx,srwonka/libGdx,Arcnor/libgdx,ricardorigodon/libgdx,PedroRomanoBarbosa/libgdx,fwolff/libgdx,davebaol/libgdx,js78/libgdx,stickyd/libgdx,anserran/libgdx,junkdog/libgdx,revo09/libgdx,nudelchef/libgdx,xpenatan/libgdx-LWJGL3,mumer92/libgdx,stickyd/libgdx,czyzby/libgdx,tell10glu/libgdx,bsmr-java/libgdx,tommycli/libgdx,shiweihappy/libgdx,xpenatan/libgdx-LWJGL3,ya7lelkom/libgdx,tommycli/libgdx,fwolff/libgdx,noelsison2/libgdx,xoppa/libgdx,UnluckyNinja/libgdx,saqsun/libgdx,basherone/libgdxcn,saltares/libgdx,snovak/libgdx,MikkelTAndersen/libgdx,sjosegarcia/libgdx,kotcrab/libgdx,zommuter/libgdx,yangweigbh/libgdx,toloudis/libgdx,GreenLightning/libgdx,petugez/libgdx,js78/libgdx,Zonglin-Li6565/libgdx,nooone/libgdx,youprofit/libgdx,1yvT0s/libgdx,anserran/libgdx,billgame/libgdx,samskivert/libgdx,saltares/libgdx,saqsun/libgdx,mumer92/libgdx,Thotep/libgdx,stinsonga/libgdx,gf11speed/libgdx,revo09/libgdx,tommyettinger/libgdx,gf11speed/libgdx,xoppa/libgdx,PedroRomanoBarbosa/libgdx,shiweihappy/libgdx,saltares/libgdx,ztv/libgdx,srwonka/libGdx,js78/libgdx,FyiurAmron/libgdx,yangweigbh/libgdx,firefly2442/libgdx,ttencate/libgdx,kagehak/libgdx,katiepino/libgdx,designcrumble/libgdx,Arcnor/libgdx,katiepino/libgdx,KrisLee/libgdx,nooone/libgdx,azakhary/libgdx,xranby/libgdx,MadcowD/libgdx,Senth/libgdx,hyvas/libgdx,junkdog/libgdx,Wisienkas/libgdx,Wisienkas/libgdx,designcrumble/libgdx,tommyettinger/libgdx,JFixby/libgdx,xpenatan/libgdx-LWJGL3,haedri/libgdx-1,MadcowD/libgdx,TheAks999/libgdx,mumer92/libgdx,youprofit/libgdx,petugez/libgdx,firefly2442/libgdx,alireza-hosseini/libgdx,shiweihappy/libgdx,bsmr-java/libgdx,kotcrab/libgdx,Gliby/libgdx,jberberick/libgdx,cypherdare/libgdx,alex-dorokhov/libgdx,JFixby/libgdx,josephknight/libgdx,tommycli/libgdx,BlueRiverInteractive/libgdx,mumer92/libgdx,nave966/libgdx,sjosegarcia/libgdx,Zonglin-Li6565/libgdx,nrallakis/libgdx,FyiurAmron/libgdx,NathanSweet/libgdx,nrallakis/libgdx,tommyettinger/libgdx,stinsonga/libgdx,ttencate/libgdx,titovmaxim/libgdx,gdos/libgdx,yangweigbh/libgdx,309746069/libgdx,ThiagoGarciaAlves/libgdx,EsikAntony/libgdx,Deftwun/libgdx,saltares/libgdx,thepullman/libgdx,del-sol/libgdx,bgroenks96/libgdx,mumer92/libgdx,petugez/libgdx,hyvas/libgdx,saltares/libgdx,djom20/libgdx,KrisLee/libgdx,ninoalma/libgdx,luischavez/libgdx,alex-dorokhov/libgdx,saqsun/libgdx,UnluckyNinja/libgdx,nrallakis/libgdx,collinsmith/libgdx,TheAks999/libgdx,BlueRiverInteractive/libgdx,fwolff/libgdx,kotcrab/libgdx,curtiszimmerman/libgdx,djom20/libgdx,UnluckyNinja/libgdx,azakhary/libgdx,curtiszimmerman/libgdx,ztv/libgdx,NathanSweet/libgdx,ztv/libgdx,KrisLee/libgdx,ThiagoGarciaAlves/libgdx,jasonwee/libgdx,xranby/libgdx,saqsun/libgdx,xpenatan/libgdx-LWJGL3,cypherdare/libgdx,GreenLightning/libgdx,copystudy/libgdx,alex-dorokhov/libgdx,BlueRiverInteractive/libgdx,TheAks999/libgdx,Heart2009/libgdx,ThiagoGarciaAlves/libgdx,billgame/libgdx,toa5/libgdx,antag99/libgdx,davebaol/libgdx,haedri/libgdx-1,gf11speed/libgdx,petugez/libgdx,azakhary/libgdx,Deftwun/libgdx,gf11speed/libgdx,JDReutt/libgdx,bsmr-java/libgdx,haedri/libgdx-1,nudelchef/libgdx,zommuter/libgdx,JDReutt/libgdx,haedri/libgdx-1,Arcnor/libgdx,GreenLightning/libgdx,flaiker/libgdx,309746069/libgdx,noelsison2/libgdx,tell10glu/libgdx,jsjolund/libgdx,saqsun/libgdx,saqsun/libgdx,snovak/libgdx,designcrumble/libgdx,mumer92/libgdx,EsikAntony/libgdx,fwolff/libgdx,js78/libgdx,realitix/libgdx,curtiszimmerman/libgdx,gf11speed/libgdx,sinistersnare/libgdx,TheAks999/libgdx,nelsonsilva/libgdx,tommycli/libgdx,libgdx/libgdx,xranby/libgdx,thepullman/libgdx,realitix/libgdx,andyvand/libgdx,stickyd/libgdx,nelsonsilva/libgdx,Gliby/libgdx,JDReutt/libgdx,hyvas/libgdx,Senth/libgdx,Badazdz/libgdx,gouessej/libgdx,stinsonga/libgdx,Wisienkas/libgdx,copystudy/libgdx,del-sol/libgdx,kotcrab/libgdx,petugez/libgdx,FredGithub/libgdx,MadcowD/libgdx,Deftwun/libgdx,tommycli/libgdx,sinistersnare/libgdx,realitix/libgdx,luischavez/libgdx,codepoke/libgdx,zommuter/libgdx,EsikAntony/libgdx,srwonka/libGdx,BlueRiverInteractive/libgdx,czyzby/libgdx,jberberick/libgdx,UnluckyNinja/libgdx,sarkanyi/libgdx,jberberick/libgdx,gouessej/libgdx,KrisLee/libgdx,luischavez/libgdx,josephknight/libgdx,PedroRomanoBarbosa/libgdx,Gliby/libgdx,Dzamir/libgdx,BlueRiverInteractive/libgdx,antag99/libgdx,shiweihappy/libgdx,zhimaijoy/libgdx,toa5/libgdx,sarkanyi/libgdx,curtiszimmerman/libgdx,hyvas/libgdx,codepoke/libgdx,ttencate/libgdx,snovak/libgdx,antag99/libgdx,MikkelTAndersen/libgdx,gouessej/libgdx,fwolff/libgdx,JDReutt/libgdx,jasonwee/libgdx,tell10glu/libgdx,MadcowD/libgdx,gouessej/libgdx,katiepino/libgdx,gdos/libgdx,xranby/libgdx,MovingBlocks/libgdx,Dzamir/libgdx,jasonwee/libgdx,FyiurAmron/libgdx,ttencate/libgdx,andyvand/libgdx,FredGithub/libgdx,luischavez/libgdx,samskivert/libgdx,Thotep/libgdx,sarkanyi/libgdx,fiesensee/libgdx,Dzamir/libgdx,Wisienkas/libgdx,fiesensee/libgdx,SidneyXu/libgdx,copystudy/libgdx,josephknight/libgdx,nave966/libgdx,alex-dorokhov/libgdx,libgdx/libgdx,JDReutt/libgdx,katiepino/libgdx,Thotep/libgdx,Badazdz/libgdx,ThiagoGarciaAlves/libgdx,FredGithub/libgdx,js78/libgdx,sjosegarcia/libgdx,zhimaijoy/libgdx,Xhanim/libgdx,js78/libgdx,Xhanim/libgdx,copystudy/libgdx,fiesensee/libgdx,nelsonsilva/libgdx,kagehak/libgdx,GreenLightning/libgdx,ya7lelkom/libgdx,designcrumble/libgdx,stickyd/libgdx,TheAks999/libgdx,hyvas/libgdx,collinsmith/libgdx,MikkelTAndersen/libgdx,ninoalma/libgdx,js78/libgdx,jsjolund/libgdx,ninoalma/libgdx,curtiszimmerman/libgdx,alireza-hosseini/libgdx,youprofit/libgdx,kotcrab/libgdx,Senth/libgdx,designcrumble/libgdx,tell10glu/libgdx,czyzby/libgdx,JFixby/libgdx,titovmaxim/libgdx,MetSystem/libgdx,realitix/libgdx,tell10glu/libgdx,GreenLightning/libgdx,basherone/libgdxcn,nave966/libgdx,jsjolund/libgdx,Thotep/libgdx,tommycli/libgdx,PedroRomanoBarbosa/libgdx,kagehak/libgdx,MetSystem/libgdx,zommuter/libgdx,Thotep/libgdx,titovmaxim/libgdx,fwolff/libgdx,srwonka/libGdx,NathanSweet/libgdx,Zomby2D/libgdx,haedri/libgdx-1,sjosegarcia/libgdx,junkdog/libgdx,shiweihappy/libgdx,firefly2442/libgdx,UnluckyNinja/libgdx,josephknight/libgdx,stickyd/libgdx,thepullman/libgdx,samskivert/libgdx,MadcowD/libgdx,czyzby/libgdx,libgdx/libgdx,Wisienkas/libgdx,Dzamir/libgdx,MikkelTAndersen/libgdx,1yvT0s/libgdx,jsjolund/libgdx,toa5/libgdx,collinsmith/libgdx,noelsison2/libgdx,gdos/libgdx,ricardorigodon/libgdx,azakhary/libgdx,katiepino/libgdx,firefly2442/libgdx,flaiker/libgdx,thepullman/libgdx,Heart2009/libgdx,Thotep/libgdx,haedri/libgdx-1,Deftwun/libgdx,haedri/libgdx-1,jsjolund/libgdx,Zonglin-Li6565/libgdx,stickyd/libgdx,FyiurAmron/libgdx,TheAks999/libgdx,sinistersnare/libgdx,youprofit/libgdx,Heart2009/libgdx,gouessej/libgdx,noelsison2/libgdx,sjosegarcia/libgdx,samskivert/libgdx,yangweigbh/libgdx,thepullman/libgdx,sjosegarcia/libgdx,xoppa/libgdx,GreenLightning/libgdx,toa5/libgdx,tell10glu/libgdx,PedroRomanoBarbosa/libgdx,nrallakis/libgdx,xranby/libgdx,yangweigbh/libgdx,billgame/libgdx,Zomby2D/libgdx,collinsmith/libgdx,noelsison2/libgdx,MadcowD/libgdx,Gliby/libgdx,billgame/libgdx,ricardorigodon/libgdx,billgame/libgdx,anserran/libgdx,nelsonsilva/libgdx,jberberick/libgdx,bgroenks96/libgdx,Xhanim/libgdx,sjosegarcia/libgdx,youprofit/libgdx,jasonwee/libgdx,bladecoder/libgdx,noelsison2/libgdx,flaiker/libgdx,Badazdz/libgdx,haedri/libgdx-1,djom20/libgdx,ninoalma/libgdx,tell10glu/libgdx,bsmr-java/libgdx,nrallakis/libgdx,ttencate/libgdx,basherone/libgdxcn,flaiker/libgdx,309746069/libgdx,FredGithub/libgdx,srwonka/libGdx,saltares/libgdx,flaiker/libgdx,1yvT0s/libgdx,tommyettinger/libgdx,Deftwun/libgdx,PedroRomanoBarbosa/libgdx,Senth/libgdx,revo09/libgdx,Arcnor/libgdx,bsmr-java/libgdx,nelsonsilva/libgdx,BlueRiverInteractive/libgdx,toa5/libgdx,Xhanim/libgdx,Dzamir/libgdx,nrallakis/libgdx,junkdog/libgdx,titovmaxim/libgdx,zhimaijoy/libgdx,js78/libgdx,davebaol/libgdx,1yvT0s/libgdx,titovmaxim/libgdx,toa5/libgdx,kotcrab/libgdx,bladecoder/libgdx,Thotep/libgdx,bgroenks96/libgdx,ya7lelkom/libgdx,collinsmith/libgdx,tommycli/libgdx,revo09/libgdx,tell10glu/libgdx,SidneyXu/libgdx,1yvT0s/libgdx,samskivert/libgdx,sarkanyi/libgdx,EsikAntony/libgdx,shiweihappy/libgdx,FredGithub/libgdx,Dzamir/libgdx,basherone/libgdxcn,cypherdare/libgdx,309746069/libgdx,xranby/libgdx,codepoke/libgdx,gf11speed/libgdx,zommuter/libgdx,Zomby2D/libgdx,xpenatan/libgdx-LWJGL3,Badazdz/libgdx,KrisLee/libgdx,jberberick/libgdx,bsmr-java/libgdx,ThiagoGarciaAlves/libgdx,TheAks999/libgdx,andyvand/libgdx,Deftwun/libgdx,JFixby/libgdx,Senth/libgdx,1yvT0s/libgdx,collinsmith/libgdx,firefly2442/libgdx,Wisienkas/libgdx,designcrumble/libgdx,Heart2009/libgdx,Zomby2D/libgdx,revo09/libgdx,TheAks999/libgdx,kagehak/libgdx,nave966/libgdx,xoppa/libgdx,gdos/libgdx,bgroenks96/libgdx,Xhanim/libgdx,revo09/libgdx,snovak/libgdx,junkdog/libgdx,xoppa/libgdx,czyzby/libgdx,xpenatan/libgdx-LWJGL3,Gliby/libgdx,BlueRiverInteractive/libgdx,MadcowD/libgdx,djom20/libgdx,sinistersnare/libgdx,zhimaijoy/libgdx,titovmaxim/libgdx,gdos/libgdx,fiesensee/libgdx,bgroenks96/libgdx,ttencate/libgdx,nudelchef/libgdx,billgame/libgdx,MovingBlocks/libgdx,noelsison2/libgdx,Heart2009/libgdx,toa5/libgdx,katiepino/libgdx,srwonka/libGdx,xoppa/libgdx,nooone/libgdx,snovak/libgdx,Heart2009/libgdx,realitix/libgdx,alireza-hosseini/libgdx,zommuter/libgdx,firefly2442/libgdx,ninoalma/libgdx,zommuter/libgdx,libgdx/libgdx,samskivert/libgdx,josephknight/libgdx,Badazdz/libgdx,ya7lelkom/libgdx,Zonglin-Li6565/libgdx,JDReutt/libgdx,nelsonsilva/libgdx,alireza-hosseini/libgdx,Arcnor/libgdx,antag99/libgdx,MovingBlocks/libgdx,Badazdz/libgdx,nudelchef/libgdx,309746069/libgdx,youprofit/libgdx,gdos/libgdx,nrallakis/libgdx,kagehak/libgdx,titovmaxim/libgdx,ztv/libgdx,anserran/libgdx,toloudis/libgdx,snovak/libgdx,bladecoder/libgdx,ztv/libgdx,fwolff/libgdx,KrisLee/libgdx,kotcrab/libgdx,PedroRomanoBarbosa/libgdx,Dzamir/libgdx,del-sol/libgdx,bladecoder/libgdx,alireza-hosseini/libgdx,copystudy/libgdx,luischavez/libgdx,kotcrab/libgdx,firefly2442/libgdx,SidneyXu/libgdx,srwonka/libGdx,del-sol/libgdx,fiesensee/libgdx,copystudy/libgdx,Zonglin-Li6565/libgdx,junkdog/libgdx,MikkelTAndersen/libgdx,toloudis/libgdx,youprofit/libgdx,MetSystem/libgdx,flaiker/libgdx,nave966/libgdx,toloudis/libgdx,kagehak/libgdx,andyvand/libgdx,katiepino/libgdx,sinistersnare/libgdx,czyzby/libgdx,ThiagoGarciaAlves/libgdx,saqsun/libgdx,hyvas/libgdx,basherone/libgdxcn,czyzby/libgdx,curtiszimmerman/libgdx,curtiszimmerman/libgdx,UnluckyNinja/libgdx,designcrumble/libgdx,toa5/libgdx,codepoke/libgdx,zhimaijoy/libgdx,nudelchef/libgdx,309746069/libgdx,cypherdare/libgdx,SidneyXu/libgdx,fiesensee/libgdx,xranby/libgdx,alex-dorokhov/libgdx,MetSystem/libgdx,EsikAntony/libgdx,EsikAntony/libgdx,SidneyXu/libgdx,Thotep/libgdx,copystudy/libgdx,Senth/libgdx,collinsmith/libgdx,Zonglin-Li6565/libgdx,thepullman/libgdx,MetSystem/libgdx,sarkanyi/libgdx,Deftwun/libgdx,nudelchef/libgdx,PedroRomanoBarbosa/libgdx,djom20/libgdx,ya7lelkom/libgdx,Zonglin-Li6565/libgdx,petugez/libgdx,toloudis/libgdx,JFixby/libgdx,jasonwee/libgdx,sarkanyi/libgdx,jasonwee/libgdx,gf11speed/libgdx,ya7lelkom/libgdx,EsikAntony/libgdx,UnluckyNinja/libgdx,djom20/libgdx,fwolff/libgdx,Arcnor/libgdx,MovingBlocks/libgdx,jsjolund/libgdx,jsjolund/libgdx,davebaol/libgdx,ztv/libgdx,copystudy/libgdx,xoppa/libgdx,nave966/libgdx,MovingBlocks/libgdx,samskivert/libgdx,xoppa/libgdx,JDReutt/libgdx,JFixby/libgdx,ThiagoGarciaAlves/libgdx,zhimaijoy/libgdx,yangweigbh/libgdx,snovak/libgdx,FredGithub/libgdx,gdos/libgdx,flaiker/libgdx,luischavez/libgdx,bsmr-java/libgdx,Wisienkas/libgdx,Gliby/libgdx,xpenatan/libgdx-LWJGL3,ztv/libgdx,fiesensee/libgdx,anserran/libgdx,FredGithub/libgdx,FyiurAmron/libgdx,ricardorigodon/libgdx,jasonwee/libgdx,NathanSweet/libgdx,mumer92/libgdx,NathanSweet/libgdx,realitix/libgdx,FyiurAmron/libgdx,bgroenks96/libgdx,JFixby/libgdx,nrallakis/libgdx,EsikAntony/libgdx
/******************************************************************************* * Copyright 2011 See AUTHORS file. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.badlogic.gdx.graphics.g2d; import com.badlogic.gdx.math.MathUtils; import com.badlogic.gdx.utils.Array; /** <p> * An Animation stores a list of {@link TextureRegion}s representing an animated sequence, e.g. for running or jumping. Each * region of an Animation is called a key frame, multiple key frames make up the animation. * </p> * * @author mzechner */ public class Animation { /** Defines possible playback modes for an {@link Animation}. */ public enum PlayMode { NORMAL, REVERSED, LOOP, LOOP_REVERSED, LOOP_PINGPONG, LOOP_RANDOM, } final TextureRegion[] keyFrames; private float frameDuration; private float animationDuration; private int lastFrameNumber; private float lastStateTime; private PlayMode playMode = PlayMode.NORMAL; /** Constructor, storing the frame duration and key frames. * * @param frameDuration the time between frames in seconds. * @param keyFrames the {@link TextureRegion}s representing the frames. */ public Animation (float frameDuration, Array<? extends TextureRegion> keyFrames) { this.frameDuration = frameDuration; this.animationDuration = keyFrames.size * frameDuration; this.keyFrames = new TextureRegion[keyFrames.size]; for (int i = 0, n = keyFrames.size; i < n; i++) { this.keyFrames[i] = keyFrames.get(i); } this.playMode = PlayMode.NORMAL; } /** Constructor, storing the frame duration, key frames and play type. * * @param frameDuration the time between frames in seconds. * @param keyFrames the {@link TextureRegion}s representing the frames. * @param playMode the animation playback mode. */ public Animation (float frameDuration, Array<? extends TextureRegion> keyFrames, PlayMode playMode) { this.frameDuration = frameDuration; this.animationDuration = keyFrames.size * frameDuration; this.keyFrames = new TextureRegion[keyFrames.size]; for (int i = 0, n = keyFrames.size; i < n; i++) { this.keyFrames[i] = keyFrames.get(i); } this.playMode = playMode; } /** Constructor, storing the frame duration and key frames. * * @param frameDuration the time between frames in seconds. * @param keyFrames the {@link TextureRegion}s representing the frames. */ public Animation (float frameDuration, TextureRegion... keyFrames) { this.frameDuration = frameDuration; this.animationDuration = keyFrames.length * frameDuration; this.keyFrames = keyFrames; this.playMode = PlayMode.NORMAL; } /** Returns a {@link TextureRegion} based on the so called state time. This is the amount of seconds an object has spent in the * state this Animation instance represents, e.g. running, jumping and so on. The mode specifies whether the animation is * looping or not. * * @param stateTime the time spent in the state represented by this animation. * @param looping whether the animation is looping or not. * @return the TextureRegion representing the frame of animation for the given state time. */ public TextureRegion getKeyFrame (float stateTime, boolean looping) { // we set the play mode by overriding the previous mode based on looping // parameter value PlayMode oldPlayMode = playMode; if (looping && (playMode == PlayMode.NORMAL || playMode == PlayMode.REVERSED)) { if (playMode == PlayMode.NORMAL) playMode = PlayMode.LOOP; else playMode = PlayMode.LOOP_REVERSED; } else if (!looping && !(playMode == PlayMode.NORMAL || playMode == PlayMode.REVERSED)) { if (playMode == PlayMode.LOOP_REVERSED) playMode = PlayMode.REVERSED; else playMode = PlayMode.LOOP; } TextureRegion frame = getKeyFrame(stateTime); playMode = oldPlayMode; return frame; } /** Returns a {@link TextureRegion} based on the so called state time. This is the amount of seconds an object has spent in the * state this Animation instance represents, e.g. running, jumping and so on using the mode specified by * {@link #setPlayMode(PlayMode)} method. * * @param stateTime * @return the TextureRegion representing the frame of animation for the given state time. */ public TextureRegion getKeyFrame (float stateTime) { int frameNumber = getKeyFrameIndex(stateTime); return keyFrames[frameNumber]; } /** Returns the current frame number. * @param stateTime * @return current frame number */ public int getKeyFrameIndex (float stateTime) { if (keyFrames.length == 1) return 0; int frameNumber = (int)(stateTime / frameDuration); switch (playMode) { case NORMAL: frameNumber = Math.min(keyFrames.length - 1, frameNumber); break; case LOOP: frameNumber = frameNumber % keyFrames.length; break; case LOOP_PINGPONG: frameNumber = frameNumber % ((keyFrames.length * 2) - 2); if (frameNumber >= keyFrames.length) frameNumber = keyFrames.length - 2 - (frameNumber - keyFrames.length); break; case LOOP_RANDOM: int lastFrameNumber = (int) ((lastStateTime) / frameDuration); if (lastFrameNumber != frameNumber) { frameNumber = MathUtils.random(keyFrames.length - 1); } else { frameNumber = this.lastFrameNumber; } break; case REVERSED: frameNumber = Math.max(keyFrames.length - frameNumber - 1, 0); break; case LOOP_REVERSED: frameNumber = frameNumber % keyFrames.length; frameNumber = keyFrames.length - frameNumber - 1; break; } lastFrameNumber = frameNumber; lastStateTime = stateTime; return frameNumber; } /** Returns the keyFrames[] array where all the TextureRegions of the animation are stored. * @return keyFrames[] field */ public TextureRegion[] getKeyFrames () { return keyFrames; } /** Returns the animation play mode. */ public PlayMode getPlayMode () { return playMode; } /** Sets the animation play mode. * * @param playMode The animation {@link PlayMode} to use. */ public void setPlayMode (PlayMode playMode) { this.playMode = playMode; } /** Whether the animation would be finished if played without looping (PlayMode#NORMAL), given the state time. * @param stateTime * @return whether the animation is finished. */ public boolean isAnimationFinished (float stateTime) { int frameNumber = (int)(stateTime / frameDuration); return keyFrames.length - 1 < frameNumber; } /** Sets duration a frame will be displayed. * @param frameDuration in seconds */ public void setFrameDuration (float frameDuration) { this.frameDuration = frameDuration; this.animationDuration = keyFrames.length * frameDuration; } /** @return the duration of a frame in seconds */ public float getFrameDuration () { return frameDuration; } /** @return the duration of the entire animation, number of frames times frame duration, in seconds */ public float getAnimationDuration () { return animationDuration; } }
gdx/src/com/badlogic/gdx/graphics/g2d/Animation.java
/******************************************************************************* * Copyright 2011 See AUTHORS file. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.badlogic.gdx.graphics.g2d; import com.badlogic.gdx.math.MathUtils; import com.badlogic.gdx.utils.Array; /** <p> * An Animation stores a list of {@link TextureRegion}s representing an animated sequence, e.g. for running or jumping. Each * region of an Animation is called a key frame, multiple key frames make up the animation. * </p> * * @author mzechner */ public class Animation { /** Defines possible playback modes for an {@link Animation}. */ public enum PlayMode { NORMAL, REVERSED, LOOP, LOOP_REVERSED, LOOP_PINGPONG, LOOP_RANDOM, } final TextureRegion[] keyFrames; private float frameDuration; private float animationDuration; private int lastFrameNumber; private float lastStateTime; private PlayMode playMode = PlayMode.NORMAL; /** Constructor, storing the frame duration and key frames. * * @param frameDuration the time between frames in seconds. * @param keyFrames the {@link TextureRegion}s representing the frames. */ public Animation (float frameDuration, Array<? extends TextureRegion> keyFrames) { this.frameDuration = frameDuration; this.animationDuration = keyFrames.size * frameDuration; this.keyFrames = new TextureRegion[keyFrames.size]; for (int i = 0, n = keyFrames.size; i < n; i++) { this.keyFrames[i] = keyFrames.get(i); } this.playMode = PlayMode.NORMAL; } /** Constructor, storing the frame duration, key frames and play type. * * @param frameDuration the time between frames in seconds. * @param keyFrames the {@link TextureRegion}s representing the frames. * @param playMode the animation playback mode. */ public Animation (float frameDuration, Array<? extends TextureRegion> keyFrames, PlayMode playMode) { this.frameDuration = frameDuration; this.animationDuration = keyFrames.size * frameDuration; this.keyFrames = new TextureRegion[keyFrames.size]; for (int i = 0, n = keyFrames.size; i < n; i++) { this.keyFrames[i] = keyFrames.get(i); } this.playMode = playMode; } /** Constructor, storing the frame duration and key frames. * * @param frameDuration the time between frames in seconds. * @param keyFrames the {@link TextureRegion}s representing the frames. */ public Animation (float frameDuration, TextureRegion... keyFrames) { this.frameDuration = frameDuration; this.animationDuration = keyFrames.length * frameDuration; this.keyFrames = keyFrames; this.playMode = PlayMode.NORMAL; } /** Returns a {@link TextureRegion} based on the so called state time. This is the amount of seconds an object has spent in the * state this Animation instance represents, e.g. running, jumping and so on. The mode specifies whether the animation is * looping or not. * * @param stateTime the time spent in the state represented by this animation. * @param looping whether the animation is looping or not. * @return the TextureRegion representing the frame of animation for the given state time. */ public TextureRegion getKeyFrame (float stateTime, boolean looping) { // we set the play mode by overriding the previous mode based on looping // parameter value PlayMode oldPlayMode = playMode; if (looping && (playMode == PlayMode.NORMAL || playMode == PlayMode.REVERSED)) { if (playMode == PlayMode.NORMAL) playMode = PlayMode.LOOP; else playMode = PlayMode.LOOP_REVERSED; } else if (!looping && !(playMode == PlayMode.NORMAL || playMode == PlayMode.REVERSED)) { if (playMode == PlayMode.LOOP_REVERSED) playMode = PlayMode.REVERSED; else playMode = PlayMode.LOOP; } TextureRegion frame = getKeyFrame(stateTime); playMode = oldPlayMode; return frame; } /** Returns a {@link TextureRegion} based on the so called state time. This is the amount of seconds an object has spent in the * state this Animation instance represents, e.g. running, jumping and so on using the mode specified by * {@link #setPlayMode(PlayMode)} method. * * @param stateTime * @return the TextureRegion representing the frame of animation for the given state time. */ public TextureRegion getKeyFrame (float stateTime) { int frameNumber = getKeyFrameIndex(stateTime); return keyFrames[frameNumber]; } /** Returns the current frame number. * @param stateTime * @return current frame number */ public int getKeyFrameIndex (float stateTime) { if (keyFrames.length == 1) return 0; int frameNumber = (int)(stateTime / frameDuration); switch (playMode) { case NORMAL: frameNumber = Math.min(keyFrames.length - 1, frameNumber); break; case LOOP: frameNumber = frameNumber % keyFrames.length; break; case LOOP_PINGPONG: frameNumber = frameNumber % ((keyFrames.length * 2) - 2); if (frameNumber >= keyFrames.length) frameNumber = keyFrames.length - 2 - (frameNumber - keyFrames.length); break; case LOOP_RANDOM: int lastFrameNumber = (int) ((stateTime - (stateTime - lastStateTime)) / frameDuration); if (lastFrameNumber != frameNumber) { frameNumber = MathUtils.random(keyFrames.length - 1); } else { frameNumber = this.lastFrameNumber; } break; case REVERSED: frameNumber = Math.max(keyFrames.length - frameNumber - 1, 0); break; case LOOP_REVERSED: frameNumber = frameNumber % keyFrames.length; frameNumber = keyFrames.length - frameNumber - 1; break; } lastFrameNumber = frameNumber; lastStateTime = stateTime; return frameNumber; } /** Returns the keyFrames[] array where all the TextureRegions of the animation are stored. * @return keyFrames[] field */ public TextureRegion[] getKeyFrames () { return keyFrames; } /** Returns the animation play mode. */ public PlayMode getPlayMode () { return playMode; } /** Sets the animation play mode. * * @param playMode The animation {@link PlayMode} to use. */ public void setPlayMode (PlayMode playMode) { this.playMode = playMode; } /** Whether the animation would be finished if played without looping (PlayMode#NORMAL), given the state time. * @param stateTime * @return whether the animation is finished. */ public boolean isAnimationFinished (float stateTime) { int frameNumber = (int)(stateTime / frameDuration); return keyFrames.length - 1 < frameNumber; } /** Sets duration a frame will be displayed. * @param frameDuration in seconds */ public void setFrameDuration (float frameDuration) { this.frameDuration = frameDuration; this.animationDuration = keyFrames.length * frameDuration; } /** @return the duration of a frame in seconds */ public float getFrameDuration () { return frameDuration; } /** @return the duration of the entire animation, number of frames times frame duration, in seconds */ public float getAnimationDuration () { return animationDuration; } }
Fixed unnecessary calculation.
gdx/src/com/badlogic/gdx/graphics/g2d/Animation.java
Fixed unnecessary calculation.
<ide><path>dx/src/com/badlogic/gdx/graphics/g2d/Animation.java <ide> if (frameNumber >= keyFrames.length) frameNumber = keyFrames.length - 2 - (frameNumber - keyFrames.length); <ide> break; <ide> case LOOP_RANDOM: <del> int lastFrameNumber = (int) ((stateTime - (stateTime - lastStateTime)) / frameDuration); <add> int lastFrameNumber = (int) ((lastStateTime) / frameDuration); <ide> if (lastFrameNumber != frameNumber) { <ide> frameNumber = MathUtils.random(keyFrames.length - 1); <ide> } else {
Java
apache-2.0
d0c7b13e442d149420f05100dc0a53da637f1c11
0
MichaelNedzelsky/intellij-community,retomerz/intellij-community,retomerz/intellij-community,TangHao1987/intellij-community,MichaelNedzelsky/intellij-community,youdonghai/intellij-community,da1z/intellij-community,akosyakov/intellij-community,TangHao1987/intellij-community,fengbaicanhe/intellij-community,vladmm/intellij-community,dslomov/intellij-community,ahb0327/intellij-community,fitermay/intellij-community,ahb0327/intellij-community,fitermay/intellij-community,samthor/intellij-community,FHannes/intellij-community,pwoodworth/intellij-community,da1z/intellij-community,petteyg/intellij-community,vvv1559/intellij-community,SerCeMan/intellij-community,ahb0327/intellij-community,FHannes/intellij-community,fnouama/intellij-community,xfournet/intellij-community,holmes/intellij-community,Lekanich/intellij-community,da1z/intellij-community,jagguli/intellij-community,samthor/intellij-community,xfournet/intellij-community,petteyg/intellij-community,hurricup/intellij-community,ftomassetti/intellij-community,petteyg/intellij-community,orekyuu/intellij-community,blademainer/intellij-community,signed/intellij-community,supersven/intellij-community,apixandru/intellij-community,ftomassetti/intellij-community,orekyuu/intellij-community,samthor/intellij-community,SerCeMan/intellij-community,michaelgallacher/intellij-community,kool79/intellij-community,orekyuu/intellij-community,fitermay/intellij-community,idea4bsd/idea4bsd,retomerz/intellij-community,jagguli/intellij-community,allotria/intellij-community,supersven/intellij-community,Lekanich/intellij-community,lucafavatella/intellij-community,apixandru/intellij-community,youdonghai/intellij-community,lucafavatella/intellij-community,MER-GROUP/intellij-community,vvv1559/intellij-community,fitermay/intellij-community,MER-GROUP/intellij-community,wreckJ/intellij-community,hurricup/intellij-community,ivan-fedorov/intellij-community,SerCeMan/intellij-community,TangHao1987/intellij-community,muntasirsyed/intellij-community,adedayo/intellij-community,clumsy/intellij-community,adedayo/intellij-community,xfournet/intellij-community,vladmm/intellij-community,clumsy/intellij-community,semonte/intellij-community,caot/intellij-community,vvv1559/intellij-community,tmpgit/intellij-community,ftomassetti/intellij-community,adedayo/intellij-community,ahb0327/intellij-community,MichaelNedzelsky/intellij-community,ibinti/intellij-community,ivan-fedorov/intellij-community,MER-GROUP/intellij-community,amith01994/intellij-community,mglukhikh/intellij-community,allotria/intellij-community,clumsy/intellij-community,gnuhub/intellij-community,robovm/robovm-studio,slisson/intellij-community,ibinti/intellij-community,alphafoobar/intellij-community,akosyakov/intellij-community,muntasirsyed/intellij-community,semonte/intellij-community,clumsy/intellij-community,michaelgallacher/intellij-community,ahb0327/intellij-community,suncycheng/intellij-community,holmes/intellij-community,youdonghai/intellij-community,Lekanich/intellij-community,tmpgit/intellij-community,lucafavatella/intellij-community,hurricup/intellij-community,semonte/intellij-community,blademainer/intellij-community,wreckJ/intellij-community,adedayo/intellij-community,vvv1559/intellij-community,Lekanich/intellij-community,semonte/intellij-community,pwoodworth/intellij-community,muntasirsyed/intellij-community,Lekanich/intellij-community,gnuhub/intellij-community,kdwink/intellij-community,ahb0327/intellij-community,idea4bsd/idea4bsd,fengbaicanhe/intellij-community,signed/intellij-community,slisson/intellij-community,lucafavatella/intellij-community,nicolargo/intellij-community,fitermay/intellij-community,suncycheng/intellij-community,clumsy/intellij-community,jagguli/intellij-community,blademainer/intellij-community,fengbaicanhe/intellij-community,caot/intellij-community,samthor/intellij-community,gnuhub/intellij-community,fitermay/intellij-community,MER-GROUP/intellij-community,lucafavatella/intellij-community,apixandru/intellij-community,akosyakov/intellij-community,vvv1559/intellij-community,muntasirsyed/intellij-community,clumsy/intellij-community,hurricup/intellij-community,slisson/intellij-community,ThiagoGarciaAlves/intellij-community,muntasirsyed/intellij-community,youdonghai/intellij-community,idea4bsd/idea4bsd,retomerz/intellij-community,retomerz/intellij-community,Distrotech/intellij-community,xfournet/intellij-community,xfournet/intellij-community,kool79/intellij-community,dslomov/intellij-community,vvv1559/intellij-community,fitermay/intellij-community,Lekanich/intellij-community,youdonghai/intellij-community,vladmm/intellij-community,ThiagoGarciaAlves/intellij-community,ThiagoGarciaAlves/intellij-community,youdonghai/intellij-community,ThiagoGarciaAlves/intellij-community,SerCeMan/intellij-community,idea4bsd/idea4bsd,wreckJ/intellij-community,jagguli/intellij-community,ahb0327/intellij-community,diorcety/intellij-community,adedayo/intellij-community,tmpgit/intellij-community,TangHao1987/intellij-community,kdwink/intellij-community,supersven/intellij-community,robovm/robovm-studio,wreckJ/intellij-community,nicolargo/intellij-community,vvv1559/intellij-community,apixandru/intellij-community,asedunov/intellij-community,SerCeMan/intellij-community,michaelgallacher/intellij-community,ibinti/intellij-community,allotria/intellij-community,asedunov/intellij-community,signed/intellij-community,diorcety/intellij-community,xfournet/intellij-community,FHannes/intellij-community,ftomassetti/intellij-community,vvv1559/intellij-community,akosyakov/intellij-community,Distrotech/intellij-community,ol-loginov/intellij-community,robovm/robovm-studio,ivan-fedorov/intellij-community,gnuhub/intellij-community,amith01994/intellij-community,supersven/intellij-community,blademainer/intellij-community,Distrotech/intellij-community,alphafoobar/intellij-community,ahb0327/intellij-community,suncycheng/intellij-community,kdwink/intellij-community,MER-GROUP/intellij-community,ryano144/intellij-community,michaelgallacher/intellij-community,petteyg/intellij-community,slisson/intellij-community,tmpgit/intellij-community,MichaelNedzelsky/intellij-community,jagguli/intellij-community,MER-GROUP/intellij-community,fnouama/intellij-community,retomerz/intellij-community,da1z/intellij-community,blademainer/intellij-community,idea4bsd/idea4bsd,holmes/intellij-community,semonte/intellij-community,fnouama/intellij-community,retomerz/intellij-community,FHannes/intellij-community,ol-loginov/intellij-community,amith01994/intellij-community,samthor/intellij-community,youdonghai/intellij-community,Lekanich/intellij-community,robovm/robovm-studio,tmpgit/intellij-community,blademainer/intellij-community,hurricup/intellij-community,robovm/robovm-studio,blademainer/intellij-community,ahb0327/intellij-community,robovm/robovm-studio,akosyakov/intellij-community,ahb0327/intellij-community,salguarnieri/intellij-community,caot/intellij-community,izonder/intellij-community,fengbaicanhe/intellij-community,caot/intellij-community,holmes/intellij-community,mglukhikh/intellij-community,retomerz/intellij-community,holmes/intellij-community,amith01994/intellij-community,da1z/intellij-community,mglukhikh/intellij-community,vvv1559/intellij-community,diorcety/intellij-community,alphafoobar/intellij-community,vladmm/intellij-community,wreckJ/intellij-community,SerCeMan/intellij-community,amith01994/intellij-community,tmpgit/intellij-community,amith01994/intellij-community,semonte/intellij-community,michaelgallacher/intellij-community,mglukhikh/intellij-community,apixandru/intellij-community,SerCeMan/intellij-community,ryano144/intellij-community,izonder/intellij-community,Distrotech/intellij-community,petteyg/intellij-community,diorcety/intellij-community,jagguli/intellij-community,allotria/intellij-community,fnouama/intellij-community,TangHao1987/intellij-community,allotria/intellij-community,clumsy/intellij-community,slisson/intellij-community,kool79/intellij-community,suncycheng/intellij-community,da1z/intellij-community,nicolargo/intellij-community,caot/intellij-community,kool79/intellij-community,hurricup/intellij-community,ol-loginov/intellij-community,TangHao1987/intellij-community,izonder/intellij-community,MichaelNedzelsky/intellij-community,ol-loginov/intellij-community,MER-GROUP/intellij-community,akosyakov/intellij-community,FHannes/intellij-community,mglukhikh/intellij-community,asedunov/intellij-community,izonder/intellij-community,orekyuu/intellij-community,jagguli/intellij-community,fnouama/intellij-community,michaelgallacher/intellij-community,hurricup/intellij-community,clumsy/intellij-community,petteyg/intellij-community,FHannes/intellij-community,ol-loginov/intellij-community,fengbaicanhe/intellij-community,Distrotech/intellij-community,petteyg/intellij-community,idea4bsd/idea4bsd,dslomov/intellij-community,amith01994/intellij-community,hurricup/intellij-community,akosyakov/intellij-community,apixandru/intellij-community,asedunov/intellij-community,TangHao1987/intellij-community,asedunov/intellij-community,nicolargo/intellij-community,kool79/intellij-community,TangHao1987/intellij-community,youdonghai/intellij-community,robovm/robovm-studio,ol-loginov/intellij-community,retomerz/intellij-community,signed/intellij-community,akosyakov/intellij-community,ivan-fedorov/intellij-community,petteyg/intellij-community,caot/intellij-community,nicolargo/intellij-community,MichaelNedzelsky/intellij-community,orekyuu/intellij-community,Distrotech/intellij-community,ThiagoGarciaAlves/intellij-community,kdwink/intellij-community,asedunov/intellij-community,ol-loginov/intellij-community,retomerz/intellij-community,diorcety/intellij-community,MER-GROUP/intellij-community,orekyuu/intellij-community,tmpgit/intellij-community,kdwink/intellij-community,alphafoobar/intellij-community,ahb0327/intellij-community,vladmm/intellij-community,amith01994/intellij-community,kdwink/intellij-community,amith01994/intellij-community,caot/intellij-community,caot/intellij-community,alphafoobar/intellij-community,pwoodworth/intellij-community,kool79/intellij-community,ibinti/intellij-community,gnuhub/intellij-community,ryano144/intellij-community,MichaelNedzelsky/intellij-community,holmes/intellij-community,supersven/intellij-community,asedunov/intellij-community,ibinti/intellij-community,MichaelNedzelsky/intellij-community,ahb0327/intellij-community,ivan-fedorov/intellij-community,Distrotech/intellij-community,vladmm/intellij-community,kool79/intellij-community,slisson/intellij-community,SerCeMan/intellij-community,nicolargo/intellij-community,dslomov/intellij-community,gnuhub/intellij-community,alphafoobar/intellij-community,idea4bsd/idea4bsd,MER-GROUP/intellij-community,Lekanich/intellij-community,kool79/intellij-community,gnuhub/intellij-community,wreckJ/intellij-community,gnuhub/intellij-community,signed/intellij-community,idea4bsd/idea4bsd,jagguli/intellij-community,mglukhikh/intellij-community,holmes/intellij-community,Distrotech/intellij-community,ivan-fedorov/intellij-community,slisson/intellij-community,asedunov/intellij-community,ftomassetti/intellij-community,salguarnieri/intellij-community,michaelgallacher/intellij-community,idea4bsd/idea4bsd,caot/intellij-community,ryano144/intellij-community,adedayo/intellij-community,ThiagoGarciaAlves/intellij-community,lucafavatella/intellij-community,mglukhikh/intellij-community,suncycheng/intellij-community,retomerz/intellij-community,orekyuu/intellij-community,hurricup/intellij-community,dslomov/intellij-community,ryano144/intellij-community,ibinti/intellij-community,tmpgit/intellij-community,dslomov/intellij-community,semonte/intellij-community,kool79/intellij-community,ThiagoGarciaAlves/intellij-community,michaelgallacher/intellij-community,suncycheng/intellij-community,adedayo/intellij-community,izonder/intellij-community,mglukhikh/intellij-community,da1z/intellij-community,Lekanich/intellij-community,samthor/intellij-community,ftomassetti/intellij-community,fnouama/intellij-community,adedayo/intellij-community,supersven/intellij-community,ol-loginov/intellij-community,FHannes/intellij-community,youdonghai/intellij-community,fengbaicanhe/intellij-community,ryano144/intellij-community,robovm/robovm-studio,SerCeMan/intellij-community,wreckJ/intellij-community,retomerz/intellij-community,vladmm/intellij-community,ibinti/intellij-community,nicolargo/intellij-community,orekyuu/intellij-community,salguarnieri/intellij-community,lucafavatella/intellij-community,ryano144/intellij-community,ibinti/intellij-community,supersven/intellij-community,signed/intellij-community,pwoodworth/intellij-community,nicolargo/intellij-community,lucafavatella/intellij-community,ivan-fedorov/intellij-community,mglukhikh/intellij-community,xfournet/intellij-community,ryano144/intellij-community,pwoodworth/intellij-community,dslomov/intellij-community,asedunov/intellij-community,fnouama/intellij-community,vladmm/intellij-community,idea4bsd/idea4bsd,ryano144/intellij-community,idea4bsd/idea4bsd,pwoodworth/intellij-community,nicolargo/intellij-community,idea4bsd/idea4bsd,Distrotech/intellij-community,slisson/intellij-community,mglukhikh/intellij-community,da1z/intellij-community,robovm/robovm-studio,muntasirsyed/intellij-community,wreckJ/intellij-community,orekyuu/intellij-community,apixandru/intellij-community,FHannes/intellij-community,wreckJ/intellij-community,da1z/intellij-community,samthor/intellij-community,MER-GROUP/intellij-community,TangHao1987/intellij-community,mglukhikh/intellij-community,allotria/intellij-community,blademainer/intellij-community,da1z/intellij-community,vladmm/intellij-community,da1z/intellij-community,salguarnieri/intellij-community,ryano144/intellij-community,semonte/intellij-community,allotria/intellij-community,MichaelNedzelsky/intellij-community,alphafoobar/intellij-community,mglukhikh/intellij-community,salguarnieri/intellij-community,muntasirsyed/intellij-community,fengbaicanhe/intellij-community,michaelgallacher/intellij-community,Distrotech/intellij-community,xfournet/intellij-community,suncycheng/intellij-community,samthor/intellij-community,michaelgallacher/intellij-community,dslomov/intellij-community,amith01994/intellij-community,ol-loginov/intellij-community,muntasirsyed/intellij-community,muntasirsyed/intellij-community,MichaelNedzelsky/intellij-community,gnuhub/intellij-community,ThiagoGarciaAlves/intellij-community,tmpgit/intellij-community,allotria/intellij-community,pwoodworth/intellij-community,izonder/intellij-community,diorcety/intellij-community,holmes/intellij-community,nicolargo/intellij-community,youdonghai/intellij-community,vvv1559/intellij-community,akosyakov/intellij-community,supersven/intellij-community,MichaelNedzelsky/intellij-community,izonder/intellij-community,hurricup/intellij-community,SerCeMan/intellij-community,muntasirsyed/intellij-community,idea4bsd/idea4bsd,FHannes/intellij-community,blademainer/intellij-community,TangHao1987/intellij-community,dslomov/intellij-community,salguarnieri/intellij-community,ryano144/intellij-community,kdwink/intellij-community,caot/intellij-community,pwoodworth/intellij-community,diorcety/intellij-community,samthor/intellij-community,supersven/intellij-community,michaelgallacher/intellij-community,lucafavatella/intellij-community,blademainer/intellij-community,lucafavatella/intellij-community,adedayo/intellij-community,mglukhikh/intellij-community,hurricup/intellij-community,clumsy/intellij-community,asedunov/intellij-community,apixandru/intellij-community,ivan-fedorov/intellij-community,TangHao1987/intellij-community,semonte/intellij-community,ibinti/intellij-community,pwoodworth/intellij-community,robovm/robovm-studio,clumsy/intellij-community,michaelgallacher/intellij-community,supersven/intellij-community,alphafoobar/intellij-community,xfournet/intellij-community,signed/intellij-community,Distrotech/intellij-community,signed/intellij-community,apixandru/intellij-community,FHannes/intellij-community,signed/intellij-community,ftomassetti/intellij-community,signed/intellij-community,blademainer/intellij-community,signed/intellij-community,wreckJ/intellij-community,slisson/intellij-community,da1z/intellij-community,kool79/intellij-community,samthor/intellij-community,petteyg/intellij-community,youdonghai/intellij-community,ibinti/intellij-community,SerCeMan/intellij-community,FHannes/intellij-community,ftomassetti/intellij-community,fitermay/intellij-community,fitermay/intellij-community,jagguli/intellij-community,pwoodworth/intellij-community,da1z/intellij-community,xfournet/intellij-community,holmes/intellij-community,suncycheng/intellij-community,fitermay/intellij-community,ibinti/intellij-community,tmpgit/intellij-community,muntasirsyed/intellij-community,izonder/intellij-community,semonte/intellij-community,ThiagoGarciaAlves/intellij-community,adedayo/intellij-community,akosyakov/intellij-community,holmes/intellij-community,TangHao1987/intellij-community,diorcety/intellij-community,kdwink/intellij-community,hurricup/intellij-community,apixandru/intellij-community,FHannes/intellij-community,fnouama/intellij-community,semonte/intellij-community,ol-loginov/intellij-community,pwoodworth/intellij-community,petteyg/intellij-community,ibinti/intellij-community,dslomov/intellij-community,gnuhub/intellij-community,orekyuu/intellij-community,amith01994/intellij-community,signed/intellij-community,suncycheng/intellij-community,fnouama/intellij-community,kdwink/intellij-community,ThiagoGarciaAlves/intellij-community,xfournet/intellij-community,apixandru/intellij-community,vvv1559/intellij-community,ol-loginov/intellij-community,Distrotech/intellij-community,kool79/intellij-community,adedayo/intellij-community,izonder/intellij-community,fnouama/intellij-community,apixandru/intellij-community,lucafavatella/intellij-community,asedunov/intellij-community,diorcety/intellij-community,apixandru/intellij-community,ftomassetti/intellij-community,youdonghai/intellij-community,izonder/intellij-community,fengbaicanhe/intellij-community,fnouama/intellij-community,izonder/intellij-community,petteyg/intellij-community,ftomassetti/intellij-community,robovm/robovm-studio,Lekanich/intellij-community,asedunov/intellij-community,pwoodworth/intellij-community,caot/intellij-community,allotria/intellij-community,fengbaicanhe/intellij-community,salguarnieri/intellij-community,ivan-fedorov/intellij-community,ryano144/intellij-community,akosyakov/intellij-community,salguarnieri/intellij-community,jagguli/intellij-community,clumsy/intellij-community,ThiagoGarciaAlves/intellij-community,izonder/intellij-community,ivan-fedorov/intellij-community,samthor/intellij-community,tmpgit/intellij-community,orekyuu/intellij-community,alphafoobar/intellij-community,diorcety/intellij-community,ftomassetti/intellij-community,nicolargo/intellij-community,MichaelNedzelsky/intellij-community,allotria/intellij-community,salguarnieri/intellij-community,dslomov/intellij-community,vladmm/intellij-community,wreckJ/intellij-community,semonte/intellij-community,apixandru/intellij-community,jagguli/intellij-community,supersven/intellij-community,FHannes/intellij-community,salguarnieri/intellij-community,slisson/intellij-community,fnouama/intellij-community,salguarnieri/intellij-community,vladmm/intellij-community,tmpgit/intellij-community,ftomassetti/intellij-community,lucafavatella/intellij-community,alphafoobar/intellij-community,alphafoobar/intellij-community,hurricup/intellij-community,suncycheng/intellij-community,vladmm/intellij-community,ivan-fedorov/intellij-community,MER-GROUP/intellij-community,diorcety/intellij-community,ol-loginov/intellij-community,dslomov/intellij-community,ivan-fedorov/intellij-community,semonte/intellij-community,holmes/intellij-community,amith01994/intellij-community,holmes/intellij-community,Lekanich/intellij-community,signed/intellij-community,wreckJ/intellij-community,xfournet/intellij-community,youdonghai/intellij-community,allotria/intellij-community,fengbaicanhe/intellij-community,orekyuu/intellij-community,SerCeMan/intellij-community,supersven/intellij-community,retomerz/intellij-community,ibinti/intellij-community,xfournet/intellij-community,muntasirsyed/intellij-community,vvv1559/intellij-community,blademainer/intellij-community,alphafoobar/intellij-community,fengbaicanhe/intellij-community,salguarnieri/intellij-community,diorcety/intellij-community,caot/intellij-community,nicolargo/intellij-community,akosyakov/intellij-community,Lekanich/intellij-community,kdwink/intellij-community,fitermay/intellij-community,gnuhub/intellij-community,kool79/intellij-community,suncycheng/intellij-community,allotria/intellij-community,ThiagoGarciaAlves/intellij-community,suncycheng/intellij-community,robovm/robovm-studio,petteyg/intellij-community,kdwink/intellij-community,lucafavatella/intellij-community,fitermay/intellij-community,gnuhub/intellij-community,samthor/intellij-community,fitermay/intellij-community,MER-GROUP/intellij-community,jagguli/intellij-community,allotria/intellij-community,kdwink/intellij-community,vvv1559/intellij-community,fengbaicanhe/intellij-community,slisson/intellij-community,slisson/intellij-community,asedunov/intellij-community,clumsy/intellij-community,adedayo/intellij-community
package com.jetbrains.python.refactoring.introduce; import com.intellij.codeInsight.CodeInsightUtilBase; import com.intellij.codeInsight.template.impl.TemplateManagerImpl; import com.intellij.codeInsight.template.impl.TemplateState; import com.intellij.openapi.actionSystem.DataContext; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.application.Result; import com.intellij.openapi.command.WriteCommandAction; import com.intellij.openapi.editor.CaretModel; import com.intellij.openapi.editor.Document; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.editor.SelectionModel; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.Pair; import com.intellij.openapi.util.Pass; import com.intellij.openapi.util.TextRange; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiFile; import com.intellij.psi.PsiWhiteSpace; import com.intellij.psi.util.PsiTreeUtil; import com.intellij.refactoring.IntroduceTargetChooser; import com.intellij.refactoring.RefactoringActionHandler; import com.intellij.refactoring.introduce.inplace.InplaceVariableIntroducer; import com.intellij.refactoring.introduce.inplace.OccurrencesChooser; import com.intellij.refactoring.util.CommonRefactoringUtil; import com.intellij.util.Function; import com.jetbrains.python.PyBundle; import com.jetbrains.python.psi.*; import com.jetbrains.python.psi.impl.PyPsiUtils; import com.jetbrains.python.psi.resolve.PyResolveContext; import com.jetbrains.python.psi.types.PyNoneType; import com.jetbrains.python.psi.types.PyType; import com.jetbrains.python.psi.types.TypeEvalContext; import com.jetbrains.python.refactoring.NameSuggesterUtil; import com.jetbrains.python.refactoring.PyRefactoringUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.*; /** * @author Alexey.Ivanov */ abstract public class IntroduceHandler implements RefactoringActionHandler { protected static PsiElement findAnchor(List<PsiElement> occurrences) { PsiElement anchor = occurrences.get(0); next: do { PyStatement statement = PsiTreeUtil.getParentOfType(anchor, PyStatement.class); final PsiElement parent = statement.getParent(); for (PsiElement element : occurrences) { if (!PsiTreeUtil.isAncestor(parent, element, true)) { anchor = statement; continue next; } } return statement; } while (true); } protected static void ensureName(IntroduceOperation operation) { if (operation.getName() == null) { final Collection<String> suggestedNames = operation.getSuggestedNames(); if (suggestedNames.size() > 0) { operation.setName(suggestedNames.iterator().next()); } else { operation.setName("x"); } } } @Nullable protected static PsiElement findOccurrenceUnderCaret(List<PsiElement> occurrences, Editor editor) { if (occurrences.isEmpty()) { return null; } int offset = editor.getCaretModel().getOffset(); for (PsiElement occurrence : occurrences) { if (occurrence.getTextRange().contains(offset)) { return occurrence; } } int line = editor.getDocument().getLineNumber(offset); for (PsiElement occurrence : occurrences) { if (occurrence.isValid() && editor.getDocument().getLineNumber(occurrence.getTextRange().getStartOffset()) == line) { return occurrence; } } for (PsiElement occurrence : occurrences) { if (occurrence.isValid()) { return occurrence; } } return null; } public enum InitPlace { SAME_METHOD, CONSTRUCTOR, SET_UP } @Nullable protected PsiElement replaceExpression(PsiElement expression, PyExpression newExpression, IntroduceOperation operation) { PyExpressionStatement statement = PsiTreeUtil.getParentOfType(expression, PyExpressionStatement.class); if (statement != null) { if (statement.getExpression() == expression) { statement.delete(); return null; } } return PyPsiUtils.replaceExpression(expression, newExpression); } private final IntroduceValidator myValidator; protected final String myDialogTitle; protected IntroduceHandler(@NotNull final IntroduceValidator validator, @NotNull final String dialogTitle) { myValidator = validator; myDialogTitle = dialogTitle; } public void invoke(@NotNull Project project, Editor editor, PsiFile file, DataContext dataContext) { performAction(new IntroduceOperation(project, editor, file, null)); } public void invoke(@NotNull Project project, @NotNull PsiElement[] elements, DataContext dataContext) { } public Collection<String> getSuggestedNames(@NotNull final PyExpression expression) { Collection<String> candidates = generateSuggestedNames(expression); Collection<String> res = new ArrayList<String>(); for (String name : candidates) { if (myValidator.checkPossibleName(name, expression)) { res.add(name); } } if (res.isEmpty()) { // no available names found, generate disambiguated suggestions for (String name : candidates) { int index = 1; while (!myValidator.checkPossibleName(name + index, expression)) { index++; } res.add(name + index); } } return res; } protected Collection<String> generateSuggestedNames(PyExpression expression) { Collection<String> candidates = new LinkedHashSet<String>(); String text = expression.getText(); if (expression instanceof PyCallExpression) { final PyExpression callee = ((PyCallExpression)expression).getCallee(); if (callee != null) { text = callee.getText(); } } if (text != null) { candidates.addAll(NameSuggesterUtil.generateNames(text)); } final TypeEvalContext context = TypeEvalContext.slow(); PyType type = expression.getType(context); if (type != null && type != PyNoneType.INSTANCE) { String typeName = type.getName(); if (typeName != null) { if (type.isBuiltin(context)) { typeName = typeName.substring(0, 1); } candidates.addAll(NameSuggesterUtil.generateNamesByType(typeName)); } } final PyKeywordArgument kwArg = PsiTreeUtil.getParentOfType(expression, PyKeywordArgument.class); if (kwArg != null && kwArg.getValueExpression() == expression) { candidates.add(kwArg.getKeyword()); } final PyArgumentList argList = PsiTreeUtil.getParentOfType(expression, PyArgumentList.class); if (argList != null) { final CallArgumentsMapping result = argList.analyzeCall(PyResolveContext.noImplicits()); if (result.getMarkedCallee() != null) { final PyNamedParameter namedParameter = result.getPlainMappedParams().get(expression); if (namedParameter != null) { candidates.add(namedParameter.getName()); } } } return candidates; } public void performAction(IntroduceOperation operation) { final PsiFile file = operation.getFile(); if (!CommonRefactoringUtil.checkReadOnlyStatus(file)) { return; } final Editor editor = operation.getEditor(); if (editor.getSettings().isVariableInplaceRenameEnabled()) { final TemplateState templateState = TemplateManagerImpl.getTemplateState(operation.getEditor()); if (templateState != null && !templateState.isFinished()) { return; } } PsiElement element1 = null; PsiElement element2 = null; final SelectionModel selectionModel = editor.getSelectionModel(); boolean singleElementSelection = false; if (selectionModel.hasSelection()) { element1 = file.findElementAt(selectionModel.getSelectionStart()); element2 = file.findElementAt(selectionModel.getSelectionEnd() - 1); if (element1 instanceof PsiWhiteSpace) { int startOffset = element1.getTextRange().getEndOffset(); element1 = file.findElementAt(startOffset); } if (element2 instanceof PsiWhiteSpace) { int endOffset = element2.getTextRange().getStartOffset(); element2 = file.findElementAt(endOffset - 1); } if (element1 == element2) { singleElementSelection = true; } } else { if (smartIntroduce(operation)) { return; } final CaretModel caretModel = editor.getCaretModel(); final Document document = editor.getDocument(); int lineNumber = document.getLineNumber(caretModel.getOffset()); if ((lineNumber >= 0) && (lineNumber < document.getLineCount())) { element1 = file.findElementAt(document.getLineStartOffset(lineNumber)); element2 = file.findElementAt(document.getLineEndOffset(lineNumber) - 1); } } final Project project = operation.getProject(); if (element1 == null || element2 == null) { showCannotPerformError(project, editor); return; } element1 = PyRefactoringUtil.getSelectedExpression(project, file, element1, element2); if (element1 == null) { showCannotPerformError(project, editor); return; } // Introduce refactoring for substrings is not supported yet TextRange r = element1.getTextRange(); if (singleElementSelection && element1 instanceof PyStringLiteralExpression && (r.getStartOffset() < selectionModel.getSelectionStart() || r.getEndOffset() > selectionModel.getSelectionEnd())) { showCannotPerformError(project, editor); return; } if (!checkIntroduceContext(file, editor, element1)) { return; } operation.setElement(element1); performActionOnElement(operation); } private void showCannotPerformError(Project project, Editor editor) { CommonRefactoringUtil.showErrorHint(project, editor, PyBundle.message("refactoring.introduce.selection.error"), myDialogTitle, "refactoring.extractMethod"); } private boolean smartIntroduce(final IntroduceOperation operation) { final Editor editor = operation.getEditor(); final PsiFile file = operation.getFile(); int offset = editor.getCaretModel().getOffset(); PsiElement elementAtCaret = file.findElementAt(offset); if (!checkIntroduceContext(file, editor, elementAtCaret)) return true; final List<PyExpression> expressions = new ArrayList<PyExpression>(); while (elementAtCaret != null) { if (elementAtCaret instanceof PyStatement || elementAtCaret instanceof PyFile) { break; } if (elementAtCaret instanceof PyExpression && isValidIntroduceVariant(elementAtCaret)) { expressions.add((PyExpression)elementAtCaret); } elementAtCaret = elementAtCaret.getParent(); } if (expressions.size() == 1 || ApplicationManager.getApplication().isUnitTestMode()) { operation.setElement(expressions.get(0)); performActionOnElement(operation); return true; } else if (expressions.size() > 1) { IntroduceTargetChooser.showChooser(editor, expressions, new Pass<PyExpression>() { @Override public void pass(PyExpression pyExpression) { operation.setElement(pyExpression); performActionOnElement(operation); } }, new Function<PyExpression, String>() { public String fun(PyExpression pyExpression) { return pyExpression.getText(); } }); return true; } return false; } protected boolean checkIntroduceContext(PsiFile file, Editor editor, PsiElement element) { if (!isValidIntroduceContext(element)) { CommonRefactoringUtil.showErrorHint(file.getProject(), editor, PyBundle.message("refactoring.introduce.selection.error"), myDialogTitle, "refactoring.extractMethod"); return false; } return true; } protected boolean isValidIntroduceContext(PsiElement element) { PyDecorator decorator = PsiTreeUtil.getParentOfType(element, PyDecorator.class); if (decorator != null && PsiTreeUtil.isAncestor(decorator.getCallee(), element, false)) { return false; } return PsiTreeUtil.getParentOfType(element, PyParameterList.class) == null; } private static boolean isValidIntroduceVariant(PsiElement element) { final PyCallExpression call = PsiTreeUtil.getParentOfType(element, PyCallExpression.class); if (call != null && PsiTreeUtil.isAncestor(call.getCallee(), element, false)) { return false; } return true; } private void performActionOnElement(IntroduceOperation operation) { if (!checkEnabled(operation)) { return; } final PsiElement element = operation.getElement(); final PsiElement parent = element.getParent(); final PyExpression initializer = parent instanceof PyAssignmentStatement ? ((PyAssignmentStatement)parent).getAssignedValue() : (PyExpression)element; operation.setInitializer(initializer); if (initializer.getUserData(PyPsiUtils.SELECTION_BREAKS_AST_NODE) == null) { operation.setOccurrences(getOccurrences(element, initializer)); } operation.setSuggestedNames(getSuggestedNames(initializer)); if (operation.getOccurrences().size() == 0) { operation.setReplaceAll(false); } performActionOnElementOccurrences(operation); } protected void performActionOnElementOccurrences(final IntroduceOperation operation) { final Editor editor = operation.getEditor(); if (editor.getSettings().isVariableInplaceRenameEnabled()) { ensureName(operation); if (operation.isReplaceAll() != null) { performInplaceIntroduce(operation); } else { OccurrencesChooser.simpleChooser(editor).showChooser(operation.getElement(), operation.getOccurrences(), new Pass<OccurrencesChooser.ReplaceChoice>() { @Override public void pass(OccurrencesChooser.ReplaceChoice replaceChoice) { operation.setReplaceAll(replaceChoice == OccurrencesChooser.ReplaceChoice.ALL); performInplaceIntroduce(operation); } }); } } else { performIntroduceWithDialog(operation); } } protected void performInplaceIntroduce(IntroduceOperation operation) { final PyAssignmentStatement statement = performRefactoring(operation); PyTargetExpression target = (PyTargetExpression) statement.getTargets() [0]; final List<PsiElement> occurrences = operation.getOccurrences(); final PsiElement occurrence = findOccurrenceUnderCaret(occurrences, operation.getEditor()); PsiElement elementForCaret = occurrence != null ? occurrence : target; operation.getEditor().getCaretModel().moveToOffset(elementForCaret.getTextRange().getStartOffset()); final InplaceVariableIntroducer<PsiElement> introducer = new PyInplaceVariableIntroducer(target, operation, occurrences); introducer.performInplaceRename(false, new LinkedHashSet<String>(operation.getSuggestedNames())); } protected void performIntroduceWithDialog(IntroduceOperation operation) { final Project project = operation.getProject(); if (operation.getName() == null) { PyIntroduceDialog dialog = new PyIntroduceDialog(project, myDialogTitle, myValidator, getHelpId(), operation); dialog.show(); if (!dialog.isOK()) { return; } operation.setName(dialog.getName()); operation.setReplaceAll(dialog.doReplaceAllOccurrences()); operation.setInitPlace(dialog.getInitPlace()); } PyAssignmentStatement declaration = performRefactoring(operation); final Editor editor = operation.getEditor(); editor.getCaretModel().moveToOffset(declaration.getTextRange().getEndOffset()); editor.getSelectionModel().removeSelection(); } protected PyAssignmentStatement performRefactoring(IntroduceOperation operation) { PyAssignmentStatement declaration = createDeclaration(operation); declaration = performReplace(declaration, operation); declaration = CodeInsightUtilBase.forcePsiPostprocessAndRestoreElement(declaration); return declaration; } public PyAssignmentStatement createDeclaration(IntroduceOperation operation) { final Project project = operation.getProject(); final PyExpression initializer = operation.getInitializer(); InitializerTextBuilder builder = new InitializerTextBuilder(); initializer.accept(builder); String assignmentText = operation.getName() + " = " + builder.result(); PsiElement anchor = operation.isReplaceAll() ? findAnchor(operation.getOccurrences()) : PsiTreeUtil.getParentOfType(initializer, PyStatement.class); return createDeclaration(project, assignmentText, anchor); } private static class InitializerTextBuilder extends PyRecursiveElementVisitor { private final StringBuilder myResult = new StringBuilder(); @Override public void visitWhiteSpace(PsiWhiteSpace space) { myResult.append(space.getText().replace('\n', ' ')); } @Override public void visitElement(PsiElement element) { if (element.getChildren().length == 0) { myResult.append(element.getText()); } else { super.visitElement(element); } } public String result() { return myResult.toString(); } } protected abstract String getHelpId(); protected PyAssignmentStatement createDeclaration(Project project, String assignmentText, PsiElement anchor) { LanguageLevel langLevel = ((PyFile) anchor.getContainingFile()).getLanguageLevel(); return PyElementGenerator.getInstance(project).createFromText(langLevel, PyAssignmentStatement.class, assignmentText); } protected boolean checkEnabled(IntroduceOperation operation) { return true; } protected List<PsiElement> getOccurrences(PsiElement element, @NotNull final PyExpression expression) { PsiElement context = PsiTreeUtil.getParentOfType(expression, PyFunction.class); if (context == null) { context = PsiTreeUtil.getParentOfType(expression, PyClass.class); } if (context == null) { context = expression.getContainingFile(); } return PyRefactoringUtil.getOccurrences(expression, context); } private PyAssignmentStatement performReplace(@NotNull final PyAssignmentStatement declaration, final IntroduceOperation operation) { final PyExpression expression = operation.getInitializer(); final Project project = operation.getProject(); return new WriteCommandAction<PyAssignmentStatement>(project, expression.getContainingFile()) { protected void run(final Result<PyAssignmentStatement> result) throws Throwable { result.setResult(addDeclaration(operation, declaration)); PyExpression newExpression = createExpression(project, operation.getName(), declaration); if (operation.isReplaceAll()) { List<PsiElement> newOccurrences = new ArrayList<PsiElement>(); for (PsiElement occurrence : operation.getOccurrences()) { final PsiElement replaced = replaceExpression(occurrence, newExpression, operation); if (replaced != null) { newOccurrences.add(replaced); } } operation.setOccurrences(newOccurrences); } else { final PsiElement replaced = replaceExpression(expression, newExpression, operation); operation.setOccurrences(Collections.singletonList(replaced)); } postRefactoring(operation.getElement()); } }.execute().getResultObject(); } @Nullable public PyAssignmentStatement addDeclaration(IntroduceOperation operation, PyAssignmentStatement declaration) { final PsiElement expression = operation.getInitializer(); final Pair<PsiElement, TextRange> data = expression.getUserData(PyPsiUtils.SELECTION_BREAKS_AST_NODE); if (data == null) { return (PyAssignmentStatement)addDeclaration(expression, declaration, operation); } else { return (PyAssignmentStatement)addDeclaration(data.first, declaration, operation); } } protected PyExpression createExpression(Project project, String name, PyAssignmentStatement declaration) { return PyElementGenerator.getInstance(project).createExpressionFromText(name); } @Nullable protected abstract PsiElement addDeclaration(@NotNull final PsiElement expression, @NotNull final PsiElement declaration, @NotNull IntroduceOperation operation); protected void postRefactoring(PsiElement element) { } private static class PyInplaceVariableIntroducer extends InplaceVariableIntroducer<PsiElement> { private final PyTargetExpression myTarget; public PyInplaceVariableIntroducer(PyTargetExpression target, IntroduceOperation operation, List<PsiElement> occurrences) { super(target, operation.getEditor(), operation.getProject(), "Introduce Variable", occurrences.toArray(new PsiElement[occurrences.size()]), null); myTarget = target; } @Override protected PsiElement checkLocalScope() { return myTarget.getContainingFile(); } } }
python/src/com/jetbrains/python/refactoring/introduce/IntroduceHandler.java
package com.jetbrains.python.refactoring.introduce; import com.intellij.codeInsight.CodeInsightUtilBase; import com.intellij.codeInsight.template.impl.TemplateManagerImpl; import com.intellij.codeInsight.template.impl.TemplateState; import com.intellij.openapi.actionSystem.DataContext; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.application.Result; import com.intellij.openapi.command.WriteCommandAction; import com.intellij.openapi.editor.CaretModel; import com.intellij.openapi.editor.Document; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.editor.SelectionModel; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.Pair; import com.intellij.openapi.util.Pass; import com.intellij.openapi.util.TextRange; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiFile; import com.intellij.psi.PsiWhiteSpace; import com.intellij.psi.util.PsiTreeUtil; import com.intellij.refactoring.IntroduceTargetChooser; import com.intellij.refactoring.RefactoringActionHandler; import com.intellij.refactoring.introduce.inplace.InplaceVariableIntroducer; import com.intellij.refactoring.introduce.inplace.OccurrencesChooser; import com.intellij.refactoring.util.CommonRefactoringUtil; import com.intellij.util.Function; import com.jetbrains.python.PyBundle; import com.jetbrains.python.psi.*; import com.jetbrains.python.psi.impl.PyPsiUtils; import com.jetbrains.python.psi.resolve.PyResolveContext; import com.jetbrains.python.psi.types.PyNoneType; import com.jetbrains.python.psi.types.PyType; import com.jetbrains.python.psi.types.TypeEvalContext; import com.jetbrains.python.refactoring.NameSuggesterUtil; import com.jetbrains.python.refactoring.PyRefactoringUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.ArrayList; import java.util.Collection; import java.util.LinkedHashSet; import java.util.List; /** * @author Alexey.Ivanov */ abstract public class IntroduceHandler implements RefactoringActionHandler { protected static PsiElement findAnchor(List<PsiElement> occurrences) { PsiElement anchor = occurrences.get(0); next: do { PyStatement statement = PsiTreeUtil.getParentOfType(anchor, PyStatement.class); final PsiElement parent = statement.getParent(); for (PsiElement element : occurrences) { if (!PsiTreeUtil.isAncestor(parent, element, true)) { anchor = statement; continue next; } } return statement; } while (true); } protected static void ensureName(IntroduceOperation operation) { if (operation.getName() == null) { final Collection<String> suggestedNames = operation.getSuggestedNames(); if (suggestedNames.size() > 0) { operation.setName(suggestedNames.iterator().next()); } else { operation.setName("x"); } } } @Nullable protected static PsiElement findOccurrenceUnderCaret(List<PsiElement> occurrences, Editor editor) { if (occurrences.isEmpty()) { return null; } int offset = editor.getCaretModel().getOffset(); for (PsiElement occurrence : occurrences) { if (occurrence.getTextRange().contains(offset)) { return occurrence; } } int line = editor.getDocument().getLineNumber(offset); for (PsiElement occurrence : occurrences) { if (editor.getDocument().getLineNumber(occurrence.getTextRange().getStartOffset()) == line) { return occurrence; } } return occurrences.get(0); } public enum InitPlace { SAME_METHOD, CONSTRUCTOR, SET_UP } @Nullable protected PsiElement replaceExpression(PsiElement expression, PyExpression newExpression, IntroduceOperation operation) { PyExpressionStatement statement = PsiTreeUtil.getParentOfType(expression, PyExpressionStatement.class); if (statement != null) { if (statement.getExpression() == expression) { statement.delete(); return null; } } return PyPsiUtils.replaceExpression(expression, newExpression); } private final IntroduceValidator myValidator; protected final String myDialogTitle; protected IntroduceHandler(@NotNull final IntroduceValidator validator, @NotNull final String dialogTitle) { myValidator = validator; myDialogTitle = dialogTitle; } public void invoke(@NotNull Project project, Editor editor, PsiFile file, DataContext dataContext) { performAction(new IntroduceOperation(project, editor, file, null)); } public void invoke(@NotNull Project project, @NotNull PsiElement[] elements, DataContext dataContext) { } public Collection<String> getSuggestedNames(@NotNull final PyExpression expression) { Collection<String> candidates = generateSuggestedNames(expression); Collection<String> res = new ArrayList<String>(); for (String name : candidates) { if (myValidator.checkPossibleName(name, expression)) { res.add(name); } } if (res.isEmpty()) { // no available names found, generate disambiguated suggestions for (String name : candidates) { int index = 1; while (!myValidator.checkPossibleName(name + index, expression)) { index++; } res.add(name + index); } } return res; } protected Collection<String> generateSuggestedNames(PyExpression expression) { Collection<String> candidates = new LinkedHashSet<String>(); String text = expression.getText(); if (expression instanceof PyCallExpression) { final PyExpression callee = ((PyCallExpression)expression).getCallee(); if (callee != null) { text = callee.getText(); } } if (text != null) { candidates.addAll(NameSuggesterUtil.generateNames(text)); } final TypeEvalContext context = TypeEvalContext.slow(); PyType type = expression.getType(context); if (type != null && type != PyNoneType.INSTANCE) { String typeName = type.getName(); if (typeName != null) { if (type.isBuiltin(context)) { typeName = typeName.substring(0, 1); } candidates.addAll(NameSuggesterUtil.generateNamesByType(typeName)); } } final PyKeywordArgument kwArg = PsiTreeUtil.getParentOfType(expression, PyKeywordArgument.class); if (kwArg != null && kwArg.getValueExpression() == expression) { candidates.add(kwArg.getKeyword()); } final PyArgumentList argList = PsiTreeUtil.getParentOfType(expression, PyArgumentList.class); if (argList != null) { final CallArgumentsMapping result = argList.analyzeCall(PyResolveContext.noImplicits()); if (result.getMarkedCallee() != null) { final PyNamedParameter namedParameter = result.getPlainMappedParams().get(expression); if (namedParameter != null) { candidates.add(namedParameter.getName()); } } } return candidates; } public void performAction(IntroduceOperation operation) { final PsiFile file = operation.getFile(); if (!CommonRefactoringUtil.checkReadOnlyStatus(file)) { return; } final Editor editor = operation.getEditor(); if (editor.getSettings().isVariableInplaceRenameEnabled()) { final TemplateState templateState = TemplateManagerImpl.getTemplateState(operation.getEditor()); if (templateState != null && !templateState.isFinished()) { return; } } PsiElement element1 = null; PsiElement element2 = null; final SelectionModel selectionModel = editor.getSelectionModel(); boolean singleElementSelection = false; if (selectionModel.hasSelection()) { element1 = file.findElementAt(selectionModel.getSelectionStart()); element2 = file.findElementAt(selectionModel.getSelectionEnd() - 1); if (element1 instanceof PsiWhiteSpace) { int startOffset = element1.getTextRange().getEndOffset(); element1 = file.findElementAt(startOffset); } if (element2 instanceof PsiWhiteSpace) { int endOffset = element2.getTextRange().getStartOffset(); element2 = file.findElementAt(endOffset - 1); } if (element1 == element2) { singleElementSelection = true; } } else { if (smartIntroduce(operation)) { return; } final CaretModel caretModel = editor.getCaretModel(); final Document document = editor.getDocument(); int lineNumber = document.getLineNumber(caretModel.getOffset()); if ((lineNumber >= 0) && (lineNumber < document.getLineCount())) { element1 = file.findElementAt(document.getLineStartOffset(lineNumber)); element2 = file.findElementAt(document.getLineEndOffset(lineNumber) - 1); } } final Project project = operation.getProject(); if (element1 == null || element2 == null) { showCannotPerformError(project, editor); return; } element1 = PyRefactoringUtil.getSelectedExpression(project, file, element1, element2); if (element1 == null) { showCannotPerformError(project, editor); return; } // Introduce refactoring for substrings is not supported yet TextRange r = element1.getTextRange(); if (singleElementSelection && element1 instanceof PyStringLiteralExpression && (r.getStartOffset() < selectionModel.getSelectionStart() || r.getEndOffset() > selectionModel.getSelectionEnd())) { showCannotPerformError(project, editor); return; } if (!checkIntroduceContext(file, editor, element1)) { return; } operation.setElement(element1); performActionOnElement(operation); } private void showCannotPerformError(Project project, Editor editor) { CommonRefactoringUtil.showErrorHint(project, editor, PyBundle.message("refactoring.introduce.selection.error"), myDialogTitle, "refactoring.extractMethod"); } private boolean smartIntroduce(final IntroduceOperation operation) { final Editor editor = operation.getEditor(); final PsiFile file = operation.getFile(); int offset = editor.getCaretModel().getOffset(); PsiElement elementAtCaret = file.findElementAt(offset); if (!checkIntroduceContext(file, editor, elementAtCaret)) return true; final List<PyExpression> expressions = new ArrayList<PyExpression>(); while (elementAtCaret != null) { if (elementAtCaret instanceof PyStatement || elementAtCaret instanceof PyFile) { break; } if (elementAtCaret instanceof PyExpression && isValidIntroduceVariant(elementAtCaret)) { expressions.add((PyExpression)elementAtCaret); } elementAtCaret = elementAtCaret.getParent(); } if (expressions.size() == 1 || ApplicationManager.getApplication().isUnitTestMode()) { operation.setElement(expressions.get(0)); performActionOnElement(operation); return true; } else if (expressions.size() > 1) { IntroduceTargetChooser.showChooser(editor, expressions, new Pass<PyExpression>() { @Override public void pass(PyExpression pyExpression) { operation.setElement(pyExpression); performActionOnElement(operation); } }, new Function<PyExpression, String>() { public String fun(PyExpression pyExpression) { return pyExpression.getText(); } }); return true; } return false; } protected boolean checkIntroduceContext(PsiFile file, Editor editor, PsiElement element) { if (!isValidIntroduceContext(element)) { CommonRefactoringUtil.showErrorHint(file.getProject(), editor, PyBundle.message("refactoring.introduce.selection.error"), myDialogTitle, "refactoring.extractMethod"); return false; } return true; } protected boolean isValidIntroduceContext(PsiElement element) { PyDecorator decorator = PsiTreeUtil.getParentOfType(element, PyDecorator.class); if (decorator != null && PsiTreeUtil.isAncestor(decorator.getCallee(), element, false)) { return false; } return PsiTreeUtil.getParentOfType(element, PyParameterList.class) == null; } private static boolean isValidIntroduceVariant(PsiElement element) { final PyCallExpression call = PsiTreeUtil.getParentOfType(element, PyCallExpression.class); if (call != null && PsiTreeUtil.isAncestor(call.getCallee(), element, false)) { return false; } return true; } private void performActionOnElement(IntroduceOperation operation) { if (!checkEnabled(operation)) { return; } final PsiElement element = operation.getElement(); final PsiElement parent = element.getParent(); final PyExpression initializer = parent instanceof PyAssignmentStatement ? ((PyAssignmentStatement)parent).getAssignedValue() : (PyExpression)element; operation.setInitializer(initializer); if (initializer.getUserData(PyPsiUtils.SELECTION_BREAKS_AST_NODE) == null) { operation.setOccurrences(getOccurrences(element, initializer)); } operation.setSuggestedNames(getSuggestedNames(initializer)); if (operation.getOccurrences().size() == 0) { operation.setReplaceAll(false); } performActionOnElementOccurrences(operation); } protected void performActionOnElementOccurrences(final IntroduceOperation operation) { final Editor editor = operation.getEditor(); if (editor.getSettings().isVariableInplaceRenameEnabled()) { ensureName(operation); if (operation.isReplaceAll() != null) { performInplaceIntroduce(operation); } else { OccurrencesChooser.simpleChooser(editor).showChooser(operation.getElement(), operation.getOccurrences(), new Pass<OccurrencesChooser.ReplaceChoice>() { @Override public void pass(OccurrencesChooser.ReplaceChoice replaceChoice) { operation.setReplaceAll(replaceChoice == OccurrencesChooser.ReplaceChoice.ALL); performInplaceIntroduce(operation); } }); } } else { performIntroduceWithDialog(operation); } } protected void performInplaceIntroduce(IntroduceOperation operation) { final PyAssignmentStatement statement = performRefactoring(operation); PyTargetExpression target = (PyTargetExpression) statement.getTargets() [0]; final List<PsiElement> occurrences = operation.getOccurrences(); final PsiElement occurrence = findOccurrenceUnderCaret(occurrences, operation.getEditor()); PsiElement elementForCaret = occurrence != null ? occurrence : target; operation.getEditor().getCaretModel().moveToOffset(elementForCaret.getTextRange().getStartOffset()); final InplaceVariableIntroducer<PsiElement> introducer = new PyInplaceVariableIntroducer(target, operation, occurrences); introducer.performInplaceRename(false, new LinkedHashSet<String>(operation.getSuggestedNames())); } protected void performIntroduceWithDialog(IntroduceOperation operation) { final Project project = operation.getProject(); if (operation.getName() == null) { PyIntroduceDialog dialog = new PyIntroduceDialog(project, myDialogTitle, myValidator, getHelpId(), operation); dialog.show(); if (!dialog.isOK()) { return; } operation.setName(dialog.getName()); operation.setReplaceAll(dialog.doReplaceAllOccurrences()); operation.setInitPlace(dialog.getInitPlace()); } PyAssignmentStatement declaration = performRefactoring(operation); final Editor editor = operation.getEditor(); editor.getCaretModel().moveToOffset(declaration.getTextRange().getEndOffset()); editor.getSelectionModel().removeSelection(); } protected PyAssignmentStatement performRefactoring(IntroduceOperation operation) { PyAssignmentStatement declaration = createDeclaration(operation); declaration = performReplace(declaration, operation); declaration = CodeInsightUtilBase.forcePsiPostprocessAndRestoreElement(declaration); return declaration; } public PyAssignmentStatement createDeclaration(IntroduceOperation operation) { final Project project = operation.getProject(); final PyExpression initializer = operation.getInitializer(); InitializerTextBuilder builder = new InitializerTextBuilder(); initializer.accept(builder); String assignmentText = operation.getName() + " = " + builder.result(); PsiElement anchor = operation.isReplaceAll() ? findAnchor(operation.getOccurrences()) : PsiTreeUtil.getParentOfType(initializer, PyStatement.class); return createDeclaration(project, assignmentText, anchor); } private static class InitializerTextBuilder extends PyRecursiveElementVisitor { private final StringBuilder myResult = new StringBuilder(); @Override public void visitWhiteSpace(PsiWhiteSpace space) { myResult.append(space.getText().replace('\n', ' ')); } @Override public void visitElement(PsiElement element) { if (element.getChildren().length == 0) { myResult.append(element.getText()); } else { super.visitElement(element); } } public String result() { return myResult.toString(); } } protected abstract String getHelpId(); protected PyAssignmentStatement createDeclaration(Project project, String assignmentText, PsiElement anchor) { LanguageLevel langLevel = ((PyFile) anchor.getContainingFile()).getLanguageLevel(); return PyElementGenerator.getInstance(project).createFromText(langLevel, PyAssignmentStatement.class, assignmentText); } protected boolean checkEnabled(IntroduceOperation operation) { return true; } protected List<PsiElement> getOccurrences(PsiElement element, @NotNull final PyExpression expression) { PsiElement context = PsiTreeUtil.getParentOfType(expression, PyFunction.class); if (context == null) { context = PsiTreeUtil.getParentOfType(expression, PyClass.class); } if (context == null) { context = expression.getContainingFile(); } return PyRefactoringUtil.getOccurrences(expression, context); } private PyAssignmentStatement performReplace(@NotNull final PyAssignmentStatement declaration, final IntroduceOperation operation) { final PyExpression expression = operation.getInitializer(); final Project project = operation.getProject(); return new WriteCommandAction<PyAssignmentStatement>(project, expression.getContainingFile()) { protected void run(final Result<PyAssignmentStatement> result) throws Throwable { result.setResult(addDeclaration(operation, declaration)); PyExpression newExpression = createExpression(project, operation.getName(), declaration); if (operation.isReplaceAll()) { List<PsiElement> newOccurrences = new ArrayList<PsiElement>(); for (PsiElement occurrence : operation.getOccurrences()) { final PsiElement replaced = replaceExpression(occurrence, newExpression, operation); if (replaced != null) { newOccurrences.add(replaced); } } operation.setOccurrences(newOccurrences); } else { replaceExpression(expression, newExpression, operation); } postRefactoring(operation.getElement()); } }.execute().getResultObject(); } @Nullable public PyAssignmentStatement addDeclaration(IntroduceOperation operation, PyAssignmentStatement declaration) { final PsiElement expression = operation.getInitializer(); final Pair<PsiElement, TextRange> data = expression.getUserData(PyPsiUtils.SELECTION_BREAKS_AST_NODE); if (data == null) { return (PyAssignmentStatement)addDeclaration(expression, declaration, operation); } else { return (PyAssignmentStatement)addDeclaration(data.first, declaration, operation); } } protected PyExpression createExpression(Project project, String name, PyAssignmentStatement declaration) { return PyElementGenerator.getInstance(project).createExpressionFromText(name); } @Nullable protected abstract PsiElement addDeclaration(@NotNull final PsiElement expression, @NotNull final PsiElement declaration, @NotNull IntroduceOperation operation); protected void postRefactoring(PsiElement element) { } private static class PyInplaceVariableIntroducer extends InplaceVariableIntroducer<PsiElement> { private final PyTargetExpression myTarget; public PyInplaceVariableIntroducer(PyTargetExpression target, IntroduceOperation operation, List<PsiElement> occurrences) { super(target, operation.getEditor(), operation.getProject(), "Introduce Variable", occurrences.toArray(new PsiElement[occurrences.size()]), null); myTarget = target; } @Override protected PsiElement checkLocalScope() { return myTarget.getContainingFile(); } } }
in-place refactorings work correctly when "replace all occurrences" is not selected (PY-5292)
python/src/com/jetbrains/python/refactoring/introduce/IntroduceHandler.java
in-place refactorings work correctly when "replace all occurrences" is not selected (PY-5292)
<ide><path>ython/src/com/jetbrains/python/refactoring/introduce/IntroduceHandler.java <ide> import org.jetbrains.annotations.NotNull; <ide> import org.jetbrains.annotations.Nullable; <ide> <del>import java.util.ArrayList; <del>import java.util.Collection; <del>import java.util.LinkedHashSet; <del>import java.util.List; <add>import java.util.*; <ide> <ide> /** <ide> * @author Alexey.Ivanov <ide> } <ide> int line = editor.getDocument().getLineNumber(offset); <ide> for (PsiElement occurrence : occurrences) { <del> if (editor.getDocument().getLineNumber(occurrence.getTextRange().getStartOffset()) == line) { <add> if (occurrence.isValid() && editor.getDocument().getLineNumber(occurrence.getTextRange().getStartOffset()) == line) { <ide> return occurrence; <ide> } <ide> } <del> return occurrences.get(0); <add> for (PsiElement occurrence : occurrences) { <add> if (occurrence.isValid()) { <add> return occurrence; <add> } <add> } <add> return null; <ide> } <ide> <ide> public enum InitPlace { <ide> operation.setOccurrences(newOccurrences); <ide> } <ide> else { <del> replaceExpression(expression, newExpression, operation); <add> final PsiElement replaced = replaceExpression(expression, newExpression, operation); <add> operation.setOccurrences(Collections.singletonList(replaced)); <ide> } <ide> <ide> postRefactoring(operation.getElement());
Java
apache-2.0
15cecec226e100b1d514b6115e0c7ee885e8e08c
0
dashorst/wicket,aldaris/wicket,AlienQueen/wicket,dashorst/wicket,aldaris/wicket,klopfdreh/wicket,dashorst/wicket,apache/wicket,AlienQueen/wicket,mafulafunk/wicket,astrapi69/wicket,Servoy/wicket,zwsong/wicket,klopfdreh/wicket,selckin/wicket,dashorst/wicket,bitstorm/wicket,topicusonderwijs/wicket,apache/wicket,bitstorm/wicket,astrapi69/wicket,mosoft521/wicket,Servoy/wicket,mosoft521/wicket,aldaris/wicket,mosoft521/wicket,AlienQueen/wicket,apache/wicket,klopfdreh/wicket,zwsong/wicket,freiheit-com/wicket,zwsong/wicket,selckin/wicket,apache/wicket,klopfdreh/wicket,klopfdreh/wicket,zwsong/wicket,mosoft521/wicket,aldaris/wicket,martin-g/wicket-osgi,mafulafunk/wicket,martin-g/wicket-osgi,topicusonderwijs/wicket,bitstorm/wicket,freiheit-com/wicket,AlienQueen/wicket,freiheit-com/wicket,bitstorm/wicket,aldaris/wicket,topicusonderwijs/wicket,AlienQueen/wicket,topicusonderwijs/wicket,dashorst/wicket,astrapi69/wicket,Servoy/wicket,selckin/wicket,Servoy/wicket,selckin/wicket,selckin/wicket,Servoy/wicket,bitstorm/wicket,mafulafunk/wicket,astrapi69/wicket,freiheit-com/wicket,martin-g/wicket-osgi,apache/wicket,topicusonderwijs/wicket,freiheit-com/wicket,mosoft521/wicket
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package wicket.extensions.markup.html.repeater.data.sort; import java.io.Serializable; import wicket.AttributeModifier; import wicket.MarkupContainer; import wicket.markup.html.link.Link; import wicket.model.Model; import wicket.util.lang.Objects; import wicket.version.undo.Change; /** * A component that represents a sort header. When the link is clicked it will * toggle the state of a sortable property within the sort state object. * * @author Phil Kulak * @author Igor Vaynberg (ivaynberg) */ public class OrderByLink extends Link { private static final long serialVersionUID = 1L; /** sortable property */ private String property; /** locator for sort state object */ private ISortStateLocator stateLocator; /** * Constructor. * * @param parent * The parent of this component The parent of this component. * @param id * the component id of the link * @param property * the name of the sortable property this link represents. this * value will be used as parameter for sort state object methods. * sort state object will be located via the stateLocator * argument. * @param stateLocator * locator used to locate sort state object that this will use to * read/write state of sorted properties */ public OrderByLink(MarkupContainer parent, final String id, String property, ISortStateLocator stateLocator) { this(parent, id, property, stateLocator, DefaultCssProvider.getInstance()); } /** * Constructor. * * @param parent * The parent of this component The parent of this component. * @param id * the component id of the link * @param property * the name of the sortable property this link represents. this * value will be used as parameter for sort state object methods. * sort state object will be located via the stateLocator * argument. * @param stateLocator * locator used to locate sort state object that this will use to * read/write state of sorted properties * @param cssProvider * CSS provider that will be used generate the value of class * attribute for this link * * @see OrderByLink.ICssProvider * */ public OrderByLink(MarkupContainer parent, final String id, String property, ISortStateLocator stateLocator, ICssProvider cssProvider) { super(parent, id); if (cssProvider == null) { throw new IllegalArgumentException("argument [cssProvider] cannot be null"); } if (property == null) { throw new IllegalArgumentException("argument [sortProperty] cannot be null"); } this.property = property; this.stateLocator = stateLocator; add(new CssModifier(this, cssProvider)); } /** * @see wicket.markup.html.link.Link */ @Override public final void onClick() { sort(); onSortChanged(); } /** * This method is a hook for subclasses to perform an action after sort has * changed */ protected void onSortChanged() { // noop } /** * Re-sort data provider according to this link * * @return this */ public final OrderByLink sort() { if (isVersioned()) { // version the old state Change change = new SortStateChange(); addStateChange(change); } ISortState state = stateLocator.getSortState(); int oldDir = state.getPropertySortOrder(property); int newDir = ISortState.ASCENDING; if (oldDir == ISortState.ASCENDING) { newDir = ISortState.DESCENDING; } state.setPropertySortOrder(property, newDir); return this; } private final class SortStateChange extends Change { private static final long serialVersionUID = 1L; private final ISortState old = Objects.cloneModel(stateLocator.getSortState()); /** * @see wicket.version.undo.Change#undo() */ @Override public void undo() { stateLocator.setSortState(old); } /** * @see java.lang.Object#toString() */ @Override public String toString() { return "[StateOrderChange old=" + old.toString() + "]"; } } /** * Uses the specified ICssProvider to add css class attributes to the link. * * @author Igor Vaynberg ( ivaynberg ) * */ public static class CssModifier extends AttributeModifier { private static final long serialVersionUID = 1L; /** * @param link * the link this modifier is being added to * @param provider * implementation of ICssProvider */ public CssModifier(final OrderByLink link, final ICssProvider provider) { super("class", true, new Model() { private static final long serialVersionUID = 1L; public Object getObject() { final ISortState sortState = link.stateLocator.getSortState(); return provider.getClassAttributeValue(sortState, link.property); } public void setObject(Object object) { throw new UnsupportedOperationException(); } }); } /** * @see wicket.AttributeModifier#isEnabled() */ @Override public boolean isEnabled() { return getReplaceModel().getObject() != null; } }; /** * Interface used to generate values of css class attribute for the anchor * tag If the generated value is null class attribute will not be added * * @author igor */ public static interface ICssProvider extends Serializable { /** * @param state * current sort state * @param property * sort property represented by the {@link OrderByLink} * @return the value of the "class" attribute for the given sort * state/sort property combination */ public String getClassAttributeValue(ISortState state, String property); } /** * Easily constructible implementation of ICSSProvider * * @author Igor Vaynberg (ivaynberg) * */ public static class CssProvider implements ICssProvider { private static final long serialVersionUID = 1L; private String ascending; private String descending; private String none; /** * @param ascending * css class when sorting is ascending * @param descending * css class when sorting is descending * @param none * css class when not sorted */ public CssProvider(String ascending, String descending, String none) { this.ascending = ascending; this.descending = descending; this.none = none; } /** * @see wicket.extensions.markup.html.repeater.data.sort.OrderByLink.ICssProvider#getClassAttributeValue(wicket.extensions.markup.html.repeater.data.sort.ISortState, * java.lang.String) */ public String getClassAttributeValue(ISortState state, String property) { int dir = state.getPropertySortOrder(property); if (dir == ISortState.ASCENDING) { return ascending; } else if (dir == ISortState.DESCENDING) { return descending; } else { return none; } } } /** * Convineince implementation of ICssProvider that always returns a null and * so never adds a class attribute * * @author Igor Vaynberg ( ivaynberg ) */ public static class VoidCssProvider extends CssProvider { private static final long serialVersionUID = 1L; private static ICssProvider instance = new VoidCssProvider(); /** * @return singleton instance */ public static ICssProvider getInstance() { return instance; } private VoidCssProvider() { super("", "", ""); } } /** * Default implementation of ICssProvider * * @author Igor Vaynberg ( ivaynberg ) */ public static class DefaultCssProvider extends CssProvider { private static final long serialVersionUID = 1L; private static DefaultCssProvider instance = new DefaultCssProvider(); private DefaultCssProvider() { super("wicket_orderUp", "wicket_orderDown", "wicket_orderNone"); } /** * @return singleton instance */ public static DefaultCssProvider getInstance() { return instance; } } }
wicket-extensions/src/main/java/wicket/extensions/markup/html/repeater/data/sort/OrderByLink.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package wicket.extensions.markup.html.repeater.data.sort; import java.io.Serializable; import wicket.AttributeModifier; import wicket.MarkupContainer; import wicket.markup.html.link.Link; import wicket.model.Model; import wicket.util.lang.Objects; import wicket.version.undo.Change; /** * A component that represents a sort header. When the link is clicked it will * toggle the state of a sortable property within the sort state object. * * @author Phil Kulak * @author Igor Vaynberg (ivaynberg) */ public class OrderByLink extends Link { private static final long serialVersionUID = 1L; /** sortable property */ private String property; /** locator for sort state object */ private ISortStateLocator stateLocator; /** * Constructor. * * @param parent * The parent of this component The parent of this component. * @param id * the component id of the link * @param property * the name of the sortable property this link represents. this * value will be used as parameter for sort state object methods. * sort state object will be located via the stateLocator * argument. * @param stateLocator * locator used to locate sort state object that this will use to * read/write state of sorted properties */ public OrderByLink(MarkupContainer parent, final String id, String property, ISortStateLocator stateLocator) { this(parent, id, property, stateLocator, DefaultCssProvider.getInstance()); } /** * Constructor. * * @param parent * The parent of this component The parent of this component. * @param id * the component id of the link * @param property * the name of the sortable property this link represents. this * value will be used as parameter for sort state object methods. * sort state object will be located via the stateLocator * argument. * @param stateLocator * locator used to locate sort state object that this will use to * read/write state of sorted properties * @param cssProvider * CSS provider that will be used generate the value of class * attribute for this link * * @see OrderByLink.ICssProvider * */ public OrderByLink(MarkupContainer parent, final String id, String property, ISortStateLocator stateLocator, ICssProvider cssProvider) { super(parent, id); if (cssProvider == null) { throw new IllegalArgumentException("argument [cssProvider] cannot be null"); } if (property == null) { throw new IllegalArgumentException("argument [sortProperty] cannot be null"); } this.property = property; this.stateLocator = stateLocator; add(new CssModifier(this, cssProvider)); } /** * @see wicket.markup.html.link.Link */ @Override public final void onClick() { sort(); onSortChanged(); } /** * This method is a hook for subclasses to perform an action after sort has * changed */ protected void onSortChanged() { // noop } /** * Re-sort data provider according to this link * * @return this */ public final OrderByLink sort() { if (isVersioned()) { // version the old state Change change = new SortStateChange(); addStateChange(change); } ISortState state = stateLocator.getSortState(); int oldDir = state.getPropertySortOrder(property); int newDir = ISortState.ASCENDING; if (oldDir == ISortState.ASCENDING) { newDir = ISortState.DESCENDING; } state.setPropertySortOrder(property, newDir); return this; } private final class SortStateChange extends Change { private static final long serialVersionUID = 1L; private final ISortState old = (ISortState)Objects.cloneModel(stateLocator.getSortState()); /** * @see wicket.version.undo.Change#undo() */ @Override public void undo() { stateLocator.setSortState(old); } /** * @see java.lang.Object#toString() */ @Override public String toString() { return "[StateOrderChange old=" + old.toString() + "]"; } } /** * Uses the specified ICssProvider to add css class attributes to the link. * * @author Igor Vaynberg ( ivaynberg ) * */ public static class CssModifier extends AttributeModifier { private static final long serialVersionUID = 1L; /** * @param link * the link this modifier is being added to * @param provider * implementation of ICssProvider */ public CssModifier(final OrderByLink link, final ICssProvider provider) { super("class", true, new Model() { private static final long serialVersionUID = 1L; public Object getObject() { final ISortState sortState = link.stateLocator.getSortState(); return provider.getClassAttributeValue(sortState, link.property); } public void setObject(Object object) { throw new UnsupportedOperationException(); } }); } /** * @see wicket.AttributeModifier#isEnabled() */ @Override public boolean isEnabled() { return getReplaceModel().getObject() != null; } }; /** * Interface used to generate values of css class attribute for the anchor * tag If the generated value is null class attribute will not be added * * @author igor */ public static interface ICssProvider extends Serializable { /** * @param state * current sort state * @param property * sort property represented by the {@link OrderByLink} * @return the value of the "class" attribute for the given sort * state/sort property combination */ public String getClassAttributeValue(ISortState state, String property); } /** * Easily constructible implementation of ICSSProvider * * @author Igor Vaynberg (ivaynberg) * */ public static class CssProvider implements ICssProvider { private static final long serialVersionUID = 1L; private String ascending; private String descending; private String none; /** * @param ascending * css class when sorting is ascending * @param descending * css class when sorting is descending * @param none * css class when not sorted */ public CssProvider(String ascending, String descending, String none) { this.ascending = ascending; this.descending = descending; this.none = none; } /** * @see wicket.extensions.markup.html.repeater.data.sort.OrderByLink.ICssProvider#getClassAttributeValue(wicket.extensions.markup.html.repeater.data.sort.ISortState, * java.lang.String) */ public String getClassAttributeValue(ISortState state, String property) { int dir = state.getPropertySortOrder(property); if (dir == ISortState.ASCENDING) { return ascending; } else if (dir == ISortState.DESCENDING) { return descending; } else { return none; } } } /** * Convineince implementation of ICssProvider that always returns a null and * so never adds a class attribute * * @author Igor Vaynberg ( ivaynberg ) */ public static class VoidCssProvider extends CssProvider { private static final long serialVersionUID = 1L; private static ICssProvider instance = new VoidCssProvider(); /** * @return singleton instance */ public static ICssProvider getInstance() { return instance; } private VoidCssProvider() { super("", "", ""); } } /** * Default implementation of ICssProvider * * @author Igor Vaynberg ( ivaynberg ) */ public static class DefaultCssProvider extends CssProvider { private static final long serialVersionUID = 1L; private static DefaultCssProvider instance = new DefaultCssProvider(); private DefaultCssProvider() { super("wicket_orderUp", "wicket_orderDown", "wicket_orderNone"); } /** * @return singleton instance */ public static DefaultCssProvider getInstance() { return instance; } } }
cast not needed git-svn-id: ac804e38dcddf5e42ac850d29d9218b7df6087b7@505447 13f79535-47bb-0310-9956-ffa450edef68
wicket-extensions/src/main/java/wicket/extensions/markup/html/repeater/data/sort/OrderByLink.java
cast not needed
<ide><path>icket-extensions/src/main/java/wicket/extensions/markup/html/repeater/data/sort/OrderByLink.java <ide> { <ide> private static final long serialVersionUID = 1L; <ide> <del> private final ISortState old = (ISortState)Objects.cloneModel(stateLocator.getSortState()); <add> private final ISortState old = Objects.cloneModel(stateLocator.getSortState()); <ide> <ide> /** <ide> * @see wicket.version.undo.Change#undo()
Java
bsd-3-clause
e379bfc9d741e6299be2444ff652ab0bfd4097db
0
Praesidio/LiveStats
package io.praesid.livestats; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableList.Builder; import com.google.common.collect.ImmutableMap; import com.google.common.util.concurrent.AtomicDouble; import lombok.ToString; import javax.annotation.concurrent.ThreadSafe; import java.util.Arrays; import java.util.Map; import java.util.concurrent.ThreadLocalRandom; import java.util.concurrent.atomic.AtomicInteger; import java.util.function.DoubleConsumer; import java.util.function.DoublePredicate; import java.util.stream.Collector; import java.util.stream.IntStream; @ThreadSafe @ToString public class LiveStats implements DoublePredicate, DoubleConsumer { private static final double[] DEFAULT_TILES = {0.5}; private final AtomicDouble minVal = new AtomicDouble(Double.MAX_VALUE); private final AtomicDouble maxVal = new AtomicDouble(Double.MIN_VALUE); private final AtomicDouble varM2 = new AtomicDouble(0); private final AtomicDouble kurtM4 = new AtomicDouble(0); private final AtomicDouble skewM3 = new AtomicDouble(0); private final AtomicInteger fullStatsCount = new AtomicInteger(0); private final AtomicDouble average = new AtomicDouble(0); private final AtomicInteger count = new AtomicInteger(0); private final double fullStatsProbability; private final ImmutableList<Quantile> tiles; /** * Constructs a LiveStats object * * @param fullStatsProbability the probability that any given item is considered for all available statistics * other items are only counted and considered for maximum and minimum. * values &lt; 0 disable full stats and values &gt; 1 always calculate full stats * @param p A list of quantiles to track (default {0.5}) */ public LiveStats(final double fullStatsProbability, final double... p) { this.fullStatsProbability = fullStatsProbability; tiles = Arrays.stream(p.length == 0 ? DEFAULT_TILES : p) .mapToObj(Quantile::new) .collect(Collector.of(ImmutableList::<Quantile>builder, Builder::add, (a, b) -> a.addAll(b.build()), Builder::build)); } /** * Adds another datum * * @param item the value to add */ @Override public void accept(final double item) { add(item); } /** * Adds another datum * * @param item the value to add * @return true if full stats were collected, false otherwise */ @Override public boolean test(final double item) { return add(item); } /** * Adds another datum * * @param item the value to add * @return true if full stats were collected, false otherwise */ public boolean add(double item) { double oldMin = minVal.get(); while (item < oldMin) { if (minVal.compareAndSet(oldMin, item)) { break; } oldMin = minVal.get(); } double oldMax = maxVal.get(); while (item > oldMax) { if (maxVal.compareAndSet(oldMax, item)) { break; } oldMax = maxVal.get(); } count.incrementAndGet(); if (ThreadLocalRandom.current().nextDouble() < fullStatsProbability) { tiles.forEach(tile -> tile.add(item)); final int myCount = fullStatsCount.incrementAndGet(); final double preDelta = item - average.get(); // This is wrong if it matters that post delta is relative to a different point in "time" than the pre delta final double postDelta = item - average.addAndGet(preDelta / myCount); final double d2 = postDelta * postDelta; //Variance(except for the scale) varM2.addAndGet(d2); final double d3 = d2 * postDelta; //Skewness skewM3.addAndGet(d3); final double d4 = d3 * postDelta; //Kurtosis kurtM4.addAndGet(d4); return true; } return false; } /** * @return a Map of quantile to approximate value */ public Map<Double, Double> quantiles() { final ImmutableMap.Builder<Double, Double> builder = ImmutableMap.builder(); for (final Quantile tile : tiles) { builder.put(tile.p, tile.quantile()); } return builder.build(); } public double maximum() { return maxVal.get(); } public double mean() { return average.get(); } public double minimum() { return minVal.get(); } public int num() { return count.get(); } public double variance() { return varM2.get() / fullStatsCount.get(); } public double kurtosis() { // k / (c * (v/c)^2) - 3 // k / (c * (v/c) * (v/c)) - 3 // k / (v * v / c) - 3 // k * c / (v * v) - 3 final double myVarM2 = varM2.get(); return kurtM4.get() * fullStatsCount.get() / (myVarM2 * myVarM2) - 3; } public double skewness() { // s / (c * (v/c)^(3/2)) // s / (c * (v/c) * (v/c)^(1/2)) // s / (v * sqrt(v/c)) // s * sqrt(c/v) / v final double myVarM2 = varM2.get(); return skewM3.get() * Math.sqrt(fullStatsCount.get() / myVarM2) / myVarM2; } @ThreadSafe @ToString private static class Quantile { private static final int N_MARKERS = 5; // dn and npos must be updated if this is changed private final double[] dn; // Immutable private final double[] npos; private final int[] pos; private final double[] heights; private int initialized = 0; public final double p; /** * Constructs a single quantile object */ public Quantile(double p) { this.p = p; dn = new double[]{0, p / 2, p, (1 + p) / 2, 1}; npos = new double[]{1, 1 + 2 * p, 1 + 4 * p, 3 + 2 * p, 5}; pos = IntStream.range(1, N_MARKERS + 1).toArray(); heights = new double[N_MARKERS]; } /** * Adds another datum */ public synchronized void add(double item) { if (initialized < N_MARKERS) { heights[initialized] = item; initialized++; if (initialized == N_MARKERS) { Arrays.sort(heights); } return; } // find cell k final int k; if (item < heights[0]) { heights[0] = item; k = 1; } else if (item >= heights[N_MARKERS - 1]) { heights[N_MARKERS - 1] = item; k = 4; } else { int i = 1; // Linear search is fastest because N_MARKERS is small while (item >= heights[i]) { i++; } k = i; } IntStream.range(k, pos.length).forEach(i -> pos[i]++); // increment all positions greater than k IntStream.range(1, npos.length).forEach(i -> npos[i] += dn[i]); adjust(); } private void adjust() { for (int i = 1; i < N_MARKERS - 1; i++) { final int n = pos[i]; final double q = heights[i]; final double d0 = npos[i] - n; if ((d0 >= 1 && pos[i + 1] > n + 1) || (d0 <= -1 && pos[i - 1] < n - 1)) { final int d = (int)Math.signum(d0); final double qp1 = heights[i + 1]; final double qm1 = heights[i - 1]; final int np1 = pos[i + 1]; final int nm1 = pos[i - 1]; final double qn = calcP2(d, q, qp1, qm1, n, np1, nm1); if (qm1 < qn && qn < qp1) { heights[i] = qn; } else { // use linear form heights[i] = q + d * (heights[i + d] - q) / (pos[i + d] - n); } pos[i] = n + d; } } } private static double calcP2(int d, double q, double qp1, double qm1, double n, double np1, double nm1) { final double outer = d / (np1 - nm1); final double innerLeft = (n - nm1 + d) * (qp1 - q) / (np1 - n); final double innerRight = (np1 - n - d) * (q - qm1) / (n - nm1); return q + outer * (innerLeft + innerRight); } public synchronized double quantile() { if (initialized == N_MARKERS) { return heights[2]; } else { Arrays.sort(heights); // Not fully initialized, probably not in order // make sure we don't overflow on p == 1 or underflow on p == 0 return heights[Math.min(Math.max(initialized - 1, 0), (int)(initialized * p))]; } } } }
src/main/java/io/praesid/livestats/LiveStats.java
package io.praesid.livestats; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableList.Builder; import com.google.common.collect.ImmutableMap; import com.google.common.util.concurrent.AtomicDouble; import javax.annotation.concurrent.ThreadSafe; import java.util.Arrays; import java.util.Map; import java.util.concurrent.ThreadLocalRandom; import java.util.concurrent.atomic.AtomicInteger; import java.util.function.DoubleConsumer; import java.util.function.DoublePredicate; import java.util.stream.Collector; import java.util.stream.IntStream; @ThreadSafe public class LiveStats implements DoublePredicate, DoubleConsumer { private static final double[] DEFAULT_TILES = {0.5}; private final AtomicDouble minVal = new AtomicDouble(Double.MAX_VALUE); private final AtomicDouble maxVal = new AtomicDouble(Double.MIN_VALUE); private final AtomicDouble varM2 = new AtomicDouble(0); private final AtomicDouble kurtM4 = new AtomicDouble(0); private final AtomicDouble skewM3 = new AtomicDouble(0); private final AtomicInteger fullStatsCount = new AtomicInteger(0); private final AtomicDouble average = new AtomicDouble(0); private final AtomicInteger count = new AtomicInteger(0); private final double fullStatsProbability; private final ImmutableList<Quantile> tiles; /** * Constructs a LiveStats object * * @param fullStatsProbability the probability that any given item is considered for all available statistics * other items are only counted and considered for maximum and minimum. * values &lt; 0 disable full stats and values &gt; 1 always calculate full stats * @param p A list of quantiles to track (default {0.5}) */ public LiveStats(final double fullStatsProbability, final double... p) { this.fullStatsProbability = fullStatsProbability; tiles = Arrays.stream(p.length == 0 ? DEFAULT_TILES : p) .mapToObj(Quantile::new) .collect(Collector.of(ImmutableList::<Quantile>builder, Builder::add, (a, b) -> a.addAll(b.build()), Builder::build)); } /** * Adds another datum * * @param item the value to add */ @Override public void accept(final double item) { add(item); } /** * Adds another datum * * @param item the value to add * @return true if full stats were collected, false otherwise */ @Override public boolean test(final double item) { return add(item); } /** * Adds another datum * * @param item the value to add * @return true if full stats were collected, false otherwise */ public boolean add(double item) { double oldMin = minVal.get(); while (item < oldMin) { if (minVal.compareAndSet(oldMin, item)) { break; } oldMin = minVal.get(); } double oldMax = maxVal.get(); while (item > oldMax) { if (maxVal.compareAndSet(oldMax, item)) { break; } oldMax = maxVal.get(); } count.incrementAndGet(); if (ThreadLocalRandom.current().nextDouble() < fullStatsProbability) { tiles.forEach(tile -> tile.add(item)); final int myCount = fullStatsCount.incrementAndGet(); final double preDelta = item - average.get(); // This is wrong if it matters that post delta is relative to a different point in "time" than the pre delta final double postDelta = item - average.addAndGet(preDelta / myCount); final double d2 = postDelta * postDelta; //Variance(except for the scale) varM2.addAndGet(d2); final double d3 = d2 * postDelta; //Skewness skewM3.addAndGet(d3); final double d4 = d3 * postDelta; //Kurtosis kurtM4.addAndGet(d4); return true; } return false; } /** * @return a Map of quantile to approximate value */ public Map<Double, Double> quantiles() { final ImmutableMap.Builder<Double, Double> builder = ImmutableMap.builder(); for (final Quantile tile : tiles) { builder.put(tile.p, tile.quantile()); } return builder.build(); } public double maximum() { return maxVal.get(); } public double mean() { return average.get(); } public double minimum() { return minVal.get(); } public int num() { return count.get(); } public double variance() { return varM2.get() / fullStatsCount.get(); } public double kurtosis() { // k / (c * (v/c)^2) - 3 // k / (c * (v/c) * (v/c)) - 3 // k / (v * v / c) - 3 // k * c / (v * v) - 3 final double myVarM2 = varM2.get(); return kurtM4.get() * fullStatsCount.get() / (myVarM2 * myVarM2) - 3; } public double skewness() { // s / (c * (v/c)^(3/2)) // s / (c * (v/c) * (v/c)^(1/2)) // s / (v * sqrt(v/c)) // s * sqrt(c/v) / v final double myVarM2 = varM2.get(); return skewM3.get() * Math.sqrt(fullStatsCount.get() / myVarM2) / myVarM2; } @ThreadSafe private static class Quantile { private static final int N_MARKERS = 5; // dn and npos must be updated if this is changed private final double[] dn; // Immutable private final double[] npos; private final int[] pos; private final double[] heights; private int initialized = 0; public final double p; /** * Constructs a single quantile object */ public Quantile(double p) { this.p = p; dn = new double[]{0, p / 2, p, (1 + p) / 2, 1}; npos = new double[]{1, 1 + 2 * p, 1 + 4 * p, 3 + 2 * p, 5}; pos = IntStream.range(1, N_MARKERS + 1).toArray(); heights = new double[N_MARKERS]; } /** * Adds another datum */ public synchronized void add(double item) { if (initialized < N_MARKERS) { heights[initialized] = item; initialized++; if (initialized == N_MARKERS) { Arrays.sort(heights); } return; } // find cell k final int k; if (item < heights[0]) { heights[0] = item; k = 1; } else if (item >= heights[N_MARKERS - 1]) { heights[N_MARKERS - 1] = item; k = 4; } else { int i = 1; // Linear search is fastest because N_MARKERS is small while (item >= heights[i]) { i++; } k = i; } IntStream.range(k, pos.length).forEach(i -> pos[i]++); // increment all positions greater than k IntStream.range(1, npos.length).forEach(i -> npos[i] += dn[i]); adjust(); } private void adjust() { for (int i = 1; i < N_MARKERS - 1; i++) { final int n = pos[i]; final double q = heights[i]; final double d0 = npos[i] - n; if ((d0 >= 1 && pos[i + 1] > n + 1) || (d0 <= -1 && pos[i - 1] < n - 1)) { final int d = (int)Math.signum(d0); final double qp1 = heights[i + 1]; final double qm1 = heights[i - 1]; final int np1 = pos[i + 1]; final int nm1 = pos[i - 1]; final double qn = calcP2(d, q, qp1, qm1, n, np1, nm1); if (qm1 < qn && qn < qp1) { heights[i] = qn; } else { // use linear form heights[i] = q + d * (heights[i + d] - q) / (pos[i + d] - n); } pos[i] = n + d; } } } private static double calcP2(int d, double q, double qp1, double qm1, double n, double np1, double nm1) { final double outer = d / (np1 - nm1); final double innerLeft = (n - nm1 + d) * (qp1 - q) / (np1 - n); final double innerRight = (np1 - n - d) * (q - qm1) / (n - nm1); return q + outer * (innerLeft + innerRight); } public synchronized double quantile() { if (initialized == N_MARKERS) { return heights[2]; } else { Arrays.sort(heights); // Not fully initialized, probably not in order // make sure we don't overflow on p == 1 or underflow on p == 0 return heights[Math.min(Math.max(initialized - 1, 0), (int)(initialized * p))]; } } } }
Make LiveStats easily printable for debugging
src/main/java/io/praesid/livestats/LiveStats.java
Make LiveStats easily printable for debugging
<ide><path>rc/main/java/io/praesid/livestats/LiveStats.java <ide> import com.google.common.collect.ImmutableList.Builder; <ide> import com.google.common.collect.ImmutableMap; <ide> import com.google.common.util.concurrent.AtomicDouble; <add>import lombok.ToString; <ide> <ide> import javax.annotation.concurrent.ThreadSafe; <ide> import java.util.Arrays; <ide> import java.util.stream.IntStream; <ide> <ide> @ThreadSafe <add>@ToString <ide> public class LiveStats implements DoublePredicate, DoubleConsumer { <ide> <ide> private static final double[] DEFAULT_TILES = {0.5}; <ide> } <ide> <ide> @ThreadSafe <add> @ToString <ide> private static class Quantile { <ide> private static final int N_MARKERS = 5; // dn and npos must be updated if this is changed <ide>
JavaScript
mit
0871799f0f987bdae9918a851204d5d53e4f49db
0
DoubleU23/tailored-react-env
'use strict' import webpack from 'webpack' import path from 'path' import ip from 'ip' // webpack/build plugins import autoprefixer from 'autoprefixer' import ExtractTextPlugin from 'extract-text-webpack-plugin' import nib from 'nib' import cssMqPacker from 'css-mqpacker' // custom libs import doubleu23Stylus from 'doubleu23-stylus' // import BrowserSyncPlugin from 'browser-sync-webpack-plugin' import constants from './constants' import appConfig from '../../config/appConfig' import objectAssign from 'object-assign-deep' const { ports, paths, isDevelopment } = appConfig const devtools = process.env.CONTINUOUS_INTEGRATION ? 'inline-source-map' // cheap-module-eval-source-map, because we want original source, but we don't // care about columns, which makes this devtool faster than eval-source-map. // http://webpack.github.io/docs/configuration.html#devtool : 'cheap-module-eval-source-map' const loaders = { 'css': '', // 'less': '!less-loader', // inject // 'sj': '!stylus-loader', // 'scss': '!sass-loader', // 'sass': '!sass-loader?indentedSyntax', 'styl': '!stylus-loader' // 'stylo': '!cssobjects-loader!stylus-loader!' } const serverIp = ip.address() const webpackGetConfig = _isDevelopment => { const isDevelopment = _isDevelopment != null ? _isDevelopment : appConfig.isDevelopment const stylesLoaders = Object.keys(loaders).map(ext => { const prefix = 'css-loader!postcss-loader' const extLoaders = prefix + loaders[ext] const loader = isDevelopment ? `style-loader!${extLoaders}` : ExtractTextPlugin.extract({ fallback: 'style-loader', loader: extLoaders }) return { loader, test: new RegExp(`\\.(${ext})$`) } }) const stylusLoaderDefinition = { loader: 'stylus-loader', options: { sourceMap: true, compress: isDevelopment, use: [nib(), doubleu23Stylus({ envVars: { // refactor: build object on top and // find a way to re-use it in webpack.DefinePlugin NODE_ENV: process.env.NODE_ENV, BUILD_STATIC: process.env.BUILD_STATIC, DEBUG: process.env.DEBUG }, envPrefix: '$ENV__' })] } } const config = { target: 'web', cache: isDevelopment, // devtool: false, // handled by "SourceMapDevToolPlugin" devtool: 'cheap-module-source-map', entry: { app: isDevelopment ? [ `webpack-hot-middleware/client?path=http://${serverIp}:${ports.HMR}/__webpack_hmr`, path.join(paths.src, 'index.js') ] : [ path.join(paths.src, 'index.js') ] }, output: isDevelopment ? { path: paths.build, filename: '[name].js', sourceMapFilename: '[name].js.map.sourceMapFilename', chunkFilename: '[name]-[chunkhash].js', publicPath: `http://${serverIp}:${ports.HMR}/build/` } : { path: paths.build, filename: '[name]-[hash].js', // sourceMapFilename: '[name]-[hash].js', chunkFilename: '[name]-[chunkhash].js' }, module: { rules: [ // URL LOADER // (different limits for different fileTypes) { loader: 'url-loader', test: /\.(gif|jpg|png|svg)(\?.*)?$/, exclude: /\.styl$/, options: { limit: 10000 } }, { loader: 'url-loader', test: /favicon\.ico$/, exclude: /\.styl$/, options: { limit: 1 } }, { loader: 'url-loader', test: /\.(ttf|eot|woff|woff2)(\?.*)?$/, exclude: /\.styl$/, options: { limit: 100000 } }, // BABEL { loader: 'babel-loader', test: /\.js$/, exclude: /(node_modules|bower_components|styles)/, options: { retainLines: true, sourceMap: true, babelrc: true, cacheDirectory: false, // presets/plugins have to match defines in .babelrc presets: [ // ['env', { modules: false }], 'es2015', 'react', 'stage-2', 'stage-3' ], plugins: [ [ 'transform-runtime', { helpers: false, polyfill: true, regenerator: false } ], 'transform-decorators-legacy' ], env: { production: { plugins: ['transform-react-constant-elements'] } } } }, // SOURCEMAPS // not needed (only handles extern sourcemaps (in module packages)) { test: /\.js$/, use: ['source-map-loader'], enforce: 'pre' }, { test: /\.styl$/, use: isDevelopment ? [ { loader: 'style-loader', options: { sourceMap: true } }, { loader: 'css-loader', options: { sourceMap: true } }, { loader: 'postcss-loader', options: { sourceMap: true } }, stylusLoaderDefinition ] // for production (https://github.com/webpack-contrib/extract-text-webpack-plugin) : ExtractTextPlugin.extract({ fallback: 'style-loader', use: ['css-loader', 'postcss-loader', stylusLoaderDefinition] }) } ] // .concat(stylesLoaders) }, externals: { 'cheerio': 'window', 'react/addons': true, 'react/lib/ExecutionEnvironment': true, 'react/lib/ReactContext': true, 'fs': {} }, plugins: (() => { const plugins = [ new webpack.LoaderOptionsPlugin({ minimize: !isDevelopment, debug: isDevelopment, // Webpack 2 no longer allows custom properties in configuration. // Loaders should be updated to allow passing options via loader options in module.rules. // Alternatively, LoaderOptionsPlugin can be used to pass options to loaders hotPort: ports.HMR, sourceMap: true, postcss: () => [ autoprefixer({ browsers: 'last 2 version' }), cssMqPacker() ] }), new webpack.DefinePlugin({ 'process.env': { NODE_ENV: JSON.stringify(isDevelopment ? 'development' : 'production'), APP_CONFIG: JSON.stringify(appConfig), BUILD_STATIC: JSON.stringify(process.env.BUILD_STATIC === 'true'), DEBUG: JSON.stringify(process.env.DEBUG === 'true'), IS_BROWSER: true } }), new webpack.ProvidePlugin({ 'Promise': 'bluebird' }) ] if (isDevelopment) { plugins.push( new webpack.HotModuleReplacementPlugin(), new webpack.NoEmitOnErrorsPlugin() ) } else { plugins.push( new webpack.LoaderOptionsPlugin({minimize: true}), new ExtractTextPlugin({ filename: 'app-[hash].css', disable: false, allChunks: true }), new webpack.optimize.OccurrenceOrderPlugin(), new webpack.optimize.UglifyJsPlugin({ sourceMap: true, compress: { screw_ie8: true, // eslint-disable-line camelcase warnings: false // Because uglify reports irrelevant warnings. } }) // // // ??? // TBD: do we need/want este`s webpackIsomorphicToolsPlugin ??? // TBD: https://github.com/kevlened/copy-webpack-plugin // new CopyWebpackPlugin( // [ // { // from: './src/common/app/favicons/', // to: 'favicons' // } // ], // { // ignore: ['original/**'] // }, // ), ) } // handled by config.devtool + config.output.sourceMapFilename // // plugins.push(new webpack.SourceMapDevToolPlugin({ // // filename: '[name].js.SourceMapDevToolPlugin.map' // filename: isDevelopment // ? '[name].js.map' // : '[name]-[chunk].js.map' // })) return plugins })(), performance: { hints: false // TODO: Reenable it once Webpack 2 will complete dead code removing. // hints: process.env.NODE_ENV === 'production' ? 'warning' : false }, resolve: { extensions: ['.js', '.styl'], modules: [paths.nodeModules], alias: { 'react$': require.resolve(path.join(paths.nodeModules, 'react')) } } } // Webpack Dev Server - Header Settings // // not needed here, because we handle the dev-server per 'webpack-dev-middleware' // so we set the headers in /webpack/devServer/start.js // anyway... // we also define it here, // so you can use the compiled config for a 'webpack-dev-server' based implementation if (_isDevelopment) { const devServer = { headers: {'Access-Control-Allow-Origin': '*'} } config.devServer = devServer } return config } export default webpackGetConfig
stack/webpack/webpackGetConfig.js
'use strict' import webpack from 'webpack' import path from 'path' import ip from 'ip' // webpack/build plugins import autoprefixer from 'autoprefixer' import ExtractTextPlugin from 'extract-text-webpack-plugin' import nib from 'nib' import cssMqPacker from 'css-mqpacker' // custom libs import doubleu23Stylus from 'doubleu23-stylus' // import BrowserSyncPlugin from 'browser-sync-webpack-plugin' import constants from './constants' import appConfig from '../../config/appConfig' import objectAssign from 'object-assign-deep' const { ports, paths, isDevelopment } = appConfig const devtools = process.env.CONTINUOUS_INTEGRATION ? 'inline-source-map' // cheap-module-eval-source-map, because we want original source, but we don't // care about columns, which makes this devtool faster than eval-source-map. // http://webpack.github.io/docs/configuration.html#devtool : 'cheap-module-eval-source-map' const loaders = { 'css': '', // 'less': '!less-loader', // inject // 'sj': '!stylus-loader', // 'scss': '!sass-loader', // 'sass': '!sass-loader?indentedSyntax', 'styl': '!stylus-loader' // 'stylo': '!cssobjects-loader!stylus-loader!' } const serverIp = ip.address() const webpackGetConfig = _isDevelopment => { console.log('[webpackGetConfig] _isDevelopment before', _isDevelopment) const isDevelopment = _isDevelopment != null ? _isDevelopment : appConfig.isDevelopment console.log('[webpackGetConfig] _isDevelopment after', _isDevelopment) // const stylesLoaders = () => { // return Object.keys(loaders).map(ext => { // const prefix = ext === 'stylo' // ? '' // : 'css-loader!postcss-loader' // const extLoaders = prefix + loaders[ext] // const loader = isDevelopment // ? `style-loader!${extLoaders}` // : ExtractTextPlugin.extract('style-loader', extLoaders) // return { // loader: loader, // test: new RegExp(`\\.(${ext})$`) // } // }) // } const stylesLoaders = Object.keys(loaders).map(ext => { const prefix = 'css-loader!postcss-loader' const extLoaders = prefix + loaders[ext] const loader = isDevelopment ? `style-loader!${extLoaders}` : ExtractTextPlugin.extract({ fallback: 'style-loader', loader: extLoaders }) return { loader, test: new RegExp(`\\.(${ext})$`) } }) console.log('stylesLoaders orig', stylesLoaders) const stylusLoaderDefinition = { loader: 'stylus-loader', options: { sourceMap: true, compress: isDevelopment, use: [nib(), doubleu23Stylus({ envVars: { // refactor: build object on top and // find a way to re-use it in webpack.DefinePlugin NODE_ENV: process.env.NODE_ENV, BUILD_STATIC: process.env.BUILD_STATIC, DEBUG: process.env.DEBUG }, envPrefix: '$ENV__' })] } } const config = { target: 'web', cache: isDevelopment, // devtool: false, // handled by "SourceMapDevToolPlugin" devtool: 'cheap-module-source-map', entry: { app: isDevelopment ? [ `webpack-hot-middleware/client?path=http://${serverIp}:${ports.HMR}/__webpack_hmr`, path.join(paths.src, 'index.js') ] : [ path.join(paths.src, 'index.js') ] }, output: isDevelopment ? { path: paths.build, filename: '[name].js', sourceMapFilename: '[name].js.map.sourceMapFilename', chunkFilename: '[name]-[chunkhash].js', publicPath: `http://${serverIp}:${ports.HMR}/build/` } : { path: paths.build, filename: '[name]-[hash].js', // sourceMapFilename: '[name]-[hash].js', chunkFilename: '[name]-[chunkhash].js' }, module: { rules: [ // URL LOADER // (different limits for different fileTypes) { loader: 'url-loader', test: /\.(gif|jpg|png|svg)(\?.*)?$/, exclude: /\.styl$/, options: { limit: 10000 } }, { loader: 'url-loader', test: /favicon\.ico$/, exclude: /\.styl$/, options: { limit: 1 } }, { loader: 'url-loader', test: /\.(ttf|eot|woff|woff2)(\?.*)?$/, exclude: /\.styl$/, options: { limit: 100000 } }, // BABEL { loader: 'babel-loader', test: /\.js$/, exclude: /(node_modules|bower_components|styles)/, options: { retainLines: true, sourceMap: true, babelrc: true, cacheDirectory: false, // presets/plugins have to match defines in .babelrc presets: [ // ['env', { modules: false }], 'es2015', 'react', 'stage-2', 'stage-3' ], plugins: [ [ 'transform-runtime', { helpers: false, polyfill: true, regenerator: false } ], 'transform-decorators-legacy' ], env: { production: { plugins: ['transform-react-constant-elements'] } } } }, // SOURCEMAPS // not needed (only handles extern sourcemaps (in module packages)) { test: /\.js$/, use: ['source-map-loader'], enforce: 'pre' }, { test: /\.styl$/, use: isDevelopment ? [ { loader: 'style-loader', options: { sourceMap: true } }, { loader: 'css-loader', options: { sourceMap: true } }, { loader: 'postcss-loader', options: { sourceMap: true } }, stylusLoaderDefinition ] // for production (https://github.com/webpack-contrib/extract-text-webpack-plugin) : ExtractTextPlugin.extract({ fallback: 'style-loader', use: ['css-loader', 'postcss-loader', stylusLoaderDefinition] }) } ] // .concat(stylesLoaders) }, externals: { 'cheerio': 'window', 'react/addons': true, 'react/lib/ExecutionEnvironment': true, 'react/lib/ReactContext': true, 'fs': {} }, plugins: (() => { console.log('stylesLoaders', stylesLoaders) const plugins = [ new webpack.LoaderOptionsPlugin({ minimize: !isDevelopment, debug: isDevelopment, // Webpack 2 no longer allows custom properties in configuration. // Loaders should be updated to allow passing options via loader options in module.rules. // Alternatively, LoaderOptionsPlugin can be used to pass options to loaders hotPort: ports.HMR, sourceMap: true, postcss: () => [ autoprefixer({ browsers: 'last 2 version' }), cssMqPacker() ] }), new webpack.DefinePlugin({ 'process.env': { NODE_ENV: JSON.stringify(isDevelopment ? 'development' : 'production'), APP_CONFIG: JSON.stringify(appConfig), BUILD_STATIC: JSON.stringify(process.env.BUILD_STATIC === 'true'), DEBUG: JSON.stringify(process.env.DEBUG === 'true'), IS_BROWSER: true } }), new webpack.ProvidePlugin({ 'Promise': 'bluebird' }) ] if (isDevelopment) { plugins.push( new webpack.HotModuleReplacementPlugin(), new webpack.NoEmitOnErrorsPlugin() ) } else { plugins.push( new webpack.LoaderOptionsPlugin({minimize: true}), new ExtractTextPlugin({ filename: 'app-[hash].css', disable: false, allChunks: true }), new webpack.optimize.OccurrenceOrderPlugin(), new webpack.optimize.UglifyJsPlugin({ sourceMap: true, compress: { screw_ie8: true, // eslint-disable-line camelcase warnings: false // Because uglify reports irrelevant warnings. } }) // // // ??? // TBD: do we need/want este`s webpackIsomorphicToolsPlugin ??? // TBD: https://github.com/kevlened/copy-webpack-plugin // new CopyWebpackPlugin( // [ // { // from: './src/common/app/favicons/', // to: 'favicons' // } // ], // { // ignore: ['original/**'] // }, // ), ) } // handled by config.devtool + config.output.sourceMapFilename // // plugins.push(new webpack.SourceMapDevToolPlugin({ // // filename: '[name].js.SourceMapDevToolPlugin.map' // filename: isDevelopment // ? '[name].js.map' // : '[name]-[chunk].js.map' // })) return plugins })(), performance: { hints: false // TODO: Reenable it once Webpack 2 will complete dead code removing. // hints: process.env.NODE_ENV === 'production' ? 'warning' : false }, resolve: { extensions: ['.js', '.styl'], modules: [paths.nodeModules], alias: { 'react$': require.resolve(path.join(paths.nodeModules, 'react')) } } } // Webpack Dev Server - Header Settings // // not needed here, because we handle the dev-server per 'webpack-dev-middleware' // so we set the headers in /webpack/devServer/start.js // anyway... // we also define it here, // so you can use the compiled config for a 'webpack-dev-server' based implementation if (_isDevelopment) { const devServer = { headers: {'Access-Control-Allow-Origin': '*'} } config.devServer = devServer } return config } export default webpackGetConfig
removed debug outputs and leftovers + comments
stack/webpack/webpackGetConfig.js
removed debug outputs and leftovers + comments
<ide><path>tack/webpack/webpackGetConfig.js <ide> const serverIp = ip.address() <ide> <ide> const webpackGetConfig = _isDevelopment => { <del> console.log('[webpackGetConfig] _isDevelopment before', _isDevelopment) <ide> const isDevelopment = _isDevelopment != null <ide> ? _isDevelopment <ide> : appConfig.isDevelopment <del> <del> console.log('[webpackGetConfig] _isDevelopment after', _isDevelopment) <del> <del> // const stylesLoaders = () => { <del> // return Object.keys(loaders).map(ext => { <del> // const prefix = ext === 'stylo' <del> // ? '' <del> // : 'css-loader!postcss-loader' <del> // const extLoaders = prefix + loaders[ext] <del> // const loader = isDevelopment <del> // ? `style-loader!${extLoaders}` <del> // : ExtractTextPlugin.extract('style-loader', extLoaders) <del> // return { <del> // loader: loader, <del> // test: new RegExp(`\\.(${ext})$`) <del> // } <del> // }) <del> // } <ide> <ide> const stylesLoaders = Object.keys(loaders).map(ext => { <ide> const prefix = 'css-loader!postcss-loader' <ide> test: new RegExp(`\\.(${ext})$`) <ide> } <ide> }) <del> console.log('stylesLoaders orig', stylesLoaders) <ide> <ide> const stylusLoaderDefinition = { <ide> loader: 'stylus-loader', <ide> 'fs': {} <ide> }, <ide> plugins: (() => { <del> console.log('stylesLoaders', stylesLoaders) <del> <ide> const plugins = [ <ide> new webpack.LoaderOptionsPlugin({ <ide> minimize: !isDevelopment,
Java
apache-2.0
10cdaab178eb9c3dd9b4dcd80142c71f0265784d
0
spinnaker/kayenta,spinnaker/kayenta
/* * Copyright 2017 Google, Inc. * * Licensed under the Apache License, Version 2.0 (the "License") * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.kayenta.controllers; import com.netflix.kayenta.canary.CanaryConfig; import com.netflix.kayenta.canary.CanaryConfigUpdateResponse; import com.netflix.kayenta.security.AccountCredentials; import com.netflix.kayenta.security.AccountCredentialsRepository; import com.netflix.kayenta.security.CredentialsHelper; import com.netflix.kayenta.storage.ObjectType; import com.netflix.kayenta.storage.StorageService; import com.netflix.kayenta.storage.StorageServiceRepository; import com.netflix.spectator.api.Registry; import com.netflix.spinnaker.kork.web.exceptions.NotFoundException; import io.swagger.annotations.ApiOperation; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.util.StringUtils; import org.springframework.web.bind.annotation.*; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.time.Instant; import java.util.List; import java.util.Map; import java.util.UUID; import java.util.regex.Pattern; @RestController @RequestMapping("/canaryConfig") @Slf4j public class CanaryConfigController { private static Pattern canaryConfigNamePattern = Pattern.compile("[A-Z,a-z,0-9,\\-,\\_]*"); private final AccountCredentialsRepository accountCredentialsRepository; private final StorageServiceRepository storageServiceRepository; @Autowired public CanaryConfigController(AccountCredentialsRepository accountCredentialsRepository, StorageServiceRepository storageServiceRepository) { this.accountCredentialsRepository = accountCredentialsRepository; this.storageServiceRepository = storageServiceRepository; } @ApiOperation(value = "Retrieve a canary config from object storage") @RequestMapping(value = "/{canaryConfigId:.+}", method = RequestMethod.GET) public CanaryConfig loadCanaryConfig(@RequestParam(required = false) final String configurationAccountName, @PathVariable String canaryConfigId) { String resolvedConfigurationAccountName = CredentialsHelper.resolveAccountByNameOrType(configurationAccountName, AccountCredentials.Type.CONFIGURATION_STORE, accountCredentialsRepository); StorageService configurationService = storageServiceRepository .getOne(resolvedConfigurationAccountName) .orElseThrow(() -> new IllegalArgumentException("No configuration service was configured; unable to read canary config from bucket.")); return configurationService.loadObject(resolvedConfigurationAccountName, ObjectType.CANARY_CONFIG, canaryConfigId); } @ApiOperation(value = "Write a canary config to object storage") @RequestMapping(consumes = "application/json", method = RequestMethod.POST) public CanaryConfigUpdateResponse storeCanaryConfig(@RequestParam(required = false) final String configurationAccountName, @RequestBody CanaryConfig canaryConfig) throws IOException { String resolvedConfigurationAccountName = CredentialsHelper.resolveAccountByNameOrType(configurationAccountName, AccountCredentials.Type.CONFIGURATION_STORE, accountCredentialsRepository); StorageService configurationService = storageServiceRepository .getOne(resolvedConfigurationAccountName) .orElseThrow(() -> new IllegalArgumentException("No configuration service was configured; unable to write canary config to bucket.")); if (canaryConfig.getCreatedTimestamp() == null) { canaryConfig.setCreatedTimestamp(System.currentTimeMillis()); } if (canaryConfig.getUpdatedTimestamp() == null) { canaryConfig.setUpdatedTimestamp(canaryConfig.getCreatedTimestamp()); } canaryConfig.setCreatedTimestampIso(Instant.ofEpochMilli(canaryConfig.getCreatedTimestamp()).toString()); canaryConfig.setUpdatedTimestampIso(Instant.ofEpochMilli(canaryConfig.getUpdatedTimestamp()).toString()); String canaryConfigId = UUID.randomUUID() + ""; // TODO(duftler): Serialize the canary config within a canary run? validateNameAndApplicationAttributes(canaryConfig); try { configurationService.loadObject(resolvedConfigurationAccountName, ObjectType.CANARY_CONFIG, canaryConfigId); } catch (NotFoundException e) { configurationService.storeObject(resolvedConfigurationAccountName, ObjectType.CANARY_CONFIG, canaryConfigId, canaryConfig, canaryConfig.getName() + ".json", false); return CanaryConfigUpdateResponse.builder().canaryConfigId(canaryConfigId).build(); } throw new IllegalArgumentException("Canary config '" + canaryConfigId + "' already exists."); } @ApiOperation(value = "Update a canary config") @RequestMapping(value = "/{canaryConfigId:.+}", consumes = "application/json", method = RequestMethod.PUT) public CanaryConfigUpdateResponse updateCanaryConfig(@RequestParam(required = false) final String configurationAccountName, @PathVariable String canaryConfigId, @RequestBody CanaryConfig canaryConfig) throws IOException { String resolvedConfigurationAccountName = CredentialsHelper.resolveAccountByNameOrType(configurationAccountName, AccountCredentials.Type.CONFIGURATION_STORE, accountCredentialsRepository); StorageService configurationService = storageServiceRepository .getOne(resolvedConfigurationAccountName) .orElseThrow(() -> new IllegalArgumentException("No configuration service was configured; unable to write canary config to bucket.")); canaryConfig.setUpdatedTimestamp(System.currentTimeMillis()); canaryConfig.setUpdatedTimestampIso(Instant.ofEpochMilli(canaryConfig.getUpdatedTimestamp()).toString()); validateNameAndApplicationAttributes(canaryConfig); try { configurationService.loadObject(resolvedConfigurationAccountName, ObjectType.CANARY_CONFIG, canaryConfigId); } catch (Exception e) { throw new IllegalArgumentException("Canary config '" + canaryConfigId + "' does not exist."); } configurationService.storeObject(resolvedConfigurationAccountName, ObjectType.CANARY_CONFIG, canaryConfigId, canaryConfig, canaryConfig.getName() + ".json", true); return CanaryConfigUpdateResponse.builder().canaryConfigId(canaryConfigId).build(); } private static void validateNameAndApplicationAttributes(@RequestBody CanaryConfig canaryConfig) { if (StringUtils.isEmpty(canaryConfig.getName())) { throw new IllegalArgumentException("Canary config must specify a name."); } else if (canaryConfig.getApplications() == null || canaryConfig.getApplications().size() == 0) { throw new IllegalArgumentException("Canary config must specify at least one application."); } String canaryConfigName = canaryConfig.getName(); if (!canaryConfigNamePattern.matcher(canaryConfigName).matches()) { throw new IllegalArgumentException("Canary config cannot be named '" + canaryConfigName + "'. Names must contain only letters, numbers, dashes (-) and underscores (_)."); } } @ApiOperation(value = "Delete a canary config") @RequestMapping(value = "/{canaryConfigId:.+}", method = RequestMethod.DELETE) public void deleteCanaryConfig(@RequestParam(required = false) final String configurationAccountName, @PathVariable String canaryConfigId, HttpServletResponse response) { String resolvedConfigurationAccountName = CredentialsHelper.resolveAccountByNameOrType(configurationAccountName, AccountCredentials.Type.CONFIGURATION_STORE, accountCredentialsRepository); StorageService configurationService = storageServiceRepository .getOne(resolvedConfigurationAccountName) .orElseThrow(() -> new IllegalArgumentException("No configuration service was configured; unable to delete canary config.")); configurationService.deleteObject(resolvedConfigurationAccountName, ObjectType.CANARY_CONFIG, canaryConfigId); response.setStatus(HttpStatus.NO_CONTENT.value()); } @ApiOperation(value = "Retrieve a list of canary config ids and timestamps") @RequestMapping(method = RequestMethod.GET) public List<Map<String, Object>> listAllCanaryConfigs(@RequestParam(required = false) final String configurationAccountName, @RequestParam(required = false, value = "application") final List<String> applications) { String resolvedConfigurationAccountName = CredentialsHelper.resolveAccountByNameOrType(configurationAccountName, AccountCredentials.Type.CONFIGURATION_STORE, accountCredentialsRepository); StorageService configurationService = storageServiceRepository .getOne(resolvedConfigurationAccountName) .orElseThrow(() -> new IllegalArgumentException("No configuration service was configured; unable to list all canary configs.")); return configurationService.listObjectKeys(resolvedConfigurationAccountName, ObjectType.CANARY_CONFIG, applications, false); } }
kayenta-web/src/main/java/com/netflix/kayenta/controllers/CanaryConfigController.java
/* * Copyright 2017 Google, Inc. * * Licensed under the Apache License, Version 2.0 (the "License") * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.kayenta.controllers; import com.netflix.kayenta.canary.CanaryConfig; import com.netflix.kayenta.canary.CanaryConfigUpdateResponse; import com.netflix.kayenta.security.AccountCredentials; import com.netflix.kayenta.security.AccountCredentialsRepository; import com.netflix.kayenta.security.CredentialsHelper; import com.netflix.kayenta.storage.ObjectType; import com.netflix.kayenta.storage.StorageService; import com.netflix.kayenta.storage.StorageServiceRepository; import com.netflix.spectator.api.Registry; import com.netflix.spinnaker.kork.web.exceptions.NotFoundException; import io.swagger.annotations.ApiOperation; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.util.StringUtils; import org.springframework.web.bind.annotation.*; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.time.Instant; import java.util.List; import java.util.Map; import java.util.UUID; import java.util.regex.Pattern; @RestController @RequestMapping("/canaryConfig") @Slf4j public class CanaryConfigController { private static Pattern canaryConfigNamePattern = Pattern.compile("[A-Z,a-z,0-9,\\-,\\_]*"); private final AccountCredentialsRepository accountCredentialsRepository; private final StorageServiceRepository storageServiceRepository; @Autowired public CanaryConfigController(AccountCredentialsRepository accountCredentialsRepository, StorageServiceRepository storageServiceRepository) { this.accountCredentialsRepository = accountCredentialsRepository; this.storageServiceRepository = storageServiceRepository; } @ApiOperation(value = "Retrieve a canary config from object storage") @RequestMapping(value = "/{canaryConfigId:.+}", method = RequestMethod.GET) public CanaryConfig loadCanaryConfig(@RequestParam(required = false) final String configurationAccountName, @PathVariable String canaryConfigId) { String resolvedConfigurationAccountName = CredentialsHelper.resolveAccountByNameOrType(configurationAccountName, AccountCredentials.Type.CONFIGURATION_STORE, accountCredentialsRepository); StorageService configurationService = storageServiceRepository .getOne(resolvedConfigurationAccountName) .orElseThrow(() -> new IllegalArgumentException("No configuration service was configured; unable to read canary config from bucket.")); return configurationService.loadObject(resolvedConfigurationAccountName, ObjectType.CANARY_CONFIG, canaryConfigId); } @ApiOperation(value = "Write a canary config to object storage") @RequestMapping(consumes = "application/json", method = RequestMethod.POST) public CanaryConfigUpdateResponse storeCanaryConfig(@RequestParam(required = false) final String configurationAccountName, @RequestBody CanaryConfig canaryConfig) throws IOException { String resolvedConfigurationAccountName = CredentialsHelper.resolveAccountByNameOrType(configurationAccountName, AccountCredentials.Type.CONFIGURATION_STORE, accountCredentialsRepository); StorageService configurationService = storageServiceRepository .getOne(resolvedConfigurationAccountName) .orElseThrow(() -> new IllegalArgumentException("No configuration service was configured; unable to write canary config to bucket.")); if (canaryConfig.getCreatedTimestamp() == null) { canaryConfig.setCreatedTimestamp(System.currentTimeMillis()); } if (canaryConfig.getUpdatedTimestamp() == null) { canaryConfig.setUpdatedTimestamp(canaryConfig.getCreatedTimestamp()); } canaryConfig.setCreatedTimestampIso(Instant.ofEpochMilli(canaryConfig.getCreatedTimestamp()).toString()); canaryConfig.setUpdatedTimestampIso(Instant.ofEpochMilli(canaryConfig.getUpdatedTimestamp()).toString()); String canaryConfigId = UUID.randomUUID() + ""; // TODO(duftler): Serialize the canary config within a canary run? if (StringUtils.isEmpty(canaryConfig.getName())) { throw new IllegalArgumentException("Canary config must specify a name."); } else if (canaryConfig.getApplications() == null || canaryConfig.getApplications().size() == 0) { throw new IllegalArgumentException("Canary config must specify at least one application."); } String canaryConfigName = canaryConfig.getName(); if (!canaryConfigNamePattern.matcher(canaryConfigName).matches()) { throw new IllegalArgumentException("Canary config cannot be named '" + canaryConfigName + "'. Names must contain only letters, numbers, dashes (-) and underscores (_)."); } try { configurationService.loadObject(resolvedConfigurationAccountName, ObjectType.CANARY_CONFIG, canaryConfigId); } catch (NotFoundException e) { configurationService.storeObject(resolvedConfigurationAccountName, ObjectType.CANARY_CONFIG, canaryConfigId, canaryConfig, canaryConfig.getName() + ".json", false); return CanaryConfigUpdateResponse.builder().canaryConfigId(canaryConfigId).build(); } throw new IllegalArgumentException("Canary config '" + canaryConfigId + "' already exists."); } @ApiOperation(value = "Update a canary config") @RequestMapping(value = "/{canaryConfigId:.+}", consumes = "application/json", method = RequestMethod.PUT) public CanaryConfigUpdateResponse updateCanaryConfig(@RequestParam(required = false) final String configurationAccountName, @PathVariable String canaryConfigId, @RequestBody CanaryConfig canaryConfig) throws IOException { String resolvedConfigurationAccountName = CredentialsHelper.resolveAccountByNameOrType(configurationAccountName, AccountCredentials.Type.CONFIGURATION_STORE, accountCredentialsRepository); StorageService configurationService = storageServiceRepository .getOne(resolvedConfigurationAccountName) .orElseThrow(() -> new IllegalArgumentException("No configuration service was configured; unable to write canary config to bucket.")); canaryConfig.setUpdatedTimestamp(System.currentTimeMillis()); canaryConfig.setUpdatedTimestampIso(Instant.ofEpochMilli(canaryConfig.getUpdatedTimestamp()).toString()); try { configurationService.loadObject(resolvedConfigurationAccountName, ObjectType.CANARY_CONFIG, canaryConfigId); } catch (Exception e) { throw new IllegalArgumentException("Canary config '" + canaryConfigId + "' does not exist."); } configurationService.storeObject(resolvedConfigurationAccountName, ObjectType.CANARY_CONFIG, canaryConfigId, canaryConfig, canaryConfig.getName() + ".json", true); return CanaryConfigUpdateResponse.builder().canaryConfigId(canaryConfigId).build(); } @ApiOperation(value = "Delete a canary config") @RequestMapping(value = "/{canaryConfigId:.+}", method = RequestMethod.DELETE) public void deleteCanaryConfig(@RequestParam(required = false) final String configurationAccountName, @PathVariable String canaryConfigId, HttpServletResponse response) { String resolvedConfigurationAccountName = CredentialsHelper.resolveAccountByNameOrType(configurationAccountName, AccountCredentials.Type.CONFIGURATION_STORE, accountCredentialsRepository); StorageService configurationService = storageServiceRepository .getOne(resolvedConfigurationAccountName) .orElseThrow(() -> new IllegalArgumentException("No configuration service was configured; unable to delete canary config.")); configurationService.deleteObject(resolvedConfigurationAccountName, ObjectType.CANARY_CONFIG, canaryConfigId); response.setStatus(HttpStatus.NO_CONTENT.value()); } @ApiOperation(value = "Retrieve a list of canary config ids and timestamps") @RequestMapping(method = RequestMethod.GET) public List<Map<String, Object>> listAllCanaryConfigs(@RequestParam(required = false) final String configurationAccountName, @RequestParam(required = false, value = "application") final List<String> applications) { String resolvedConfigurationAccountName = CredentialsHelper.resolveAccountByNameOrType(configurationAccountName, AccountCredentials.Type.CONFIGURATION_STORE, accountCredentialsRepository); StorageService configurationService = storageServiceRepository .getOne(resolvedConfigurationAccountName) .orElseThrow(() -> new IllegalArgumentException("No configuration service was configured; unable to list all canary configs.")); return configurationService.listObjectKeys(resolvedConfigurationAccountName, ObjectType.CANARY_CONFIG, applications, false); } }
fix(canary-config): Ensure that PUT applies same validation as POST. (#215)
kayenta-web/src/main/java/com/netflix/kayenta/controllers/CanaryConfigController.java
fix(canary-config): Ensure that PUT applies same validation as POST. (#215)
<ide><path>ayenta-web/src/main/java/com/netflix/kayenta/controllers/CanaryConfigController.java <ide> String canaryConfigId = UUID.randomUUID() + ""; <ide> <ide> // TODO(duftler): Serialize the canary config within a canary run? <del> if (StringUtils.isEmpty(canaryConfig.getName())) { <del> throw new IllegalArgumentException("Canary config must specify a name."); <del> } else if (canaryConfig.getApplications() == null || canaryConfig.getApplications().size() == 0) { <del> throw new IllegalArgumentException("Canary config must specify at least one application."); <del> } <del> <del> String canaryConfigName = canaryConfig.getName(); <del> <del> if (!canaryConfigNamePattern.matcher(canaryConfigName).matches()) { <del> throw new IllegalArgumentException("Canary config cannot be named '" + canaryConfigName + <del> "'. Names must contain only letters, numbers, dashes (-) and underscores (_)."); <del> } <add> validateNameAndApplicationAttributes(canaryConfig); <ide> <ide> try { <ide> configurationService.loadObject(resolvedConfigurationAccountName, ObjectType.CANARY_CONFIG, canaryConfigId); <ide> canaryConfig.setUpdatedTimestamp(System.currentTimeMillis()); <ide> canaryConfig.setUpdatedTimestampIso(Instant.ofEpochMilli(canaryConfig.getUpdatedTimestamp()).toString()); <ide> <add> validateNameAndApplicationAttributes(canaryConfig); <add> <ide> try { <ide> configurationService.loadObject(resolvedConfigurationAccountName, ObjectType.CANARY_CONFIG, canaryConfigId); <ide> } catch (Exception e) { <ide> configurationService.storeObject(resolvedConfigurationAccountName, ObjectType.CANARY_CONFIG, canaryConfigId, canaryConfig, canaryConfig.getName() + ".json", true); <ide> <ide> return CanaryConfigUpdateResponse.builder().canaryConfigId(canaryConfigId).build(); <add> } <add> <add> private static void validateNameAndApplicationAttributes(@RequestBody CanaryConfig canaryConfig) { <add> if (StringUtils.isEmpty(canaryConfig.getName())) { <add> throw new IllegalArgumentException("Canary config must specify a name."); <add> } else if (canaryConfig.getApplications() == null || canaryConfig.getApplications().size() == 0) { <add> throw new IllegalArgumentException("Canary config must specify at least one application."); <add> } <add> <add> String canaryConfigName = canaryConfig.getName(); <add> <add> if (!canaryConfigNamePattern.matcher(canaryConfigName).matches()) { <add> throw new IllegalArgumentException("Canary config cannot be named '" + canaryConfigName + <add> "'. Names must contain only letters, numbers, dashes (-) and underscores (_)."); <add> } <ide> } <ide> <ide> @ApiOperation(value = "Delete a canary config")
Java
mit
307682ccd0daa84ccf8dccc85eed309e616e950a
0
Raizlabs/DBFlow,janzoner/DBFlow,mickele/DBFlow,Raizlabs/DBFlow,mickele/DBFlow
package com.raizlabs.android.dbflow.processor.definition.column; import com.raizlabs.android.dbflow.annotation.Column; import com.raizlabs.android.dbflow.annotation.ForeignKey; import com.raizlabs.android.dbflow.annotation.ForeignKeyAction; import com.raizlabs.android.dbflow.annotation.ForeignKeyReference; import com.raizlabs.android.dbflow.processor.ClassNames; import com.raizlabs.android.dbflow.processor.ProcessorUtils; import com.raizlabs.android.dbflow.processor.definition.TableDefinition; import com.raizlabs.android.dbflow.processor.definition.method.BindToContentValuesMethod; import com.raizlabs.android.dbflow.processor.definition.method.BindToStatementMethod; import com.raizlabs.android.dbflow.processor.definition.method.LoadFromCursorMethod; import com.raizlabs.android.dbflow.processor.model.ProcessorManager; import com.raizlabs.android.dbflow.processor.utils.ModelUtils; import com.raizlabs.android.dbflow.processor.utils.StringUtils; import com.raizlabs.android.dbflow.sql.QueryBuilder; import com.squareup.javapoet.ClassName; import com.squareup.javapoet.CodeBlock; import com.squareup.javapoet.FieldSpec; import com.squareup.javapoet.MethodSpec; import com.squareup.javapoet.ParameterizedTypeName; import com.squareup.javapoet.TypeName; import com.squareup.javapoet.TypeSpec; import java.util.ArrayList; import java.util.List; import java.util.concurrent.atomic.AtomicInteger; import javax.lang.model.element.Element; import javax.lang.model.element.Modifier; import javax.lang.model.element.TypeElement; import javax.lang.model.type.MirroredTypeException; /** * Description: */ public class ForeignKeyColumnDefinition extends ColumnDefinition { public final List<ForeignKeyReferenceDefinition> foreignKeyReferenceDefinitionList = new ArrayList<>(); public final TableDefinition tableDefinition; public ClassName referencedTableClassName; public ForeignKeyAction onDelete; public ForeignKeyAction onUpdate; public boolean isModelContainer; public boolean isModel; public boolean needsReferences; public boolean nonModelColumn; public boolean saveForeignKeyModel; public ForeignKeyColumnDefinition(ProcessorManager manager, TableDefinition tableDefinition, Element typeElement, boolean isPackagePrivate) { super(manager, typeElement, tableDefinition, isPackagePrivate); this.tableDefinition = tableDefinition; ForeignKey foreignKey = typeElement.getAnnotation(ForeignKey.class); onUpdate = foreignKey.onUpdate(); onDelete = foreignKey.onDelete(); try { foreignKey.tableClass(); } catch (MirroredTypeException mte) { referencedTableClassName = ClassName.get(manager.getElements().getTypeElement(mte.getTypeMirror().toString())); } // hopefully intentionally left blank if (referencedTableClassName.equals(TypeName.OBJECT)) { if (elementTypeName instanceof ParameterizedTypeName) { List<TypeName> args = ((ParameterizedTypeName) elementTypeName).typeArguments; if (args.size() > 0) { referencedTableClassName = ClassName.bestGuess(args.get(0).toString()); isModelContainer = true; } } else { referencedTableClassName = ClassName.bestGuess(elementTypeName.toString()); } } if (referencedTableClassName == null) { manager.logError("Referenced was null for %1s within %1s", typeElement, elementTypeName); } TypeElement element = manager.getElements().getTypeElement( manager.getTypeUtils().erasure(typeElement.asType()).toString()); isModel = ProcessorUtils.implementsClass(manager.getProcessingEnvironment(), ClassNames.MODEL.toString(), element); isModelContainer = isModelContainer || ProcessorUtils.implementsClass(manager.getProcessingEnvironment(), ClassNames.MODEL_CONTAINER.toString(), element); nonModelColumn = !isModel && !isModelContainer; saveForeignKeyModel = foreignKey.saveForeignKeyModel(); // we need to recheck for this instance if (columnAccess instanceof TypeConverterAccess) { if (typeElement.getModifiers().contains(Modifier.PRIVATE)) { boolean useIs = elementTypeName.box().equals(TypeName.BOOLEAN.box()) && tableDefinition.useIsForPrivateBooleans; columnAccess = new PrivateColumnAccess(typeElement.getAnnotation(Column.class), useIs); } else { columnAccess = new SimpleColumnAccess(); } } ForeignKeyReference[] references = foreignKey.references(); if (references.length == 0) { // no references specified we will delegate references call to post-evaluation needsReferences = true; } else { for (ForeignKeyReference reference : references) { ForeignKeyReferenceDefinition referenceDefinition = new ForeignKeyReferenceDefinition(manager, elementName, reference, columnAccess, this); // TODO: add validation foreignKeyReferenceDefinitionList.add(referenceDefinition); } } } @Override public void addPropertyDefinition(TypeSpec.Builder typeBuilder, TypeName tableClassName) { checkNeedsReferences(); for (ForeignKeyReferenceDefinition reference : foreignKeyReferenceDefinitionList) { TypeName propParam; if (reference.columnClassName.isPrimitive() && !reference.columnClassName.equals(TypeName.BOOLEAN)) { propParam = ClassName.get(ClassNames.PROPERTY_PACKAGE, StringUtils.capitalize(reference.columnClassName.toString()) + "Property"); } else { propParam = ParameterizedTypeName.get(ClassNames.PROPERTY, reference.columnClassName.box()); } typeBuilder.addField(FieldSpec.builder(propParam, reference.columnName, Modifier.PUBLIC, Modifier.STATIC, Modifier.FINAL) .initializer("new $T($T.class, $S)", propParam, tableClassName, reference.columnName).build()); } } @Override public void addPropertyCase(MethodSpec.Builder methodBuilder) { checkNeedsReferences(); for (ForeignKeyReferenceDefinition reference : foreignKeyReferenceDefinitionList) { methodBuilder.beginControlFlow("case $S: ", reference.columnName); methodBuilder.addStatement("return $L", reference.columnName); methodBuilder.endControlFlow(); } } @Override public CodeBlock getInsertStatementColumnName() { checkNeedsReferences(); CodeBlock.Builder builder = CodeBlock.builder(); for (int i = 0; i < foreignKeyReferenceDefinitionList.size(); i++) { if (i > 0) { builder.add(","); } ForeignKeyReferenceDefinition referenceDefinition = foreignKeyReferenceDefinitionList.get(i); builder.add("$L", QueryBuilder.quote(referenceDefinition.columnName)); } return builder.build(); } @Override public CodeBlock getInsertStatementValuesString() { checkNeedsReferences(); CodeBlock.Builder builder = CodeBlock.builder(); for (int i = 0; i < foreignKeyReferenceDefinitionList.size(); i++) { if (i > 0) { builder.add(","); } builder.add("?"); } return builder.build(); } @Override public CodeBlock getCreationName() { checkNeedsReferences(); CodeBlock.Builder builder = CodeBlock.builder(); for (int i = 0; i < foreignKeyReferenceDefinitionList.size(); i++) { if (i > 0) { builder.add(" ,"); } ForeignKeyReferenceDefinition referenceDefinition = foreignKeyReferenceDefinitionList.get(i); builder.add(referenceDefinition.getCreationStatement()); } return builder.build(); } @Override public CodeBlock getContentValuesStatement(boolean isModelContainerAdapter) { if (nonModelColumn) { return super.getContentValuesStatement(isModelContainerAdapter); } else { checkNeedsReferences(); CodeBlock.Builder builder = CodeBlock.builder(); String statement = columnAccess .getColumnAccessString(elementTypeName, elementName, elementName, ModelUtils.getVariable(isModelContainerAdapter), isModelContainerAdapter, false); String finalAccessStatement = getFinalAccessStatement(builder, isModelContainerAdapter, statement); builder.beginControlFlow("if ($L != null)", finalAccessStatement); CodeBlock.Builder elseBuilder = CodeBlock.builder(); for (ForeignKeyReferenceDefinition referenceDefinition : foreignKeyReferenceDefinitionList) { builder.add(referenceDefinition.getContentValuesStatement(isModelContainerAdapter)); elseBuilder.addStatement("$L.putNull($S)", BindToContentValuesMethod.PARAM_CONTENT_VALUES, QueryBuilder.quote(referenceDefinition.columnName)); } if (saveForeignKeyModel) { builder.addStatement("$L.save()", finalAccessStatement); } builder.nextControlFlow("else") .add(elseBuilder.build()) .endControlFlow(); return builder.build(); } } @Override public CodeBlock getSQLiteStatementMethod(AtomicInteger index, boolean isModelContainerAdapter) { if (nonModelColumn) { return super.getSQLiteStatementMethod(index, isModelContainerAdapter); } else { checkNeedsReferences(); CodeBlock.Builder builder = CodeBlock.builder(); String statement = columnAccess .getColumnAccessString(elementTypeName, elementName, elementName, ModelUtils.getVariable(isModelContainerAdapter), isModelContainerAdapter, true); String finalAccessStatement = getFinalAccessStatement(builder, isModelContainerAdapter, statement); builder.beginControlFlow("if ($L != null)", finalAccessStatement); if (saveForeignKeyModel) { builder.addStatement("$L.save()", finalAccessStatement); } CodeBlock.Builder elseBuilder = CodeBlock.builder(); for (int i = 0; i < foreignKeyReferenceDefinitionList.size(); i++) { if (i > 0) { index.incrementAndGet(); } ForeignKeyReferenceDefinition referenceDefinition = foreignKeyReferenceDefinitionList.get(i); builder.add(referenceDefinition.getSQLiteStatementMethod(index, isModelContainerAdapter)); elseBuilder.addStatement("$L.bindNull($L)", BindToStatementMethod.PARAM_STATEMENT, index.intValue() + " + " + BindToStatementMethod.PARAM_START); } builder.nextControlFlow("else") .add(elseBuilder.build()) .endControlFlow(); return builder.build(); } } @Override public CodeBlock getLoadFromCursorMethod(boolean isModelContainerAdapter, boolean putNullForContainerAdapter, boolean endNonPrimitiveIf) { if (nonModelColumn) { return super.getLoadFromCursorMethod(isModelContainerAdapter, putNullForContainerAdapter, endNonPrimitiveIf); } else { checkNeedsReferences(); CodeBlock.Builder builder = CodeBlock.builder() .add("//// Only load model if references match, for efficiency\n"); CodeBlock.Builder ifNullBuilder = CodeBlock.builder() .add("if ("); CodeBlock.Builder selectBuilder = CodeBlock.builder(); for (int i = 0; i < foreignKeyReferenceDefinitionList.size(); i++) { ForeignKeyReferenceDefinition referenceDefinition = foreignKeyReferenceDefinitionList.get(i); String indexName = "index" + referenceDefinition.columnName; builder.addStatement("int $L = $L.getColumnIndex($S)", indexName, LoadFromCursorMethod.PARAM_CURSOR, referenceDefinition.columnName); if (i > 0) { ifNullBuilder.add(" && "); } ifNullBuilder.add("$L != -1 && !$L.isNull($L)", indexName, LoadFromCursorMethod.PARAM_CURSOR, indexName); // TODO: respect separator here. selectBuilder.add("\n.and($L.$L.eq($L))", ClassName.get(referencedTableClassName.packageName(), referencedTableClassName.simpleName() + "_" + TableDefinition.DBFLOW_TABLE_TAG), referenceDefinition.foreignColumnName, CodeBlock.builder().add("$L.$L($L)", LoadFromCursorMethod.PARAM_CURSOR, DefinitionUtils.getLoadFromCursorMethodString(referenceDefinition.columnClassName, referenceDefinition.columnAccess), indexName).build()); } ifNullBuilder.add(")"); builder.beginControlFlow(ifNullBuilder.build().toString()); CodeBlock.Builder initializer = CodeBlock.builder(); initializer.add("new $T().from($T.class).where()", ClassNames.SELECT, referencedTableClassName) .add(selectBuilder.build()); if (!isModelContainerAdapter && !isModelContainer) { initializer.add(".querySingle()"); } else { if (isModelContainerAdapter) { initializer.add(".queryModelContainer($L.getInstance($L.newDataInstance(), $T.class)).getData()", ModelUtils.getVariable(true), ModelUtils.getVariable(true), referencedTableClassName); } else { initializer.add(".queryModelContainer(new $T($T.class))", elementTypeName, referencedTableClassName); } } builder.addStatement(columnAccess.setColumnAccessString(elementTypeName, elementName, elementName, isModelContainerAdapter, ModelUtils.getVariable(isModelContainerAdapter), initializer.build(), false)); boolean putDefaultValue = putNullForContainerAdapter; if (putContainerDefaultValue != putDefaultValue && isModelContainerAdapter) { putDefaultValue = putContainerDefaultValue; } if (putDefaultValue) { builder.nextControlFlow("else"); builder.addStatement("$L.putDefault($S)", ModelUtils.getVariable(true), columnName); } if (endNonPrimitiveIf) { builder.endControlFlow(); } return builder.build(); } } @Override public CodeBlock getToModelMethod() { checkNeedsReferences(); if (nonModelColumn) { return super.getToModelMethod(); } else { CodeBlock.Builder builder = CodeBlock.builder(); String statement = columnAccess .getColumnAccessString(elementTypeName, elementName, elementName, ModelUtils.getVariable(true), true, true); String finalAccessStatement = getFinalAccessStatement(builder, true, statement); builder.beginControlFlow("if ($L != null)", finalAccessStatement); if (!isModelContainer) { CodeBlock.Builder modelContainerRetrieval = CodeBlock.builder(); modelContainerRetrieval.add("$L.getContainerAdapter($T.class).toModel($L)", ClassNames.FLOW_MANAGER, referencedTableClassName, finalAccessStatement); builder.addStatement(columnAccess.setColumnAccessString(elementTypeName, elementName, elementName, false, ModelUtils.getVariable(false), modelContainerRetrieval.build(), true)); } else { builder.addStatement(columnAccess.setColumnAccessString(elementTypeName, elementName, elementName, false, ModelUtils.getVariable(false), CodeBlock.builder().add("new $T($L)", elementTypeName, finalAccessStatement).build(), true)); } builder.endControlFlow(); return builder.build(); } } String getFinalAccessStatement(CodeBlock.Builder codeBuilder, boolean isModelContainerAdapter, String statement) { String finalAccessStatement = statement; if (columnAccess instanceof TypeConverterAccess || columnAccess instanceof ModelContainerAccess || isModelContainerAdapter) { finalAccessStatement = getRefName(); TypeName typeName; if (columnAccess instanceof TypeConverterAccess) { typeName = ((TypeConverterAccess) columnAccess).typeConverterDefinition.getDbTypeName(); } else if (columnAccess instanceof ModelContainerAccess) { typeName = ModelUtils.getModelContainerType(manager, referencedTableClassName); } else { if (isModelContainer || isModel) { typeName = ModelUtils.getModelContainerType(manager, referencedTableClassName); statement = ModelUtils.getVariable(isModelContainerAdapter) + ".getInstance(" + statement + ", " + referencedTableClassName + ".class)"; } else { typeName = referencedTableClassName; } } codeBuilder.addStatement("$T $L = $L", typeName, finalAccessStatement, statement); } return finalAccessStatement; } String getForeignKeyReferenceAccess(boolean isModelContainerAdapter, String statement) { if (columnAccess instanceof TypeConverterAccess || columnAccess instanceof ModelContainerAccess || isModelContainerAdapter) { return getRefName(); } else { return statement; } } public String getRefName() { return "ref" + elementName; } public List<ForeignKeyReferenceDefinition> getForeignKeyReferenceDefinitionList() { checkNeedsReferences(); return foreignKeyReferenceDefinitionList; } /** * If {@link ForeignKey} has no {@link ForeignKeyReference}s, we use the primary key the referenced * table. We do this post-evaluation so all of the {@link TableDefinition} can be generated. */ private void checkNeedsReferences() { TableDefinition referencedTableDefinition = manager.getTableDefinition(tableDefinition.databaseTypeName, referencedTableClassName); if (referencedTableDefinition == null) { manager.logError("Could not find the referenced table definition %1s from %1s. Ensure it exists in the same" + "database %1s", referencedTableClassName, tableDefinition.tableName, tableDefinition.databaseTypeName); } else { if (needsReferences) { List<ColumnDefinition> primaryColumns = referencedTableDefinition.getPrimaryColumnDefinitions(); for (ColumnDefinition primaryColumn : primaryColumns) { ForeignKeyReferenceDefinition foreignKeyReferenceDefinition = new ForeignKeyReferenceDefinition(manager, elementName, primaryColumn, columnAccess, this); foreignKeyReferenceDefinitionList.add(foreignKeyReferenceDefinition); } if (nonModelColumn) { columnName = foreignKeyReferenceDefinitionList.get(0).columnName; } needsReferences = false; } } } }
dbflow-processor/src/main/java/com/raizlabs/android/dbflow/processor/definition/column/ForeignKeyColumnDefinition.java
package com.raizlabs.android.dbflow.processor.definition.column; import com.raizlabs.android.dbflow.annotation.Column; import com.raizlabs.android.dbflow.annotation.ForeignKey; import com.raizlabs.android.dbflow.annotation.ForeignKeyAction; import com.raizlabs.android.dbflow.annotation.ForeignKeyReference; import com.raizlabs.android.dbflow.processor.ClassNames; import com.raizlabs.android.dbflow.processor.ProcessorUtils; import com.raizlabs.android.dbflow.processor.definition.TableDefinition; import com.raizlabs.android.dbflow.processor.definition.method.BindToContentValuesMethod; import com.raizlabs.android.dbflow.processor.definition.method.BindToStatementMethod; import com.raizlabs.android.dbflow.processor.definition.method.LoadFromCursorMethod; import com.raizlabs.android.dbflow.processor.model.ProcessorManager; import com.raizlabs.android.dbflow.processor.utils.ModelUtils; import com.raizlabs.android.dbflow.processor.utils.StringUtils; import com.raizlabs.android.dbflow.sql.QueryBuilder; import com.squareup.javapoet.ClassName; import com.squareup.javapoet.CodeBlock; import com.squareup.javapoet.FieldSpec; import com.squareup.javapoet.MethodSpec; import com.squareup.javapoet.ParameterizedTypeName; import com.squareup.javapoet.TypeName; import com.squareup.javapoet.TypeSpec; import java.util.ArrayList; import java.util.List; import java.util.concurrent.atomic.AtomicInteger; import javax.lang.model.element.Element; import javax.lang.model.element.Modifier; import javax.lang.model.element.TypeElement; import javax.lang.model.type.MirroredTypeException; /** * Description: */ public class ForeignKeyColumnDefinition extends ColumnDefinition { public final List<ForeignKeyReferenceDefinition> foreignKeyReferenceDefinitionList = new ArrayList<>(); public final TableDefinition tableDefinition; public ClassName referencedTableClassName; public ForeignKeyAction onDelete; public ForeignKeyAction onUpdate; public boolean isModelContainer; public boolean isModel; public boolean needsReferences; public boolean nonModelColumn; public boolean saveForeignKeyModel; public ForeignKeyColumnDefinition(ProcessorManager manager, TableDefinition tableDefinition, Element typeElement, boolean isPackagePrivate) { super(manager, typeElement, tableDefinition, isPackagePrivate); this.tableDefinition = tableDefinition; ForeignKey foreignKey = typeElement.getAnnotation(ForeignKey.class); onUpdate = foreignKey.onUpdate(); onDelete = foreignKey.onDelete(); try { foreignKey.tableClass(); } catch (MirroredTypeException mte) { referencedTableClassName = ClassName.get(manager.getElements().getTypeElement(mte.getTypeMirror().toString())); } // hopefully intentionally left blank if (referencedTableClassName.equals(TypeName.OBJECT)) { if (elementTypeName instanceof ParameterizedTypeName) { List<TypeName> args = ((ParameterizedTypeName) elementTypeName).typeArguments; if (args.size() > 0) { referencedTableClassName = ClassName.bestGuess(args.get(0).toString()); isModelContainer = true; } } else { referencedTableClassName = ClassName.bestGuess(elementTypeName.toString()); } } if (referencedTableClassName == null) { manager.logError("Referenced was null for %1s within %1s", typeElement, elementTypeName); } TypeElement element = manager.getElements().getTypeElement( manager.getTypeUtils().erasure(typeElement.asType()).toString()); isModel = ProcessorUtils.implementsClass(manager.getProcessingEnvironment(), ClassNames.MODEL.toString(), element); isModelContainer = isModelContainer || ProcessorUtils.implementsClass(manager.getProcessingEnvironment(), ClassNames.MODEL_CONTAINER.toString(), element); nonModelColumn = !isModel && !isModelContainer; saveForeignKeyModel = foreignKey.saveForeignKeyModel(); // we need to recheck for this instance if (columnAccess instanceof TypeConverterAccess) { if (typeElement.getModifiers().contains(Modifier.PRIVATE)) { boolean useIs = elementTypeName.box().equals(TypeName.BOOLEAN.box()) && tableDefinition.useIsForPrivateBooleans; columnAccess = new PrivateColumnAccess(typeElement.getAnnotation(Column.class), useIs); } else { columnAccess = new SimpleColumnAccess(); } } ForeignKeyReference[] references = foreignKey.references(); if (references.length == 0) { // no references specified we will delegate references call to post-evaluation needsReferences = true; } else { for (ForeignKeyReference reference : references) { ForeignKeyReferenceDefinition referenceDefinition = new ForeignKeyReferenceDefinition(manager, elementName, reference, columnAccess, this); // TODO: add validation foreignKeyReferenceDefinitionList.add(referenceDefinition); } } } @Override public void addPropertyDefinition(TypeSpec.Builder typeBuilder, TypeName tableClassName) { checkNeedsReferences(); for (ForeignKeyReferenceDefinition reference : foreignKeyReferenceDefinitionList) { TypeName propParam; if (reference.columnClassName.isPrimitive() && !reference.columnClassName.equals(TypeName.BOOLEAN)) { propParam = ClassName.get(ClassNames.PROPERTY_PACKAGE, StringUtils.capitalize(reference.columnClassName.toString()) + "Property"); } else { propParam = ParameterizedTypeName.get(ClassNames.PROPERTY, reference.columnClassName.box()); } typeBuilder.addField(FieldSpec.builder(propParam, reference.columnName, Modifier.PUBLIC, Modifier.STATIC, Modifier.FINAL) .initializer("new $T($T.class, $S)", propParam, tableClassName, reference.columnName).build()); } } @Override public void addPropertyCase(MethodSpec.Builder methodBuilder) { checkNeedsReferences(); for (ForeignKeyReferenceDefinition reference : foreignKeyReferenceDefinitionList) { methodBuilder.beginControlFlow("case $S: ", reference.columnName); methodBuilder.addStatement("return $L", reference.columnName); methodBuilder.endControlFlow(); } } @Override public CodeBlock getInsertStatementColumnName() { checkNeedsReferences(); CodeBlock.Builder builder = CodeBlock.builder(); for (int i = 0; i < foreignKeyReferenceDefinitionList.size(); i++) { if (i > 0) { builder.add(","); } ForeignKeyReferenceDefinition referenceDefinition = foreignKeyReferenceDefinitionList.get(i); builder.add("$L", QueryBuilder.quote(referenceDefinition.columnName)); } return builder.build(); } @Override public CodeBlock getInsertStatementValuesString() { checkNeedsReferences(); CodeBlock.Builder builder = CodeBlock.builder(); for (int i = 0; i < foreignKeyReferenceDefinitionList.size(); i++) { if (i > 0) { builder.add(","); } builder.add("?"); } return builder.build(); } @Override public CodeBlock getCreationName() { checkNeedsReferences(); CodeBlock.Builder builder = CodeBlock.builder(); for (int i = 0; i < foreignKeyReferenceDefinitionList.size(); i++) { if (i > 0) { builder.add(" ,"); } ForeignKeyReferenceDefinition referenceDefinition = foreignKeyReferenceDefinitionList.get(i); builder.add(referenceDefinition.getCreationStatement()); } return builder.build(); } @Override public CodeBlock getContentValuesStatement(boolean isModelContainerAdapter) { if (nonModelColumn) { return super.getContentValuesStatement(isModelContainerAdapter); } else { checkNeedsReferences(); CodeBlock.Builder builder = CodeBlock.builder(); String statement = columnAccess .getColumnAccessString(elementTypeName, elementName, elementName, ModelUtils.getVariable(isModelContainerAdapter), isModelContainerAdapter, false); String finalAccessStatement = getFinalAccessStatement(builder, isModelContainerAdapter, statement); builder.beginControlFlow("if ($L != null)", finalAccessStatement); CodeBlock.Builder elseBuilder = CodeBlock.builder(); for (ForeignKeyReferenceDefinition referenceDefinition : foreignKeyReferenceDefinitionList) { builder.add(referenceDefinition.getContentValuesStatement(isModelContainerAdapter)); elseBuilder.addStatement("$L.putNull($S)", BindToContentValuesMethod.PARAM_CONTENT_VALUES, QueryBuilder.quote(referenceDefinition.columnName)); } if (saveForeignKeyModel) { builder.addStatement("$L.save()", finalAccessStatement); } builder.nextControlFlow("else") .add(elseBuilder.build()) .endControlFlow(); return builder.build(); } } @Override public CodeBlock getSQLiteStatementMethod(AtomicInteger index, boolean isModelContainerAdapter) { if (nonModelColumn) { return super.getSQLiteStatementMethod(index, isModelContainerAdapter); } else { checkNeedsReferences(); CodeBlock.Builder builder = CodeBlock.builder(); String statement = columnAccess .getColumnAccessString(elementTypeName, elementName, elementName, ModelUtils.getVariable(isModelContainerAdapter), isModelContainerAdapter, true); String finalAccessStatement = getFinalAccessStatement(builder, isModelContainerAdapter, statement); builder.beginControlFlow("if ($L != null)", finalAccessStatement); CodeBlock.Builder elseBuilder = CodeBlock.builder(); for (int i = 0; i < foreignKeyReferenceDefinitionList.size(); i++) { if (i > 0) { index.incrementAndGet(); } ForeignKeyReferenceDefinition referenceDefinition = foreignKeyReferenceDefinitionList.get(i); builder.add(referenceDefinition.getSQLiteStatementMethod(index, isModelContainerAdapter)); elseBuilder.addStatement("$L.bindNull($L)", BindToStatementMethod.PARAM_STATEMENT, index.intValue() + " + " + BindToStatementMethod.PARAM_START); } if (saveForeignKeyModel) { builder.addStatement("$L.save()", finalAccessStatement); } builder.nextControlFlow("else") .add(elseBuilder.build()) .endControlFlow(); return builder.build(); } } @Override public CodeBlock getLoadFromCursorMethod(boolean isModelContainerAdapter, boolean putNullForContainerAdapter, boolean endNonPrimitiveIf) { if (nonModelColumn) { return super.getLoadFromCursorMethod(isModelContainerAdapter, putNullForContainerAdapter, endNonPrimitiveIf); } else { checkNeedsReferences(); CodeBlock.Builder builder = CodeBlock.builder() .add("//// Only load model if references match, for efficiency\n"); CodeBlock.Builder ifNullBuilder = CodeBlock.builder() .add("if ("); CodeBlock.Builder selectBuilder = CodeBlock.builder(); for (int i = 0; i < foreignKeyReferenceDefinitionList.size(); i++) { ForeignKeyReferenceDefinition referenceDefinition = foreignKeyReferenceDefinitionList.get(i); String indexName = "index" + referenceDefinition.columnName; builder.addStatement("int $L = $L.getColumnIndex($S)", indexName, LoadFromCursorMethod.PARAM_CURSOR, referenceDefinition.columnName); if (i > 0) { ifNullBuilder.add(" && "); } ifNullBuilder.add("$L != -1 && !$L.isNull($L)", indexName, LoadFromCursorMethod.PARAM_CURSOR, indexName); // TODO: respect separator here. selectBuilder.add("\n.and($L.$L.eq($L))", ClassName.get(referencedTableClassName.packageName(), referencedTableClassName.simpleName() + "_" + TableDefinition.DBFLOW_TABLE_TAG), referenceDefinition.foreignColumnName, CodeBlock.builder().add("$L.$L($L)", LoadFromCursorMethod.PARAM_CURSOR, DefinitionUtils.getLoadFromCursorMethodString(referenceDefinition.columnClassName, referenceDefinition.columnAccess), indexName).build()); } ifNullBuilder.add(")"); builder.beginControlFlow(ifNullBuilder.build().toString()); CodeBlock.Builder initializer = CodeBlock.builder(); initializer.add("new $T().from($T.class).where()", ClassNames.SELECT, referencedTableClassName) .add(selectBuilder.build()); if (!isModelContainerAdapter && !isModelContainer) { initializer.add(".querySingle()"); } else { if (isModelContainerAdapter) { initializer.add(".queryModelContainer($L.getInstance($L.newDataInstance(), $T.class)).getData()", ModelUtils.getVariable(true), ModelUtils.getVariable(true), referencedTableClassName); } else { initializer.add(".queryModelContainer(new $T($T.class))", elementTypeName, referencedTableClassName); } } builder.addStatement(columnAccess.setColumnAccessString(elementTypeName, elementName, elementName, isModelContainerAdapter, ModelUtils.getVariable(isModelContainerAdapter), initializer.build(), false)); boolean putDefaultValue = putNullForContainerAdapter; if (putContainerDefaultValue != putDefaultValue && isModelContainerAdapter) { putDefaultValue = putContainerDefaultValue; } if (putDefaultValue) { builder.nextControlFlow("else"); builder.addStatement("$L.putDefault($S)", ModelUtils.getVariable(true), columnName); } if (endNonPrimitiveIf) { builder.endControlFlow(); } return builder.build(); } } @Override public CodeBlock getToModelMethod() { checkNeedsReferences(); if (nonModelColumn) { return super.getToModelMethod(); } else { CodeBlock.Builder builder = CodeBlock.builder(); String statement = columnAccess .getColumnAccessString(elementTypeName, elementName, elementName, ModelUtils.getVariable(true), true, true); String finalAccessStatement = getFinalAccessStatement(builder, true, statement); builder.beginControlFlow("if ($L != null)", finalAccessStatement); if (!isModelContainer) { CodeBlock.Builder modelContainerRetrieval = CodeBlock.builder(); modelContainerRetrieval.add("$L.getContainerAdapter($T.class).toModel($L)", ClassNames.FLOW_MANAGER, referencedTableClassName, finalAccessStatement); builder.addStatement(columnAccess.setColumnAccessString(elementTypeName, elementName, elementName, false, ModelUtils.getVariable(false), modelContainerRetrieval.build(), true)); } else { builder.addStatement(columnAccess.setColumnAccessString(elementTypeName, elementName, elementName, false, ModelUtils.getVariable(false), CodeBlock.builder().add("new $T($L)", elementTypeName, finalAccessStatement).build(), true)); } builder.endControlFlow(); return builder.build(); } } String getFinalAccessStatement(CodeBlock.Builder codeBuilder, boolean isModelContainerAdapter, String statement) { String finalAccessStatement = statement; if (columnAccess instanceof TypeConverterAccess || columnAccess instanceof ModelContainerAccess || isModelContainerAdapter) { finalAccessStatement = getRefName(); TypeName typeName; if (columnAccess instanceof TypeConverterAccess) { typeName = ((TypeConverterAccess) columnAccess).typeConverterDefinition.getDbTypeName(); } else if (columnAccess instanceof ModelContainerAccess) { typeName = ModelUtils.getModelContainerType(manager, referencedTableClassName); } else { if (isModelContainer || isModel) { typeName = ModelUtils.getModelContainerType(manager, referencedTableClassName); statement = ModelUtils.getVariable(isModelContainerAdapter) + ".getInstance(" + statement + ", " + referencedTableClassName + ".class)"; } else { typeName = referencedTableClassName; } } codeBuilder.addStatement("$T $L = $L", typeName, finalAccessStatement, statement); } return finalAccessStatement; } String getForeignKeyReferenceAccess(boolean isModelContainerAdapter, String statement) { if (columnAccess instanceof TypeConverterAccess || columnAccess instanceof ModelContainerAccess || isModelContainerAdapter) { return getRefName(); } else { return statement; } } public String getRefName() { return "ref" + elementName; } public List<ForeignKeyReferenceDefinition> getForeignKeyReferenceDefinitionList() { checkNeedsReferences(); return foreignKeyReferenceDefinitionList; } /** * If {@link ForeignKey} has no {@link ForeignKeyReference}s, we use the primary key the referenced * table. We do this post-evaluation so all of the {@link TableDefinition} can be generated. */ private void checkNeedsReferences() { TableDefinition referencedTableDefinition = manager.getTableDefinition(tableDefinition.databaseTypeName, referencedTableClassName); if (referencedTableDefinition == null) { manager.logError("Could not find the referenced table definition %1s from %1s. Ensure it exists in the same" + "database %1s", referencedTableClassName, tableDefinition.tableName, tableDefinition.databaseTypeName); } else { if (needsReferences) { List<ColumnDefinition> primaryColumns = referencedTableDefinition.getPrimaryColumnDefinitions(); for (ColumnDefinition primaryColumn : primaryColumns) { ForeignKeyReferenceDefinition foreignKeyReferenceDefinition = new ForeignKeyReferenceDefinition(manager, elementName, primaryColumn, columnAccess, this); foreignKeyReferenceDefinitionList.add(foreignKeyReferenceDefinition); } if (nonModelColumn) { columnName = foreignKeyReferenceDefinitionList.get(0).columnName; } needsReferences = false; } } } }
During generation of the insert statement for a foreign key column, the related model should be saved before it's ID parameter is bound. This allows the ID to be the generated (in the case of inserting a related object with auto increment primary key) before it is used to the parameter list. Fixes #577 fixes #377
dbflow-processor/src/main/java/com/raizlabs/android/dbflow/processor/definition/column/ForeignKeyColumnDefinition.java
During generation of the insert statement for a foreign key column, the related model should be saved before it's ID parameter is bound. This allows the ID to be the generated (in the case of inserting a related object with auto increment primary key) before it is used to the parameter list. Fixes #577 fixes #377
<ide><path>bflow-processor/src/main/java/com/raizlabs/android/dbflow/processor/definition/column/ForeignKeyColumnDefinition.java <ide> ModelUtils.getVariable(isModelContainerAdapter), isModelContainerAdapter, true); <ide> String finalAccessStatement = getFinalAccessStatement(builder, isModelContainerAdapter, statement); <ide> builder.beginControlFlow("if ($L != null)", finalAccessStatement); <add> <add> if (saveForeignKeyModel) { <add> builder.addStatement("$L.save()", finalAccessStatement); <add> } <add> <ide> CodeBlock.Builder elseBuilder = CodeBlock.builder(); <ide> for (int i = 0; i < foreignKeyReferenceDefinitionList.size(); i++) { <ide> if (i > 0) { <ide> ForeignKeyReferenceDefinition referenceDefinition = foreignKeyReferenceDefinitionList.get(i); <ide> builder.add(referenceDefinition.getSQLiteStatementMethod(index, isModelContainerAdapter)); <ide> elseBuilder.addStatement("$L.bindNull($L)", BindToStatementMethod.PARAM_STATEMENT, index.intValue() + " + " + BindToStatementMethod.PARAM_START); <del> } <del> <del> if (saveForeignKeyModel) { <del> builder.addStatement("$L.save()", finalAccessStatement); <ide> } <ide> <ide> builder.nextControlFlow("else")
Java
bsd-3-clause
0316bec713294ae39496c682f52b065af4cf89aa
0
jMonkeyEngine/jmonkeyengine,OpenGrabeso/jmonkeyengine,GreenCubes/jmonkeyengine,delftsre/jmonkeyengine,olafmaas/jmonkeyengine,weilichuang/jmonkeyengine,InShadow/jmonkeyengine,atomixnmc/jmonkeyengine,g-rocket/jmonkeyengine,phr00t/jmonkeyengine,d235j/jmonkeyengine,shurun19851206/jMonkeyEngine,skapi1992/jmonkeyengine,rbottema/jmonkeyengine,danteinforno/jmonkeyengine,atomixnmc/jmonkeyengine,g-rocket/jmonkeyengine,skapi1992/jmonkeyengine,InShadow/jmonkeyengine,rbottema/jmonkeyengine,aaronang/jmonkeyengine,zzuegg/jmonkeyengine,GreenCubes/jmonkeyengine,mbenson/jmonkeyengine,olafmaas/jmonkeyengine,shurun19851206/jMonkeyEngine,yetanotherindie/jMonkey-Engine,atomixnmc/jmonkeyengine,delftsre/jmonkeyengine,yetanotherindie/jMonkey-Engine,amit2103/jmonkeyengine,mbenson/jmonkeyengine,bertleft/jmonkeyengine,nickschot/jmonkeyengine,wrvangeest/jmonkeyengine,jMonkeyEngine/jmonkeyengine,skapi1992/jmonkeyengine,delftsre/jmonkeyengine,rbottema/jmonkeyengine,rbottema/jmonkeyengine,bertleft/jmonkeyengine,yetanotherindie/jMonkey-Engine,jMonkeyEngine/jmonkeyengine,amit2103/jmonkeyengine,mbenson/jmonkeyengine,aaronang/jmonkeyengine,zzuegg/jmonkeyengine,Georgeto/jmonkeyengine,OpenGrabeso/jmonkeyengine,tr0k/jmonkeyengine,OpenGrabeso/jmonkeyengine,d235j/jmonkeyengine,atomixnmc/jmonkeyengine,OpenGrabeso/jmonkeyengine,InShadow/jmonkeyengine,weilichuang/jmonkeyengine,mbenson/jmonkeyengine,g-rocket/jmonkeyengine,sandervdo/jmonkeyengine,jMonkeyEngine/jmonkeyengine,weilichuang/jmonkeyengine,danteinforno/jmonkeyengine,aaronang/jmonkeyengine,zzuegg/jmonkeyengine,davidB/jmonkeyengine,olafmaas/jmonkeyengine,g-rocket/jmonkeyengine,bsmr-java/jmonkeyengine,d235j/jmonkeyengine,d235j/jmonkeyengine,nickschot/jmonkeyengine,delftsre/jmonkeyengine,shurun19851206/jMonkeyEngine,amit2103/jmonkeyengine,amit2103/jmonkeyengine,yetanotherindie/jMonkey-Engine,shurun19851206/jMonkeyEngine,bsmr-java/jmonkeyengine,Georgeto/jmonkeyengine,yetanotherindie/jMonkey-Engine,aaronang/jmonkeyengine,bertleft/jmonkeyengine,sandervdo/jmonkeyengine,Georgeto/jmonkeyengine,yetanotherindie/jMonkey-Engine,shurun19851206/jMonkeyEngine,davidB/jmonkeyengine,OpenGrabeso/jmonkeyengine,Georgeto/jmonkeyengine,mbenson/jmonkeyengine,danteinforno/jmonkeyengine,g-rocket/jmonkeyengine,danteinforno/jmonkeyengine,tr0k/jmonkeyengine,InShadow/jmonkeyengine,tr0k/jmonkeyengine,amit2103/jmonkeyengine,phr00t/jmonkeyengine,g-rocket/jmonkeyengine,wrvangeest/jmonkeyengine,atomixnmc/jmonkeyengine,davidB/jmonkeyengine,wrvangeest/jmonkeyengine,tr0k/jmonkeyengine,bsmr-java/jmonkeyengine,skapi1992/jmonkeyengine,nickschot/jmonkeyengine,davidB/jmonkeyengine,wrvangeest/jmonkeyengine,weilichuang/jmonkeyengine,GreenCubes/jmonkeyengine,shurun19851206/jMonkeyEngine,mbenson/jmonkeyengine,sandervdo/jmonkeyengine,OpenGrabeso/jmonkeyengine,danteinforno/jmonkeyengine,bertleft/jmonkeyengine,sandervdo/jmonkeyengine,weilichuang/jmonkeyengine,d235j/jmonkeyengine,amit2103/jmonkeyengine,weilichuang/jmonkeyengine,GreenCubes/jmonkeyengine,d235j/jmonkeyengine,olafmaas/jmonkeyengine,Georgeto/jmonkeyengine,davidB/jmonkeyengine,phr00t/jmonkeyengine,davidB/jmonkeyengine,danteinforno/jmonkeyengine,zzuegg/jmonkeyengine,phr00t/jmonkeyengine,atomixnmc/jmonkeyengine,Georgeto/jmonkeyengine,nickschot/jmonkeyengine,bsmr-java/jmonkeyengine
package com.jme3.util; import com.jme3.asset.AssetManager; import com.jme3.asset.TextureKey; import com.jme3.bounding.BoundingSphere; import com.jme3.material.Material; import com.jme3.math.Vector3f; import com.jme3.renderer.queue.RenderQueue.Bucket; import com.jme3.scene.Geometry; import com.jme3.scene.Spatial; import com.jme3.scene.shape.Sphere; import com.jme3.texture.Image; import com.jme3.texture.Image.Format; import com.jme3.texture.Texture; import com.jme3.texture.TextureCubeMap; public class SkyFactory { public static Spatial createSky(AssetManager assetManager, Texture texture, Vector3f normalScale, boolean sphereMap){ return createSky(assetManager, texture, normalScale, sphereMap, 10); } public static Spatial createSky(AssetManager assetManager, Texture texture, Vector3f normalScale, boolean sphereMap, int sphereRadius){ if (texture == null) throw new IllegalArgumentException("texture cannot be null"); final Sphere sphereMesh = new Sphere(10, 10, sphereRadius, false, true); Geometry sky = new Geometry("Sky", sphereMesh); sky.setQueueBucket(Bucket.Sky); sky.setCullHint(Spatial.CullHint.Never); sky.setModelBound(new BoundingSphere(Float.POSITIVE_INFINITY, Vector3f.ZERO)); Material skyMat = new Material(assetManager, "Common/MatDefs/Misc/Sky.j3md"); skyMat.setVector3("NormalScale", normalScale); if (sphereMap){ skyMat.setBoolean("SphereMap", sphereMap); }else if (!(texture instanceof TextureCubeMap)){ // make sure its a cubemap Image img = texture.getImage(); texture = new TextureCubeMap(); texture.setImage(img); } skyMat.setTexture("Texture", texture); sky.setMaterial(skyMat); return sky; } private static void checkImage(Image image){ // if (image.getDepth() != 1) // throw new IllegalArgumentException("3D/Array images not allowed"); if (image.getWidth() != image.getHeight()) throw new IllegalArgumentException("Image width and height must be the same"); if (image.getMultiSamples() != 1) throw new IllegalArgumentException("Multisample textures not allowed"); } private static void checkImagesForCubeMap(Image ... images){ if (images.length == 1) return; Format fmt = images[0].getFormat(); int width = images[0].getWidth(); int size = images[0].getData(0).capacity(); checkImage(images[0]); for (int i = 1; i < images.length; i++){ Image image = images[i]; checkImage(images[i]); if (image.getFormat() != fmt) throw new IllegalArgumentException("Images must have same format"); if (image.getWidth() != width) throw new IllegalArgumentException("Images must have same resolution"); if (image.getData(0).capacity() != size) throw new IllegalArgumentException("Images must have same size"); } } public static Spatial createSky(AssetManager assetManager, Texture west, Texture east, Texture north, Texture south, Texture up, Texture down, Vector3f normalScale){ return createSky(assetManager, west, east, north, south, up, down, normalScale, 10); } public static Spatial createSky(AssetManager assetManager, Texture west, Texture east, Texture north, Texture south, Texture up, Texture down, Vector3f normalScale, int sphereRadius){ final Sphere sphereMesh = new Sphere(10, 10, sphereRadius, false, true); Geometry sky = new Geometry("Sky", sphereMesh); sky.setQueueBucket(Bucket.Sky); sky.setCullHint(Spatial.CullHint.Never); sky.setModelBound(new BoundingSphere(Float.POSITIVE_INFINITY, Vector3f.ZERO)); Image westImg = west.getImage(); Image eastImg = east.getImage(); Image northImg = north.getImage(); Image southImg = south.getImage(); Image upImg = up.getImage(); Image downImg = down.getImage(); checkImagesForCubeMap(westImg, eastImg, northImg, southImg, upImg, downImg); Image cubeImage = new Image(westImg.getFormat(), westImg.getWidth(), westImg.getHeight(), null); cubeImage.addData(westImg.getData(0)); cubeImage.addData(eastImg.getData(0)); cubeImage.addData(downImg.getData(0)); cubeImage.addData(upImg.getData(0)); cubeImage.addData(southImg.getData(0)); cubeImage.addData(northImg.getData(0)); TextureCubeMap cubeMap = new TextureCubeMap(cubeImage); cubeMap.setAnisotropicFilter(0); cubeMap.setMagFilter(Texture.MagFilter.Bilinear); cubeMap.setMinFilter(Texture.MinFilter.NearestNoMipMaps); cubeMap.setWrap(Texture.WrapMode.EdgeClamp); Material skyMat = new Material(assetManager, "Common/MatDefs/Misc/Sky.j3md"); skyMat.setTexture("Texture", cubeMap); skyMat.setVector3("NormalScale", normalScale); sky.setMaterial(skyMat); return sky; } public static Spatial createSky(AssetManager assetManager, Texture west, Texture east, Texture north, Texture south, Texture up, Texture down){ return createSky(assetManager, west, east, north, south, up, down, Vector3f.UNIT_XYZ); } public static Spatial createSky(AssetManager assetManager, Texture texture, boolean sphereMap){ return createSky(assetManager, texture, Vector3f.UNIT_XYZ, sphereMap); } public static Spatial createSky(AssetManager assetManager, String textureName, boolean sphereMap){ TextureKey key = new TextureKey(textureName, true); key.setGenerateMips(true); key.setAsCube(!sphereMap); Texture tex = assetManager.loadTexture(key); return createSky(assetManager, tex, sphereMap); } }
engine/src/core/com/jme3/util/SkyFactory.java
package com.jme3.util; import com.jme3.asset.AssetManager; import com.jme3.asset.TextureKey; import com.jme3.bounding.BoundingSphere; import com.jme3.material.Material; import com.jme3.math.Vector3f; import com.jme3.renderer.queue.RenderQueue.Bucket; import com.jme3.scene.Geometry; import com.jme3.scene.Spatial; import com.jme3.scene.shape.Sphere; import com.jme3.texture.Image; import com.jme3.texture.Image.Format; import com.jme3.texture.Texture; import com.jme3.texture.TextureCubeMap; public class SkyFactory { private static final Sphere sphereMesh = new Sphere(10, 10, 10, false, true); public static Spatial createSky(AssetManager assetManager, Texture texture, Vector3f normalScale, boolean sphereMap){ if (texture == null) throw new IllegalArgumentException("texture cannot be null"); Geometry sky = new Geometry("Sky", sphereMesh); sky.setQueueBucket(Bucket.Sky); sky.setCullHint(Spatial.CullHint.Never); sky.setModelBound(new BoundingSphere(Float.POSITIVE_INFINITY, Vector3f.ZERO)); Material skyMat = new Material(assetManager, "Common/MatDefs/Misc/Sky.j3md"); skyMat.setVector3("NormalScale", normalScale); if (sphereMap){ skyMat.setBoolean("SphereMap", sphereMap); }else if (!(texture instanceof TextureCubeMap)){ // make sure its a cubemap Image img = texture.getImage(); texture = new TextureCubeMap(); texture.setImage(img); } skyMat.setTexture("Texture", texture); sky.setMaterial(skyMat); return sky; } private static void checkImage(Image image){ // if (image.getDepth() != 1) // throw new IllegalArgumentException("3D/Array images not allowed"); if (image.getWidth() != image.getHeight()) throw new IllegalArgumentException("Image width and height must be the same"); if (image.getMultiSamples() != 1) throw new IllegalArgumentException("Multisample textures not allowed"); } private static void checkImagesForCubeMap(Image ... images){ if (images.length == 1) return; Format fmt = images[0].getFormat(); int width = images[0].getWidth(); int size = images[0].getData(0).capacity(); checkImage(images[0]); for (int i = 1; i < images.length; i++){ Image image = images[i]; checkImage(images[i]); if (image.getFormat() != fmt) throw new IllegalArgumentException("Images must have same format"); if (image.getWidth() != width) throw new IllegalArgumentException("Images must have same resolution"); if (image.getData(0).capacity() != size) throw new IllegalArgumentException("Images must have same size"); } } public static Spatial createSky(AssetManager assetManager, Texture west, Texture east, Texture north, Texture south, Texture up, Texture down, Vector3f normalScale){ Geometry sky = new Geometry("Sky", sphereMesh); sky.setQueueBucket(Bucket.Sky); sky.setCullHint(Spatial.CullHint.Never); sky.setModelBound(new BoundingSphere(Float.POSITIVE_INFINITY, Vector3f.ZERO)); Image westImg = west.getImage(); Image eastImg = east.getImage(); Image northImg = north.getImage(); Image southImg = south.getImage(); Image upImg = up.getImage(); Image downImg = down.getImage(); checkImagesForCubeMap(westImg, eastImg, northImg, southImg, upImg, downImg); Image cubeImage = new Image(westImg.getFormat(), westImg.getWidth(), westImg.getHeight(), null); cubeImage.addData(westImg.getData(0)); cubeImage.addData(eastImg.getData(0)); cubeImage.addData(downImg.getData(0)); cubeImage.addData(upImg.getData(0)); cubeImage.addData(southImg.getData(0)); cubeImage.addData(northImg.getData(0)); TextureCubeMap cubeMap = new TextureCubeMap(cubeImage); cubeMap.setAnisotropicFilter(0); cubeMap.setMagFilter(Texture.MagFilter.Bilinear); cubeMap.setMinFilter(Texture.MinFilter.NearestNoMipMaps); cubeMap.setWrap(Texture.WrapMode.EdgeClamp); Material skyMat = new Material(assetManager, "Common/MatDefs/Misc/Sky.j3md"); skyMat.setTexture("Texture", cubeMap); skyMat.setVector3("NormalScale", normalScale); sky.setMaterial(skyMat); return sky; } public static Spatial createSky(AssetManager assetManager, Texture west, Texture east, Texture north, Texture south, Texture up, Texture down){ return createSky(assetManager, west, east, north, south, up, down, Vector3f.UNIT_XYZ); } public static Spatial createSky(AssetManager assetManager, Texture texture, boolean sphereMap){ return createSky(assetManager, texture, Vector3f.UNIT_XYZ, sphereMap); } public static Spatial createSky(AssetManager assetManager, String textureName, boolean sphereMap){ TextureKey key = new TextureKey(textureName, true); key.setGenerateMips(true); key.setAsCube(!sphereMap); Texture tex = assetManager.loadTexture(key); return createSky(assetManager, tex, sphereMap); } }
SkyFactory : you can now specify the sky sphere radius when creating a sky to avoid near plane clipping when it's set too close to the radius value. see this post http://jmonkeyengine.org/groups/graphics/forum/topic/why-is-the-skybox-culling-when-i-adjust-my-camera-frustum/#post-139378 git-svn-id: f9411aee4f13664f2fc428a5b3e824fe43a079a3@8023 75d07b2b-3a1a-0410-a2c5-0572b91ccdca
engine/src/core/com/jme3/util/SkyFactory.java
SkyFactory : you can now specify the sky sphere radius when creating a sky to avoid near plane clipping when it's set too close to the radius value. see this post http://jmonkeyengine.org/groups/graphics/forum/topic/why-is-the-skybox-culling-when-i-adjust-my-camera-frustum/#post-139378
<ide><path>ngine/src/core/com/jme3/util/SkyFactory.java <ide> <ide> public class SkyFactory { <ide> <del> private static final Sphere sphereMesh = new Sphere(10, 10, 10, false, true); <del> <del> public static Spatial createSky(AssetManager assetManager, Texture texture, Vector3f normalScale, boolean sphereMap){ <add> <add> public static Spatial createSky(AssetManager assetManager, Texture texture, Vector3f normalScale, boolean sphereMap){ <add> return createSky(assetManager, texture, normalScale, sphereMap, 10); <add> } <add> public static Spatial createSky(AssetManager assetManager, Texture texture, Vector3f normalScale, boolean sphereMap, int sphereRadius){ <ide> if (texture == null) <ide> throw new IllegalArgumentException("texture cannot be null"); <add> final Sphere sphereMesh = new Sphere(10, 10, sphereRadius, false, true); <ide> <ide> Geometry sky = new Geometry("Sky", sphereMesh); <ide> sky.setQueueBucket(Bucket.Sky); <ide> } <ide> <ide> public static Spatial createSky(AssetManager assetManager, Texture west, Texture east, Texture north, Texture south, Texture up, Texture down, Vector3f normalScale){ <add> return createSky(assetManager, west, east, north, south, up, down, normalScale, 10); <add> } <add> <add> public static Spatial createSky(AssetManager assetManager, Texture west, Texture east, Texture north, Texture south, Texture up, Texture down, Vector3f normalScale, int sphereRadius){ <add> final Sphere sphereMesh = new Sphere(10, 10, sphereRadius, false, true); <ide> Geometry sky = new Geometry("Sky", sphereMesh); <ide> sky.setQueueBucket(Bucket.Sky); <ide> sky.setCullHint(Spatial.CullHint.Never);
Java
mit
666b5f505aac73e5cb0a24ed467bc1e50bd5b56e
0
icode/ameba-utils
package ameba.util.bean; import org.apache.commons.lang3.ArrayUtils; import java.util.*; /** * @author icode */ public abstract class BeanTransformer<T> { public static final BeanTransformer DEFAULT = new BeanTransformer() { @Override protected Object onTransform(Object obj) { return new BeanMap<>(obj); } }; protected abstract T onTransform(Object obj); protected boolean needTransform(Object obj) { Class clazz = obj.getClass(); return !clazz.isPrimitive() && !clazz.getName().startsWith("java."); } @SuppressWarnings("unchecked") public Object transform(final Object obj) { if (obj != null && !(obj instanceof BeanMap)) { Class clazz = obj.getClass(); if (clazz.isArray()) { return _transform((Object[]) obj); } else if (obj instanceof Map) { return _transform((List) obj); } else if (obj instanceof List) { return _transform((List) obj); } else if (obj instanceof Set) { return _transform((Set) obj); } else if (obj instanceof Collection) { return _transform((Collection) obj); } else if (obj instanceof Iterable) { return _transform((Iterable) obj); } else if (obj instanceof Iterator) { return _transform((Iterator) obj); } else if (needTransform(obj)) { return onTransform(obj); } } return obj; } @SuppressWarnings("unchecked") protected List _transform(final List list) { if (list == null) return null; if (list instanceof BeanList) return list; return new BeanList(list, this); } @SuppressWarnings("unchecked") protected Set _transform(final Set set) { if (set == null) return null; if (set instanceof BeanSet) return set; return new BeanSet<>(set, this); } @SuppressWarnings("unchecked") protected Collection _transform(final Collection collection) { if (collection == null) return null; if (collection instanceof BeanCollection) return collection; return new BeanCollection(collection, this); } protected Object[] _transform(final Object[] array) { Object[] result = new Object[array.length]; for (Object object : array) { ArrayUtils.add(result, transform(object)); } return result; } @SuppressWarnings("unchecked") protected Iterable _transform(final Iterable iterable) { if (iterable == null) return null; if (iterable instanceof BeanIterable) return iterable; return new BeanIterable<>(iterable, this); } @SuppressWarnings("unchecked") protected Iterator _transform(final Iterator iterator) { if (iterator == null) return null; if (iterator instanceof BeanIterator) return iterator; return new BeanIterator(iterator, this); } @SuppressWarnings("unchecked") protected ListIterator _transform(final ListIterator listIterator) { return new BeanListIterator(listIterator, this); } @SuppressWarnings("unchecked") protected BeanMap _transform(final Map map) { return new BeanMap<>(map); } }
src/main/java/ameba/util/bean/BeanTransformer.java
package ameba.util.bean; import org.apache.commons.lang3.ArrayUtils; import java.util.*; /** * @author icode */ public abstract class BeanTransformer<T> { public static final BeanTransformer DEFAULT = new BeanTransformer() { @Override protected Object onTransform(Object obj) { return new BeanMap<>(obj); } }; protected abstract T onTransform(Object obj); protected boolean needTransform(Object obj) { Class clazz = obj.getClass(); return !clazz.isPrimitive() && !clazz.getName().startsWith("java."); } @SuppressWarnings("unchecked") public Object transform(final Object obj) { if (obj != null && !(obj instanceof BeanMap)) { Class clazz = obj.getClass(); if (clazz.isArray()) { return _transform((Object[]) obj); } else if (obj instanceof List) { return _transform((List) obj); } else if (obj instanceof Set) { return _transform((Set) obj); } else if (obj instanceof Collection) { return _transform((Collection) obj); } else if (obj instanceof Iterable) { return _transform((Iterable) obj); } else if (obj instanceof Iterator) { return _transform((Iterator) obj); } else if (needTransform(obj)) { return onTransform(obj); } } return obj; } @SuppressWarnings("unchecked") protected List _transform(final List list) { if (list == null) return null; if (list instanceof BeanList) return list; return new BeanList(list, this); } @SuppressWarnings("unchecked") protected Set _transform(final Set set) { if (set == null) return null; if (set instanceof BeanSet) return set; return new BeanSet<>(set, this); } @SuppressWarnings("unchecked") protected Collection _transform(final Collection collection) { if (collection == null) return null; if (collection instanceof BeanCollection) return collection; return new BeanCollection(collection, this); } protected Object[] _transform(final Object[] array) { Object[] result = new Object[array.length]; for (Object object : array) { ArrayUtils.add(result, transform(object)); } return result; } @SuppressWarnings("unchecked") protected Iterable _transform(final Iterable iterable) { if (iterable == null) return null; if (iterable instanceof BeanIterable) return iterable; return new BeanIterable<>(iterable, this); } @SuppressWarnings("unchecked") protected Iterator _transform(final Iterator iterator) { if (iterator == null) return null; if (iterator instanceof BeanIterator) return iterator; return new BeanIterator(iterator, this); } @SuppressWarnings("unchecked") protected ListIterator _transform(final ListIterator listIterator) { return new BeanListIterator(listIterator, this); } }
增强bean transformer
src/main/java/ameba/util/bean/BeanTransformer.java
增强bean transformer
<ide><path>rc/main/java/ameba/util/bean/BeanTransformer.java <ide> Class clazz = obj.getClass(); <ide> if (clazz.isArray()) { <ide> return _transform((Object[]) obj); <add> } else if (obj instanceof Map) { <add> return _transform((List) obj); <ide> } else if (obj instanceof List) { <ide> return _transform((List) obj); <ide> } else if (obj instanceof Set) { <ide> return new BeanListIterator(listIterator, this); <ide> } <ide> <add> @SuppressWarnings("unchecked") <add> protected BeanMap _transform(final Map map) { <add> return new BeanMap<>(map); <add> } <ide> }
Java
mit
9e373062a1fdec28128ca9d4948afb1806a6f2d1
0
OpenAMEE/amee.platform.api
package com.amee.messaging; import com.amee.messaging.config.ExchangeConfig; import com.amee.messaging.config.MessagingConfig; import com.amee.messaging.config.QueueConfig; import com.rabbitmq.client.Channel; import com.rabbitmq.client.ShutdownSignalException; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import javax.annotation.PostConstruct; import javax.annotation.PreDestroy; import java.io.IOException; public abstract class MessageConsumer implements Runnable, ApplicationContextAware { private final Log log = LogFactory.getLog(getClass()); @Autowired protected MessageService messageService; @Autowired protected MessagingConfig messagingConfig; protected Channel channel; protected Thread thread; protected boolean stopping = false; protected ApplicationContext applicationContext; @PostConstruct public synchronized void start() { log.info("start()"); thread = new Thread(this); thread.start(); } @PreDestroy public synchronized void stop() { log.info("stop()"); stopping = true; if (thread != null) { thread.interrupt(); thread = null; } } public void run() { log.info("run()"); while (!Thread.currentThread().isInterrupted()) { try { log.debug("run() Waiting."); // Wait before first-run and subsequent retries. Thread.sleep(messagingConfig.getRunSleep()); log.debug("run() Starting."); // Start the Consumer and handle the deliveries. configureChannel(); consume(); // We got here if there is no channel or this was stopped. log.debug("run() No channel or stopped."); } catch (IOException e) { log.warn("run() Caught IOException. We'll try restarting the consumer. Message was: " + ((e.getCause() != null) ? e.getCause().getMessage() : e.getMessage())); } catch (ShutdownSignalException e) { log.warn("run() Caught ShutdownSignalException. We'll try restarting the consumer. Message was: " + e.getMessage()); } catch (InterruptedException e) { log.info("run() Interrupted."); closeAndClear(); return; } catch (Exception e) { log.error("run() Caught Exception: " + e.getMessage(), e); } catch (Throwable t) { log.error("run() Caught Throwable: " + t.getMessage(), t); } } } protected void configureChannel() throws IOException { // Ensure the channel is closed & consumer is cleared before starting. closeAndClear(); // Try to get a channel for our configuration. channel = messageService.getChannelAndBind( getExchangeConfig(), getQueueConfig(), getBindingKey()); } protected abstract void consume() throws IOException, InterruptedException; protected synchronized void closeAndClear() { log.debug("closeAndClear()"); if (channel != null) { try { channel.close(); } catch (IOException e) { // Swallow. } catch (ShutdownSignalException e) { // Swallow. } channel = null; } } public abstract ExchangeConfig getExchangeConfig(); public abstract QueueConfig getQueueConfig(); public abstract String getBindingKey(); public void setApplicationContext(ApplicationContext applicationContext) { this.applicationContext = applicationContext; } }
src/main/java/com/amee/messaging/MessageConsumer.java
package com.amee.messaging; import com.amee.messaging.config.ExchangeConfig; import com.amee.messaging.config.MessagingConfig; import com.amee.messaging.config.QueueConfig; import com.rabbitmq.client.Channel; import com.rabbitmq.client.ShutdownSignalException; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import javax.annotation.PostConstruct; import javax.annotation.PreDestroy; import java.io.IOException; public abstract class MessageConsumer implements Runnable, ApplicationContextAware { private final Log log = LogFactory.getLog(getClass()); @Autowired protected MessageService messageService; @Autowired protected MessagingConfig messagingConfig; protected Channel channel; protected Thread thread; protected boolean stopping = false; protected ApplicationContext applicationContext; @PostConstruct public synchronized void start() { log.info("start()"); thread = new Thread(this); thread.start(); } @PreDestroy public synchronized void stop() { log.info("stop()"); stopping = true; if (thread != null) { thread.interrupt(); thread = null; } } public void run() { log.info("run()"); while (!Thread.currentThread().isInterrupted()) { try { log.debug("run() Waiting."); // Wait before first-run and subsequent retries. Thread.sleep(messagingConfig.getRunSleep()); log.debug("run() Starting."); // Start the Consumer and handle the deliveries. configureChannel(); consume(); // We got here if there is no channel or this was stopped. log.debug("run() No channel or stopped."); } catch (IOException e) { log.warn("run() Caught IOException. We'll try restarting the consumer. Message was: " + e.getMessage()); } catch (ShutdownSignalException e) { log.warn("run() Caught ShutdownSignalException. We'll try restarting the consumer. Message was: " + e.getMessage()); } catch (InterruptedException e) { log.info("run() Interrupted."); closeAndClear(); return; } catch (Exception e) { log.error("run() Caught Exception: " + e.getMessage(), e); } catch (Throwable t) { log.error("run() Caught Throwable: " + t.getMessage(), t); } } } protected void configureChannel() throws IOException { // Ensure the channel is closed & consumer is cleared before starting. closeAndClear(); // Try to get a channel for our configuration. channel = messageService.getChannelAndBind( getExchangeConfig(), getQueueConfig(), getBindingKey()); } protected abstract void consume() throws IOException, InterruptedException; protected synchronized void closeAndClear() { log.debug("closeAndClear()"); if (channel != null) { try { channel.close(); } catch (IOException e) { // Swallow. } catch (ShutdownSignalException e) { // Swallow. } channel = null; } } public abstract ExchangeConfig getExchangeConfig(); public abstract QueueConfig getQueueConfig(); public abstract String getBindingKey(); public void setApplicationContext(ApplicationContext applicationContext) { this.applicationContext = applicationContext; } }
PL-1506 - Improved exception handling.
src/main/java/com/amee/messaging/MessageConsumer.java
PL-1506 - Improved exception handling.
<ide><path>rc/main/java/com/amee/messaging/MessageConsumer.java <ide> // We got here if there is no channel or this was stopped. <ide> log.debug("run() No channel or stopped."); <ide> } catch (IOException e) { <del> log.warn("run() Caught IOException. We'll try restarting the consumer. Message was: " + e.getMessage()); <add> log.warn("run() Caught IOException. We'll try restarting the consumer. Message was: " + <add> ((e.getCause() != null) ? e.getCause().getMessage() : e.getMessage())); <ide> } catch (ShutdownSignalException e) { <del> log.warn("run() Caught ShutdownSignalException. We'll try restarting the consumer. Message was: " + e.getMessage()); <add> log.warn("run() Caught ShutdownSignalException. We'll try restarting the consumer. Message was: " + <add> e.getMessage()); <ide> } catch (InterruptedException e) { <ide> log.info("run() Interrupted."); <ide> closeAndClear();
Java
apache-2.0
22fde16fedd17ad1194ca0880b4b607ebe011665
0
apache/tomcat,Nickname0806/Test_Q4,Nickname0806/Test_Q4,Nickname0806/Test_Q4,Nickname0806/Test_Q4,apache/tomcat,apache/tomcat,apache/tomcat,apache/tomcat
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.catalina.manager; import java.io.File; import java.io.IOException; import java.io.PrintWriter; import java.io.StringWriter; import java.text.MessageFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.Date; import java.util.Iterator; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Random; import java.util.Set; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import javax.servlet.http.Part; import org.apache.catalina.Container; import org.apache.catalina.Context; import org.apache.catalina.DistributedManager; import org.apache.catalina.Manager; import org.apache.catalina.Session; import org.apache.catalina.manager.util.BaseSessionComparator; import org.apache.catalina.manager.util.ReverseComparator; import org.apache.catalina.manager.util.SessionUtils; import org.apache.catalina.util.ContextName; import org.apache.catalina.util.RequestUtil; import org.apache.catalina.util.ServerInfo; import org.apache.catalina.util.URLEncoder; import org.apache.tomcat.util.http.fileupload.ParameterParser; import org.apache.tomcat.util.res.StringManager; /** * Servlet that enables remote management of the web applications deployed * within the same virtual host as this web application is. Normally, this * functionality will be protected by a security constraint in the web * application deployment descriptor. However, this requirement can be * relaxed during testing. * <p> * The difference between the <code>ManagerServlet</code> and this * Servlet is that this Servlet prints out a HTML interface which * makes it easier to administrate. * <p> * However if you use a software that parses the output of * <code>ManagerServlet</code> you won't be able to upgrade * to this Servlet since the output are not in the * same format ar from <code>ManagerServlet</code> * * @author Bip Thelin * @author Malcolm Edgar * @author Glenn L. Nielsen * @version $Id$ * @see ManagerServlet */ public final class HTMLManagerServlet extends ManagerServlet { private static final long serialVersionUID = 1L; protected static final URLEncoder URL_ENCODER; protected static final String APPLICATION_MESSAGE = "message"; protected static final String APPLICATION_ERROR = "error"; protected static final String sessionsListJspPath = "/WEB-INF/jsp/sessionsList.jsp"; protected static final String sessionDetailJspPath = "/WEB-INF/jsp/sessionDetail.jsp"; static { URL_ENCODER = new URLEncoder(); // '/' should not be encoded in context paths URL_ENCODER.addSafeCharacter('/'); } private final Random randomSource = new Random(); private boolean showProxySessions = false; // --------------------------------------------------------- Public Methods /** * Process a GET request for the specified resource. * * @param request The servlet request we are processing * @param response The servlet response we are creating * * @exception IOException if an input/output error occurs * @exception ServletException if a servlet-specified error occurs */ @Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { StringManager smClient = getStringManager(request); // Identify the request parameters that we need // By obtaining the command from the pathInfo, per-command security can // be configured in web.xml String command = request.getPathInfo(); String path = request.getParameter("path"); // Prepare our output writer to generate the response message response.setContentType("text/html; charset=" + Constants.CHARSET); String message = ""; // Process the requested command if (command == null || command.equals("/")) { // No command == list } else if (command.equals("/list")) { // List always displayed - nothing to do here } else if (command.equals("/sessions")) { try { doSessions(path, request, response, smClient); return; } catch (Exception e) { log("HTMLManagerServlet.sessions[" + path + "]", e); message = smClient.getString("managerServlet.exception", e.toString()); } } else if (command.equals("/upload") || command.equals("/deploy") || command.equals("/reload") || command.equals("/undeploy") || command.equals("/expire") || command.equals("/start") || command.equals("/stop")) { message = smClient.getString("managerServlet.postCommand", command); } else { message = smClient.getString("managerServlet.unknownCommand", command); } list(request, response, message, smClient); } /** * Process a POST request for the specified resource. * * @param request The servlet request we are processing * @param response The servlet response we are creating * * @exception IOException if an input/output error occurs * @exception ServletException if a servlet-specified error occurs */ @Override public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { StringManager smClient = getStringManager(request); // Identify the request parameters that we need // By obtaining the command from the pathInfo, per-command security can // be configured in web.xml String command = request.getPathInfo(); String path = request.getParameter("path"); String deployPath = request.getParameter("deployPath"); String deployConfig = request.getParameter("deployConfig"); String deployWar = request.getParameter("deployWar"); // Prepare our output writer to generate the response message response.setContentType("text/html; charset=" + Constants.CHARSET); String message = ""; if (command == null || command.length() == 0) { // No command == list // List always displayed -> do nothing } else if (command.equals("/upload")) { message = upload(request, smClient); } else if (command.equals("/deploy")) { message = deployInternal(deployConfig, deployPath, deployWar, smClient); } else if (command.equals("/reload")) { message = reload(path, smClient); } else if (command.equals("/undeploy")) { message = undeploy(path, smClient); } else if (command.equals("/expire")) { message = expireSessions(path, request, smClient); } else if (command.equals("/start")) { message = start(path, smClient); } else if (command.equals("/stop")) { message = stop(path, smClient); } else if (command.equals("/findleaks")) { message = findleaks(smClient); } else { // Try GET doGet(request,response); return; } list(request, response, message, smClient); } /** * Generate a once time token (nonce) for authenticating subsequent * requests. This will also add the token to the session. The nonce * generation is a simplified version of ManagerBase.generateSessionId(). * */ protected String generateNonce() { byte random[] = new byte[16]; // Render the result as a String of hexadecimal digits StringBuilder buffer = new StringBuilder(); randomSource.nextBytes(random); for (int j = 0; j < random.length; j++) { byte b1 = (byte) ((random[j] & 0xf0) >> 4); byte b2 = (byte) (random[j] & 0x0f); if (b1 < 10) buffer.append((char) ('0' + b1)); else buffer.append((char) ('A' + (b1 - 10))); if (b2 < 10) buffer.append((char) ('0' + b2)); else buffer.append((char) ('A' + (b2 - 10))); } return buffer.toString(); } protected String upload(HttpServletRequest request, StringManager smClient) throws IOException, ServletException { String message = ""; Part warPart = null; String filename = null; Collection<Part> parts = request.getParts(); Iterator<Part> iter = parts.iterator(); try { while (iter.hasNext()) { Part part = iter.next(); if (part.getName().equals("deployWar") && warPart == null) { warPart = part; } else { part.delete(); } } while (true) { if (warPart == null) { message = smClient.getString( "htmlManagerServlet.deployUploadNoFile"); break; } filename = extractFilename(warPart.getHeader("Content-Disposition")); if (!filename.toLowerCase(Locale.ENGLISH).endsWith(".war")) { message = smClient.getString( "htmlManagerServlet.deployUploadNotWar", filename); break; } // Get the filename if uploaded name includes a path if (filename.lastIndexOf('\\') >= 0) { filename = filename.substring(filename.lastIndexOf('\\') + 1); } if (filename.lastIndexOf('/') >= 0) { filename = filename.substring(filename.lastIndexOf('/') + 1); } // Identify the appBase of the owning Host of this Context // (if any) File file = new File(getAppBase(), filename); if (file.exists()) { message = smClient.getString( "htmlManagerServlet.deployUploadWarExists", filename); break; } ContextName cn = new ContextName(filename); String name = cn.getName(); if ((host.findChild(name) != null) && !isDeployed(name)) { message = smClient.getString( "htmlManagerServlet.deployUploadInServerXml", filename); break; } if (!isServiced(name)) { addServiced(name); try { warPart.write(file.getAbsolutePath()); // Perform new deployment check(name); } finally { removeServiced(name); } } break; } } catch(Exception e) { message = smClient.getString ("htmlManagerServlet.deployUploadFail", e.getMessage()); log(message, e); } finally { if (warPart != null) { warPart.delete(); } warPart = null; } return message; } /* * Adapted from FileUploadBase.getFileName() */ private String extractFilename(String cd) { String fileName = null; if (cd != null) { String cdl = cd.toLowerCase(Locale.ENGLISH); if (cdl.startsWith("form-data") || cdl.startsWith("attachment")) { ParameterParser parser = new ParameterParser(); parser.setLowerCaseNames(true); // Parameter parser can handle null input Map<String,String> params = parser.parse(cd, ';'); if (params.containsKey("filename")) { fileName = params.get("filename"); if (fileName != null) { fileName = fileName.trim(); } else { // Even if there is no value, the parameter is present, // so we return an empty file name rather than no file // name. fileName = ""; } } } } return fileName; } /** * Deploy an application for the specified path from the specified * web application archive. * * @param config URL of the context configuration file to be deployed * @param path Context path of the application to be deployed * @param war URL of the web application archive to be deployed * @return message String */ protected String deployInternal(String config, String path, String war, StringManager smClient) { StringWriter stringWriter = new StringWriter(); PrintWriter printWriter = new PrintWriter(stringWriter); super.deploy(printWriter, config, path, war, false, smClient); return stringWriter.toString(); } /** * Render a HTML list of the currently active Contexts in our virtual host, * and memory and server status information. * * @param request The request * @param response The response * @param message a message to display */ protected void list(HttpServletRequest request, HttpServletResponse response, String message, StringManager smClient) throws IOException { if (debug >= 1) log("list: Listing contexts for virtual host '" + host.getName() + "'"); PrintWriter writer = response.getWriter(); // HTML Header Section writer.print(Constants.HTML_HEADER_SECTION); // Body Header Section Object[] args = new Object[2]; args[0] = request.getContextPath(); args[1] = smClient.getString("htmlManagerServlet.title"); writer.print(MessageFormat.format (Constants.BODY_HEADER_SECTION, args)); // Message Section args = new Object[3]; args[0] = smClient.getString("htmlManagerServlet.messageLabel"); if (message == null || message.length() == 0) { args[1] = "OK"; } else { args[1] = RequestUtil.filter(message); } writer.print(MessageFormat.format(Constants.MESSAGE_SECTION, args)); // Manager Section args = new Object[9]; args[0] = smClient.getString("htmlManagerServlet.manager"); args[1] = response.encodeURL(request.getContextPath() + "/html/list"); args[2] = smClient.getString("htmlManagerServlet.list"); args[3] = response.encodeURL (request.getContextPath() + "/" + smClient.getString("htmlManagerServlet.helpHtmlManagerFile")); args[4] = smClient.getString("htmlManagerServlet.helpHtmlManager"); args[5] = response.encodeURL (request.getContextPath() + "/" + smClient.getString("htmlManagerServlet.helpManagerFile")); args[6] = smClient.getString("htmlManagerServlet.helpManager"); args[7] = response.encodeURL (request.getContextPath() + "/status"); args[8] = smClient.getString("statusServlet.title"); writer.print(MessageFormat.format(Constants.MANAGER_SECTION, args)); // Apps Header Section args = new Object[7]; args[0] = smClient.getString("htmlManagerServlet.appsTitle"); args[1] = smClient.getString("htmlManagerServlet.appsPath"); args[2] = smClient.getString("htmlManagerServlet.appsVersion"); args[3] = smClient.getString("htmlManagerServlet.appsName"); args[4] = smClient.getString("htmlManagerServlet.appsAvailable"); args[5] = smClient.getString("htmlManagerServlet.appsSessions"); args[6] = smClient.getString("htmlManagerServlet.appsTasks"); writer.print(MessageFormat.format(APPS_HEADER_SECTION, args)); // Apps Row Section // Create sorted map of deployed applications by context name. Container children[] = host.findChildren(); String contextNames[] = new String[children.length]; for (int i = 0; i < children.length; i++) contextNames[i] = children[i].getName(); Arrays.sort(contextNames); String appsStart = smClient.getString("htmlManagerServlet.appsStart"); String appsStop = smClient.getString("htmlManagerServlet.appsStop"); String appsReload = smClient.getString("htmlManagerServlet.appsReload"); String appsUndeploy = smClient.getString("htmlManagerServlet.appsUndeploy"); String appsExpire = smClient.getString("htmlManagerServlet.appsExpire"); String noVersion = "<i>" + smClient.getString("htmlManagerServlet.noVersion") + "</i>"; boolean isHighlighted = true; boolean isDeployed = true; String highlightColor = null; for (String contextName : contextNames) { Context ctxt = (Context) host.findChild(contextName); if (ctxt != null) { // Bugzilla 34818, alternating row colors isHighlighted = !isHighlighted; if(isHighlighted) { highlightColor = "#C3F3C3"; } else { highlightColor = "#FFFFFF"; } String contextPath = ctxt.getPath(); String displayPath = contextPath; if (displayPath.equals("")) { displayPath = "/"; } try { isDeployed = isDeployed(contextName); } catch (Exception e) { // Assume false on failure for safety isDeployed = false; } args = new Object[7]; args[0] = "<a href=\"" + URL_ENCODER.encode(displayPath) + "\">" + displayPath + "</a>"; args[1] = ctxt.getWebappVersion(); if ("".equals(args[1])) { args[1]= noVersion; } args[2] = ctxt.getDisplayName(); if (args[2] == null) { args[2] = "&nbsp;"; } args[3] = new Boolean(ctxt.getAvailable()); args[4] = response.encodeURL (request.getContextPath() + "/html/sessions?path=" + URL_ENCODER.encode(displayPath)); Manager manager = ctxt.getManager(); if (manager instanceof DistributedManager && showProxySessions) { args[5] = new Integer( ((DistributedManager)manager).getActiveSessionsFull()); } else if (ctxt.getManager() != null){ args[5] = new Integer(manager.getActiveSessions()); } else { args[5] = new Integer(0); } args[6] = highlightColor; writer.print (MessageFormat.format(APPS_ROW_DETAILS_SECTION, args)); args = new Object[14]; args[0] = response.encodeURL (request.getContextPath() + "/html/start?path=" + URL_ENCODER.encode(displayPath)); args[1] = appsStart; args[2] = response.encodeURL (request.getContextPath() + "/html/stop?path=" + URL_ENCODER.encode(displayPath)); args[3] = appsStop; args[4] = response.encodeURL (request.getContextPath() + "/html/reload?path=" + URL_ENCODER.encode(displayPath)); args[5] = appsReload; args[6] = response.encodeURL (request.getContextPath() + "/html/undeploy?path=" + URL_ENCODER.encode(displayPath)); args[7] = appsUndeploy; args[8] = response.encodeURL (request.getContextPath() + "/html/expire?path=" + URL_ENCODER.encode(displayPath)); args[9] = appsExpire; args[10] = smClient.getString( "htmlManagerServlet.expire.explain"); if (manager == null) { args[11] = smClient.getString( "htmlManagerServlet.noManager"); } else { args[11] = new Integer( ctxt.getManager().getMaxInactiveInterval()/60); } args[12] = smClient.getString("htmlManagerServlet.expire.unit"); args[13] = highlightColor; if (ctxt.getName().equals(this.context.getName())) { writer.print(MessageFormat.format( MANAGER_APP_ROW_BUTTON_SECTION, args)); } else if (ctxt.getAvailable() && isDeployed) { writer.print(MessageFormat.format( STARTED_DEPLOYED_APPS_ROW_BUTTON_SECTION, args)); } else if (ctxt.getAvailable() && !isDeployed) { writer.print(MessageFormat.format( STARTED_NONDEPLOYED_APPS_ROW_BUTTON_SECTION, args)); } else if (!ctxt.getAvailable() && isDeployed) { writer.print(MessageFormat.format( STOPPED_DEPLOYED_APPS_ROW_BUTTON_SECTION, args)); } else { writer.print(MessageFormat.format( STOPPED_NONDEPLOYED_APPS_ROW_BUTTON_SECTION, args)); } } } // Deploy Section args = new Object[7]; args[0] = smClient.getString("htmlManagerServlet.deployTitle"); args[1] = smClient.getString("htmlManagerServlet.deployServer"); args[2] = response.encodeURL(request.getContextPath() + "/html/deploy"); args[3] = smClient.getString("htmlManagerServlet.deployPath"); args[4] = smClient.getString("htmlManagerServlet.deployConfig"); args[5] = smClient.getString("htmlManagerServlet.deployWar"); args[6] = smClient.getString("htmlManagerServlet.deployButton"); writer.print(MessageFormat.format(DEPLOY_SECTION, args)); args = new Object[4]; args[0] = smClient.getString("htmlManagerServlet.deployUpload"); args[1] = response.encodeURL(request.getContextPath() + "/html/upload"); args[2] = smClient.getString("htmlManagerServlet.deployUploadFile"); args[3] = smClient.getString("htmlManagerServlet.deployButton"); writer.print(MessageFormat.format(UPLOAD_SECTION, args)); // Diagnostics section args = new Object[5]; args[0] = smClient.getString("htmlManagerServlet.diagnosticsTitle"); args[1] = smClient.getString("htmlManagerServlet.diagnosticsLeak"); args[2] = response.encodeURL( request.getContextPath() + "/html/findleaks"); args[3] = smClient.getString("htmlManagerServlet.diagnosticsLeakWarning"); args[4] = smClient.getString("htmlManagerServlet.diagnosticsLeakButton"); writer.print(MessageFormat.format(DIAGNOSTICS_SECTION, args)); // Server Header Section args = new Object[7]; args[0] = smClient.getString("htmlManagerServlet.serverTitle"); args[1] = smClient.getString("htmlManagerServlet.serverVersion"); args[2] = smClient.getString("htmlManagerServlet.serverJVMVersion"); args[3] = smClient.getString("htmlManagerServlet.serverJVMVendor"); args[4] = smClient.getString("htmlManagerServlet.serverOSName"); args[5] = smClient.getString("htmlManagerServlet.serverOSVersion"); args[6] = smClient.getString("htmlManagerServlet.serverOSArch"); writer.print(MessageFormat.format (Constants.SERVER_HEADER_SECTION, args)); // Server Row Section args = new Object[6]; args[0] = ServerInfo.getServerInfo(); args[1] = System.getProperty("java.runtime.version"); args[2] = System.getProperty("java.vm.vendor"); args[3] = System.getProperty("os.name"); args[4] = System.getProperty("os.version"); args[5] = System.getProperty("os.arch"); writer.print(MessageFormat.format(Constants.SERVER_ROW_SECTION, args)); // HTML Tail Section writer.print(Constants.HTML_TAIL_SECTION); // Finish up the response writer.flush(); writer.close(); } /** * Reload the web application at the specified context path. * * @see ManagerServlet#reload(PrintWriter, String, StringManager) * * @param path Context path of the application to be restarted * @return message String */ protected String reload(String path, StringManager smClient) { StringWriter stringWriter = new StringWriter(); PrintWriter printWriter = new PrintWriter(stringWriter); super.reload(printWriter, path, smClient); return stringWriter.toString(); } /** * Undeploy the web application at the specified context path. * * @see ManagerServlet#undeploy(PrintWriter, String, StringManager) * * @param path Context path of the application to be undeployed * @return message String */ protected String undeploy(String path, StringManager smClient) { StringWriter stringWriter = new StringWriter(); PrintWriter printWriter = new PrintWriter(stringWriter); super.undeploy(printWriter, path, smClient); return stringWriter.toString(); } /** * Display session information and invoke list. * * @see ManagerServlet#sessions(PrintWriter, String, int, StringManager) * * @param path Context path of the application to list session information * @param idle Expire all sessions with idle time &ge; idle for this context * @return message String */ protected String sessions(String path, int idle, StringManager smClient) { StringWriter stringWriter = new StringWriter(); PrintWriter printWriter = new PrintWriter(stringWriter); super.sessions(printWriter, path, idle, smClient); return stringWriter.toString(); } /** * Start the web application at the specified context path. * * @see ManagerServlet#start(PrintWriter, String, StringManager) * * @param path Context path of the application to be started * @return message String */ protected String start(String path, StringManager smClient) { StringWriter stringWriter = new StringWriter(); PrintWriter printWriter = new PrintWriter(stringWriter); super.start(printWriter, path, smClient); return stringWriter.toString(); } /** * Stop the web application at the specified context path. * * @see ManagerServlet#stop(PrintWriter, String, StringManager) * * @param path Context path of the application to be stopped * @return message String */ protected String stop(String path, StringManager smClient) { StringWriter stringWriter = new StringWriter(); PrintWriter printWriter = new PrintWriter(stringWriter); super.stop(printWriter, path, smClient); return stringWriter.toString(); } /** * Find potential memory leaks caused by web application reload. * * @see ManagerServlet#findleaks(PrintWriter, StringManager) * * @return message String */ protected String findleaks(StringManager smClient) { StringBuilder msg = new StringBuilder(); StringWriter stringWriter = new StringWriter(); PrintWriter printWriter = new PrintWriter(stringWriter); super.findleaks(printWriter, smClient); if (stringWriter.getBuffer().length() > 0) { msg.append(smClient.getString("htmlManagerServlet.findleaksList")); msg.append(stringWriter.toString()); } else { msg.append(smClient.getString("htmlManagerServlet.findleaksNone")); } return msg.toString(); } /** * @see javax.servlet.Servlet#getServletInfo() */ @Override public String getServletInfo() { return "HTMLManagerServlet, Copyright (c) 1999-2010, The Apache Software Foundation"; } /** * @see javax.servlet.GenericServlet#init() */ @Override public void init() throws ServletException { super.init(); // Set our properties from the initialization parameters String value = null; value = getServletConfig().getInitParameter("showProxySessions"); showProxySessions = Boolean.parseBoolean(value); } // ------------------------------------------------ Sessions administration /** * * Extract the expiration request parameter * * @param path * @param req */ protected String expireSessions(String path, HttpServletRequest req, StringManager smClient) { int idle = -1; String idleParam = req.getParameter("idle"); if (idleParam != null) { try { idle = Integer.parseInt(idleParam); } catch (NumberFormatException e) { log("Could not parse idle parameter to an int: " + idleParam); } } return sessions(path, idle, smClient); } /** * * @param req * @param resp * @throws ServletException * @throws IOException */ protected void doSessions(String path, HttpServletRequest req, HttpServletResponse resp, StringManager smClient) throws ServletException, IOException { req.setAttribute("path", path); String action = req.getParameter("action"); if (debug >= 1) { log("sessions: Session action '" + action + "' for web application at '" + path + "'"); } if ("sessionDetail".equals(action)) { String sessionId = req.getParameter("sessionId"); displaySessionDetailPage(req, resp, path, sessionId, smClient); return; } else if ("invalidateSessions".equals(action)) { String[] sessionIds = req.getParameterValues("sessionIds"); int i = invalidateSessions(path, sessionIds, smClient); req.setAttribute(APPLICATION_MESSAGE, "" + i + " sessions invalidated."); } else if ("removeSessionAttribute".equals(action)) { String sessionId = req.getParameter("sessionId"); String name = req.getParameter("attributeName"); boolean removed = removeSessionAttribute(path, sessionId, name, smClient); String outMessage = removed ? "Session attribute '" + name + "' removed." : "Session did not contain any attribute named '" + name + "'"; req.setAttribute(APPLICATION_MESSAGE, outMessage); resp.sendRedirect(resp.encodeRedirectURL(req.getRequestURL().append("?path=").append(path).append("&action=sessionDetail&sessionId=").append(sessionId).toString())); return; } // else displaySessionsListPage(path, req, resp, smClient); } protected List<Session> getSessionsForPath(String path, StringManager smClient) { if ((path == null) || (!path.startsWith("/") && path.equals(""))) { throw new IllegalArgumentException(smClient.getString( "managerServlet.invalidPath", RequestUtil.filter(path))); } String searchPath = path; if( path.equals("/") ) searchPath = ""; Context ctxt = (Context) host.findChild(searchPath); if (null == ctxt) { throw new IllegalArgumentException(smClient.getString( "managerServlet.noContext", RequestUtil.filter(path))); } Manager manager = ctxt.getManager(); List<Session> sessions = new ArrayList<Session>(); sessions.addAll(Arrays.asList(manager.findSessions())); if (manager instanceof DistributedManager && showProxySessions) { // Add dummy proxy sessions Set<String> sessionIds = ((DistributedManager) manager).getSessionIdsFull(); // Remove active (primary and backup) session IDs from full list for (Session session : sessions) { sessionIds.remove(session.getId()); } // Left with just proxy sessions - add them for (String sessionId : sessionIds) { sessions.add(new DummyProxySession(sessionId)); } } return sessions; } protected Session getSessionForPathAndId(String path, String id, StringManager smClient) throws IOException { if ((path == null) || (!path.startsWith("/") && path.equals(""))) { throw new IllegalArgumentException(smClient.getString( "managerServlet.invalidPath", RequestUtil.filter(path))); } String searchPath = path; if( path.equals("/") ) searchPath = ""; Context ctxt = (Context) host.findChild(searchPath); if (null == ctxt) { throw new IllegalArgumentException(smClient.getString( "managerServlet.noContext", RequestUtil.filter(path))); } Session session = ctxt.getManager().findSession(id); return session; } /** * * @param req * @param resp * @throws ServletException * @throws IOException */ protected void displaySessionsListPage(String path, HttpServletRequest req, HttpServletResponse resp, StringManager smClient) throws ServletException, IOException { List<Session> sessions = getSessionsForPath(path, smClient); String sortBy = req.getParameter("sort"); String orderBy = null; if (null != sortBy && !"".equals(sortBy.trim())) { Comparator<Session> comparator = getComparator(sortBy); if (comparator != null) { orderBy = req.getParameter("order"); if ("DESC".equalsIgnoreCase(orderBy)) { comparator = new ReverseComparator(comparator); // orderBy = "ASC"; } else { //orderBy = "DESC"; } try { Collections.sort(sessions, comparator); } catch (IllegalStateException ise) { // at least 1 of the sessions is invalidated req.setAttribute(APPLICATION_ERROR, "Can't sort session list: one session is invalidated"); } } else { log("WARNING: unknown sort order: " + sortBy); } } // keep sort order req.setAttribute("sort", sortBy); req.setAttribute("order", orderBy); req.setAttribute("activeSessions", sessions); //strong>NOTE</strong> - This header will be overridden // automatically if a <code>RequestDispatcher.forward()</code> call is // ultimately invoked. resp.setHeader("Pragma", "No-cache"); // HTTP 1.0 resp.setHeader("Cache-Control", "no-cache,no-store,max-age=0"); // HTTP 1.1 resp.setDateHeader("Expires", 0); // 0 means now getServletContext().getRequestDispatcher(sessionsListJspPath).include(req, resp); } /** * * @param req * @param resp * @throws ServletException * @throws IOException */ protected void displaySessionDetailPage(HttpServletRequest req, HttpServletResponse resp, String path, String sessionId, StringManager smClient) throws ServletException, IOException { Session session = getSessionForPathAndId(path, sessionId, smClient); //strong>NOTE</strong> - This header will be overridden // automatically if a <code>RequestDispatcher.forward()</code> call is // ultimately invoked. resp.setHeader("Pragma", "No-cache"); // HTTP 1.0 resp.setHeader("Cache-Control", "no-cache,no-store,max-age=0"); // HTTP 1.1 resp.setDateHeader("Expires", 0); // 0 means now req.setAttribute("currentSession", session); getServletContext().getRequestDispatcher(resp.encodeURL(sessionDetailJspPath)).include(req, resp); } /** * Invalidate HttpSessions * @param sessionIds * @return number of invalidated sessions * @throws IOException */ protected int invalidateSessions(String path, String[] sessionIds, StringManager smClient) throws IOException { if (null == sessionIds) { return 0; } int nbAffectedSessions = 0; for (int i = 0; i < sessionIds.length; ++i) { String sessionId = sessionIds[i]; HttpSession session = getSessionForPathAndId(path, sessionId, smClient).getSession(); if (null == session) { // Shouldn't happen, but let's play nice... if (debug >= 1) { log("WARNING: can't invalidate null session " + sessionId); } continue; } try { session.invalidate(); ++nbAffectedSessions; if (debug >= 1) { log("Invalidating session id " + sessionId); } } catch (IllegalStateException ise) { if (debug >= 1) { log("Can't invalidate already invalidated session id " + sessionId); } } } return nbAffectedSessions; } /** * Removes an attribute from an HttpSession * @param sessionId * @param attributeName * @return true if there was an attribute removed, false otherwise * @throws IOException */ protected boolean removeSessionAttribute(String path, String sessionId, String attributeName, StringManager smClient) throws IOException { HttpSession session = getSessionForPathAndId(path, sessionId, smClient).getSession(); if (null == session) { // Shouldn't happen, but let's play nice... if (debug >= 1) { log("WARNING: can't remove attribute '" + attributeName + "' for null session " + sessionId); } return false; } boolean wasPresent = (null != session.getAttribute(attributeName)); try { session.removeAttribute(attributeName); } catch (IllegalStateException ise) { if (debug >= 1) { log("Can't remote attribute '" + attributeName + "' for invalidated session id " + sessionId); } } return wasPresent; } protected Comparator<Session> getComparator(String sortBy) { Comparator<Session> comparator = null; if ("CreationTime".equalsIgnoreCase(sortBy)) { comparator = new BaseSessionComparator<Date>() { @Override public Comparable<Date> getComparableObject(Session session) { return new Date(session.getCreationTime()); } }; } else if ("id".equalsIgnoreCase(sortBy)) { comparator = new BaseSessionComparator<String>() { @Override public Comparable<String> getComparableObject(Session session) { return session.getId(); } }; } else if ("LastAccessedTime".equalsIgnoreCase(sortBy)) { comparator = new BaseSessionComparator<Date>() { @Override public Comparable<Date> getComparableObject(Session session) { return new Date(session.getLastAccessedTime()); } }; } else if ("MaxInactiveInterval".equalsIgnoreCase(sortBy)) { comparator = new BaseSessionComparator<Date>() { @Override public Comparable<Date> getComparableObject(Session session) { return new Date(session.getMaxInactiveInterval()); } }; } else if ("new".equalsIgnoreCase(sortBy)) { comparator = new BaseSessionComparator<Boolean>() { @Override public Comparable<Boolean> getComparableObject(Session session) { return Boolean.valueOf(session.getSession().isNew()); } }; } else if ("locale".equalsIgnoreCase(sortBy)) { comparator = new BaseSessionComparator<String>() { @Override public Comparable<String> getComparableObject(Session session) { return JspHelper.guessDisplayLocaleFromSession(session); } }; } else if ("user".equalsIgnoreCase(sortBy)) { comparator = new BaseSessionComparator<String>() { @Override public Comparable<String> getComparableObject(Session session) { return JspHelper.guessDisplayUserFromSession(session); } }; } else if ("UsedTime".equalsIgnoreCase(sortBy)) { comparator = new BaseSessionComparator<Date>() { @Override public Comparable<Date> getComparableObject(Session session) { return new Date(SessionUtils.getUsedTimeForSession(session)); } }; } else if ("InactiveTime".equalsIgnoreCase(sortBy)) { comparator = new BaseSessionComparator<Date>() { @Override public Comparable<Date> getComparableObject(Session session) { return new Date(SessionUtils.getInactiveTimeForSession(session)); } }; } else if ("TTL".equalsIgnoreCase(sortBy)) { comparator = new BaseSessionComparator<Date>() { @Override public Comparable<Date> getComparableObject(Session session) { return new Date(SessionUtils.getTTLForSession(session)); } }; } //TODO: complete this to TTL, etc. return comparator; } // ------------------------------------------------------ Private Constants // These HTML sections are broken in relatively small sections, because of // limited number of substitutions MessageFormat can process // (maximum of 10). private static final String APPS_HEADER_SECTION = "<table border=\"1\" cellspacing=\"0\" cellpadding=\"3\">\n" + "<tr>\n" + " <td colspan=\"6\" class=\"title\">{0}</td>\n" + "</tr>\n" + "<tr>\n" + " <td class=\"header-left\"><small>{1}</small></td>\n" + " <td class=\"header-left\"><small>{2}</small></td>\n" + " <td class=\"header-center\"><small>{3}</small></td>\n" + " <td class=\"header-center\"><small>{4}</small></td>\n" + " <td class=\"header-left\"><small>{5}</small></td>\n" + " <td class=\"header-left\"><small>{6}</small></td>\n" + "</tr>\n"; private static final String APPS_ROW_DETAILS_SECTION = "<tr>\n" + " <td class=\"row-left\" bgcolor=\"{6}\" rowspan=\"2\"><small>{0}</small></td>\n" + " <td class=\"row-left\" bgcolor=\"{6}\" rowspan=\"2\"><small>{1}</small></td>\n" + " <td class=\"row-left\" bgcolor=\"{6}\" rowspan=\"2\"><small>{2}</small></td>\n" + " <td class=\"row-center\" bgcolor=\"{6}\" rowspan=\"2\"><small>{3}</small></td>\n" + " <td class=\"row-center\" bgcolor=\"{6}\" rowspan=\"2\">" + "<small><a href=\"{4}\">{5}</a></small></td>\n"; private static final String MANAGER_APP_ROW_BUTTON_SECTION = " <td class=\"row-left\" bgcolor=\"{13}\">\n" + " <small>\n" + " &nbsp;{1}&nbsp;\n" + " &nbsp;{3}&nbsp;\n" + " &nbsp;{5}&nbsp;\n" + " &nbsp;{7}&nbsp;\n" + " </small>\n" + " </td>\n" + "</tr><tr>\n" + " <td class=\"row-left\" bgcolor=\"{13}\">\n" + " <form method=\"POST\" action=\"{8}\">\n" + " <small>\n" + " &nbsp;<input type=\"submit\" value=\"{9}\">&nbsp;{10}&nbsp;<input type=\"text\" name=\"idle\" size=\"5\" value=\"{11}\">&nbsp;{12}&nbsp;\n" + " </small>\n" + " </form>\n" + " </td>\n" + "</tr>\n"; private static final String STARTED_DEPLOYED_APPS_ROW_BUTTON_SECTION = " <td class=\"row-left\" bgcolor=\"{13}\">\n" + " &nbsp;<small>{1}</small>&nbsp;\n" + " <form class=\"inline\" method=\"POST\" action=\"{2}\">" + " <small><input type=\"submit\" value=\"{3}\"></small>" + " </form>\n" + " <form class=\"inline\" method=\"POST\" action=\"{4}\">" + " <small><input type=\"submit\" value=\"{5}\"></small>" + " </form>\n" + " <form class=\"inline\" method=\"POST\" action=\"{6}\">" + " <small><input type=\"submit\" value=\"{7}\"></small>" + " </form>\n" + " </td>\n" + " </tr><tr>\n" + " <td class=\"row-left\" bgcolor=\"{13}\">\n" + " <form method=\"POST\" action=\"{8}\">\n" + " <small>\n" + " &nbsp;<input type=\"submit\" value=\"{9}\">&nbsp;{10}&nbsp;<input type=\"text\" name=\"idle\" size=\"5\" value=\"{11}\">&nbsp;{12}&nbsp;\n" + " </small>\n" + " </form>\n" + " </td>\n" + "</tr>\n"; private static final String STOPPED_DEPLOYED_APPS_ROW_BUTTON_SECTION = " <td class=\"row-left\" bgcolor=\"{13}\" rowspan=\"2\">\n" + " <form class=\"inline\" method=\"POST\" action=\"{0}\">" + " <small><input type=\"submit\" value=\"{1}\"></small>" + " </form>\n" + " &nbsp;<small>{3}</small>&nbsp;\n" + " &nbsp;<small>{5}</small>&nbsp;\n" + " <form class=\"inline\" method=\"POST\" action=\"{6}\">" + " <small><input type=\"submit\" value=\"{7}\"></small>" + " </form>\n" + " </td>\n" + "</tr>\n<tr></tr>\n"; private static final String STARTED_NONDEPLOYED_APPS_ROW_BUTTON_SECTION = " <td class=\"row-left\" bgcolor=\"{13}\" rowspan=\"2\">\n" + " &nbsp;<small>{1}</small>&nbsp;\n" + " <form class=\"inline\" method=\"POST\" action=\"{2}\">" + " <small><input type=\"submit\" value=\"{3}\"></small>" + " </form>\n" + " <form class=\"inline\" method=\"POST\" action=\"{4}\">" + " <small><input type=\"submit\" value=\"{5}\"></small>" + " </form>\n" + " &nbsp;<small>{7}</small>&nbsp;\n" + " </td>\n" + "</tr>\n<tr></tr>\n"; private static final String STOPPED_NONDEPLOYED_APPS_ROW_BUTTON_SECTION = " <td class=\"row-left\" bgcolor=\"{13}\" rowspan=\"2\">\n" + " <form class=\"inline\" method=\"POST\" action=\"{0}\">" + " <small><input type=\"submit\" value=\"{1}\"></small>" + " </form>\n" + " &nbsp;<small>{3}</small>&nbsp;\n" + " &nbsp;<small>{5}</small>&nbsp;\n" + " &nbsp;<small>{7}</small>&nbsp;\n" + " </td>\n" + "</tr>\n<tr></tr>\n"; private static final String DEPLOY_SECTION = "</table>\n" + "<br>\n" + "<table border=\"1\" cellspacing=\"0\" cellpadding=\"3\">\n" + "<tr>\n" + " <td colspan=\"2\" class=\"title\">{0}</td>\n" + "</tr>\n" + "<tr>\n" + " <td colspan=\"2\" class=\"header-left\"><small>{1}</small></td>\n" + "</tr>\n" + "<tr>\n" + " <td colspan=\"2\">\n" + "<form method=\"post\" action=\"{2}\">\n" + "<table cellspacing=\"0\" cellpadding=\"3\">\n" + "<tr>\n" + " <td class=\"row-right\">\n" + " <small>{3}</small>\n" + " </td>\n" + " <td class=\"row-left\">\n" + " <input type=\"text\" name=\"deployPath\" size=\"20\">\n" + " </td>\n" + "</tr>\n" + "<tr>\n" + " <td class=\"row-right\">\n" + " <small>{4}</small>\n" + " </td>\n" + " <td class=\"row-left\">\n" + " <input type=\"text\" name=\"deployConfig\" size=\"20\">\n" + " </td>\n" + "</tr>\n" + "<tr>\n" + " <td class=\"row-right\">\n" + " <small>{5}</small>\n" + " </td>\n" + " <td class=\"row-left\">\n" + " <input type=\"text\" name=\"deployWar\" size=\"40\">\n" + " </td>\n" + "</tr>\n" + "<tr>\n" + " <td class=\"row-right\">\n" + " &nbsp;\n" + " </td>\n" + " <td class=\"row-left\">\n" + " <input type=\"submit\" value=\"{6}\">\n" + " </td>\n" + "</tr>\n" + "</table>\n" + "</form>\n" + "</td>\n" + "</tr>\n"; private static final String UPLOAD_SECTION = "<tr>\n" + " <td colspan=\"2\" class=\"header-left\"><small>{0}</small></td>\n" + "</tr>\n" + "<tr>\n" + " <td colspan=\"2\">\n" + "<form method=\"post\" action=\"{1}\" " + "enctype=\"multipart/form-data\">\n" + "<table cellspacing=\"0\" cellpadding=\"3\">\n" + "<tr>\n" + " <td class=\"row-right\">\n" + " <small>{2}</small>\n" + " </td>\n" + " <td class=\"row-left\">\n" + " <input type=\"file\" name=\"deployWar\" size=\"40\">\n" + " </td>\n" + "</tr>\n" + "<tr>\n" + " <td class=\"row-right\">\n" + " &nbsp;\n" + " </td>\n" + " <td class=\"row-left\">\n" + " <input type=\"submit\" value=\"{3}\">\n" + " </td>\n" + "</tr>\n" + "</table>\n" + "</form>\n" + "</table>\n" + "<br>\n" + "\n"; private static final String DIAGNOSTICS_SECTION = "<table border=\"1\" cellspacing=\"0\" cellpadding=\"3\">\n" + "<tr>\n" + " <td colspan=\"2\" class=\"title\">{0}</td>\n" + "</tr>\n" + "<tr>\n" + " <td colspan=\"2\" class=\"header-left\"><small>{1}</small></td>\n" + "</tr>\n" + "<tr>\n" + " <td colspan=\"2\">\n" + "<form method=\"post\" action=\"{2}\">\n" + "<table cellspacing=\"0\" cellpadding=\"3\">\n" + "<tr>\n" + " <td class=\"row-left\">\n" + " <input type=\"submit\" value=\"{4}\">\n" + " </td>\n" + " <td class=\"row-left\">\n" + " <small>{3}</small>\n" + " </td>\n" + "</tr>\n" + "</table>\n" + "</form>\n" + "</td>\n" + "</tr>\n" + "</table>\n" + "<br>"; }
java/org/apache/catalina/manager/HTMLManagerServlet.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.catalina.manager; import java.io.File; import java.io.IOException; import java.io.PrintWriter; import java.io.StringWriter; import java.text.MessageFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.Date; import java.util.Iterator; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Random; import java.util.Set; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import javax.servlet.http.Part; import org.apache.catalina.Container; import org.apache.catalina.Context; import org.apache.catalina.DistributedManager; import org.apache.catalina.Manager; import org.apache.catalina.Session; import org.apache.catalina.manager.util.BaseSessionComparator; import org.apache.catalina.manager.util.ReverseComparator; import org.apache.catalina.manager.util.SessionUtils; import org.apache.catalina.util.ContextName; import org.apache.catalina.util.RequestUtil; import org.apache.catalina.util.ServerInfo; import org.apache.catalina.util.URLEncoder; import org.apache.tomcat.util.http.fileupload.ParameterParser; import org.apache.tomcat.util.res.StringManager; /** * Servlet that enables remote management of the web applications deployed * within the same virtual host as this web application is. Normally, this * functionality will be protected by a security constraint in the web * application deployment descriptor. However, this requirement can be * relaxed during testing. * <p> * The difference between the <code>ManagerServlet</code> and this * Servlet is that this Servlet prints out a HTML interface which * makes it easier to administrate. * <p> * However if you use a software that parses the output of * <code>ManagerServlet</code> you won't be able to upgrade * to this Servlet since the output are not in the * same format ar from <code>ManagerServlet</code> * * @author Bip Thelin * @author Malcolm Edgar * @author Glenn L. Nielsen * @version $Id$ * @see ManagerServlet */ public final class HTMLManagerServlet extends ManagerServlet { private static final long serialVersionUID = 1L; protected static final URLEncoder URL_ENCODER; protected static final String APPLICATION_MESSAGE = "message"; protected static final String APPLICATION_ERROR = "error"; protected static final String sessionsListJspPath = "/WEB-INF/jsp/sessionsList.jsp"; protected static final String sessionDetailJspPath = "/WEB-INF/jsp/sessionDetail.jsp"; static { URL_ENCODER = new URLEncoder(); // '/' should not be encoded in context paths URL_ENCODER.addSafeCharacter('/'); } private final Random randomSource = new Random(); private boolean showProxySessions = false; // --------------------------------------------------------- Public Methods /** * Process a GET request for the specified resource. * * @param request The servlet request we are processing * @param response The servlet response we are creating * * @exception IOException if an input/output error occurs * @exception ServletException if a servlet-specified error occurs */ @Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { StringManager smClient = getStringManager(request); // Identify the request parameters that we need // By obtaining the command from the pathInfo, per-command security can // be configured in web.xml String command = request.getPathInfo(); String path = request.getParameter("path"); // Prepare our output writer to generate the response message response.setContentType("text/html; charset=" + Constants.CHARSET); String message = ""; // Process the requested command if (command == null || command.equals("/")) { // No command == list } else if (command.equals("/list")) { // List always displayed - nothing to do here } else if (command.equals("/sessions")) { try { doSessions(path, request, response, smClient); return; } catch (Exception e) { log("HTMLManagerServlet.sessions[" + path + "]", e); message = smClient.getString("managerServlet.exception", e.toString()); } } else if (command.equals("/upload") || command.equals("/deploy") || command.equals("/reload") || command.equals("/undeploy") || command.equals("/expire") || command.equals("/start") || command.equals("/stop")) { message = smClient.getString("managerServlet.postCommand", command); } else { message = smClient.getString("managerServlet.unknownCommand", command); } list(request, response, message, smClient); } /** * Process a POST request for the specified resource. * * @param request The servlet request we are processing * @param response The servlet response we are creating * * @exception IOException if an input/output error occurs * @exception ServletException if a servlet-specified error occurs */ @Override public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { StringManager smClient = getStringManager(request); // Identify the request parameters that we need // By obtaining the command from the pathInfo, per-command security can // be configured in web.xml String command = request.getPathInfo(); String path = request.getParameter("path"); String deployPath = request.getParameter("deployPath"); String deployConfig = request.getParameter("deployConfig"); String deployWar = request.getParameter("deployWar"); // Prepare our output writer to generate the response message response.setContentType("text/html; charset=" + Constants.CHARSET); String message = ""; if (command == null || command.length() == 0) { // No command == list // List always displayed -> do nothing } else if (command.equals("/upload")) { message = upload(request, smClient); } else if (command.equals("/deploy")) { message = deployInternal(deployConfig, deployPath, deployWar, smClient); } else if (command.equals("/reload")) { message = reload(path, smClient); } else if (command.equals("/undeploy")) { message = undeploy(path, smClient); } else if (command.equals("/expire")) { message = expireSessions(path, request, smClient); } else if (command.equals("/start")) { message = start(path, smClient); } else if (command.equals("/stop")) { message = stop(path, smClient); } else if (command.equals("/findleaks")) { message = findleaks(smClient); } else { // Try GET doGet(request,response); return; } list(request, response, message, smClient); } /** * Generate a once time token (nonce) for authenticating subsequent * requests. This will also add the token to the session. The nonce * generation is a simplified version of ManagerBase.generateSessionId(). * */ protected String generateNonce() { byte random[] = new byte[16]; // Render the result as a String of hexadecimal digits StringBuilder buffer = new StringBuilder(); randomSource.nextBytes(random); for (int j = 0; j < random.length; j++) { byte b1 = (byte) ((random[j] & 0xf0) >> 4); byte b2 = (byte) (random[j] & 0x0f); if (b1 < 10) buffer.append((char) ('0' + b1)); else buffer.append((char) ('A' + (b1 - 10))); if (b2 < 10) buffer.append((char) ('0' + b2)); else buffer.append((char) ('A' + (b2 - 10))); } return buffer.toString(); } protected String upload(HttpServletRequest request, StringManager smClient) throws IOException, ServletException { String message = ""; Part warPart = null; String filename = null; Collection<Part> parts = request.getParts(); Iterator<Part> iter = parts.iterator(); try { while (iter.hasNext()) { Part part = iter.next(); if (part.getName().equals("deployWar") && warPart == null) { warPart = part; } else { part.delete(); } } while (true) { if (warPart == null) { message = smClient.getString( "htmlManagerServlet.deployUploadNoFile"); break; } filename = extractFilename(warPart.getHeader("Content-Disposition")); if (!filename.toLowerCase(Locale.ENGLISH).endsWith(".war")) { message = smClient.getString( "htmlManagerServlet.deployUploadNotWar", filename); break; } // Get the filename if uploaded name includes a path if (filename.lastIndexOf('\\') >= 0) { filename = filename.substring(filename.lastIndexOf('\\') + 1); } if (filename.lastIndexOf('/') >= 0) { filename = filename.substring(filename.lastIndexOf('/') + 1); } // Identify the appBase of the owning Host of this Context // (if any) File file = new File(getAppBase(), filename); if (file.exists()) { message = smClient.getString( "htmlManagerServlet.deployUploadWarExists", filename); break; } ContextName cn = new ContextName(filename); String name = cn.getName(); if ((host.findChild(name) != null) && !isDeployed(name)) { message = smClient.getString( "htmlManagerServlet.deployUploadInServerXml", filename); break; } if (!isServiced(name)) { addServiced(name); try { warPart.write(file.getAbsolutePath()); // Perform new deployment check(name); } finally { removeServiced(name); } } break; } } catch(Exception e) { message = smClient.getString ("htmlManagerServlet.deployUploadFail", e.getMessage()); log(message, e); } finally { if (warPart != null) { warPart.delete(); } warPart = null; } return message; } /* * Adapted from FileUploadBase.getFileName() */ private String extractFilename(String cd) { String fileName = null; if (cd != null) { String cdl = cd.toLowerCase(Locale.ENGLISH); if (cdl.startsWith("form-data") || cdl.startsWith("attachment")) { ParameterParser parser = new ParameterParser(); parser.setLowerCaseNames(true); // Parameter parser can handle null input Map<String,String> params = parser.parse(cd, ';'); if (params.containsKey("filename")) { fileName = params.get("filename"); if (fileName != null) { fileName = fileName.trim(); } else { // Even if there is no value, the parameter is present, // so we return an empty file name rather than no file // name. fileName = ""; } } } } return fileName; } /** * Deploy an application for the specified path from the specified * web application archive. * * @param config URL of the context configuration file to be deployed * @param path Context path of the application to be deployed * @param war URL of the web application archive to be deployed * @return message String */ protected String deployInternal(String config, String path, String war, StringManager smClient) { StringWriter stringWriter = new StringWriter(); PrintWriter printWriter = new PrintWriter(stringWriter); super.deploy(printWriter, config, path, war, false, smClient); return stringWriter.toString(); } /** * Render a HTML list of the currently active Contexts in our virtual host, * and memory and server status information. * * @param request The request * @param response The response * @param message a message to display */ public void list(HttpServletRequest request, HttpServletResponse response, String message, StringManager smClient) throws IOException { if (debug >= 1) log("list: Listing contexts for virtual host '" + host.getName() + "'"); PrintWriter writer = response.getWriter(); // HTML Header Section writer.print(Constants.HTML_HEADER_SECTION); // Body Header Section Object[] args = new Object[2]; args[0] = request.getContextPath(); args[1] = smClient.getString("htmlManagerServlet.title"); writer.print(MessageFormat.format (Constants.BODY_HEADER_SECTION, args)); // Message Section args = new Object[3]; args[0] = smClient.getString("htmlManagerServlet.messageLabel"); if (message == null || message.length() == 0) { args[1] = "OK"; } else { args[1] = RequestUtil.filter(message); } writer.print(MessageFormat.format(Constants.MESSAGE_SECTION, args)); // Manager Section args = new Object[9]; args[0] = smClient.getString("htmlManagerServlet.manager"); args[1] = response.encodeURL(request.getContextPath() + "/html/list"); args[2] = smClient.getString("htmlManagerServlet.list"); args[3] = response.encodeURL (request.getContextPath() + "/" + smClient.getString("htmlManagerServlet.helpHtmlManagerFile")); args[4] = smClient.getString("htmlManagerServlet.helpHtmlManager"); args[5] = response.encodeURL (request.getContextPath() + "/" + smClient.getString("htmlManagerServlet.helpManagerFile")); args[6] = smClient.getString("htmlManagerServlet.helpManager"); args[7] = response.encodeURL (request.getContextPath() + "/status"); args[8] = smClient.getString("statusServlet.title"); writer.print(MessageFormat.format(Constants.MANAGER_SECTION, args)); // Apps Header Section args = new Object[7]; args[0] = smClient.getString("htmlManagerServlet.appsTitle"); args[1] = smClient.getString("htmlManagerServlet.appsPath"); args[2] = smClient.getString("htmlManagerServlet.appsVersion"); args[3] = smClient.getString("htmlManagerServlet.appsName"); args[4] = smClient.getString("htmlManagerServlet.appsAvailable"); args[5] = smClient.getString("htmlManagerServlet.appsSessions"); args[6] = smClient.getString("htmlManagerServlet.appsTasks"); writer.print(MessageFormat.format(APPS_HEADER_SECTION, args)); // Apps Row Section // Create sorted map of deployed applications by context name. Container children[] = host.findChildren(); String contextNames[] = new String[children.length]; for (int i = 0; i < children.length; i++) contextNames[i] = children[i].getName(); Arrays.sort(contextNames); String appsStart = smClient.getString("htmlManagerServlet.appsStart"); String appsStop = smClient.getString("htmlManagerServlet.appsStop"); String appsReload = smClient.getString("htmlManagerServlet.appsReload"); String appsUndeploy = smClient.getString("htmlManagerServlet.appsUndeploy"); String appsExpire = smClient.getString("htmlManagerServlet.appsExpire"); String noVersion = "<i>" + smClient.getString("htmlManagerServlet.noVersion") + "</i>"; boolean isHighlighted = true; boolean isDeployed = true; String highlightColor = null; for (String contextName : contextNames) { Context ctxt = (Context) host.findChild(contextName); if (ctxt != null) { // Bugzilla 34818, alternating row colors isHighlighted = !isHighlighted; if(isHighlighted) { highlightColor = "#C3F3C3"; } else { highlightColor = "#FFFFFF"; } String contextPath = ctxt.getPath(); String displayPath = contextPath; if (displayPath.equals("")) { displayPath = "/"; } try { isDeployed = isDeployed(contextName); } catch (Exception e) { // Assume false on failure for safety isDeployed = false; } args = new Object[7]; args[0] = "<a href=\"" + URL_ENCODER.encode(displayPath) + "\">" + displayPath + "</a>"; args[1] = ctxt.getWebappVersion(); if ("".equals(args[1])) { args[1]= noVersion; } args[2] = ctxt.getDisplayName(); if (args[2] == null) { args[2] = "&nbsp;"; } args[3] = new Boolean(ctxt.getAvailable()); args[4] = response.encodeURL (request.getContextPath() + "/html/sessions?path=" + URL_ENCODER.encode(displayPath)); Manager manager = ctxt.getManager(); if (manager instanceof DistributedManager && showProxySessions) { args[5] = new Integer( ((DistributedManager)manager).getActiveSessionsFull()); } else if (ctxt.getManager() != null){ args[5] = new Integer(manager.getActiveSessions()); } else { args[5] = new Integer(0); } args[6] = highlightColor; writer.print (MessageFormat.format(APPS_ROW_DETAILS_SECTION, args)); args = new Object[14]; args[0] = response.encodeURL (request.getContextPath() + "/html/start?path=" + URL_ENCODER.encode(displayPath)); args[1] = appsStart; args[2] = response.encodeURL (request.getContextPath() + "/html/stop?path=" + URL_ENCODER.encode(displayPath)); args[3] = appsStop; args[4] = response.encodeURL (request.getContextPath() + "/html/reload?path=" + URL_ENCODER.encode(displayPath)); args[5] = appsReload; args[6] = response.encodeURL (request.getContextPath() + "/html/undeploy?path=" + URL_ENCODER.encode(displayPath)); args[7] = appsUndeploy; args[8] = response.encodeURL (request.getContextPath() + "/html/expire?path=" + URL_ENCODER.encode(displayPath)); args[9] = appsExpire; args[10] = smClient.getString( "htmlManagerServlet.expire.explain"); if (manager == null) { args[11] = smClient.getString( "htmlManagerServlet.noManager"); } else { args[11] = new Integer( ctxt.getManager().getMaxInactiveInterval()/60); } args[12] = smClient.getString("htmlManagerServlet.expire.unit"); args[13] = highlightColor; if (ctxt.getName().equals(this.context.getName())) { writer.print(MessageFormat.format( MANAGER_APP_ROW_BUTTON_SECTION, args)); } else if (ctxt.getAvailable() && isDeployed) { writer.print(MessageFormat.format( STARTED_DEPLOYED_APPS_ROW_BUTTON_SECTION, args)); } else if (ctxt.getAvailable() && !isDeployed) { writer.print(MessageFormat.format( STARTED_NONDEPLOYED_APPS_ROW_BUTTON_SECTION, args)); } else if (!ctxt.getAvailable() && isDeployed) { writer.print(MessageFormat.format( STOPPED_DEPLOYED_APPS_ROW_BUTTON_SECTION, args)); } else { writer.print(MessageFormat.format( STOPPED_NONDEPLOYED_APPS_ROW_BUTTON_SECTION, args)); } } } // Deploy Section args = new Object[7]; args[0] = smClient.getString("htmlManagerServlet.deployTitle"); args[1] = smClient.getString("htmlManagerServlet.deployServer"); args[2] = response.encodeURL(request.getContextPath() + "/html/deploy"); args[3] = smClient.getString("htmlManagerServlet.deployPath"); args[4] = smClient.getString("htmlManagerServlet.deployConfig"); args[5] = smClient.getString("htmlManagerServlet.deployWar"); args[6] = smClient.getString("htmlManagerServlet.deployButton"); writer.print(MessageFormat.format(DEPLOY_SECTION, args)); args = new Object[4]; args[0] = smClient.getString("htmlManagerServlet.deployUpload"); args[1] = response.encodeURL(request.getContextPath() + "/html/upload"); args[2] = smClient.getString("htmlManagerServlet.deployUploadFile"); args[3] = smClient.getString("htmlManagerServlet.deployButton"); writer.print(MessageFormat.format(UPLOAD_SECTION, args)); // Diagnostics section args = new Object[5]; args[0] = smClient.getString("htmlManagerServlet.diagnosticsTitle"); args[1] = smClient.getString("htmlManagerServlet.diagnosticsLeak"); args[2] = response.encodeURL( request.getContextPath() + "/html/findleaks"); args[3] = smClient.getString("htmlManagerServlet.diagnosticsLeakWarning"); args[4] = smClient.getString("htmlManagerServlet.diagnosticsLeakButton"); writer.print(MessageFormat.format(DIAGNOSTICS_SECTION, args)); // Server Header Section args = new Object[7]; args[0] = smClient.getString("htmlManagerServlet.serverTitle"); args[1] = smClient.getString("htmlManagerServlet.serverVersion"); args[2] = smClient.getString("htmlManagerServlet.serverJVMVersion"); args[3] = smClient.getString("htmlManagerServlet.serverJVMVendor"); args[4] = smClient.getString("htmlManagerServlet.serverOSName"); args[5] = smClient.getString("htmlManagerServlet.serverOSVersion"); args[6] = smClient.getString("htmlManagerServlet.serverOSArch"); writer.print(MessageFormat.format (Constants.SERVER_HEADER_SECTION, args)); // Server Row Section args = new Object[6]; args[0] = ServerInfo.getServerInfo(); args[1] = System.getProperty("java.runtime.version"); args[2] = System.getProperty("java.vm.vendor"); args[3] = System.getProperty("os.name"); args[4] = System.getProperty("os.version"); args[5] = System.getProperty("os.arch"); writer.print(MessageFormat.format(Constants.SERVER_ROW_SECTION, args)); // HTML Tail Section writer.print(Constants.HTML_TAIL_SECTION); // Finish up the response writer.flush(); writer.close(); } /** * Reload the web application at the specified context path. * * @see ManagerServlet#reload(PrintWriter, String, StringManager) * * @param path Context path of the application to be restarted * @return message String */ protected String reload(String path, StringManager smClient) { StringWriter stringWriter = new StringWriter(); PrintWriter printWriter = new PrintWriter(stringWriter); super.reload(printWriter, path, smClient); return stringWriter.toString(); } /** * Undeploy the web application at the specified context path. * * @see ManagerServlet#undeploy(PrintWriter, String, StringManager) * * @param path Context path of the application to be undeployed * @return message String */ protected String undeploy(String path, StringManager smClient) { StringWriter stringWriter = new StringWriter(); PrintWriter printWriter = new PrintWriter(stringWriter); super.undeploy(printWriter, path, smClient); return stringWriter.toString(); } /** * Display session information and invoke list. * * @see ManagerServlet#sessions(PrintWriter, String, int, StringManager) * * @param path Context path of the application to list session information * @param idle Expire all sessions with idle time &ge; idle for this context * @return message String */ public String sessions(String path, int idle, StringManager smClient) { StringWriter stringWriter = new StringWriter(); PrintWriter printWriter = new PrintWriter(stringWriter); super.sessions(printWriter, path, idle, smClient); return stringWriter.toString(); } /** * Display session information and invoke list. * * @see ManagerServlet#sessions(PrintWriter, String, StringManager) * * @param path Context path of the application to list session information * @return message String */ public String sessions(String path, StringManager smClient) { return sessions(path, -1, smClient); } /** * Start the web application at the specified context path. * * @see ManagerServlet#start(PrintWriter, String, StringManager) * * @param path Context path of the application to be started * @return message String */ public String start(String path, StringManager smClient) { StringWriter stringWriter = new StringWriter(); PrintWriter printWriter = new PrintWriter(stringWriter); super.start(printWriter, path, smClient); return stringWriter.toString(); } /** * Stop the web application at the specified context path. * * @see ManagerServlet#stop(PrintWriter, String, StringManager) * * @param path Context path of the application to be stopped * @return message String */ protected String stop(String path, StringManager smClient) { StringWriter stringWriter = new StringWriter(); PrintWriter printWriter = new PrintWriter(stringWriter); super.stop(printWriter, path, smClient); return stringWriter.toString(); } /** * Find potential memory leaks caused by web application reload. * * @see ManagerServlet#findleaks(PrintWriter, StringManager) * * @return message String */ protected String findleaks(StringManager smClient) { StringBuilder msg = new StringBuilder(); StringWriter stringWriter = new StringWriter(); PrintWriter printWriter = new PrintWriter(stringWriter); super.findleaks(printWriter, smClient); if (stringWriter.getBuffer().length() > 0) { msg.append(smClient.getString("htmlManagerServlet.findleaksList")); msg.append(stringWriter.toString()); } else { msg.append(smClient.getString("htmlManagerServlet.findleaksNone")); } return msg.toString(); } /** * @see javax.servlet.Servlet#getServletInfo() */ @Override public String getServletInfo() { return "HTMLManagerServlet, Copyright (c) 1999-2010, The Apache Software Foundation"; } /** * @see javax.servlet.GenericServlet#init() */ @Override public void init() throws ServletException { super.init(); // Set our properties from the initialization parameters String value = null; value = getServletConfig().getInitParameter("showProxySessions"); showProxySessions = Boolean.parseBoolean(value); } // ------------------------------------------------ Sessions administration /** * * Extract the expiration request parameter * * @param path * @param req */ protected String expireSessions(String path, HttpServletRequest req, StringManager smClient) { int idle = -1; String idleParam = req.getParameter("idle"); if (idleParam != null) { try { idle = Integer.parseInt(idleParam); } catch (NumberFormatException e) { log("Could not parse idle parameter to an int: " + idleParam); } } return sessions(path, idle, smClient); } /** * * @param req * @param resp * @throws ServletException * @throws IOException */ protected void doSessions(String path, HttpServletRequest req, HttpServletResponse resp, StringManager smClient) throws ServletException, IOException { req.setAttribute("path", path); String action = req.getParameter("action"); if (debug >= 1) { log("sessions: Session action '" + action + "' for web application at '" + path + "'"); } if ("sessionDetail".equals(action)) { String sessionId = req.getParameter("sessionId"); displaySessionDetailPage(req, resp, path, sessionId, smClient); return; } else if ("invalidateSessions".equals(action)) { String[] sessionIds = req.getParameterValues("sessionIds"); int i = invalidateSessions(path, sessionIds, smClient); req.setAttribute(APPLICATION_MESSAGE, "" + i + " sessions invalidated."); } else if ("removeSessionAttribute".equals(action)) { String sessionId = req.getParameter("sessionId"); String name = req.getParameter("attributeName"); boolean removed = removeSessionAttribute(path, sessionId, name, smClient); String outMessage = removed ? "Session attribute '" + name + "' removed." : "Session did not contain any attribute named '" + name + "'"; req.setAttribute(APPLICATION_MESSAGE, outMessage); resp.sendRedirect(resp.encodeRedirectURL(req.getRequestURL().append("?path=").append(path).append("&action=sessionDetail&sessionId=").append(sessionId).toString())); return; } // else displaySessionsListPage(path, req, resp, smClient); } protected List<Session> getSessionsForPath(String path, StringManager smClient) { if ((path == null) || (!path.startsWith("/") && path.equals(""))) { throw new IllegalArgumentException(smClient.getString( "managerServlet.invalidPath", RequestUtil.filter(path))); } String searchPath = path; if( path.equals("/") ) searchPath = ""; Context ctxt = (Context) host.findChild(searchPath); if (null == ctxt) { throw new IllegalArgumentException(smClient.getString( "managerServlet.noContext", RequestUtil.filter(path))); } Manager manager = ctxt.getManager(); List<Session> sessions = new ArrayList<Session>(); sessions.addAll(Arrays.asList(manager.findSessions())); if (manager instanceof DistributedManager && showProxySessions) { // Add dummy proxy sessions Set<String> sessionIds = ((DistributedManager) manager).getSessionIdsFull(); // Remove active (primary and backup) session IDs from full list for (Session session : sessions) { sessionIds.remove(session.getId()); } // Left with just proxy sessions - add them for (String sessionId : sessionIds) { sessions.add(new DummyProxySession(sessionId)); } } return sessions; } protected Session getSessionForPathAndId(String path, String id, StringManager smClient) throws IOException { if ((path == null) || (!path.startsWith("/") && path.equals(""))) { throw new IllegalArgumentException(smClient.getString( "managerServlet.invalidPath", RequestUtil.filter(path))); } String searchPath = path; if( path.equals("/") ) searchPath = ""; Context ctxt = (Context) host.findChild(searchPath); if (null == ctxt) { throw new IllegalArgumentException(smClient.getString( "managerServlet.noContext", RequestUtil.filter(path))); } Session session = ctxt.getManager().findSession(id); return session; } /** * * @param req * @param resp * @throws ServletException * @throws IOException */ protected void displaySessionsListPage(String path, HttpServletRequest req, HttpServletResponse resp, StringManager smClient) throws ServletException, IOException { List<Session> sessions = getSessionsForPath(path, smClient); String sortBy = req.getParameter("sort"); String orderBy = null; if (null != sortBy && !"".equals(sortBy.trim())) { Comparator<Session> comparator = getComparator(sortBy); if (comparator != null) { orderBy = req.getParameter("order"); if ("DESC".equalsIgnoreCase(orderBy)) { comparator = new ReverseComparator(comparator); // orderBy = "ASC"; } else { //orderBy = "DESC"; } try { Collections.sort(sessions, comparator); } catch (IllegalStateException ise) { // at least 1 of the sessions is invalidated req.setAttribute(APPLICATION_ERROR, "Can't sort session list: one session is invalidated"); } } else { log("WARNING: unknown sort order: " + sortBy); } } // keep sort order req.setAttribute("sort", sortBy); req.setAttribute("order", orderBy); req.setAttribute("activeSessions", sessions); //strong>NOTE</strong> - This header will be overridden // automatically if a <code>RequestDispatcher.forward()</code> call is // ultimately invoked. resp.setHeader("Pragma", "No-cache"); // HTTP 1.0 resp.setHeader("Cache-Control", "no-cache,no-store,max-age=0"); // HTTP 1.1 resp.setDateHeader("Expires", 0); // 0 means now getServletContext().getRequestDispatcher(sessionsListJspPath).include(req, resp); } /** * * @param req * @param resp * @throws ServletException * @throws IOException */ protected void displaySessionDetailPage(HttpServletRequest req, HttpServletResponse resp, String path, String sessionId, StringManager smClient) throws ServletException, IOException { Session session = getSessionForPathAndId(path, sessionId, smClient); //strong>NOTE</strong> - This header will be overridden // automatically if a <code>RequestDispatcher.forward()</code> call is // ultimately invoked. resp.setHeader("Pragma", "No-cache"); // HTTP 1.0 resp.setHeader("Cache-Control", "no-cache,no-store,max-age=0"); // HTTP 1.1 resp.setDateHeader("Expires", 0); // 0 means now req.setAttribute("currentSession", session); getServletContext().getRequestDispatcher(resp.encodeURL(sessionDetailJspPath)).include(req, resp); } /** * Invalidate HttpSessions * @param sessionIds * @return number of invalidated sessions * @throws IOException */ public int invalidateSessions(String path, String[] sessionIds, StringManager smClient) throws IOException { if (null == sessionIds) { return 0; } int nbAffectedSessions = 0; for (int i = 0; i < sessionIds.length; ++i) { String sessionId = sessionIds[i]; HttpSession session = getSessionForPathAndId(path, sessionId, smClient).getSession(); if (null == session) { // Shouldn't happen, but let's play nice... if (debug >= 1) { log("WARNING: can't invalidate null session " + sessionId); } continue; } try { session.invalidate(); ++nbAffectedSessions; if (debug >= 1) { log("Invalidating session id " + sessionId); } } catch (IllegalStateException ise) { if (debug >= 1) { log("Can't invalidate already invalidated session id " + sessionId); } } } return nbAffectedSessions; } /** * Removes an attribute from an HttpSession * @param sessionId * @param attributeName * @return true if there was an attribute removed, false otherwise * @throws IOException */ public boolean removeSessionAttribute(String path, String sessionId, String attributeName, StringManager smClient) throws IOException { HttpSession session = getSessionForPathAndId(path, sessionId, smClient).getSession(); if (null == session) { // Shouldn't happen, but let's play nice... if (debug >= 1) { log("WARNING: can't remove attribute '" + attributeName + "' for null session " + sessionId); } return false; } boolean wasPresent = (null != session.getAttribute(attributeName)); try { session.removeAttribute(attributeName); } catch (IllegalStateException ise) { if (debug >= 1) { log("Can't remote attribute '" + attributeName + "' for invalidated session id " + sessionId); } } return wasPresent; } /** * Sets the maximum inactive interval (session timeout) an HttpSession * @param sessionId * @param maxInactiveInterval in seconds * @return old value for maxInactiveInterval * @throws IOException */ public int setSessionMaxInactiveInterval(String path, String sessionId, int maxInactiveInterval, StringManager smClient) throws IOException { HttpSession session = getSessionForPathAndId(path, sessionId, smClient).getSession(); if (null == session) { // Shouldn't happen, but let's play nice... if (debug >= 1) { log("WARNING: can't set timout for null session " + sessionId); } return 0; } try { int oldMaxInactiveInterval = session.getMaxInactiveInterval(); session.setMaxInactiveInterval(maxInactiveInterval); return oldMaxInactiveInterval; } catch (IllegalStateException ise) { if (debug >= 1) { log("Can't set MaxInactiveInterval '" + maxInactiveInterval + "' for invalidated session id " + sessionId); } return 0; } } protected Comparator<Session> getComparator(String sortBy) { Comparator<Session> comparator = null; if ("CreationTime".equalsIgnoreCase(sortBy)) { comparator = new BaseSessionComparator<Date>() { @Override public Comparable<Date> getComparableObject(Session session) { return new Date(session.getCreationTime()); } }; } else if ("id".equalsIgnoreCase(sortBy)) { comparator = new BaseSessionComparator<String>() { @Override public Comparable<String> getComparableObject(Session session) { return session.getId(); } }; } else if ("LastAccessedTime".equalsIgnoreCase(sortBy)) { comparator = new BaseSessionComparator<Date>() { @Override public Comparable<Date> getComparableObject(Session session) { return new Date(session.getLastAccessedTime()); } }; } else if ("MaxInactiveInterval".equalsIgnoreCase(sortBy)) { comparator = new BaseSessionComparator<Date>() { @Override public Comparable<Date> getComparableObject(Session session) { return new Date(session.getMaxInactiveInterval()); } }; } else if ("new".equalsIgnoreCase(sortBy)) { comparator = new BaseSessionComparator<Boolean>() { @Override public Comparable<Boolean> getComparableObject(Session session) { return Boolean.valueOf(session.getSession().isNew()); } }; } else if ("locale".equalsIgnoreCase(sortBy)) { comparator = new BaseSessionComparator<String>() { @Override public Comparable<String> getComparableObject(Session session) { return JspHelper.guessDisplayLocaleFromSession(session); } }; } else if ("user".equalsIgnoreCase(sortBy)) { comparator = new BaseSessionComparator<String>() { @Override public Comparable<String> getComparableObject(Session session) { return JspHelper.guessDisplayUserFromSession(session); } }; } else if ("UsedTime".equalsIgnoreCase(sortBy)) { comparator = new BaseSessionComparator<Date>() { @Override public Comparable<Date> getComparableObject(Session session) { return new Date(SessionUtils.getUsedTimeForSession(session)); } }; } else if ("InactiveTime".equalsIgnoreCase(sortBy)) { comparator = new BaseSessionComparator<Date>() { @Override public Comparable<Date> getComparableObject(Session session) { return new Date(SessionUtils.getInactiveTimeForSession(session)); } }; } else if ("TTL".equalsIgnoreCase(sortBy)) { comparator = new BaseSessionComparator<Date>() { @Override public Comparable<Date> getComparableObject(Session session) { return new Date(SessionUtils.getTTLForSession(session)); } }; } //TODO: complete this to TTL, etc. return comparator; } // ------------------------------------------------------ Private Constants // These HTML sections are broken in relatively small sections, because of // limited number of substitutions MessageFormat can process // (maximum of 10). private static final String APPS_HEADER_SECTION = "<table border=\"1\" cellspacing=\"0\" cellpadding=\"3\">\n" + "<tr>\n" + " <td colspan=\"6\" class=\"title\">{0}</td>\n" + "</tr>\n" + "<tr>\n" + " <td class=\"header-left\"><small>{1}</small></td>\n" + " <td class=\"header-left\"><small>{2}</small></td>\n" + " <td class=\"header-center\"><small>{3}</small></td>\n" + " <td class=\"header-center\"><small>{4}</small></td>\n" + " <td class=\"header-left\"><small>{5}</small></td>\n" + " <td class=\"header-left\"><small>{6}</small></td>\n" + "</tr>\n"; private static final String APPS_ROW_DETAILS_SECTION = "<tr>\n" + " <td class=\"row-left\" bgcolor=\"{6}\" rowspan=\"2\"><small>{0}</small></td>\n" + " <td class=\"row-left\" bgcolor=\"{6}\" rowspan=\"2\"><small>{1}</small></td>\n" + " <td class=\"row-left\" bgcolor=\"{6}\" rowspan=\"2\"><small>{2}</small></td>\n" + " <td class=\"row-center\" bgcolor=\"{6}\" rowspan=\"2\"><small>{3}</small></td>\n" + " <td class=\"row-center\" bgcolor=\"{6}\" rowspan=\"2\">" + "<small><a href=\"{4}\">{5}</a></small></td>\n"; private static final String MANAGER_APP_ROW_BUTTON_SECTION = " <td class=\"row-left\" bgcolor=\"{13}\">\n" + " <small>\n" + " &nbsp;{1}&nbsp;\n" + " &nbsp;{3}&nbsp;\n" + " &nbsp;{5}&nbsp;\n" + " &nbsp;{7}&nbsp;\n" + " </small>\n" + " </td>\n" + "</tr><tr>\n" + " <td class=\"row-left\" bgcolor=\"{13}\">\n" + " <form method=\"POST\" action=\"{8}\">\n" + " <small>\n" + " &nbsp;<input type=\"submit\" value=\"{9}\">&nbsp;{10}&nbsp;<input type=\"text\" name=\"idle\" size=\"5\" value=\"{11}\">&nbsp;{12}&nbsp;\n" + " </small>\n" + " </form>\n" + " </td>\n" + "</tr>\n"; private static final String STARTED_DEPLOYED_APPS_ROW_BUTTON_SECTION = " <td class=\"row-left\" bgcolor=\"{13}\">\n" + " &nbsp;<small>{1}</small>&nbsp;\n" + " <form class=\"inline\" method=\"POST\" action=\"{2}\">" + " <small><input type=\"submit\" value=\"{3}\"></small>" + " </form>\n" + " <form class=\"inline\" method=\"POST\" action=\"{4}\">" + " <small><input type=\"submit\" value=\"{5}\"></small>" + " </form>\n" + " <form class=\"inline\" method=\"POST\" action=\"{6}\">" + " <small><input type=\"submit\" value=\"{7}\"></small>" + " </form>\n" + " </td>\n" + " </tr><tr>\n" + " <td class=\"row-left\" bgcolor=\"{13}\">\n" + " <form method=\"POST\" action=\"{8}\">\n" + " <small>\n" + " &nbsp;<input type=\"submit\" value=\"{9}\">&nbsp;{10}&nbsp;<input type=\"text\" name=\"idle\" size=\"5\" value=\"{11}\">&nbsp;{12}&nbsp;\n" + " </small>\n" + " </form>\n" + " </td>\n" + "</tr>\n"; private static final String STOPPED_DEPLOYED_APPS_ROW_BUTTON_SECTION = " <td class=\"row-left\" bgcolor=\"{13}\" rowspan=\"2\">\n" + " <form class=\"inline\" method=\"POST\" action=\"{0}\">" + " <small><input type=\"submit\" value=\"{1}\"></small>" + " </form>\n" + " &nbsp;<small>{3}</small>&nbsp;\n" + " &nbsp;<small>{5}</small>&nbsp;\n" + " <form class=\"inline\" method=\"POST\" action=\"{6}\">" + " <small><input type=\"submit\" value=\"{7}\"></small>" + " </form>\n" + " </td>\n" + "</tr>\n<tr></tr>\n"; private static final String STARTED_NONDEPLOYED_APPS_ROW_BUTTON_SECTION = " <td class=\"row-left\" bgcolor=\"{13}\" rowspan=\"2\">\n" + " &nbsp;<small>{1}</small>&nbsp;\n" + " <form class=\"inline\" method=\"POST\" action=\"{2}\">" + " <small><input type=\"submit\" value=\"{3}\"></small>" + " </form>\n" + " <form class=\"inline\" method=\"POST\" action=\"{4}\">" + " <small><input type=\"submit\" value=\"{5}\"></small>" + " </form>\n" + " &nbsp;<small>{7}</small>&nbsp;\n" + " </td>\n" + "</tr>\n<tr></tr>\n"; private static final String STOPPED_NONDEPLOYED_APPS_ROW_BUTTON_SECTION = " <td class=\"row-left\" bgcolor=\"{13}\" rowspan=\"2\">\n" + " <form class=\"inline\" method=\"POST\" action=\"{0}\">" + " <small><input type=\"submit\" value=\"{1}\"></small>" + " </form>\n" + " &nbsp;<small>{3}</small>&nbsp;\n" + " &nbsp;<small>{5}</small>&nbsp;\n" + " &nbsp;<small>{7}</small>&nbsp;\n" + " </td>\n" + "</tr>\n<tr></tr>\n"; private static final String DEPLOY_SECTION = "</table>\n" + "<br>\n" + "<table border=\"1\" cellspacing=\"0\" cellpadding=\"3\">\n" + "<tr>\n" + " <td colspan=\"2\" class=\"title\">{0}</td>\n" + "</tr>\n" + "<tr>\n" + " <td colspan=\"2\" class=\"header-left\"><small>{1}</small></td>\n" + "</tr>\n" + "<tr>\n" + " <td colspan=\"2\">\n" + "<form method=\"post\" action=\"{2}\">\n" + "<table cellspacing=\"0\" cellpadding=\"3\">\n" + "<tr>\n" + " <td class=\"row-right\">\n" + " <small>{3}</small>\n" + " </td>\n" + " <td class=\"row-left\">\n" + " <input type=\"text\" name=\"deployPath\" size=\"20\">\n" + " </td>\n" + "</tr>\n" + "<tr>\n" + " <td class=\"row-right\">\n" + " <small>{4}</small>\n" + " </td>\n" + " <td class=\"row-left\">\n" + " <input type=\"text\" name=\"deployConfig\" size=\"20\">\n" + " </td>\n" + "</tr>\n" + "<tr>\n" + " <td class=\"row-right\">\n" + " <small>{5}</small>\n" + " </td>\n" + " <td class=\"row-left\">\n" + " <input type=\"text\" name=\"deployWar\" size=\"40\">\n" + " </td>\n" + "</tr>\n" + "<tr>\n" + " <td class=\"row-right\">\n" + " &nbsp;\n" + " </td>\n" + " <td class=\"row-left\">\n" + " <input type=\"submit\" value=\"{6}\">\n" + " </td>\n" + "</tr>\n" + "</table>\n" + "</form>\n" + "</td>\n" + "</tr>\n"; private static final String UPLOAD_SECTION = "<tr>\n" + " <td colspan=\"2\" class=\"header-left\"><small>{0}</small></td>\n" + "</tr>\n" + "<tr>\n" + " <td colspan=\"2\">\n" + "<form method=\"post\" action=\"{1}\" " + "enctype=\"multipart/form-data\">\n" + "<table cellspacing=\"0\" cellpadding=\"3\">\n" + "<tr>\n" + " <td class=\"row-right\">\n" + " <small>{2}</small>\n" + " </td>\n" + " <td class=\"row-left\">\n" + " <input type=\"file\" name=\"deployWar\" size=\"40\">\n" + " </td>\n" + "</tr>\n" + "<tr>\n" + " <td class=\"row-right\">\n" + " &nbsp;\n" + " </td>\n" + " <td class=\"row-left\">\n" + " <input type=\"submit\" value=\"{3}\">\n" + " </td>\n" + "</tr>\n" + "</table>\n" + "</form>\n" + "</table>\n" + "<br>\n" + "\n"; private static final String DIAGNOSTICS_SECTION = "<table border=\"1\" cellspacing=\"0\" cellpadding=\"3\">\n" + "<tr>\n" + " <td colspan=\"2\" class=\"title\">{0}</td>\n" + "</tr>\n" + "<tr>\n" + " <td colspan=\"2\" class=\"header-left\"><small>{1}</small></td>\n" + "</tr>\n" + "<tr>\n" + " <td colspan=\"2\">\n" + "<form method=\"post\" action=\"{2}\">\n" + "<table cellspacing=\"0\" cellpadding=\"3\">\n" + "<tr>\n" + " <td class=\"row-left\">\n" + " <input type=\"submit\" value=\"{4}\">\n" + " </td>\n" + " <td class=\"row-left\">\n" + " <small>{3}</small>\n" + " </td>\n" + "</tr>\n" + "</table>\n" + "</form>\n" + "</td>\n" + "</tr>\n" + "</table>\n" + "<br>"; }
Remove unused methods Reduce visibility of methods where possible git-svn-id: 79cef5a5a257cc9dbe40a45ac190115b4780e2d0@1035371 13f79535-47bb-0310-9956-ffa450edef68
java/org/apache/catalina/manager/HTMLManagerServlet.java
Remove unused methods Reduce visibility of methods where possible
<ide><path>ava/org/apache/catalina/manager/HTMLManagerServlet.java <ide> * @param response The response <ide> * @param message a message to display <ide> */ <del> public void list(HttpServletRequest request, <add> protected void list(HttpServletRequest request, <ide> HttpServletResponse response, <ide> String message, <ide> StringManager smClient) throws IOException { <ide> * @param idle Expire all sessions with idle time &ge; idle for this context <ide> * @return message String <ide> */ <del> public String sessions(String path, int idle, StringManager smClient) { <add> protected String sessions(String path, int idle, StringManager smClient) { <ide> <ide> StringWriter stringWriter = new StringWriter(); <ide> PrintWriter printWriter = new PrintWriter(stringWriter); <ide> } <ide> <ide> /** <del> * Display session information and invoke list. <del> * <del> * @see ManagerServlet#sessions(PrintWriter, String, StringManager) <del> * <del> * @param path Context path of the application to list session information <del> * @return message String <del> */ <del> public String sessions(String path, StringManager smClient) { <del> <del> return sessions(path, -1, smClient); <del> } <del> <del> /** <ide> * Start the web application at the specified context path. <ide> * <ide> * @see ManagerServlet#start(PrintWriter, String, StringManager) <ide> * @param path Context path of the application to be started <ide> * @return message String <ide> */ <del> public String start(String path, StringManager smClient) { <add> protected String start(String path, StringManager smClient) { <ide> <ide> StringWriter stringWriter = new StringWriter(); <ide> PrintWriter printWriter = new PrintWriter(stringWriter); <ide> * @return number of invalidated sessions <ide> * @throws IOException <ide> */ <del> public int invalidateSessions(String path, String[] sessionIds, <add> protected int invalidateSessions(String path, String[] sessionIds, <ide> StringManager smClient) throws IOException { <ide> if (null == sessionIds) { <ide> return 0; <ide> * @return true if there was an attribute removed, false otherwise <ide> * @throws IOException <ide> */ <del> public boolean removeSessionAttribute(String path, String sessionId, <add> protected boolean removeSessionAttribute(String path, String sessionId, <ide> String attributeName, StringManager smClient) throws IOException { <ide> HttpSession session = getSessionForPathAndId(path, sessionId, smClient).getSession(); <ide> if (null == session) { <ide> } <ide> } <ide> return wasPresent; <del> } <del> <del> /** <del> * Sets the maximum inactive interval (session timeout) an HttpSession <del> * @param sessionId <del> * @param maxInactiveInterval in seconds <del> * @return old value for maxInactiveInterval <del> * @throws IOException <del> */ <del> public int setSessionMaxInactiveInterval(String path, String sessionId, <del> int maxInactiveInterval, StringManager smClient) throws IOException { <del> HttpSession session = getSessionForPathAndId(path, sessionId, smClient).getSession(); <del> if (null == session) { <del> // Shouldn't happen, but let's play nice... <del> if (debug >= 1) { <del> log("WARNING: can't set timout for null session " + sessionId); <del> } <del> return 0; <del> } <del> try { <del> int oldMaxInactiveInterval = session.getMaxInactiveInterval(); <del> session.setMaxInactiveInterval(maxInactiveInterval); <del> return oldMaxInactiveInterval; <del> } catch (IllegalStateException ise) { <del> if (debug >= 1) { <del> log("Can't set MaxInactiveInterval '" + maxInactiveInterval + "' for invalidated session id " + sessionId); <del> } <del> return 0; <del> } <ide> } <ide> <ide> protected Comparator<Session> getComparator(String sortBy) {
JavaScript
bsd-2-clause
1acb7ada3f16f6b346c4bf871e98af0a3900babd
0
robcolburn/escope,estools/escope,mysticatea/escope,jscrambler/escope
/* Copyright (C) 2012-2014 Yusuke Suzuki <[email protected]> Copyright (C) 2013 Alex Seville <[email protected]> Copyright (C) 2014 Thiago de Arruda <[email protected]> Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /** * Escope (<a href="http://github.com/Constellation/escope">escope</a>) is an <a * href="http://www.ecma-international.org/publications/standards/Ecma-262.htm">ECMAScript</a> * scope analyzer extracted from the <a * href="http://github.com/Constellation/esmangle">esmangle project</a/>. * <p> * <em>escope</em> finds lexical scopes in a source program, i.e. areas of that * program where different occurrences of the same identifier refer to the same * variable. With each scope the contained variables are collected, and each * identifier reference in code is linked to its corresponding variable (if * possible). * <p> * <em>escope</em> works on a syntax tree of the parsed source code which has * to adhere to the <a * href="https://developer.mozilla.org/en-US/docs/SpiderMonkey/Parser_API"> * Mozilla Parser API</a>. E.g. <a href="http://esprima.org">esprima</a> is a parser * that produces such syntax trees. * <p> * The main interface is the {@link analyze} function. * @module */ /*jslint bitwise:true */ (function () { 'use strict'; var Syntax, Map, estraverse, currentScope, globalScope, scopes, options; estraverse = require('estraverse'); Syntax = estraverse.Syntax; if (typeof global.Map !== 'undefined') { // ES6 Map Map = global.Map; } else { Map = function Map() { this.__data = {}; }; Map.prototype.get = function MapGet(key) { key = '$' + key; if (this.__data.hasOwnProperty(key)) { return this.__data[key]; } return undefined; }; Map.prototype.has = function MapHas(key) { key = '$' + key; return this.__data.hasOwnProperty(key); }; Map.prototype.set = function MapSet(key, val) { key = '$' + key; this.__data[key] = val; }; Map.prototype['delete'] = function MapDelete(key) { key = '$' + key; return delete this.__data[key]; }; } function assert(cond, text) { if (!cond) { throw new Error(text); } } function defaultOptions() { return { optimistic: false, directive: false, ecmaVersion: 5 }; } function updateDeeply(target, override) { var key, val; function isHashObject(target) { return typeof target === 'object' && target instanceof Object && !(target instanceof RegExp); } for (key in override) { if (override.hasOwnProperty(key)) { val = override[key]; if (isHashObject(val)) { if (isHashObject(target[key])) { updateDeeply(target[key], val); } else { target[key] = updateDeeply({}, val); } } else { target[key] = val; } } } return target; } /** * A Reference represents a single occurrence of an identifier in code. * @class Reference */ function Reference(ident, scope, flag, writeExpr, maybeImplicitGlobal, partial) { /** * Identifier syntax node. * @member {esprima#Identifier} Reference#identifier */ this.identifier = ident; /** * Reference to the enclosing Scope. * @member {Scope} Reference#from */ this.from = scope; /** * Whether the reference comes from a dynamic scope (such as 'eval', * 'with', etc.), and may be trapped by dynamic scopes. * @member {boolean} Reference#tainted */ this.tainted = false; /** * The variable this reference is resolved with. * @member {Variable} Reference#resolved */ this.resolved = null; /** * The read-write mode of the reference. (Value is one of {@link * Reference.READ}, {@link Reference.RW}, {@link Reference.WRITE}). * @member {number} Reference#flag * @private */ this.flag = flag; if (this.isWrite()) { /** * If reference is writeable, this is the tree being written to it. * @member {esprima#Node} Reference#writeExpr */ this.writeExpr = writeExpr; /** * Whether the Reference might refer to a partial value of writeExpr. * @member {boolean} Reference#partial */ this.partial = partial; } this.__maybeImplicitGlobal = maybeImplicitGlobal; } /** * @constant Reference.READ * @private */ Reference.READ = 0x1; /** * @constant Reference.WRITE * @private */ Reference.WRITE = 0x2; /** * @constant Reference.RW * @private */ Reference.RW = Reference.READ | Reference.WRITE; /** * Whether the reference is static. * @method Reference#isStatic * @return {boolean} */ Reference.prototype.isStatic = function isStatic() { return !this.tainted && this.resolved && this.resolved.scope.isStatic(); }; /** * Whether the reference is writeable. * @method Reference#isWrite * @return {boolean} */ Reference.prototype.isWrite = function isWrite() { return !!(this.flag & Reference.WRITE); }; /** * Whether the reference is readable. * @method Reference#isRead * @return {boolean} */ Reference.prototype.isRead = function isRead() { return !!(this.flag & Reference.READ); }; /** * Whether the reference is read-only. * @method Reference#isReadOnly * @return {boolean} */ Reference.prototype.isReadOnly = function isReadOnly() { return this.flag === Reference.READ; }; /** * Whether the reference is write-only. * @method Reference#isWriteOnly * @return {boolean} */ Reference.prototype.isWriteOnly = function isWriteOnly() { return this.flag === Reference.WRITE; }; /** * Whether the reference is read-write. * @method Reference#isReadWrite * @return {boolean} */ Reference.prototype.isReadWrite = function isReadWrite() { return this.flag === Reference.RW; }; /** * A Variable represents a locally scoped identifier. These include arguments to * functions. * @class Variable */ function Variable(name, scope) { /** * The variable name, as given in the source code. * @member {String} Variable#name */ this.name = name; /** * List of defining occurrences of this variable (like in 'var ...' * statements or as parameter), as AST nodes. * @member {esprima.Identifier[]} Variable#identifiers */ this.identifiers = []; /** * List of {@link Reference|references} of this variable (excluding parameter entries) * in its defining scope and all nested scopes. For defining * occurrences only see {@link Variable#defs}. * @member {Reference[]} Variable#references */ this.references = []; /** * List of defining occurrences of this variable (like in 'var ...' * statements or as parameter), as custom objects. * @typedef {Object} DefEntry * @property {String} DefEntry.type - the type of the occurrence (e.g. * "Parameter", "Variable", ...) * @property {esprima.Identifier} DefEntry.name - the identifier AST node of the occurrence * @property {esprima.Node} DefEntry.node - the enclosing node of the * identifier * @property {esprima.Node} [DefEntry.parent] - the enclosing statement * node of the identifier * @member {DefEntry[]} Variable#defs */ this.defs = []; this.tainted = false; /** * Whether this is a stack variable. * @member {boolean} Variable#stack */ this.stack = true; /** * Reference to the enclosing Scope. * @member {Scope} Variable#scope */ this.scope = scope; } Variable.CatchClause = 'CatchClause'; Variable.Parameter = 'Parameter'; Variable.FunctionName = 'FunctionName'; Variable.ClassName = 'ClassName'; Variable.Variable = 'Variable'; Variable.TDZ = 'TDZ'; Variable.ImplicitGlobalVariable = 'ImplicitGlobalVariable'; function isMethodDefinition(block, parent) { // Check // + Class MethodDefinition // + Object MethodDefiniton // cases. if (block.type !== Syntax.FunctionExpression) { return false; } if (!parent) { return false; } if (parent.type === Syntax.MethodDefinition && block === parent.value) { return true; } if (parent.type === Syntax.Property && parent.method && block === parent.value) { return true; } return false; } function isStrictScope(scope, block, parent) { var body, i, iz, stmt, expr; // When upper scope is exists and strict, inner scope is also strict. if (scope.upper && scope.upper.isStrict) { return true; } // ArrowFunctionExpression's scope is always strict scope. if (block.type === Syntax.ArrowFunctionExpression) { return true; } if (parent) { if (isMethodDefinition(block, parent)) { return true; } } if (scope.type === 'class') { return true; } else if (scope.type === 'function') { body = block.body; } else if (scope.type === 'global') { body = block; } else { return false; } // Search 'use strict' directive. if (options.directive) { for (i = 0, iz = body.body.length; i < iz; ++i) { stmt = body.body[i]; if (stmt.type !== 'DirectiveStatement') { break; } if (stmt.raw === '"use strict"' || stmt.raw === '\'use strict\'') { return true; } } } else { for (i = 0, iz = body.body.length; i < iz; ++i) { stmt = body.body[i]; if (stmt.type !== Syntax.ExpressionStatement) { break; } expr = stmt.expression; if (expr.type !== Syntax.Literal || typeof expr.value !== 'string') { break; } if (expr.raw != null) { if (expr.raw === '"use strict"' || expr.raw === '\'use strict\'') { return true; } } else { if (expr.value === 'use strict') { return true; } } } } return false; } /* Special Scope types. */ var SCOPE_NORMAL = 0, SCOPE_FUNCTION_EXPRESSION_NAME = 1, SCOPE_TDZ = 2; /** * @class Scope */ function Scope(scopeManager, block, parent, scopeType) { /** * One of 'catch', 'with', 'function', 'global' or 'block'. * @member {String} Scope#type */ this.type = (scopeType === SCOPE_TDZ) ? 'TDZ' : (block.type === Syntax.BlockStatement) ? 'block' : (block.type === Syntax.FunctionExpression || block.type === Syntax.FunctionDeclaration || block.type === Syntax.ArrowFunctionExpression) ? 'function' : (block.type === Syntax.CatchClause) ? 'catch' : (block.type === Syntax.ForInStatement || block.type === Syntax.ForOfStatement || block.type === Syntax.ForStatement) ? 'for' : (block.type === Syntax.WithStatement) ? 'with' : (block.type === Syntax.ClassBody) ? 'class' : 'global'; /** * The scoped {@link Variable}s of this scope, as <code>{ Variable.name * : Variable }</code>. * @member {Map} Scope#set */ this.set = new Map(); /** * The tainted variables of this scope, as <code>{ Variable.name : * boolean }</code>. * @member {Map} Scope#taints */ this.taints = new Map(); /** * Generally, through the lexical scoping of JS you can always know * which variable an identifier in the source code refers to. There are * a few exceptions to this rule. With 'global' and 'with' scopes you * can only decide at runtime which variable a reference refers to. * Moreover, if 'eval()' is used in a scope, it might introduce new * bindings in this or its prarent scopes. * All those scopes are considered 'dynamic'. * @member {boolean} Scope#dynamic */ this.dynamic = this.type === 'global' || this.type === 'with'; /** * A reference to the scope-defining syntax node. * @member {esprima.Node} Scope#block */ this.block = block; /** * The {@link Reference|references} that are not resolved with this scope. * @member {Reference[]} Scope#through */ this.through = []; /** * The scoped {@link Variable}s of this scope. In the case of a * 'function' scope this includes the automatic argument <em>arguments</em> as * its first element, as well as all further formal arguments. * @member {Variable[]} Scope#variables */ this.variables = []; /** * Any variable {@link Reference|reference} found in this scope. This * includes occurrences of local variables as well as variables from * parent scopes (including the global scope). For local variables * this also includes defining occurrences (like in a 'var' statement). * In a 'function' scope this does not include the occurrences of the * formal parameter in the parameter list. * @member {Reference[]} Scope#references */ this.references = []; /** * For 'global' and 'function' scopes, this is a self-reference. For * other scope types this is the <em>variableScope</em> value of the * parent scope. * @member {Scope} Scope#variableScope */ this.variableScope = (this.type === 'global' || this.type === 'function') ? this : currentScope.variableScope; /** * Whether this scope is created by a FunctionExpression. * @member {boolean} Scope#functionExpressionScope */ this.functionExpressionScope = false; /** * Whether this is a scope that contains an 'eval()' invocation. * @member {boolean} Scope#directCallToEvalScope */ this.directCallToEvalScope = false; /** * @member {boolean} Scope#thisFound */ this.thisFound = false; this.__left = []; if (scopeType === SCOPE_FUNCTION_EXPRESSION_NAME) { this.__define(block.id, { type: Variable.FunctionName, name: block.id, node: block }); this.functionExpressionScope = true; } else { if (this.type === 'function') { this.__defineArguments(); } if (block.type === Syntax.FunctionExpression && block.id && !isMethodDefinition(block, parent)) { scopeManager.__nestFunctionExpressionNameScope(block, parent); } } /** * Reference to the parent {@link Scope|scope}. * @member {Scope} Scope#upper */ this.upper = currentScope; /** * Whether 'use strict' is in effect in this scope. * @member {boolean} Scope#isStrict */ this.isStrict = isStrictScope(this, block, parent); /** * List of nested {@link Scope}s. * @member {Scope[]} Scope#childScopes */ this.childScopes = []; if (currentScope) { currentScope.childScopes.push(this); } // RAII currentScope = this; if (this.type === 'global') { globalScope = this; globalScope.implicit = { set: new Map(), variables: [], /** * List of {@link Reference}s that are left to be resolved (i.e. which * need to be linked to the variable they refer to). * @member {Reference[]} Scope#implicit#left */ left: [] }; } scopes.push(this); } Scope.prototype.__close = function __close() { var i, iz, ref, current, implicit, info; // Because if this is global environment, upper is null if (!this.dynamic || options.optimistic) { // static resolve for (i = 0, iz = this.__left.length; i < iz; ++i) { ref = this.__left[i]; if (!this.__resolve(ref)) { this.__delegateToUpperScope(ref); } } } else { // this is "global" / "with" / "function with eval" environment if (this.type === 'with') { for (i = 0, iz = this.__left.length; i < iz; ++i) { ref = this.__left[i]; ref.tainted = true; this.__delegateToUpperScope(ref); } } else { for (i = 0, iz = this.__left.length; i < iz; ++i) { // notify all names are through to global ref = this.__left[i]; current = this; do { current.through.push(ref); current = current.upper; } while (current); } } } if (this.type === 'global') { implicit = []; for (i = 0, iz = this.__left.length; i < iz; ++i) { ref = this.__left[i]; if (ref.__maybeImplicitGlobal && !this.set.has(ref.identifier.name)) { implicit.push(ref.__maybeImplicitGlobal); } } // create an implicit global variable from assignment expression for (i = 0, iz = implicit.length; i < iz; ++i) { info = implicit[i]; this.__defineImplicit(info.pattern, { type: Variable.ImplicitGlobalVariable, name: info.pattern, node: info.node }); } this.implicit.left = this.__left; } this.__left = null; currentScope = this.upper; }; Scope.prototype.__resolve = function __resolve(ref) { var variable, name; name = ref.identifier.name; if (this.set.has(name)) { variable = this.set.get(name); variable.references.push(ref); variable.stack = variable.stack && ref.from.variableScope === this.variableScope; if (ref.tainted) { variable.tainted = true; this.taints.set(variable.name, true); } ref.resolved = variable; return true; } return false; }; Scope.prototype.__delegateToUpperScope = function __delegateToUpperScope(ref) { if (this.upper) { this.upper.__left.push(ref); } this.through.push(ref); }; Scope.prototype.__defineGeneric = function (name, set, variables, node, info) { var variable; variable = set.get(name); if (!variable) { variable = new Variable(name, this); set.set(name, variable); variables.push(variable); } if (info) { variable.defs.push(info); } if (node) { variable.identifiers.push(node); } }; Scope.prototype.__defineArguments = function () { this.__defineGeneric('arguments', this.set, this.variables); this.taints.set('arguments', true); }; Scope.prototype.__defineImplicit = function (node, info) { if (node && node.type === Syntax.Identifier) { this.__defineGeneric(node.name, this.implicit.set, this.implicit.variables, node, info); } }; Scope.prototype.__define = function (node, info) { if (node && node.type === Syntax.Identifier) { this.__defineGeneric(node.name, this.set, this.variables, node, info); } }; Scope.prototype.__referencing = function __referencing(node, assign, writeExpr, maybeImplicitGlobal, partial) { var ref; // because Array element may be null if (node && node.type === Syntax.Identifier) { ref = new Reference(node, this, assign || Reference.READ, writeExpr, maybeImplicitGlobal, !!partial); this.references.push(ref); this.__left.push(ref); } }; Scope.prototype.__detectEval = function __detectEval() { var current; current = this; this.directCallToEvalScope = true; do { current.dynamic = true; current = current.upper; } while (current); }; Scope.prototype.__detectThis = function __detectThis() { this.thisFound = true; }; Scope.prototype.__isClosed = function isClosed() { return this.__left === null; }; // API Scope#resolve(name) // returns resolved reference Scope.prototype.resolve = function resolve(ident) { var ref, i, iz; assert(this.__isClosed(), 'scope should be closed'); assert(ident.type === Syntax.Identifier, 'target should be identifier'); for (i = 0, iz = this.references.length; i < iz; ++i) { ref = this.references[i]; if (ref.identifier === ident) { return ref; } } return null; }; // API Scope#isStatic // returns this scope is static Scope.prototype.isStatic = function isStatic() { return !this.dynamic; }; // API Scope#isArgumentsMaterialized // return this scope has materialized arguments Scope.prototype.isArgumentsMaterialized = function isArgumentsMaterialized() { // TODO(Constellation) // We can more aggressive on this condition like this. // // function t() { // // arguments of t is always hidden. // function arguments() { // } // } var variable; // This is not function scope if (this.type !== 'function') { return true; } if (!this.isStatic()) { return true; } variable = this.set.get('arguments'); assert(variable, 'always have arguments variable'); return variable.tainted || variable.references.length !== 0; }; // API Scope#isThisMaterialized // return this scope has materialized `this` reference Scope.prototype.isThisMaterialized = function isThisMaterialized() { // This is not function scope if (this.type !== 'function') { return true; } if (!this.isStatic()) { return true; } return this.thisFound; }; Scope.mangledName = '__$escope$__'; Scope.prototype.attach = function attach() { if (!this.functionExpressionScope) { this.block[Scope.mangledName] = this; } }; Scope.prototype.detach = function detach() { if (!this.functionExpressionScope) { delete this.block[Scope.mangledName]; } }; Scope.prototype.isUsedName = function (name) { if (this.set.has(name)) { return true; } for (var i = 0, iz = this.through.length; i < iz; ++i) { if (this.through[i].identifier.name === name) { return true; } } return false; }; /** * @class ScopeManager */ function ScopeManager(scopes, options) { this.scopes = scopes; this.attached = false; this.__options = options; } // Returns appropliate scope for this node ScopeManager.prototype.__get = function __get(node) { var i, iz, scope; if (this.attached) { return node[Scope.mangledName] || null; } for (i = 0, iz = this.scopes.length; i < iz; ++i) { scope = this.scopes[i]; if (!scope.functionExpressionScope) { if (scope.block === node) { return scope; } } } return null; }; ScopeManager.prototype.acquire = function acquire(node) { return this.__get(node); }; ScopeManager.prototype.release = function release(node) { var scope = this.__get(node); if (scope) { scope = scope.upper; while (scope) { if (!scope.functionExpressionScope) { return scope; } scope = scope.upper; } } return null; }; ScopeManager.prototype.attach = function attach() { var i, iz; for (i = 0, iz = this.scopes.length; i < iz; ++i) { this.scopes[i].attach(); } this.attached = true; }; ScopeManager.prototype.detach = function detach() { var i, iz; for (i = 0, iz = this.scopes.length; i < iz; ++i) { this.scopes[i].detach(); } this.attached = false; }; ScopeManager.prototype.__nestScope = function (node, parent) { return new Scope(this, node, parent, SCOPE_NORMAL); }; ScopeManager.prototype.__nestTDZScope = function (node, iterationNode) { return new Scope(this, node, iterationNode, SCOPE_TDZ); }; ScopeManager.prototype.__nestFunctionExpressionNameScope = function (node, parent) { return new Scope(this, node, parent, SCOPE_FUNCTION_EXPRESSION_NAME); }; ScopeManager.prototype.__isES6 = function () { return this.__options.ecmaVersion >= 6; }; function traverseIdentifierInPattern(rootPattern, callback) { estraverse.traverse(rootPattern, { enter: function (pattern, parent) { var i, iz, element, property; switch (pattern.type) { case Syntax.Identifier: // Toplevel identifier. if (parent === null) { callback(pattern, true); } break; case Syntax.SpreadElement: if (pattern.argument.type === Syntax.Identifier) { callback(pattern.argument, false); } break; case Syntax.ObjectPattern: for (i = 0, iz = pattern.properties.length; i < iz; ++i) { property = pattern.properties[i]; if (property.shorthand) { callback(property.key, false); continue; } if (property.value.type === Syntax.Identifier) { callback(property.value, false); continue; } } break; case Syntax.ArrayPattern: for (i = 0, iz = pattern.elements.length; i < iz; ++i) { element = pattern.elements[i]; if (element && element.type === Syntax.Identifier) { callback(element, false); } } break; } } }); } function doVariableDeclaration(variableTargetScope, type, node, index) { var decl, init; decl = node.declarations[index]; init = decl.init; // FIXME: Don't consider initializer with complex patterns. // Such as, // var [a, b, c = 20] = array; traverseIdentifierInPattern(decl.id, function (pattern, toplevel) { variableTargetScope.__define(pattern, { type: type, name: pattern, node: decl, index: index, kind: node.kind, parent: node }); if (init) { currentScope.__referencing(pattern, Reference.WRITE, init, null, !toplevel); } }); } function materializeTDZScope(scopeManager, node, iterationNode) { // http://people.mozilla.org/~jorendorff/es6-draft.html#sec-runtime-semantics-forin-div-ofexpressionevaluation-abstract-operation // TDZ scope hides the declaration's names. scopeManager.__nestTDZScope(node, iterationNode); doVariableDeclaration(currentScope, Variable.TDZ, iterationNode.left, 0); currentScope.__referencing(node); } function materializeIterationScope(scopeManager, node) { // Generate iteration scope for upper ForIn/ForOf Statements. // parent node for __nestScope is only necessary to // distinguish MethodDefinition. var letOrConstDecl; scopeManager.__nestScope(node, null); letOrConstDecl = node.left; doVariableDeclaration(currentScope, Variable.Variable, letOrConstDecl, 0); traverseIdentifierInPattern(letOrConstDecl.declarations[0].id, function (pattern) { currentScope.__referencing(pattern, Reference.WRITE, node.right, null, true); }); } /** * Main interface function. Takes an Esprima syntax tree and returns the * analyzed scopes. * @function analyze * @param {esprima.Tree} tree * @param {Object} providedOptions - Options that tailor the scope analysis * @param {boolean} [providedOptions.optimistic=false] - the optimistic flag * @param {boolean} [providedOptions.directive=false]- the directive flag * @param {boolean} [providedOptions.ignoreEval=false]- whether to check 'eval()' calls * @return {ScopeManager} */ function analyze(tree, providedOptions) { var resultScopes, scopeManager; options = updateDeeply(defaultOptions(), providedOptions); resultScopes = scopes = []; currentScope = null; globalScope = null; scopeManager = new ScopeManager(resultScopes, options); // attach scope and collect / resolve names estraverse.traverse(tree, { enter: function enter(node, parent) { var i, iz, decl, variableTargetScope; // Special path for ForIn/ForOf Statement block scopes. if (parent && (parent.type === Syntax.ForInStatement || parent.type === Syntax.ForOfStatement) && parent.left.type === Syntax.VariableDeclaration && parent.left.kind !== 'var') { // Construct TDZ scope. if (parent.right === node) { materializeTDZScope(scopeManager, node, parent); } if (parent.body === node) { materializeIterationScope(scopeManager, parent); } } switch (this.type()) { case Syntax.AssignmentExpression: if (node.operator === '=') { traverseIdentifierInPattern(node.left, function (pattern, toplevel) { var maybeImplicitGlobal = null; if (!currentScope.isStrict) { maybeImplicitGlobal = { pattern: pattern, node: node }; } currentScope.__referencing(pattern, Reference.WRITE, node.right, maybeImplicitGlobal, !toplevel); }); } else { currentScope.__referencing(node.left, Reference.RW, node.right); } currentScope.__referencing(node.right); break; case Syntax.ArrayExpression: for (i = 0, iz = node.elements.length; i < iz; ++i) { currentScope.__referencing(node.elements[i]); } break; case Syntax.BlockStatement: if (scopeManager.__isES6()) { if (!parent || parent.type !== Syntax.FunctionExpression && parent.type !== Syntax.FunctionDeclaration && parent.type !== Syntax.ArrowFunctionExpression) { scopeManager.__nestScope(node, parent); } } break; case Syntax.BinaryExpression: currentScope.__referencing(node.left); currentScope.__referencing(node.right); break; case Syntax.BreakStatement: break; case Syntax.CallExpression: currentScope.__referencing(node.callee); for (i = 0, iz = node['arguments'].length; i < iz; ++i) { currentScope.__referencing(node['arguments'][i]); } // Check this is direct call to eval if (!options.ignoreEval && node.callee.type === Syntax.Identifier && node.callee.name === 'eval') { // NOTE: This should be `variableScope`. Since direct eval call always creates Lexical environment and // let / const should be enclosed into it. Only VariableDeclaration affects on the caller's environment. currentScope.variableScope.__detectEval(); } break; case Syntax.CatchClause: scopeManager.__nestScope(node, parent); traverseIdentifierInPattern(node.param, function (pattern) { currentScope.__define(pattern, { type: Variable.CatchClause, name: node.param, node: node }); }); break; case Syntax.ClassDeclaration: // Outer block scope. currentScope.__define(node.id, { type: Variable.ClassName, name: node.id, node: node }); currentScope.__referencing(node.superClass); break; case Syntax.ClassBody: // ClassBody scope. scopeManager.__nestScope(node, parent); if (parent && parent.id) { currentScope.__define(parent.id, { type: Variable.ClassName, name: node.id, node: node }); } break; case Syntax.ClassExpression: currentScope.__referencing(node.superClass); break; case Syntax.ConditionalExpression: currentScope.__referencing(node.test); currentScope.__referencing(node.consequent); currentScope.__referencing(node.alternate); break; case Syntax.ContinueStatement: break; case Syntax.DirectiveStatement: break; case Syntax.DoWhileStatement: currentScope.__referencing(node.test); break; case Syntax.DebuggerStatement: break; case Syntax.EmptyStatement: break; case Syntax.ExpressionStatement: currentScope.__referencing(node.expression); break; case Syntax.ForStatement: if (node.init && node.init.type === Syntax.VariableDeclaration && node.init.kind !== 'var') { // Create ForStatement declaration. // NOTE: In ES6, ForStatement dynamically generates // per iteration environment. However, escope is // a static analyzer, we only generate one scope for ForStatement. scopeManager.__nestScope(node, parent); } currentScope.__referencing(node.init); currentScope.__referencing(node.test); currentScope.__referencing(node.update); break; case Syntax.ForOfStatement: case Syntax.ForInStatement: if (node.left.type === Syntax.VariableDeclaration) { if (node.left.kind !== 'var') { // LetOrConst Declarations are specially handled. break; } traverseIdentifierInPattern(node.left.declarations[0].id, function (pattern) { currentScope.__referencing(pattern, Reference.WRITE, node.right, null, true); }); } else { traverseIdentifierInPattern(node.left, function (pattern) { var maybeImplicitGlobal = null; if (!currentScope.isStrict) { maybeImplicitGlobal = { pattern: pattern, node: node }; } currentScope.__referencing(pattern, Reference.WRITE, node.right, maybeImplicitGlobal, true); }); } currentScope.__referencing(node.right); break; case Syntax.FunctionDeclaration: // FunctionDeclaration name is defined in upper scope // NOTE: Not referring variableScope. It is intended. // Since // in ES5, FunctionDeclaration should be in FunctionBody. // in ES6, FunctionDeclaration should be block scoped. currentScope.__define(node.id, { type: Variable.FunctionName, name: node.id, node: node }); // falls through case Syntax.FunctionExpression: case Syntax.ArrowFunctionExpression: // id is defined in upper scope scopeManager.__nestScope(node, parent); for (i = 0, iz = node.params.length; i < iz; ++i) { traverseIdentifierInPattern(node.params[i], function (pattern) { currentScope.__define(pattern, { type: Variable.Parameter, name: pattern, node: node, index: i }); }); } break; case Syntax.Identifier: break; case Syntax.IfStatement: currentScope.__referencing(node.test); break; case Syntax.Literal: break; case Syntax.LabeledStatement: break; case Syntax.LogicalExpression: currentScope.__referencing(node.left); currentScope.__referencing(node.right); break; case Syntax.MemberExpression: currentScope.__referencing(node.object); if (node.computed) { currentScope.__referencing(node.property); } break; case Syntax.NewExpression: currentScope.__referencing(node.callee); for (i = 0, iz = node['arguments'].length; i < iz; ++i) { currentScope.__referencing(node['arguments'][i]); } break; case Syntax.ObjectExpression: break; case Syntax.Program: scopeManager.__nestScope(node, parent); break; case Syntax.Property: // Don't referencing variables when the parent type is ObjectPattern. if (parent.type !== Syntax.ObjectExpression) { break; } if (node.computed) { currentScope.__referencing(node.key); } if (node.kind === 'init') { currentScope.__referencing(node.value); } break; case Syntax.MethodDefinition: if (node.computed) { currentScope.__referencing(node.key); } break; case Syntax.ReturnStatement: currentScope.__referencing(node.argument); break; case Syntax.SequenceExpression: for (i = 0, iz = node.expressions.length; i < iz; ++i) { currentScope.__referencing(node.expressions[i]); } break; case Syntax.SwitchStatement: currentScope.__referencing(node.discriminant); break; case Syntax.SwitchCase: currentScope.__referencing(node.test); break; case Syntax.TaggedTemplateExpression: currentScope.__referencing(node.tag); break; case Syntax.TemplateLiteral: for (i = 0, iz = node.expressions.length; i < iz; ++i) { currentScope.__referencing(node.expressions[i]); } break; case Syntax.ThisExpression: currentScope.variableScope.__detectThis(); break; case Syntax.ThrowStatement: currentScope.__referencing(node.argument); break; case Syntax.TryStatement: break; case Syntax.UnaryExpression: currentScope.__referencing(node.argument); break; case Syntax.UpdateExpression: currentScope.__referencing(node.argument, Reference.RW, null); break; case Syntax.VariableDeclaration: if (node.kind !== 'var' && parent) { if (parent.type === Syntax.ForInStatement || parent.type === Syntax.ForOfStatement) { // e.g. // for (let i in abc); // In this case, they are specially handled in ForIn/ForOf statements. break; } } variableTargetScope = (node.kind === 'var') ? currentScope.variableScope : currentScope; for (i = 0, iz = node.declarations.length; i < iz; ++i) { decl = node.declarations[i]; doVariableDeclaration(variableTargetScope, Variable.Variable, node, i); if (decl.init) { currentScope.__referencing(decl.init); } } break; case Syntax.VariableDeclarator: break; case Syntax.WhileStatement: currentScope.__referencing(node.test); break; case Syntax.WithStatement: currentScope.__referencing(node.object); // Then nest scope for WithStatement. scopeManager.__nestScope(node, parent); break; } }, leave: function leave(node) { while (currentScope && node === currentScope.block) { currentScope.__close(); } } }); assert(currentScope === null); globalScope = null; scopes = null; options = null; return scopeManager; } /** @name module:escope.version */ exports.version = '2.0.0-dev'; /** @name module:escope.Reference */ exports.Reference = Reference; /** @name module:escope.Variable */ exports.Variable = Variable; /** @name module:escope.Scope */ exports.Scope = Scope; /** @name module:escope.ScopeManager */ exports.ScopeManager = ScopeManager; /** @name module:escope.analyze */ exports.analyze = analyze; }()); /* vim: set sw=4 ts=4 et tw=80 : */
escope.js
/* Copyright (C) 2012-2014 Yusuke Suzuki <[email protected]> Copyright (C) 2013 Alex Seville <[email protected]> Copyright (C) 2014 Thiago de Arruda <[email protected]> Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /** * Escope (<a href="http://github.com/Constellation/escope">escope</a>) is an <a * href="http://www.ecma-international.org/publications/standards/Ecma-262.htm">ECMAScript</a> * scope analyzer extracted from the <a * href="http://github.com/Constellation/esmangle">esmangle project</a/>. * <p> * <em>escope</em> finds lexical scopes in a source program, i.e. areas of that * program where different occurrences of the same identifier refer to the same * variable. With each scope the contained variables are collected, and each * identifier reference in code is linked to its corresponding variable (if * possible). * <p> * <em>escope</em> works on a syntax tree of the parsed source code which has * to adhere to the <a * href="https://developer.mozilla.org/en-US/docs/SpiderMonkey/Parser_API"> * Mozilla Parser API</a>. E.g. <a href="http://esprima.org">esprima</a> is a parser * that produces such syntax trees. * <p> * The main interface is the {@link analyze} function. * @module */ /*jslint bitwise:true */ /*global exports:true, define:true, require:true*/ (function (factory, global) { 'use strict'; function namespace(str, obj) { var i, iz, names, name; names = str.split('.'); for (i = 0, iz = names.length; i < iz; ++i) { name = names[i]; if (obj.hasOwnProperty(name)) { obj = obj[name]; } else { obj = (obj[name] = {}); } } return obj; } // Universal Module Definition (UMD) to support AMD, CommonJS/Node.js, // and plain browser loading, if (typeof define === 'function' && define.amd) { define('escope', ['exports', 'estraverse'], function (exports, estraverse) { factory(exports, global, estraverse); }); } else if (typeof exports !== 'undefined') { factory(exports, global, require('estraverse')); } else { factory(namespace('escope', global), global, global.estraverse); } }(function (exports, global, estraverse) { 'use strict'; var Syntax, Map, currentScope, globalScope, scopes, options; Syntax = estraverse.Syntax; if (typeof global.Map !== 'undefined') { // ES6 Map Map = global.Map; } else { Map = function Map() { this.__data = {}; }; Map.prototype.get = function MapGet(key) { key = '$' + key; if (this.__data.hasOwnProperty(key)) { return this.__data[key]; } return undefined; }; Map.prototype.has = function MapHas(key) { key = '$' + key; return this.__data.hasOwnProperty(key); }; Map.prototype.set = function MapSet(key, val) { key = '$' + key; this.__data[key] = val; }; Map.prototype['delete'] = function MapDelete(key) { key = '$' + key; return delete this.__data[key]; }; } function assert(cond, text) { if (!cond) { throw new Error(text); } } function defaultOptions() { return { optimistic: false, directive: false, ecmaVersion: 5 }; } function updateDeeply(target, override) { var key, val; function isHashObject(target) { return typeof target === 'object' && target instanceof Object && !(target instanceof RegExp); } for (key in override) { if (override.hasOwnProperty(key)) { val = override[key]; if (isHashObject(val)) { if (isHashObject(target[key])) { updateDeeply(target[key], val); } else { target[key] = updateDeeply({}, val); } } else { target[key] = val; } } } return target; } /** * A Reference represents a single occurrence of an identifier in code. * @class Reference */ function Reference(ident, scope, flag, writeExpr, maybeImplicitGlobal, partial) { /** * Identifier syntax node. * @member {esprima#Identifier} Reference#identifier */ this.identifier = ident; /** * Reference to the enclosing Scope. * @member {Scope} Reference#from */ this.from = scope; /** * Whether the reference comes from a dynamic scope (such as 'eval', * 'with', etc.), and may be trapped by dynamic scopes. * @member {boolean} Reference#tainted */ this.tainted = false; /** * The variable this reference is resolved with. * @member {Variable} Reference#resolved */ this.resolved = null; /** * The read-write mode of the reference. (Value is one of {@link * Reference.READ}, {@link Reference.RW}, {@link Reference.WRITE}). * @member {number} Reference#flag * @private */ this.flag = flag; if (this.isWrite()) { /** * If reference is writeable, this is the tree being written to it. * @member {esprima#Node} Reference#writeExpr */ this.writeExpr = writeExpr; /** * Whether the Reference might refer to a partial value of writeExpr. * @member {boolean} Reference#partial */ this.partial = partial; } this.__maybeImplicitGlobal = maybeImplicitGlobal; } /** * @constant Reference.READ * @private */ Reference.READ = 0x1; /** * @constant Reference.WRITE * @private */ Reference.WRITE = 0x2; /** * @constant Reference.RW * @private */ Reference.RW = Reference.READ | Reference.WRITE; /** * Whether the reference is static. * @method Reference#isStatic * @return {boolean} */ Reference.prototype.isStatic = function isStatic() { return !this.tainted && this.resolved && this.resolved.scope.isStatic(); }; /** * Whether the reference is writeable. * @method Reference#isWrite * @return {boolean} */ Reference.prototype.isWrite = function isWrite() { return !!(this.flag & Reference.WRITE); }; /** * Whether the reference is readable. * @method Reference#isRead * @return {boolean} */ Reference.prototype.isRead = function isRead() { return !!(this.flag & Reference.READ); }; /** * Whether the reference is read-only. * @method Reference#isReadOnly * @return {boolean} */ Reference.prototype.isReadOnly = function isReadOnly() { return this.flag === Reference.READ; }; /** * Whether the reference is write-only. * @method Reference#isWriteOnly * @return {boolean} */ Reference.prototype.isWriteOnly = function isWriteOnly() { return this.flag === Reference.WRITE; }; /** * Whether the reference is read-write. * @method Reference#isReadWrite * @return {boolean} */ Reference.prototype.isReadWrite = function isReadWrite() { return this.flag === Reference.RW; }; /** * A Variable represents a locally scoped identifier. These include arguments to * functions. * @class Variable */ function Variable(name, scope) { /** * The variable name, as given in the source code. * @member {String} Variable#name */ this.name = name; /** * List of defining occurrences of this variable (like in 'var ...' * statements or as parameter), as AST nodes. * @member {esprima.Identifier[]} Variable#identifiers */ this.identifiers = []; /** * List of {@link Reference|references} of this variable (excluding parameter entries) * in its defining scope and all nested scopes. For defining * occurrences only see {@link Variable#defs}. * @member {Reference[]} Variable#references */ this.references = []; /** * List of defining occurrences of this variable (like in 'var ...' * statements or as parameter), as custom objects. * @typedef {Object} DefEntry * @property {String} DefEntry.type - the type of the occurrence (e.g. * "Parameter", "Variable", ...) * @property {esprima.Identifier} DefEntry.name - the identifier AST node of the occurrence * @property {esprima.Node} DefEntry.node - the enclosing node of the * identifier * @property {esprima.Node} [DefEntry.parent] - the enclosing statement * node of the identifier * @member {DefEntry[]} Variable#defs */ this.defs = []; this.tainted = false; /** * Whether this is a stack variable. * @member {boolean} Variable#stack */ this.stack = true; /** * Reference to the enclosing Scope. * @member {Scope} Variable#scope */ this.scope = scope; } Variable.CatchClause = 'CatchClause'; Variable.Parameter = 'Parameter'; Variable.FunctionName = 'FunctionName'; Variable.ClassName = 'ClassName'; Variable.Variable = 'Variable'; Variable.TDZ = 'TDZ'; Variable.ImplicitGlobalVariable = 'ImplicitGlobalVariable'; function isMethodDefinition(block, parent) { // Check // + Class MethodDefinition // + Object MethodDefiniton // cases. if (block.type !== Syntax.FunctionExpression) { return false; } if (!parent) { return false; } if (parent.type === Syntax.MethodDefinition && block === parent.value) { return true; } if (parent.type === Syntax.Property && parent.method && block === parent.value) { return true; } return false; } function isStrictScope(scope, block, parent) { var body, i, iz, stmt, expr; // When upper scope is exists and strict, inner scope is also strict. if (scope.upper && scope.upper.isStrict) { return true; } // ArrowFunctionExpression's scope is always strict scope. if (block.type === Syntax.ArrowFunctionExpression) { return true; } if (parent) { if (isMethodDefinition(block, parent)) { return true; } } if (scope.type === 'class') { return true; } else if (scope.type === 'function') { body = block.body; } else if (scope.type === 'global') { body = block; } else { return false; } // Search 'use strict' directive. if (options.directive) { for (i = 0, iz = body.body.length; i < iz; ++i) { stmt = body.body[i]; if (stmt.type !== 'DirectiveStatement') { break; } if (stmt.raw === '"use strict"' || stmt.raw === '\'use strict\'') { return true; } } } else { for (i = 0, iz = body.body.length; i < iz; ++i) { stmt = body.body[i]; if (stmt.type !== Syntax.ExpressionStatement) { break; } expr = stmt.expression; if (expr.type !== Syntax.Literal || typeof expr.value !== 'string') { break; } if (expr.raw != null) { if (expr.raw === '"use strict"' || expr.raw === '\'use strict\'') { return true; } } else { if (expr.value === 'use strict') { return true; } } } } return false; } /* Special Scope types. */ var SCOPE_NORMAL = 0, SCOPE_FUNCTION_EXPRESSION_NAME = 1, SCOPE_TDZ = 2; /** * @class Scope */ function Scope(scopeManager, block, parent, scopeType) { /** * One of 'catch', 'with', 'function', 'global' or 'block'. * @member {String} Scope#type */ this.type = (scopeType === SCOPE_TDZ) ? 'TDZ' : (block.type === Syntax.BlockStatement) ? 'block' : (block.type === Syntax.FunctionExpression || block.type === Syntax.FunctionDeclaration || block.type === Syntax.ArrowFunctionExpression) ? 'function' : (block.type === Syntax.CatchClause) ? 'catch' : (block.type === Syntax.ForInStatement || block.type === Syntax.ForOfStatement || block.type === Syntax.ForStatement) ? 'for' : (block.type === Syntax.WithStatement) ? 'with' : (block.type === Syntax.ClassBody) ? 'class' : 'global'; /** * The scoped {@link Variable}s of this scope, as <code>{ Variable.name * : Variable }</code>. * @member {Map} Scope#set */ this.set = new Map(); /** * The tainted variables of this scope, as <code>{ Variable.name : * boolean }</code>. * @member {Map} Scope#taints */ this.taints = new Map(); /** * Generally, through the lexical scoping of JS you can always know * which variable an identifier in the source code refers to. There are * a few exceptions to this rule. With 'global' and 'with' scopes you * can only decide at runtime which variable a reference refers to. * Moreover, if 'eval()' is used in a scope, it might introduce new * bindings in this or its prarent scopes. * All those scopes are considered 'dynamic'. * @member {boolean} Scope#dynamic */ this.dynamic = this.type === 'global' || this.type === 'with'; /** * A reference to the scope-defining syntax node. * @member {esprima.Node} Scope#block */ this.block = block; /** * The {@link Reference|references} that are not resolved with this scope. * @member {Reference[]} Scope#through */ this.through = []; /** * The scoped {@link Variable}s of this scope. In the case of a * 'function' scope this includes the automatic argument <em>arguments</em> as * its first element, as well as all further formal arguments. * @member {Variable[]} Scope#variables */ this.variables = []; /** * Any variable {@link Reference|reference} found in this scope. This * includes occurrences of local variables as well as variables from * parent scopes (including the global scope). For local variables * this also includes defining occurrences (like in a 'var' statement). * In a 'function' scope this does not include the occurrences of the * formal parameter in the parameter list. * @member {Reference[]} Scope#references */ this.references = []; /** * For 'global' and 'function' scopes, this is a self-reference. For * other scope types this is the <em>variableScope</em> value of the * parent scope. * @member {Scope} Scope#variableScope */ this.variableScope = (this.type === 'global' || this.type === 'function') ? this : currentScope.variableScope; /** * Whether this scope is created by a FunctionExpression. * @member {boolean} Scope#functionExpressionScope */ this.functionExpressionScope = false; /** * Whether this is a scope that contains an 'eval()' invocation. * @member {boolean} Scope#directCallToEvalScope */ this.directCallToEvalScope = false; /** * @member {boolean} Scope#thisFound */ this.thisFound = false; this.__left = []; if (scopeType === SCOPE_FUNCTION_EXPRESSION_NAME) { this.__define(block.id, { type: Variable.FunctionName, name: block.id, node: block }); this.functionExpressionScope = true; } else { if (this.type === 'function') { this.__defineArguments(); } if (block.type === Syntax.FunctionExpression && block.id && !isMethodDefinition(block, parent)) { scopeManager.__nestFunctionExpressionNameScope(block, parent); } } /** * Reference to the parent {@link Scope|scope}. * @member {Scope} Scope#upper */ this.upper = currentScope; /** * Whether 'use strict' is in effect in this scope. * @member {boolean} Scope#isStrict */ this.isStrict = isStrictScope(this, block, parent); /** * List of nested {@link Scope}s. * @member {Scope[]} Scope#childScopes */ this.childScopes = []; if (currentScope) { currentScope.childScopes.push(this); } // RAII currentScope = this; if (this.type === 'global') { globalScope = this; globalScope.implicit = { set: new Map(), variables: [], /** * List of {@link Reference}s that are left to be resolved (i.e. which * need to be linked to the variable they refer to). * @member {Reference[]} Scope#implicit#left */ left: [] }; } scopes.push(this); } Scope.prototype.__close = function __close() { var i, iz, ref, current, implicit, info; // Because if this is global environment, upper is null if (!this.dynamic || options.optimistic) { // static resolve for (i = 0, iz = this.__left.length; i < iz; ++i) { ref = this.__left[i]; if (!this.__resolve(ref)) { this.__delegateToUpperScope(ref); } } } else { // this is "global" / "with" / "function with eval" environment if (this.type === 'with') { for (i = 0, iz = this.__left.length; i < iz; ++i) { ref = this.__left[i]; ref.tainted = true; this.__delegateToUpperScope(ref); } } else { for (i = 0, iz = this.__left.length; i < iz; ++i) { // notify all names are through to global ref = this.__left[i]; current = this; do { current.through.push(ref); current = current.upper; } while (current); } } } if (this.type === 'global') { implicit = []; for (i = 0, iz = this.__left.length; i < iz; ++i) { ref = this.__left[i]; if (ref.__maybeImplicitGlobal && !this.set.has(ref.identifier.name)) { implicit.push(ref.__maybeImplicitGlobal); } } // create an implicit global variable from assignment expression for (i = 0, iz = implicit.length; i < iz; ++i) { info = implicit[i]; this.__defineImplicit(info.pattern, { type: Variable.ImplicitGlobalVariable, name: info.pattern, node: info.node }); } this.implicit.left = this.__left; } this.__left = null; currentScope = this.upper; }; Scope.prototype.__resolve = function __resolve(ref) { var variable, name; name = ref.identifier.name; if (this.set.has(name)) { variable = this.set.get(name); variable.references.push(ref); variable.stack = variable.stack && ref.from.variableScope === this.variableScope; if (ref.tainted) { variable.tainted = true; this.taints.set(variable.name, true); } ref.resolved = variable; return true; } return false; }; Scope.prototype.__delegateToUpperScope = function __delegateToUpperScope(ref) { if (this.upper) { this.upper.__left.push(ref); } this.through.push(ref); }; Scope.prototype.__defineGeneric = function (name, set, variables, node, info) { var variable; variable = set.get(name); if (!variable) { variable = new Variable(name, this); set.set(name, variable); variables.push(variable); } if (info) { variable.defs.push(info); } if (node) { variable.identifiers.push(node); } }; Scope.prototype.__defineArguments = function () { this.__defineGeneric('arguments', this.set, this.variables); this.taints.set('arguments', true); }; Scope.prototype.__defineImplicit = function (node, info) { if (node && node.type === Syntax.Identifier) { this.__defineGeneric(node.name, this.implicit.set, this.implicit.variables, node, info); } }; Scope.prototype.__define = function (node, info) { if (node && node.type === Syntax.Identifier) { this.__defineGeneric(node.name, this.set, this.variables, node, info); } }; Scope.prototype.__referencing = function __referencing(node, assign, writeExpr, maybeImplicitGlobal, partial) { var ref; // because Array element may be null if (node && node.type === Syntax.Identifier) { ref = new Reference(node, this, assign || Reference.READ, writeExpr, maybeImplicitGlobal, !!partial); this.references.push(ref); this.__left.push(ref); } }; Scope.prototype.__detectEval = function __detectEval() { var current; current = this; this.directCallToEvalScope = true; do { current.dynamic = true; current = current.upper; } while (current); }; Scope.prototype.__detectThis = function __detectThis() { this.thisFound = true; }; Scope.prototype.__isClosed = function isClosed() { return this.__left === null; }; // API Scope#resolve(name) // returns resolved reference Scope.prototype.resolve = function resolve(ident) { var ref, i, iz; assert(this.__isClosed(), 'scope should be closed'); assert(ident.type === Syntax.Identifier, 'target should be identifier'); for (i = 0, iz = this.references.length; i < iz; ++i) { ref = this.references[i]; if (ref.identifier === ident) { return ref; } } return null; }; // API Scope#isStatic // returns this scope is static Scope.prototype.isStatic = function isStatic() { return !this.dynamic; }; // API Scope#isArgumentsMaterialized // return this scope has materialized arguments Scope.prototype.isArgumentsMaterialized = function isArgumentsMaterialized() { // TODO(Constellation) // We can more aggressive on this condition like this. // // function t() { // // arguments of t is always hidden. // function arguments() { // } // } var variable; // This is not function scope if (this.type !== 'function') { return true; } if (!this.isStatic()) { return true; } variable = this.set.get('arguments'); assert(variable, 'always have arguments variable'); return variable.tainted || variable.references.length !== 0; }; // API Scope#isThisMaterialized // return this scope has materialized `this` reference Scope.prototype.isThisMaterialized = function isThisMaterialized() { // This is not function scope if (this.type !== 'function') { return true; } if (!this.isStatic()) { return true; } return this.thisFound; }; Scope.mangledName = '__$escope$__'; Scope.prototype.attach = function attach() { if (!this.functionExpressionScope) { this.block[Scope.mangledName] = this; } }; Scope.prototype.detach = function detach() { if (!this.functionExpressionScope) { delete this.block[Scope.mangledName]; } }; Scope.prototype.isUsedName = function (name) { if (this.set.has(name)) { return true; } for (var i = 0, iz = this.through.length; i < iz; ++i) { if (this.through[i].identifier.name === name) { return true; } } return false; }; /** * @class ScopeManager */ function ScopeManager(scopes, options) { this.scopes = scopes; this.attached = false; this.__options = options; } // Returns appropliate scope for this node ScopeManager.prototype.__get = function __get(node) { var i, iz, scope; if (this.attached) { return node[Scope.mangledName] || null; } for (i = 0, iz = this.scopes.length; i < iz; ++i) { scope = this.scopes[i]; if (!scope.functionExpressionScope) { if (scope.block === node) { return scope; } } } return null; }; ScopeManager.prototype.acquire = function acquire(node) { return this.__get(node); }; ScopeManager.prototype.release = function release(node) { var scope = this.__get(node); if (scope) { scope = scope.upper; while (scope) { if (!scope.functionExpressionScope) { return scope; } scope = scope.upper; } } return null; }; ScopeManager.prototype.attach = function attach() { var i, iz; for (i = 0, iz = this.scopes.length; i < iz; ++i) { this.scopes[i].attach(); } this.attached = true; }; ScopeManager.prototype.detach = function detach() { var i, iz; for (i = 0, iz = this.scopes.length; i < iz; ++i) { this.scopes[i].detach(); } this.attached = false; }; ScopeManager.prototype.__nestScope = function (node, parent) { return new Scope(this, node, parent, SCOPE_NORMAL); }; ScopeManager.prototype.__nestTDZScope = function (node, iterationNode) { return new Scope(this, node, iterationNode, SCOPE_TDZ); }; ScopeManager.prototype.__nestFunctionExpressionNameScope = function (node, parent) { return new Scope(this, node, parent, SCOPE_FUNCTION_EXPRESSION_NAME); }; ScopeManager.prototype.__isES6 = function () { return this.__options.ecmaVersion >= 6; }; function traverseIdentifierInPattern(rootPattern, callback) { estraverse.traverse(rootPattern, { enter: function (pattern, parent) { var i, iz, element, property; switch (pattern.type) { case Syntax.Identifier: // Toplevel identifier. if (parent === null) { callback(pattern, true); } break; case Syntax.SpreadElement: if (pattern.argument.type === Syntax.Identifier) { callback(pattern.argument, false); } break; case Syntax.ObjectPattern: for (i = 0, iz = pattern.properties.length; i < iz; ++i) { property = pattern.properties[i]; if (property.shorthand) { callback(property.key, false); continue; } if (property.value.type === Syntax.Identifier) { callback(property.value, false); continue; } } break; case Syntax.ArrayPattern: for (i = 0, iz = pattern.elements.length; i < iz; ++i) { element = pattern.elements[i]; if (element && element.type === Syntax.Identifier) { callback(element, false); } } break; } } }); } function doVariableDeclaration(variableTargetScope, type, node, index) { var decl, init; decl = node.declarations[index]; init = decl.init; // FIXME: Don't consider initializer with complex patterns. // Such as, // var [a, b, c = 20] = array; traverseIdentifierInPattern(decl.id, function (pattern, toplevel) { variableTargetScope.__define(pattern, { type: type, name: pattern, node: decl, index: index, kind: node.kind, parent: node }); if (init) { currentScope.__referencing(pattern, Reference.WRITE, init, null, !toplevel); } }); } function materializeTDZScope(scopeManager, node, iterationNode) { // http://people.mozilla.org/~jorendorff/es6-draft.html#sec-runtime-semantics-forin-div-ofexpressionevaluation-abstract-operation // TDZ scope hides the declaration's names. scopeManager.__nestTDZScope(node, iterationNode); doVariableDeclaration(currentScope, Variable.TDZ, iterationNode.left, 0); currentScope.__referencing(node); } function materializeIterationScope(scopeManager, node) { // Generate iteration scope for upper ForIn/ForOf Statements. // parent node for __nestScope is only necessary to // distinguish MethodDefinition. var letOrConstDecl; scopeManager.__nestScope(node, null); letOrConstDecl = node.left; doVariableDeclaration(currentScope, Variable.Variable, letOrConstDecl, 0); traverseIdentifierInPattern(letOrConstDecl.declarations[0].id, function (pattern) { currentScope.__referencing(pattern, Reference.WRITE, node.right, null, true); }); } /** * Main interface function. Takes an Esprima syntax tree and returns the * analyzed scopes. * @function analyze * @param {esprima.Tree} tree * @param {Object} providedOptions - Options that tailor the scope analysis * @param {boolean} [providedOptions.optimistic=false] - the optimistic flag * @param {boolean} [providedOptions.directive=false]- the directive flag * @param {boolean} [providedOptions.ignoreEval=false]- whether to check 'eval()' calls * @return {ScopeManager} */ function analyze(tree, providedOptions) { var resultScopes, scopeManager; options = updateDeeply(defaultOptions(), providedOptions); resultScopes = scopes = []; currentScope = null; globalScope = null; scopeManager = new ScopeManager(resultScopes, options); // attach scope and collect / resolve names estraverse.traverse(tree, { enter: function enter(node, parent) { var i, iz, decl, variableTargetScope; // Special path for ForIn/ForOf Statement block scopes. if (parent && (parent.type === Syntax.ForInStatement || parent.type === Syntax.ForOfStatement) && parent.left.type === Syntax.VariableDeclaration && parent.left.kind !== 'var') { // Construct TDZ scope. if (parent.right === node) { materializeTDZScope(scopeManager, node, parent); } if (parent.body === node) { materializeIterationScope(scopeManager, parent); } } switch (this.type()) { case Syntax.AssignmentExpression: if (node.operator === '=') { traverseIdentifierInPattern(node.left, function (pattern, toplevel) { var maybeImplicitGlobal = null; if (!currentScope.isStrict) { maybeImplicitGlobal = { pattern: pattern, node: node }; } currentScope.__referencing(pattern, Reference.WRITE, node.right, maybeImplicitGlobal, !toplevel); }); } else { currentScope.__referencing(node.left, Reference.RW, node.right); } currentScope.__referencing(node.right); break; case Syntax.ArrayExpression: for (i = 0, iz = node.elements.length; i < iz; ++i) { currentScope.__referencing(node.elements[i]); } break; case Syntax.BlockStatement: if (scopeManager.__isES6()) { if (!parent || parent.type !== Syntax.FunctionExpression && parent.type !== Syntax.FunctionDeclaration && parent.type !== Syntax.ArrowFunctionExpression) { scopeManager.__nestScope(node, parent); } } break; case Syntax.BinaryExpression: currentScope.__referencing(node.left); currentScope.__referencing(node.right); break; case Syntax.BreakStatement: break; case Syntax.CallExpression: currentScope.__referencing(node.callee); for (i = 0, iz = node['arguments'].length; i < iz; ++i) { currentScope.__referencing(node['arguments'][i]); } // Check this is direct call to eval if (!options.ignoreEval && node.callee.type === Syntax.Identifier && node.callee.name === 'eval') { // NOTE: This should be `variableScope`. Since direct eval call always creates Lexical environment and // let / const should be enclosed into it. Only VariableDeclaration affects on the caller's environment. currentScope.variableScope.__detectEval(); } break; case Syntax.CatchClause: scopeManager.__nestScope(node, parent); traverseIdentifierInPattern(node.param, function (pattern) { currentScope.__define(pattern, { type: Variable.CatchClause, name: node.param, node: node }); }); break; case Syntax.ClassDeclaration: // Outer block scope. currentScope.__define(node.id, { type: Variable.ClassName, name: node.id, node: node }); currentScope.__referencing(node.superClass); break; case Syntax.ClassBody: // ClassBody scope. scopeManager.__nestScope(node, parent); if (parent && parent.id) { currentScope.__define(parent.id, { type: Variable.ClassName, name: node.id, node: node }); } break; case Syntax.ClassExpression: currentScope.__referencing(node.superClass); break; case Syntax.ConditionalExpression: currentScope.__referencing(node.test); currentScope.__referencing(node.consequent); currentScope.__referencing(node.alternate); break; case Syntax.ContinueStatement: break; case Syntax.DirectiveStatement: break; case Syntax.DoWhileStatement: currentScope.__referencing(node.test); break; case Syntax.DebuggerStatement: break; case Syntax.EmptyStatement: break; case Syntax.ExpressionStatement: currentScope.__referencing(node.expression); break; case Syntax.ForStatement: if (node.init && node.init.type === Syntax.VariableDeclaration && node.init.kind !== 'var') { // Create ForStatement declaration. // NOTE: In ES6, ForStatement dynamically generates // per iteration environment. However, escope is // a static analyzer, we only generate one scope for ForStatement. scopeManager.__nestScope(node, parent); } currentScope.__referencing(node.init); currentScope.__referencing(node.test); currentScope.__referencing(node.update); break; case Syntax.ForOfStatement: case Syntax.ForInStatement: if (node.left.type === Syntax.VariableDeclaration) { if (node.left.kind !== 'var') { // LetOrConst Declarations are specially handled. break; } traverseIdentifierInPattern(node.left.declarations[0].id, function (pattern) { currentScope.__referencing(pattern, Reference.WRITE, node.right, null, true); }); } else { traverseIdentifierInPattern(node.left, function (pattern) { var maybeImplicitGlobal = null; if (!currentScope.isStrict) { maybeImplicitGlobal = { pattern: pattern, node: node }; } currentScope.__referencing(pattern, Reference.WRITE, node.right, maybeImplicitGlobal, true); }); } currentScope.__referencing(node.right); break; case Syntax.FunctionDeclaration: // FunctionDeclaration name is defined in upper scope // NOTE: Not referring variableScope. It is intended. // Since // in ES5, FunctionDeclaration should be in FunctionBody. // in ES6, FunctionDeclaration should be block scoped. currentScope.__define(node.id, { type: Variable.FunctionName, name: node.id, node: node }); // falls through case Syntax.FunctionExpression: case Syntax.ArrowFunctionExpression: // id is defined in upper scope scopeManager.__nestScope(node, parent); for (i = 0, iz = node.params.length; i < iz; ++i) { traverseIdentifierInPattern(node.params[i], function (pattern) { currentScope.__define(pattern, { type: Variable.Parameter, name: pattern, node: node, index: i }); }); } break; case Syntax.Identifier: break; case Syntax.IfStatement: currentScope.__referencing(node.test); break; case Syntax.Literal: break; case Syntax.LabeledStatement: break; case Syntax.LogicalExpression: currentScope.__referencing(node.left); currentScope.__referencing(node.right); break; case Syntax.MemberExpression: currentScope.__referencing(node.object); if (node.computed) { currentScope.__referencing(node.property); } break; case Syntax.NewExpression: currentScope.__referencing(node.callee); for (i = 0, iz = node['arguments'].length; i < iz; ++i) { currentScope.__referencing(node['arguments'][i]); } break; case Syntax.ObjectExpression: break; case Syntax.Program: scopeManager.__nestScope(node, parent); break; case Syntax.Property: // Don't referencing variables when the parent type is ObjectPattern. if (parent.type !== Syntax.ObjectExpression) { break; } if (node.computed) { currentScope.__referencing(node.key); } if (node.kind === 'init') { currentScope.__referencing(node.value); } break; case Syntax.MethodDefinition: if (node.computed) { currentScope.__referencing(node.key); } break; case Syntax.ReturnStatement: currentScope.__referencing(node.argument); break; case Syntax.SequenceExpression: for (i = 0, iz = node.expressions.length; i < iz; ++i) { currentScope.__referencing(node.expressions[i]); } break; case Syntax.SwitchStatement: currentScope.__referencing(node.discriminant); break; case Syntax.SwitchCase: currentScope.__referencing(node.test); break; case Syntax.TaggedTemplateExpression: currentScope.__referencing(node.tag); break; case Syntax.TemplateLiteral: for (i = 0, iz = node.expressions.length; i < iz; ++i) { currentScope.__referencing(node.expressions[i]); } break; case Syntax.ThisExpression: currentScope.variableScope.__detectThis(); break; case Syntax.ThrowStatement: currentScope.__referencing(node.argument); break; case Syntax.TryStatement: break; case Syntax.UnaryExpression: currentScope.__referencing(node.argument); break; case Syntax.UpdateExpression: currentScope.__referencing(node.argument, Reference.RW, null); break; case Syntax.VariableDeclaration: if (node.kind !== 'var' && parent) { if (parent.type === Syntax.ForInStatement || parent.type === Syntax.ForOfStatement) { // e.g. // for (let i in abc); // In this case, they are specially handled in ForIn/ForOf statements. break; } } variableTargetScope = (node.kind === 'var') ? currentScope.variableScope : currentScope; for (i = 0, iz = node.declarations.length; i < iz; ++i) { decl = node.declarations[i]; doVariableDeclaration(variableTargetScope, Variable.Variable, node, i); if (decl.init) { currentScope.__referencing(decl.init); } } break; case Syntax.VariableDeclarator: break; case Syntax.WhileStatement: currentScope.__referencing(node.test); break; case Syntax.WithStatement: currentScope.__referencing(node.object); // Then nest scope for WithStatement. scopeManager.__nestScope(node, parent); break; } }, leave: function leave(node) { while (currentScope && node === currentScope.block) { currentScope.__close(); } } }); assert(currentScope === null); globalScope = null; scopes = null; options = null; return scopeManager; } /** @name module:escope.version */ exports.version = '2.0.0-dev'; /** @name module:escope.Reference */ exports.Reference = Reference; /** @name module:escope.Variable */ exports.Variable = Variable; /** @name module:escope.Scope */ exports.Scope = Scope; /** @name module:escope.ScopeManager */ exports.ScopeManager = ScopeManager; /** @name module:escope.analyze */ exports.analyze = analyze; }, this)); /* vim: set sw=4 ts=4 et tw=80 : */
Drop AMD style
escope.js
Drop AMD style
<ide><path>scope.js <ide> */ <ide> <ide> /*jslint bitwise:true */ <del>/*global exports:true, define:true, require:true*/ <del>(function (factory, global) { <del> 'use strict'; <del> <del> function namespace(str, obj) { <del> var i, iz, names, name; <del> names = str.split('.'); <del> for (i = 0, iz = names.length; i < iz; ++i) { <del> name = names[i]; <del> if (obj.hasOwnProperty(name)) { <del> obj = obj[name]; <del> } else { <del> obj = (obj[name] = {}); <del> } <del> } <del> return obj; <del> } <del> <del> // Universal Module Definition (UMD) to support AMD, CommonJS/Node.js, <del> // and plain browser loading, <del> if (typeof define === 'function' && define.amd) { <del> define('escope', ['exports', 'estraverse'], function (exports, estraverse) { <del> factory(exports, global, estraverse); <del> }); <del> } else if (typeof exports !== 'undefined') { <del> factory(exports, global, require('estraverse')); <del> } else { <del> factory(namespace('escope', global), global, global.estraverse); <del> } <del>}(function (exports, global, estraverse) { <add>(function () { <ide> 'use strict'; <ide> <ide> var Syntax, <ide> Map, <add> estraverse, <ide> currentScope, <ide> globalScope, <ide> scopes, <ide> options; <ide> <add> estraverse = require('estraverse'); <ide> Syntax = estraverse.Syntax; <ide> <ide> if (typeof global.Map !== 'undefined') { <ide> exports.ScopeManager = ScopeManager; <ide> /** @name module:escope.analyze */ <ide> exports.analyze = analyze; <del>}, this)); <add>}()); <ide> /* vim: set sw=4 ts=4 et tw=80 : */
Java
mit
3ee24408e9d61a4f0909e4fbada4ccc83d7658bf
0
Porrux/Threat
package com.porrux.threat; import android.content.Intent; import android.os.Bundle; import android.support.design.widget.FloatingActionButton; import android.support.design.widget.Snackbar; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.View; import android.view.MenuItem; import android.widget.Adapter; import android.widget.ArrayAdapter; import android.widget.EditText; import android.widget.ListView; import android.widget.TextView; import com.porrux.threat.api.ApiClient; import com.porrux.threat.models.Event; import java.util.ArrayList; import java.util.List; import retrofit.Callback; import retrofit.Response; import retrofit.Retrofit; public class ThreaTListActivity extends AppCompatActivity { // View's component element ListView listLocal; ListView listInternantional; private ArrayAdapter<String> adapter; private List<String> liste; public List<Event> events; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_threatlist); this.loadLocalThreat(); // The button to add events FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab); fab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Snackbar.make(view, "Ajout d'un évènement", Snackbar.LENGTH_SHORT).setAction("Action", null).show(); Intent form_event = new Intent(ThreaTListActivity.this, ThreaTFormActivity.class); startActivity(form_event); } }); } @Override protected void onResume() { super.onResume(); this.loadLocalThreat(); } private void loadLocalThreat() { listLocal = (ListView) findViewById(R.id.listLocal); listInternantional = (ListView) findViewById(R.id.listInternational); final TextView emptyLocalListMessage = (TextView) findViewById(R.id.empty_local); final ApiClient apiClient = new ApiClient(this); apiClient.listEvents().enqueue(new Callback<List<Event>>() { @Override public void onResponse(Response<List<Event>> response, Retrofit retrofit) { liste = new ArrayList<String>(); events = response.body(); for (int i = 0; i < events.size(); i++) { liste.add(events.get(i).getTitle()); } adapter = new ArrayAdapter<String>(ThreaTListActivity.this, android.R.layout.simple_list_item_1, liste); listLocal.setAdapter(adapter); if (events.size() > 0) { emptyLocalListMessage.setVisibility(View.GONE); } } @Override public void onFailure(Throwable t) { } }); } }
app/src/main/java/com/porrux/threat/ThreaTListActivity.java
package com.porrux.threat; import android.content.Intent; import android.os.Bundle; import android.support.design.widget.FloatingActionButton; import android.support.design.widget.Snackbar; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.View; import android.view.MenuItem; import android.widget.Adapter; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.TextView; import com.porrux.threat.api.ApiClient; import com.porrux.threat.models.Event; import java.util.ArrayList; import java.util.List; import retrofit.Callback; import retrofit.Response; import retrofit.Retrofit; public class ThreaTListActivity extends AppCompatActivity { // View's component element ListView listLocal; ListView listInternantional; private ArrayAdapter<String> adapter; private List<String> liste; public List<Event> events; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_threatlist); listLocal = (ListView) findViewById(R.id.listLocal); listInternantional = (ListView) findViewById(R.id.listInternational); final ApiClient apiClient = new ApiClient(this); apiClient.listEvents().enqueue(new Callback<List<Event>>() { @Override public void onResponse(Response<List<Event>> response, Retrofit retrofit) { liste = new ArrayList<String>(); events = response.body(); for (int i = 0; i < events.size(); i++) { liste.add(events.get(i).getTitle()); } adapter = new ArrayAdapter<String>(ThreaTListActivity.this, android.R.layout.simple_list_item_1, liste); listLocal.setAdapter(adapter); } @Override public void onFailure(Throwable t) { } }); // The button to add events FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab); fab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Snackbar.make(view, "Ajout d'un évènement", Snackbar.LENGTH_SHORT).setAction("Action", null).show(); Intent form_event = new Intent(ThreaTListActivity.this, ThreaTFormActivity.class); startActivity(form_event); } }); //Hello TextView emptyText1 = (TextView)findViewById(R.id.empty_inter); TextView emptyText2 = (TextView)findViewById(R.id.empty_local); listLocal.setEmptyView(emptyText1); listInternantional.setEmptyView(emptyText2); } }
MAJ de la liste des threats locaux
app/src/main/java/com/porrux/threat/ThreaTListActivity.java
MAJ de la liste des threats locaux
<ide><path>pp/src/main/java/com/porrux/threat/ThreaTListActivity.java <ide> import android.view.MenuItem; <ide> import android.widget.Adapter; <ide> import android.widget.ArrayAdapter; <add>import android.widget.EditText; <ide> import android.widget.ListView; <ide> import android.widget.TextView; <ide> <ide> super.onCreate(savedInstanceState); <ide> setContentView(R.layout.activity_threatlist); <ide> <add> this.loadLocalThreat(); <add> <add> // The button to add events <add> FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab); <add> fab.setOnClickListener(new View.OnClickListener() { <add> @Override <add> public void onClick(View view) { <add> Snackbar.make(view, "Ajout d'un évènement", Snackbar.LENGTH_SHORT).setAction("Action", null).show(); <add> <add> Intent form_event = new Intent(ThreaTListActivity.this, ThreaTFormActivity.class); <add> startActivity(form_event); <add> } <add> }); <add> } <add> <add> @Override <add> protected void onResume() { <add> super.onResume(); <add> <add> this.loadLocalThreat(); <add> } <add> <add> private void loadLocalThreat() { <ide> listLocal = (ListView) findViewById(R.id.listLocal); <ide> listInternantional = (ListView) findViewById(R.id.listInternational); <add> <add> final TextView emptyLocalListMessage = (TextView) findViewById(R.id.empty_local); <ide> <ide> final ApiClient apiClient = new ApiClient(this); <ide> <ide> } <ide> adapter = new ArrayAdapter<String>(ThreaTListActivity.this, android.R.layout.simple_list_item_1, liste); <ide> listLocal.setAdapter(adapter); <add> <add> if (events.size() > 0) { <add> emptyLocalListMessage.setVisibility(View.GONE); <add> } <ide> } <ide> <ide> @Override <ide> <ide> } <ide> }); <del> <del> // The button to add events <del> FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab); <del> fab.setOnClickListener(new View.OnClickListener() { <del> @Override <del> public void onClick(View view) { <del> Snackbar.make(view, "Ajout d'un évènement", Snackbar.LENGTH_SHORT).setAction("Action", null).show(); <del> <del> Intent form_event = new Intent(ThreaTListActivity.this, ThreaTFormActivity.class); <del> startActivity(form_event); <del> } <del> }); <del> <del> //Hello <del> TextView emptyText1 = (TextView)findViewById(R.id.empty_inter); <del> TextView emptyText2 = (TextView)findViewById(R.id.empty_local); <del> listLocal.setEmptyView(emptyText1); <del> listInternantional.setEmptyView(emptyText2); <del> <ide> } <ide> }
Java
mit
df44c614997bd0e518e39558b19e4445e493ab03
0
siamx/STP_Registration
package controller; import model.FixFile; import model.Operations; import model.Record; import java.io.File; import java.util.ArrayList; import static controller.Controller.setUIFlavour; /* * Created by Ahmed on 08-Aug-16. */ public class Main { public static ArrayList<Record> dataRecords = new ArrayList<>(); public static final ArrayList<Record> attendeesRecords = new ArrayList<>(); public static final String CREATED_CSV = "created.csv"; public static final String ATTENDEES_CSV = "attendees.csv"; private static final String SOURCE_CSV = "source.csv"; public static void main(String[] args) { if (new File(CREATED_CSV).isFile()) Operations.setFileName(CREATED_CSV); else if (new File(SOURCE_CSV).isFile()) new FixFile(SOURCE_CSV, CREATED_CSV); Operations.setFileName(CREATED_CSV); setUIFlavour(); new Controller(); Operations.countUnique(); } }
src/controller/Main.java
package controller; import model.FixFile; import model.Operations; import model.Record; import java.io.File; import java.util.ArrayList; import static controller.Controller.setUIFlavour; /* * Created by Ahmed on 08-Aug-16. */ public class Main { public static ArrayList<Record> dataRecords = new ArrayList<>(); public static final ArrayList<Record> attendeesRecords = new ArrayList<>(); public static final String CREATED_CSV = "created.csv"; public static final String ATTENDEES_CSV = "attendees.csv"; private static final String SOURCE_CSV = "source.csv"; public static void main(String[] args) { if (new File(CREATED_CSV).isFile()) Operations.setFileName(CREATED_CSV); else if (new File(SOURCE_CSV).isFile()) new FixFile(SOURCE_CSV, CREATED_CSV); Operations.setFileName(CREATED_CSV); setUIFlavour(); new Controller(); Operations.countUnique(); } }
Update 1 1-Read/Write files names were generalized Read file = "source.csv" Write file = "attendees.csv" 2-Empty Class -Signle_Instance.java- Added 15-Oct-2016
src/controller/Main.java
Update 1
<ide><path>rc/controller/Main.java <ide> /* <ide> * Created by Ahmed on 08-Aug-16. <ide> */ <add> <ide> <ide> public class Main { <ide> public static ArrayList<Record> dataRecords = new ArrayList<>();
Java
apache-2.0
40163c6bb7980fa1faf8413bd0bbededd8d033d0
0
tmpgit/intellij-community,hurricup/intellij-community,semonte/intellij-community,ftomassetti/intellij-community,kdwink/intellij-community,gnuhub/intellij-community,ol-loginov/intellij-community,asedunov/intellij-community,asedunov/intellij-community,ThiagoGarciaAlves/intellij-community,izonder/intellij-community,ol-loginov/intellij-community,apixandru/intellij-community,mglukhikh/intellij-community,MER-GROUP/intellij-community,petteyg/intellij-community,xfournet/intellij-community,retomerz/intellij-community,MichaelNedzelsky/intellij-community,fitermay/intellij-community,TangHao1987/intellij-community,clumsy/intellij-community,xfournet/intellij-community,ahb0327/intellij-community,caot/intellij-community,da1z/intellij-community,kool79/intellij-community,michaelgallacher/intellij-community,fengbaicanhe/intellij-community,supersven/intellij-community,idea4bsd/idea4bsd,idea4bsd/idea4bsd,asedunov/intellij-community,kdwink/intellij-community,xfournet/intellij-community,wreckJ/intellij-community,mglukhikh/intellij-community,tmpgit/intellij-community,FHannes/intellij-community,wreckJ/intellij-community,apixandru/intellij-community,akosyakov/intellij-community,caot/intellij-community,orekyuu/intellij-community,vladmm/intellij-community,samthor/intellij-community,akosyakov/intellij-community,xfournet/intellij-community,Distrotech/intellij-community,FHannes/intellij-community,nicolargo/intellij-community,orekyuu/intellij-community,idea4bsd/idea4bsd,orekyuu/intellij-community,hurricup/intellij-community,allotria/intellij-community,muntasirsyed/intellij-community,apixandru/intellij-community,mglukhikh/intellij-community,allotria/intellij-community,pwoodworth/intellij-community,ivan-fedorov/intellij-community,fengbaicanhe/intellij-community,signed/intellij-community,amith01994/intellij-community,vladmm/intellij-community,ivan-fedorov/intellij-community,blademainer/intellij-community,FHannes/intellij-community,ibinti/intellij-community,ryano144/intellij-community,michaelgallacher/intellij-community,alphafoobar/intellij-community,apixandru/intellij-community,TangHao1987/intellij-community,MichaelNedzelsky/intellij-community,supersven/intellij-community,salguarnieri/intellij-community,suncycheng/intellij-community,ibinti/intellij-community,da1z/intellij-community,orekyuu/intellij-community,semonte/intellij-community,ryano144/intellij-community,xfournet/intellij-community,apixandru/intellij-community,vladmm/intellij-community,orekyuu/intellij-community,ivan-fedorov/intellij-community,salguarnieri/intellij-community,ivan-fedorov/intellij-community,idea4bsd/idea4bsd,youdonghai/intellij-community,fitermay/intellij-community,clumsy/intellij-community,ftomassetti/intellij-community,diorcety/intellij-community,adedayo/intellij-community,MER-GROUP/intellij-community,blademainer/intellij-community,izonder/intellij-community,fnouama/intellij-community,vvv1559/intellij-community,kdwink/intellij-community,apixandru/intellij-community,supersven/intellij-community,allotria/intellij-community,ThiagoGarciaAlves/intellij-community,lucafavatella/intellij-community,izonder/intellij-community,clumsy/intellij-community,diorcety/intellij-community,FHannes/intellij-community,michaelgallacher/intellij-community,jagguli/intellij-community,amith01994/intellij-community,signed/intellij-community,izonder/intellij-community,pwoodworth/intellij-community,ahb0327/intellij-community,caot/intellij-community,dslomov/intellij-community,adedayo/intellij-community,lucafavatella/intellij-community,ryano144/intellij-community,fnouama/intellij-community,diorcety/intellij-community,allotria/intellij-community,orekyuu/intellij-community,kool79/intellij-community,michaelgallacher/intellij-community,vvv1559/intellij-community,wreckJ/intellij-community,jagguli/intellij-community,semonte/intellij-community,robovm/robovm-studio,dslomov/intellij-community,jagguli/intellij-community,ibinti/intellij-community,ibinti/intellij-community,SerCeMan/intellij-community,ahb0327/intellij-community,supersven/intellij-community,asedunov/intellij-community,supersven/intellij-community,da1z/intellij-community,petteyg/intellij-community,gnuhub/intellij-community,ahb0327/intellij-community,amith01994/intellij-community,dslomov/intellij-community,kool79/intellij-community,ThiagoGarciaAlves/intellij-community,alphafoobar/intellij-community,holmes/intellij-community,Distrotech/intellij-community,ftomassetti/intellij-community,allotria/intellij-community,suncycheng/intellij-community,michaelgallacher/intellij-community,TangHao1987/intellij-community,ahb0327/intellij-community,xfournet/intellij-community,xfournet/intellij-community,semonte/intellij-community,retomerz/intellij-community,muntasirsyed/intellij-community,mglukhikh/intellij-community,signed/intellij-community,ibinti/intellij-community,Distrotech/intellij-community,retomerz/intellij-community,orekyuu/intellij-community,kool79/intellij-community,ivan-fedorov/intellij-community,Lekanich/intellij-community,Distrotech/intellij-community,kdwink/intellij-community,tmpgit/intellij-community,MER-GROUP/intellij-community,clumsy/intellij-community,hurricup/intellij-community,ibinti/intellij-community,Distrotech/intellij-community,MER-GROUP/intellij-community,MichaelNedzelsky/intellij-community,vladmm/intellij-community,allotria/intellij-community,vladmm/intellij-community,wreckJ/intellij-community,suncycheng/intellij-community,robovm/robovm-studio,idea4bsd/idea4bsd,holmes/intellij-community,signed/intellij-community,MER-GROUP/intellij-community,pwoodworth/intellij-community,supersven/intellij-community,retomerz/intellij-community,semonte/intellij-community,muntasirsyed/intellij-community,da1z/intellij-community,gnuhub/intellij-community,Lekanich/intellij-community,supersven/intellij-community,fitermay/intellij-community,mglukhikh/intellij-community,ol-loginov/intellij-community,retomerz/intellij-community,blademainer/intellij-community,blademainer/intellij-community,vvv1559/intellij-community,FHannes/intellij-community,akosyakov/intellij-community,mglukhikh/intellij-community,hurricup/intellij-community,wreckJ/intellij-community,muntasirsyed/intellij-community,fitermay/intellij-community,mglukhikh/intellij-community,nicolargo/intellij-community,SerCeMan/intellij-community,alphafoobar/intellij-community,petteyg/intellij-community,orekyuu/intellij-community,asedunov/intellij-community,clumsy/intellij-community,fitermay/intellij-community,retomerz/intellij-community,ol-loginov/intellij-community,alphafoobar/intellij-community,youdonghai/intellij-community,samthor/intellij-community,diorcety/intellij-community,semonte/intellij-community,suncycheng/intellij-community,fitermay/intellij-community,pwoodworth/intellij-community,FHannes/intellij-community,pwoodworth/intellij-community,Distrotech/intellij-community,Distrotech/intellij-community,slisson/intellij-community,kool79/intellij-community,Lekanich/intellij-community,vvv1559/intellij-community,ol-loginov/intellij-community,ibinti/intellij-community,kool79/intellij-community,kdwink/intellij-community,wreckJ/intellij-community,semonte/intellij-community,ftomassetti/intellij-community,vvv1559/intellij-community,muntasirsyed/intellij-community,michaelgallacher/intellij-community,Distrotech/intellij-community,vvv1559/intellij-community,retomerz/intellij-community,supersven/intellij-community,hurricup/intellij-community,TangHao1987/intellij-community,samthor/intellij-community,nicolargo/intellij-community,ThiagoGarciaAlves/intellij-community,vladmm/intellij-community,xfournet/intellij-community,gnuhub/intellij-community,wreckJ/intellij-community,asedunov/intellij-community,fengbaicanhe/intellij-community,MichaelNedzelsky/intellij-community,ThiagoGarciaAlves/intellij-community,ftomassetti/intellij-community,ftomassetti/intellij-community,muntasirsyed/intellij-community,nicolargo/intellij-community,vvv1559/intellij-community,wreckJ/intellij-community,slisson/intellij-community,retomerz/intellij-community,muntasirsyed/intellij-community,caot/intellij-community,youdonghai/intellij-community,caot/intellij-community,ol-loginov/intellij-community,allotria/intellij-community,hurricup/intellij-community,robovm/robovm-studio,blademainer/intellij-community,petteyg/intellij-community,tmpgit/intellij-community,SerCeMan/intellij-community,lucafavatella/intellij-community,MER-GROUP/intellij-community,mglukhikh/intellij-community,kool79/intellij-community,tmpgit/intellij-community,lucafavatella/intellij-community,apixandru/intellij-community,blademainer/intellij-community,vvv1559/intellij-community,asedunov/intellij-community,akosyakov/intellij-community,ryano144/intellij-community,slisson/intellij-community,youdonghai/intellij-community,semonte/intellij-community,jagguli/intellij-community,caot/intellij-community,Distrotech/intellij-community,clumsy/intellij-community,vladmm/intellij-community,ibinti/intellij-community,samthor/intellij-community,kool79/intellij-community,fengbaicanhe/intellij-community,alphafoobar/intellij-community,izonder/intellij-community,ol-loginov/intellij-community,da1z/intellij-community,fengbaicanhe/intellij-community,Distrotech/intellij-community,SerCeMan/intellij-community,ahb0327/intellij-community,tmpgit/intellij-community,robovm/robovm-studio,caot/intellij-community,kdwink/intellij-community,michaelgallacher/intellij-community,TangHao1987/intellij-community,nicolargo/intellij-community,MER-GROUP/intellij-community,FHannes/intellij-community,slisson/intellij-community,ivan-fedorov/intellij-community,asedunov/intellij-community,muntasirsyed/intellij-community,salguarnieri/intellij-community,da1z/intellij-community,vvv1559/intellij-community,MichaelNedzelsky/intellij-community,da1z/intellij-community,robovm/robovm-studio,fitermay/intellij-community,kool79/intellij-community,ryano144/intellij-community,vladmm/intellij-community,orekyuu/intellij-community,FHannes/intellij-community,ftomassetti/intellij-community,diorcety/intellij-community,michaelgallacher/intellij-community,kdwink/intellij-community,xfournet/intellij-community,apixandru/intellij-community,robovm/robovm-studio,fnouama/intellij-community,alphafoobar/intellij-community,vladmm/intellij-community,lucafavatella/intellij-community,Lekanich/intellij-community,tmpgit/intellij-community,alphafoobar/intellij-community,gnuhub/intellij-community,blademainer/intellij-community,dslomov/intellij-community,holmes/intellij-community,ol-loginov/intellij-community,salguarnieri/intellij-community,fnouama/intellij-community,ThiagoGarciaAlves/intellij-community,signed/intellij-community,kdwink/intellij-community,lucafavatella/intellij-community,apixandru/intellij-community,SerCeMan/intellij-community,salguarnieri/intellij-community,slisson/intellij-community,michaelgallacher/intellij-community,petteyg/intellij-community,MER-GROUP/intellij-community,muntasirsyed/intellij-community,wreckJ/intellij-community,slisson/intellij-community,xfournet/intellij-community,nicolargo/intellij-community,ThiagoGarciaAlves/intellij-community,diorcety/intellij-community,Lekanich/intellij-community,gnuhub/intellij-community,da1z/intellij-community,amith01994/intellij-community,alphafoobar/intellij-community,ahb0327/intellij-community,alphafoobar/intellij-community,akosyakov/intellij-community,Lekanich/intellij-community,da1z/intellij-community,MichaelNedzelsky/intellij-community,adedayo/intellij-community,ahb0327/intellij-community,kool79/intellij-community,ahb0327/intellij-community,asedunov/intellij-community,orekyuu/intellij-community,dslomov/intellij-community,fengbaicanhe/intellij-community,tmpgit/intellij-community,ftomassetti/intellij-community,idea4bsd/idea4bsd,MichaelNedzelsky/intellij-community,suncycheng/intellij-community,allotria/intellij-community,nicolargo/intellij-community,akosyakov/intellij-community,amith01994/intellij-community,fitermay/intellij-community,jagguli/intellij-community,samthor/intellij-community,signed/intellij-community,apixandru/intellij-community,TangHao1987/intellij-community,adedayo/intellij-community,retomerz/intellij-community,SerCeMan/intellij-community,supersven/intellij-community,pwoodworth/intellij-community,ivan-fedorov/intellij-community,idea4bsd/idea4bsd,alphafoobar/intellij-community,xfournet/intellij-community,youdonghai/intellij-community,akosyakov/intellij-community,ftomassetti/intellij-community,Lekanich/intellij-community,gnuhub/intellij-community,michaelgallacher/intellij-community,diorcety/intellij-community,ahb0327/intellij-community,holmes/intellij-community,petteyg/intellij-community,adedayo/intellij-community,fengbaicanhe/intellij-community,signed/intellij-community,pwoodworth/intellij-community,amith01994/intellij-community,akosyakov/intellij-community,adedayo/intellij-community,jagguli/intellij-community,clumsy/intellij-community,signed/intellij-community,holmes/intellij-community,gnuhub/intellij-community,pwoodworth/intellij-community,suncycheng/intellij-community,caot/intellij-community,MichaelNedzelsky/intellij-community,dslomov/intellij-community,robovm/robovm-studio,retomerz/intellij-community,amith01994/intellij-community,kdwink/intellij-community,supersven/intellij-community,SerCeMan/intellij-community,petteyg/intellij-community,samthor/intellij-community,allotria/intellij-community,diorcety/intellij-community,clumsy/intellij-community,salguarnieri/intellij-community,salguarnieri/intellij-community,allotria/intellij-community,suncycheng/intellij-community,ThiagoGarciaAlves/intellij-community,jagguli/intellij-community,fengbaicanhe/intellij-community,da1z/intellij-community,adedayo/intellij-community,apixandru/intellij-community,muntasirsyed/intellij-community,amith01994/intellij-community,izonder/intellij-community,hurricup/intellij-community,TangHao1987/intellij-community,ryano144/intellij-community,lucafavatella/intellij-community,caot/intellij-community,idea4bsd/idea4bsd,salguarnieri/intellij-community,gnuhub/intellij-community,dslomov/intellij-community,dslomov/intellij-community,allotria/intellij-community,MER-GROUP/intellij-community,clumsy/intellij-community,Lekanich/intellij-community,fnouama/intellij-community,mglukhikh/intellij-community,akosyakov/intellij-community,dslomov/intellij-community,suncycheng/intellij-community,MichaelNedzelsky/intellij-community,blademainer/intellij-community,petteyg/intellij-community,youdonghai/intellij-community,ibinti/intellij-community,muntasirsyed/intellij-community,FHannes/intellij-community,caot/intellij-community,kdwink/intellij-community,michaelgallacher/intellij-community,idea4bsd/idea4bsd,samthor/intellij-community,tmpgit/intellij-community,semonte/intellij-community,robovm/robovm-studio,ivan-fedorov/intellij-community,semonte/intellij-community,jagguli/intellij-community,izonder/intellij-community,signed/intellij-community,blademainer/intellij-community,lucafavatella/intellij-community,adedayo/intellij-community,asedunov/intellij-community,xfournet/intellij-community,hurricup/intellij-community,holmes/intellij-community,samthor/intellij-community,robovm/robovm-studio,diorcety/intellij-community,diorcety/intellij-community,da1z/intellij-community,lucafavatella/intellij-community,fitermay/intellij-community,izonder/intellij-community,vladmm/intellij-community,orekyuu/intellij-community,FHannes/intellij-community,SerCeMan/intellij-community,youdonghai/intellij-community,clumsy/intellij-community,vvv1559/intellij-community,TangHao1987/intellij-community,Lekanich/intellij-community,fnouama/intellij-community,adedayo/intellij-community,ftomassetti/intellij-community,idea4bsd/idea4bsd,kdwink/intellij-community,slisson/intellij-community,semonte/intellij-community,fnouama/intellij-community,MER-GROUP/intellij-community,retomerz/intellij-community,caot/intellij-community,retomerz/intellij-community,kdwink/intellij-community,retomerz/intellij-community,dslomov/intellij-community,gnuhub/intellij-community,izonder/intellij-community,petteyg/intellij-community,akosyakov/intellij-community,tmpgit/intellij-community,holmes/intellij-community,adedayo/intellij-community,wreckJ/intellij-community,slisson/intellij-community,ftomassetti/intellij-community,hurricup/intellij-community,salguarnieri/intellij-community,idea4bsd/idea4bsd,SerCeMan/intellij-community,da1z/intellij-community,gnuhub/intellij-community,FHannes/intellij-community,ryano144/intellij-community,hurricup/intellij-community,mglukhikh/intellij-community,youdonghai/intellij-community,ThiagoGarciaAlves/intellij-community,mglukhikh/intellij-community,lucafavatella/intellij-community,blademainer/intellij-community,muntasirsyed/intellij-community,izonder/intellij-community,petteyg/intellij-community,holmes/intellij-community,xfournet/intellij-community,ibinti/intellij-community,suncycheng/intellij-community,ryano144/intellij-community,tmpgit/intellij-community,MichaelNedzelsky/intellij-community,nicolargo/intellij-community,semonte/intellij-community,ol-loginov/intellij-community,adedayo/intellij-community,ol-loginov/intellij-community,nicolargo/intellij-community,TangHao1987/intellij-community,suncycheng/intellij-community,akosyakov/intellij-community,kool79/intellij-community,apixandru/intellij-community,izonder/intellij-community,youdonghai/intellij-community,robovm/robovm-studio,slisson/intellij-community,akosyakov/intellij-community,da1z/intellij-community,michaelgallacher/intellij-community,ryano144/intellij-community,caot/intellij-community,orekyuu/intellij-community,salguarnieri/intellij-community,petteyg/intellij-community,fengbaicanhe/intellij-community,signed/intellij-community,samthor/intellij-community,vvv1559/intellij-community,ahb0327/intellij-community,izonder/intellij-community,slisson/intellij-community,asedunov/intellij-community,SerCeMan/intellij-community,fnouama/intellij-community,ftomassetti/intellij-community,fitermay/intellij-community,Lekanich/intellij-community,ryano144/intellij-community,jagguli/intellij-community,salguarnieri/intellij-community,ivan-fedorov/intellij-community,slisson/intellij-community,jagguli/intellij-community,adedayo/intellij-community,jagguli/intellij-community,suncycheng/intellij-community,ivan-fedorov/intellij-community,pwoodworth/intellij-community,MichaelNedzelsky/intellij-community,diorcety/intellij-community,samthor/intellij-community,blademainer/intellij-community,vladmm/intellij-community,vvv1559/intellij-community,fnouama/intellij-community,alphafoobar/intellij-community,lucafavatella/intellij-community,ol-loginov/intellij-community,clumsy/intellij-community,vvv1559/intellij-community,dslomov/intellij-community,salguarnieri/intellij-community,wreckJ/intellij-community,amith01994/intellij-community,samthor/intellij-community,TangHao1987/intellij-community,apixandru/intellij-community,fengbaicanhe/intellij-community,ibinti/intellij-community,gnuhub/intellij-community,MichaelNedzelsky/intellij-community,MER-GROUP/intellij-community,kool79/intellij-community,mglukhikh/intellij-community,holmes/intellij-community,tmpgit/intellij-community,ryano144/intellij-community,dslomov/intellij-community,Distrotech/intellij-community,fengbaicanhe/intellij-community,clumsy/intellij-community,jagguli/intellij-community,blademainer/intellij-community,fitermay/intellij-community,samthor/intellij-community,FHannes/intellij-community,ryano144/intellij-community,ivan-fedorov/intellij-community,idea4bsd/idea4bsd,asedunov/intellij-community,fnouama/intellij-community,suncycheng/intellij-community,petteyg/intellij-community,ivan-fedorov/intellij-community,TangHao1987/intellij-community,SerCeMan/intellij-community,FHannes/intellij-community,holmes/intellij-community,SerCeMan/intellij-community,hurricup/intellij-community,ibinti/intellij-community,pwoodworth/intellij-community,fengbaicanhe/intellij-community,fitermay/intellij-community,signed/intellij-community,Distrotech/intellij-community,pwoodworth/intellij-community,nicolargo/intellij-community,youdonghai/intellij-community,alphafoobar/intellij-community,allotria/intellij-community,wreckJ/intellij-community,asedunov/intellij-community,amith01994/intellij-community,youdonghai/intellij-community,ThiagoGarciaAlves/intellij-community,pwoodworth/intellij-community,fnouama/intellij-community,fnouama/intellij-community,amith01994/intellij-community,fitermay/intellij-community,ol-loginov/intellij-community,ThiagoGarciaAlves/intellij-community,holmes/intellij-community,supersven/intellij-community,lucafavatella/intellij-community,youdonghai/intellij-community,nicolargo/intellij-community,supersven/intellij-community,robovm/robovm-studio,ibinti/intellij-community,lucafavatella/intellij-community,slisson/intellij-community,Lekanich/intellij-community,semonte/intellij-community,hurricup/intellij-community,diorcety/intellij-community,signed/intellij-community,MER-GROUP/intellij-community,youdonghai/intellij-community,holmes/intellij-community,TangHao1987/intellij-community,signed/intellij-community,mglukhikh/intellij-community,idea4bsd/idea4bsd,vladmm/intellij-community,amith01994/intellij-community,ThiagoGarciaAlves/intellij-community,allotria/intellij-community,Lekanich/intellij-community,robovm/robovm-studio,hurricup/intellij-community,nicolargo/intellij-community,apixandru/intellij-community,ahb0327/intellij-community
/* * Copyright 2000-2013 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.openapi.vfs.impl.local; import com.intellij.execution.process.OSProcessHandler; import com.intellij.execution.process.ProcessAdapter; import com.intellij.execution.process.ProcessEvent; import com.intellij.execution.process.ProcessOutputTypes; import com.intellij.ide.actions.ShowFilePathAction; import com.intellij.notification.*; import com.intellij.openapi.application.*; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.util.*; import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.vfs.LocalFileSystem; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.openapi.vfs.newvfs.ManagingFS; import com.intellij.util.SmartList; import com.intellij.util.TimeoutUtil; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.TestOnly; import javax.swing.event.HyperlinkEvent; import java.io.BufferedWriter; import java.io.File; import java.io.IOException; import java.io.OutputStreamWriter; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Set; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import static com.intellij.util.containers.ContainerUtil.*; /** * @author max */ public class FileWatcher { @NonNls public static final String PROPERTY_WATCHER_DISABLED = "idea.filewatcher.disabled"; @NonNls public static final String PROPERTY_WATCHER_EXECUTABLE_PATH = "idea.filewatcher.executable.path"; public static final NotNullLazyValue<NotificationGroup> NOTIFICATION_GROUP = new NotNullLazyValue<NotificationGroup>() { @NotNull @Override protected NotificationGroup compute() { return new NotificationGroup("File Watcher Messages", NotificationDisplayType.STICKY_BALLOON, true); } }; public static class DirtyPaths { public final List<String> dirtyPaths = newArrayList(); public final List<String> dirtyPathsRecursive = newArrayList(); public final List<String> dirtyDirectories = newArrayList(); } private static final Logger LOG = Logger.getInstance("#com.intellij.openapi.vfs.impl.local.FileWatcher"); @NonNls private static final String ROOTS_COMMAND = "ROOTS"; @NonNls private static final String EXIT_COMMAND = "EXIT"; private static final int MAX_PROCESS_LAUNCH_ATTEMPT_COUNT = 10; private final ManagingFS myManagingFS; private final File myExecutable; private volatile MyProcessHandler myProcessHandler; private volatile int myStartAttemptCount = 0; private volatile boolean myIsShuttingDown = false; private final AtomicBoolean myFailureShownToTheUser = new AtomicBoolean(false); private final AtomicInteger mySettingRoots = new AtomicInteger(0); private volatile List<String> myRecursiveWatchRoots = emptyList(); private volatile List<String> myFlatWatchRoots = emptyList(); private volatile List<String> myManualWatchRoots = emptyList(); private volatile List<Pair<String, String>> myMapping = emptyList(); private final Object myLock = new Object(); private DirtyPaths myDirtyPaths = new DirtyPaths(); private final String[] myLastChangedPathes = new String[2]; private int myLastChangedPathIndex; /** @deprecated use {@linkplain com.intellij.openapi.vfs.impl.local.LocalFileSystemImpl#getFileWatcher()} (to remove in IDEA 13) */ public static FileWatcher getInstance() { return ((LocalFileSystemImpl)LocalFileSystem.getInstance()).getFileWatcher(); } FileWatcher(@NotNull ManagingFS managingFS) { myManagingFS = managingFS; boolean disabled = Boolean.parseBoolean(System.getProperty(PROPERTY_WATCHER_DISABLED)); myExecutable = getExecutable(); if (disabled) { LOG.info("Native file watcher is disabled"); } else if (myExecutable == null) { LOG.info("Native file watcher is not supported on this platform"); } else if (!myExecutable.exists()) { notifyOnFailure(ApplicationBundle.message("watcher.exe.not.found"), null); } else if (!myExecutable.canExecute()) { notifyOnFailure(ApplicationBundle.message("watcher.exe.not.exe", myExecutable), new NotificationListener() { @Override public void hyperlinkUpdate(@NotNull Notification notification, @NotNull HyperlinkEvent event) { ShowFilePathAction.openFile(myExecutable); } }); } else if (!isUpToDate(myExecutable)) { notifyOnFailure(ApplicationBundle.message("watcher.exe.outdated"), null); } else { try { startupProcess(false); LOG.info("Native file watcher is operational."); } catch (IOException e) { LOG.warn(e.getMessage()); notifyOnFailure(ApplicationBundle.message("watcher.failed.to.start"), null); } } } public void dispose() { myIsShuttingDown = true; shutdownProcess(); } public boolean isOperational() { return myProcessHandler != null; } public boolean isSettingRoots() { return isOperational() && mySettingRoots.get() > 0; } @NotNull public DirtyPaths getDirtyPaths() { synchronized (myLock) { DirtyPaths dirtyPaths = myDirtyPaths; myDirtyPaths = new DirtyPaths(); myLastChangedPathIndex = 0; for(int i = 0; i < myLastChangedPathes.length; ++i) myLastChangedPathes[i] = null; return dirtyPaths; } } @NotNull public List<String> getManualWatchRoots() { return myManualWatchRoots; } public void setWatchRoots(@NotNull List<String> recursive, @NotNull List<String> flat) { setWatchRoots(recursive, flat, false); } public boolean isWatched(@NotNull VirtualFile file) { return isOperational() && !checkWatchable(file.getPresentableUrl(), true, true).isEmpty(); } /* internal stuff */ @Nullable private static File getExecutable() { String execPath = null; final String altExecPath = System.getProperty(PROPERTY_WATCHER_EXECUTABLE_PATH); if (altExecPath != null && new File(altExecPath).isFile()) { execPath = FileUtil.toSystemDependentName(altExecPath); } if (execPath == null) { final String execName = getExecutableName(false); if (execName == null) { return null; } execPath = FileUtil.join(PathManager.getBinPath(), execName); } File exec = new File(execPath); if (!exec.exists()) { String homePath = PathManager.getHomePath(); if (new File(homePath, "community").exists()) { homePath += File.separator + "community"; } exec = new File(FileUtil.join(homePath, "bin", getExecutableName(true))); } return exec; } @Nullable private static String getExecutableName(final boolean withSubDir) { if (SystemInfo.isWindows) return (withSubDir ? "win" + File.separator : "") + "fsnotifier.exe"; else if (SystemInfo.isMac) return (withSubDir ? "mac" + File.separator : "") + "fsnotifier"; else if (SystemInfo.isLinux) return (withSubDir ? "linux" + File.separator : "") + (SystemInfo.isAMD64 ? "fsnotifier64" : "fsnotifier"); return null; } private static boolean isUpToDate(File executable) { long length = SystemInfo.isWindows ? 70216 : SystemInfo.isMac ? 13924 : SystemInfo.isLinux ? SystemInfo.isAMD64 ? 29155 : 22791 : -1; return length < 0 || length == executable.length(); } public void notifyOnFailure(final String cause, @Nullable final NotificationListener listener) { LOG.warn(cause); if (myFailureShownToTheUser.compareAndSet(false, true)) { ApplicationManager.getApplication().invokeLater(new Runnable() { public void run() { String title = ApplicationBundle.message("watcher.slow.sync"); Notifications.Bus.notify(NOTIFICATION_GROUP.getValue().createNotification(title, cause, NotificationType.WARNING, listener)); } }, ModalityState.NON_MODAL); } } private void startupProcess(boolean restart) throws IOException { if (myIsShuttingDown) { return; } if (ShutDownTracker.isShutdownHookRunning()) { myIsShuttingDown = true; return; } if (myStartAttemptCount++ > MAX_PROCESS_LAUNCH_ATTEMPT_COUNT) { notifyOnFailure(ApplicationBundle.message("watcher.failed.to.start"), null); return; } if (restart) { shutdownProcess(); } LOG.info("Starting file watcher: " + myExecutable); ProcessBuilder processBuilder = new ProcessBuilder(myExecutable.getAbsolutePath()); Process process = processBuilder.start(); myProcessHandler = new MyProcessHandler(process); myProcessHandler.addProcessListener(new MyProcessAdapter()); myProcessHandler.startNotify(); if (restart) { List<String> recursive = myRecursiveWatchRoots; List<String> flat = myFlatWatchRoots; if (recursive.size() + flat.size() > 0) { setWatchRoots(recursive, flat, true); } } } private void shutdownProcess() { final OSProcessHandler processHandler = myProcessHandler; if (processHandler != null) { if (!processHandler.isProcessTerminated()) { boolean forceQuite = true; try { writeLine(EXIT_COMMAND); forceQuite = !processHandler.waitFor(500); if (forceQuite) { LOG.warn("File watcher is still alive. Doing a force quit."); } } catch (IOException ignore) { } if (forceQuite) { processHandler.destroyProcess(); } } myProcessHandler = null; } } private synchronized void setWatchRoots(List<String> recursive, List<String> flat, boolean restart) { if (myProcessHandler == null || myProcessHandler.isProcessTerminated()) return; if (ApplicationManager.getApplication().isDisposeInProgress()) { recursive = flat = Collections.emptyList(); } if (!restart && myRecursiveWatchRoots.equals(recursive) && myFlatWatchRoots.equals(flat)) { return; } mySettingRoots.incrementAndGet(); myMapping = emptyList(); myRecursiveWatchRoots = recursive; myFlatWatchRoots = flat; try { writeLine(ROOTS_COMMAND); for (String path : recursive) { writeLine(path); } for (String path : flat) { writeLine("|" + path); } writeLine("#"); } catch (IOException e) { LOG.warn(e); } } private void writeLine(final String line) throws IOException { if (LOG.isDebugEnabled()) { LOG.debug("<< " + line); } final MyProcessHandler processHandler = myProcessHandler; if (processHandler != null) { processHandler.writeLine(line); } } private static class MyProcessHandler extends OSProcessHandler { private final BufferedWriter myWriter; @SuppressWarnings("IOResourceOpenedButNotSafelyClosed") private MyProcessHandler(@NotNull Process process) { super(process, null, null); // do not access EncodingManager here myWriter = new BufferedWriter(new OutputStreamWriter(process.getOutputStream())); } private void writeLine(String line) throws IOException { myWriter.write(line); myWriter.newLine(); myWriter.flush(); } @Override protected boolean useAdaptiveSleepingPolicyWhenReadingOutput() { return true; } } @NotNull private Collection<String> checkWatchable(String reportedPath, boolean isExact, boolean fastPath) { if (reportedPath == null) return Collections.emptyList(); List<String> flatWatchRoots = myFlatWatchRoots; List<String> recursiveWatchRoots = myRecursiveWatchRoots; if (flatWatchRoots.isEmpty() && recursiveWatchRoots.isEmpty()) return Collections.emptyList(); List<Pair<String, String>> mapping = myMapping; Collection <String> affectedPaths = new SmartList<String>(reportedPath); for (Pair<String, String> map : mapping) { if (FileUtil.startsWith(reportedPath, map.first)) { affectedPaths.add(map.second + reportedPath.substring(map.first.length())); } else if (FileUtil.startsWith(reportedPath, map.second)) { affectedPaths.add(map.first + reportedPath.substring(map.second.length())); } } Collection<String> changedPaths = new SmartList<String>(); ext: for (String path : affectedPaths) { if (fastPath && !changedPaths.isEmpty()) break; for (String root : flatWatchRoots) { if (FileUtil.pathsEqual(path, root)) { changedPaths.add(path); continue ext; } if (isExact) { String parentPath = new File(path).getParent(); if (parentPath != null && FileUtil.pathsEqual(parentPath, root)) { changedPaths.add(path); continue ext; } } } for (String root : recursiveWatchRoots) { if (FileUtil.startsWith(path, root)) { changedPaths.add(path); continue ext; } if (!isExact) { String parentPath = new File(root).getParent(); if (parentPath != null && FileUtil.pathsEqual(path, parentPath)) { changedPaths.add(root); continue ext; } } } } return changedPaths; } @SuppressWarnings("SpellCheckingInspection") private enum WatcherOp { GIVEUP, RESET, UNWATCHEABLE, REMAP, MESSAGE, CREATE, DELETE, STATS, CHANGE, DIRTY, RECDIRTY } private class MyProcessAdapter extends ProcessAdapter { private WatcherOp myLastOp = null; private final List<String> myLines = newArrayList(); @Override public void processTerminated(ProcessEvent event) { LOG.warn("Watcher terminated with exit code " + event.getExitCode()); myProcessHandler = null; try { startupProcess(true); } catch (IOException e) { shutdownProcess(); LOG.warn("Watcher terminated and attempt to restart has failed. Exiting watching thread.", e); } } @Override public void onTextAvailable(ProcessEvent event, Key outputType) { if (outputType == ProcessOutputTypes.STDERR) { LOG.warn(event.getText().trim()); } if (outputType != ProcessOutputTypes.STDOUT) { return; } final String line = event.getText().trim(); if (LOG.isDebugEnabled()) { LOG.debug(">> " + line); } if (myLastOp == null) { final WatcherOp watcherOp; try { watcherOp = WatcherOp.valueOf(line); } catch (IllegalArgumentException e) { final String message = "Illegal watcher command: " + line; if (ApplicationManager.getApplication().isUnitTestMode()) LOG.debug(message); else LOG.error(message); return; } if (watcherOp == WatcherOp.GIVEUP) { notifyOnFailure(ApplicationBundle.message("watcher.gave.up"), null); myIsShuttingDown = true; } else if (watcherOp == WatcherOp.RESET) { reset(); } else { myLastOp = watcherOp; } } else if (myLastOp == WatcherOp.MESSAGE) { notifyOnFailure(line, NotificationListener.URL_OPENING_LISTENER); myLastOp = null; } else if (myLastOp == WatcherOp.REMAP || myLastOp == WatcherOp.UNWATCHEABLE) { if ("#".equals(line)) { if (myLastOp == WatcherOp.REMAP) { processRemap(); } else { mySettingRoots.decrementAndGet(); processUnwatchable(); } myLines.clear(); myLastOp = null; } else { myLines.add(line); } } else { String path = line.replace('\0', '\n'); // unescape processChange(path, myLastOp); myLastOp = null; } } private void processRemap() { Set<Pair<String, String>> pairs = newHashSet(); for (int i = 0; i < myLines.size() - 1; i += 2) { String pathA = preparePathForMapping(myLines.get(i)); String pathB = preparePathForMapping(myLines.get(i + 1)); pairs.add(Pair.create(pathA, pathB)); } myMapping = newArrayList(pairs); notifyOnEvent(); } private String preparePathForMapping(String path) { String localPath = FileUtil.toSystemDependentName(path); return localPath.endsWith(File.separator) ? localPath : localPath + File.separator; } private void processUnwatchable() { myManualWatchRoots = Collections.unmodifiableList(newArrayList(myLines)); notifyOnEvent(); } private void reset() { VirtualFile[] localRoots = myManagingFS.getLocalRoots(); synchronized (myLock) { for (VirtualFile root : localRoots) { myDirtyPaths.dirtyPathsRecursive.add(root.getPresentableUrl()); } } notifyOnEvent(); } private int myChangeRequests, myFilteredRequests; private void processChange(String path, WatcherOp op) { if (SystemInfo.isWindows && op == WatcherOp.RECDIRTY && path.length() == 3 && Character.isLetter(path.charAt(0))) { VirtualFile root = LocalFileSystem.getInstance().findFileByPath(path); if (root != null) { synchronized (myLock) { myDirtyPaths.dirtyPathsRecursive.add(root.getPresentableUrl()); } } notifyOnEvent(); return; } if (op == WatcherOp.CHANGE) { synchronized (myLock) { ++myChangeRequests; // TODO: remove logging once finalized if ((myChangeRequests & 0x3ff) == 0) LOG.info("Change requests:" + myChangeRequests + ", filtered:" + myFilteredRequests); for(int i = 0; i < myLastChangedPathes.length; ++i) { int last = myLastChangedPathIndex - i - 1; if (last < 0) last += myLastChangedPathes.length; String lastChangedPath = myLastChangedPathes[last]; if (lastChangedPath != null && lastChangedPath.equals(path)) { ++myFilteredRequests; return; } } myLastChangedPathes[myLastChangedPathIndex ++] = path; if (myLastChangedPathIndex == myLastChangedPathes.length) myLastChangedPathIndex = 0; } } boolean exactPath = op != WatcherOp.DIRTY && op != WatcherOp.RECDIRTY; Collection<String> paths = checkWatchable(path, exactPath, false); if (paths.isEmpty()) { if (LOG.isDebugEnabled()) { LOG.debug("Not watchable, filtered: " + path); } return; } synchronized (myLock) { switch (op) { case STATS: case CHANGE: myDirtyPaths.dirtyPaths.addAll(paths); break; case CREATE: case DELETE: for (String p : paths) { String parentPath = new File(p).getParent(); myDirtyPaths.dirtyPaths.add(parentPath != null ? parentPath : p); } break; case DIRTY: myDirtyPaths.dirtyDirectories.addAll(paths); break; case RECDIRTY: myDirtyPaths.dirtyPathsRecursive.addAll(paths); break; default: LOG.error("Unexpected op: " + op); } } notifyOnEvent(); } } /* test data and methods */ private volatile Runnable myNotifier = null; private void notifyOnEvent() { final Runnable notifier = myNotifier; if (notifier != null) { notifier.run(); } } @TestOnly public static Logger getLog() { return LOG; } @TestOnly public void startup(@Nullable final Runnable notifier) throws IOException { final Application app = ApplicationManager.getApplication(); assert app != null && app.isUnitTestMode() : app; myIsShuttingDown = false; myStartAttemptCount = 0; startupProcess(false); myNotifier = notifier; } @TestOnly public void shutdown() throws InterruptedException { final Application app = ApplicationManager.getApplication(); assert app != null && app.isUnitTestMode() : app; myNotifier = null; final MyProcessHandler processHandler = myProcessHandler; if (processHandler != null) { myIsShuttingDown = true; shutdownProcess(); long t = System.currentTimeMillis(); while (!processHandler.isProcessTerminated()) { if ((System.currentTimeMillis() - t) > 5000) { throw new InterruptedException("Timed out waiting watcher process to terminate"); } TimeoutUtil.sleep(100); } } } }
platform/platform-impl/src/com/intellij/openapi/vfs/impl/local/FileWatcher.java
/* * Copyright 2000-2013 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.openapi.vfs.impl.local; import com.intellij.execution.process.OSProcessHandler; import com.intellij.execution.process.ProcessAdapter; import com.intellij.execution.process.ProcessEvent; import com.intellij.execution.process.ProcessOutputTypes; import com.intellij.ide.actions.ShowFilePathAction; import com.intellij.notification.*; import com.intellij.openapi.application.*; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.util.*; import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.vfs.LocalFileSystem; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.openapi.vfs.newvfs.ManagingFS; import com.intellij.util.SmartList; import com.intellij.util.TimeoutUtil; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.TestOnly; import javax.swing.event.HyperlinkEvent; import java.io.BufferedWriter; import java.io.File; import java.io.IOException; import java.io.OutputStreamWriter; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Set; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import static com.intellij.util.containers.ContainerUtil.*; /** * @author max */ public class FileWatcher { @NonNls public static final String PROPERTY_WATCHER_DISABLED = "idea.filewatcher.disabled"; @NonNls public static final String PROPERTY_WATCHER_EXECUTABLE_PATH = "idea.filewatcher.executable.path"; public static final NotNullLazyValue<NotificationGroup> NOTIFICATION_GROUP = new NotNullLazyValue<NotificationGroup>() { @NotNull @Override protected NotificationGroup compute() { return new NotificationGroup("File Watcher Messages", NotificationDisplayType.STICKY_BALLOON, true); } }; public static class DirtyPaths { public final List<String> dirtyPaths = newArrayList(); public final List<String> dirtyPathsRecursive = newArrayList(); public final List<String> dirtyDirectories = newArrayList(); } private static final Logger LOG = Logger.getInstance("#com.intellij.openapi.vfs.impl.local.FileWatcher"); @NonNls private static final String ROOTS_COMMAND = "ROOTS"; @NonNls private static final String EXIT_COMMAND = "EXIT"; private static final int MAX_PROCESS_LAUNCH_ATTEMPT_COUNT = 10; private final ManagingFS myManagingFS; private final File myExecutable; private volatile MyProcessHandler myProcessHandler; private volatile int myStartAttemptCount = 0; private volatile boolean myIsShuttingDown = false; private final AtomicBoolean myFailureShownToTheUser = new AtomicBoolean(false); private final AtomicInteger mySettingRoots = new AtomicInteger(0); private volatile List<String> myRecursiveWatchRoots = emptyList(); private volatile List<String> myFlatWatchRoots = emptyList(); private volatile List<String> myManualWatchRoots = emptyList(); private volatile List<Pair<String, String>> myMapping = emptyList(); private final Object myLock = new Object(); private DirtyPaths myDirtyPaths = new DirtyPaths(); /** @deprecated use {@linkplain com.intellij.openapi.vfs.impl.local.LocalFileSystemImpl#getFileWatcher()} (to remove in IDEA 13) */ public static FileWatcher getInstance() { return ((LocalFileSystemImpl)LocalFileSystem.getInstance()).getFileWatcher(); } FileWatcher(@NotNull ManagingFS managingFS) { myManagingFS = managingFS; boolean disabled = Boolean.parseBoolean(System.getProperty(PROPERTY_WATCHER_DISABLED)); myExecutable = getExecutable(); if (disabled) { LOG.info("Native file watcher is disabled"); } else if (myExecutable == null) { LOG.info("Native file watcher is not supported on this platform"); } else if (!myExecutable.exists()) { notifyOnFailure(ApplicationBundle.message("watcher.exe.not.found"), null); } else if (!myExecutable.canExecute()) { notifyOnFailure(ApplicationBundle.message("watcher.exe.not.exe", myExecutable), new NotificationListener() { @Override public void hyperlinkUpdate(@NotNull Notification notification, @NotNull HyperlinkEvent event) { ShowFilePathAction.openFile(myExecutable); } }); } else if (!isUpToDate(myExecutable)) { notifyOnFailure(ApplicationBundle.message("watcher.exe.outdated"), null); } else { try { startupProcess(false); LOG.info("Native file watcher is operational."); } catch (IOException e) { LOG.warn(e.getMessage()); notifyOnFailure(ApplicationBundle.message("watcher.failed.to.start"), null); } } } public void dispose() { myIsShuttingDown = true; shutdownProcess(); } public boolean isOperational() { return myProcessHandler != null; } public boolean isSettingRoots() { return isOperational() && mySettingRoots.get() > 0; } @NotNull public DirtyPaths getDirtyPaths() { synchronized (myLock) { DirtyPaths dirtyPaths = myDirtyPaths; myDirtyPaths = new DirtyPaths(); return dirtyPaths; } } @NotNull public List<String> getManualWatchRoots() { return myManualWatchRoots; } public void setWatchRoots(@NotNull List<String> recursive, @NotNull List<String> flat) { setWatchRoots(recursive, flat, false); } public boolean isWatched(@NotNull VirtualFile file) { return isOperational() && !checkWatchable(file.getPresentableUrl(), true, true).isEmpty(); } /* internal stuff */ @Nullable private static File getExecutable() { String execPath = null; final String altExecPath = System.getProperty(PROPERTY_WATCHER_EXECUTABLE_PATH); if (altExecPath != null && new File(altExecPath).isFile()) { execPath = FileUtil.toSystemDependentName(altExecPath); } if (execPath == null) { final String execName = getExecutableName(false); if (execName == null) { return null; } execPath = FileUtil.join(PathManager.getBinPath(), execName); } File exec = new File(execPath); if (!exec.exists()) { String homePath = PathManager.getHomePath(); if (new File(homePath, "community").exists()) { homePath += File.separator + "community"; } exec = new File(FileUtil.join(homePath, "bin", getExecutableName(true))); } return exec; } @Nullable private static String getExecutableName(final boolean withSubDir) { if (SystemInfo.isWindows) return (withSubDir ? "win" + File.separator : "") + "fsnotifier.exe"; else if (SystemInfo.isMac) return (withSubDir ? "mac" + File.separator : "") + "fsnotifier"; else if (SystemInfo.isLinux) return (withSubDir ? "linux" + File.separator : "") + (SystemInfo.isAMD64 ? "fsnotifier64" : "fsnotifier"); return null; } private static boolean isUpToDate(File executable) { long length = SystemInfo.isWindows ? 70216 : SystemInfo.isMac ? 13924 : SystemInfo.isLinux ? SystemInfo.isAMD64 ? 29155 : 22791 : -1; return length < 0 || length == executable.length(); } public void notifyOnFailure(final String cause, @Nullable final NotificationListener listener) { LOG.warn(cause); if (myFailureShownToTheUser.compareAndSet(false, true)) { ApplicationManager.getApplication().invokeLater(new Runnable() { public void run() { String title = ApplicationBundle.message("watcher.slow.sync"); Notifications.Bus.notify(NOTIFICATION_GROUP.getValue().createNotification(title, cause, NotificationType.WARNING, listener)); } }, ModalityState.NON_MODAL); } } private void startupProcess(boolean restart) throws IOException { if (myIsShuttingDown) { return; } if (ShutDownTracker.isShutdownHookRunning()) { myIsShuttingDown = true; return; } if (myStartAttemptCount++ > MAX_PROCESS_LAUNCH_ATTEMPT_COUNT) { notifyOnFailure(ApplicationBundle.message("watcher.failed.to.start"), null); return; } if (restart) { shutdownProcess(); } LOG.info("Starting file watcher: " + myExecutable); ProcessBuilder processBuilder = new ProcessBuilder(myExecutable.getAbsolutePath()); Process process = processBuilder.start(); myProcessHandler = new MyProcessHandler(process); myProcessHandler.addProcessListener(new MyProcessAdapter()); myProcessHandler.startNotify(); if (restart) { List<String> recursive = myRecursiveWatchRoots; List<String> flat = myFlatWatchRoots; if (recursive.size() + flat.size() > 0) { setWatchRoots(recursive, flat, true); } } } private void shutdownProcess() { final OSProcessHandler processHandler = myProcessHandler; if (processHandler != null) { if (!processHandler.isProcessTerminated()) { boolean forceQuite = true; try { writeLine(EXIT_COMMAND); forceQuite = !processHandler.waitFor(500); if (forceQuite) { LOG.warn("File watcher is still alive. Doing a force quit."); } } catch (IOException ignore) { } if (forceQuite) { processHandler.destroyProcess(); } } myProcessHandler = null; } } private synchronized void setWatchRoots(List<String> recursive, List<String> flat, boolean restart) { if (myProcessHandler == null || myProcessHandler.isProcessTerminated()) return; if (ApplicationManager.getApplication().isDisposeInProgress()) { recursive = flat = Collections.emptyList(); } if (!restart && myRecursiveWatchRoots.equals(recursive) && myFlatWatchRoots.equals(flat)) { return; } mySettingRoots.incrementAndGet(); myMapping = emptyList(); myRecursiveWatchRoots = recursive; myFlatWatchRoots = flat; try { writeLine(ROOTS_COMMAND); for (String path : recursive) { writeLine(path); } for (String path : flat) { writeLine("|" + path); } writeLine("#"); } catch (IOException e) { LOG.warn(e); } } private void writeLine(final String line) throws IOException { if (LOG.isDebugEnabled()) { LOG.debug("<< " + line); } final MyProcessHandler processHandler = myProcessHandler; if (processHandler != null) { processHandler.writeLine(line); } } private static class MyProcessHandler extends OSProcessHandler { private final BufferedWriter myWriter; @SuppressWarnings("IOResourceOpenedButNotSafelyClosed") private MyProcessHandler(@NotNull Process process) { super(process, null, null); // do not access EncodingManager here myWriter = new BufferedWriter(new OutputStreamWriter(process.getOutputStream())); } private void writeLine(String line) throws IOException { myWriter.write(line); myWriter.newLine(); myWriter.flush(); } @Override protected boolean useAdaptiveSleepingPolicyWhenReadingOutput() { return true; } } @NotNull private Collection<String> checkWatchable(String reportedPath, boolean isExact, boolean fastPath) { if (reportedPath == null) return Collections.emptyList(); List<String> flatWatchRoots = myFlatWatchRoots; List<String> recursiveWatchRoots = myRecursiveWatchRoots; if (flatWatchRoots.isEmpty() && recursiveWatchRoots.isEmpty()) return Collections.emptyList(); List<Pair<String, String>> mapping = myMapping; Collection <String> affectedPaths = new SmartList<String>(reportedPath); for (Pair<String, String> map : mapping) { if (FileUtil.startsWith(reportedPath, map.first)) { affectedPaths.add(map.second + reportedPath.substring(map.first.length())); } else if (FileUtil.startsWith(reportedPath, map.second)) { affectedPaths.add(map.first + reportedPath.substring(map.second.length())); } } Collection<String> changedPaths = new SmartList<String>(); ext: for (String path : affectedPaths) { if (fastPath && !changedPaths.isEmpty()) break; for (String root : flatWatchRoots) { if (FileUtil.pathsEqual(path, root)) { changedPaths.add(path); continue ext; } if (isExact) { String parentPath = new File(path).getParent(); if (parentPath != null && FileUtil.pathsEqual(parentPath, root)) { changedPaths.add(path); continue ext; } } } for (String root : recursiveWatchRoots) { if (FileUtil.startsWith(path, root)) { changedPaths.add(path); continue ext; } if (!isExact) { String parentPath = new File(root).getParent(); if (parentPath != null && FileUtil.pathsEqual(path, parentPath)) { changedPaths.add(root); continue ext; } } } } return changedPaths; } @SuppressWarnings("SpellCheckingInspection") private enum WatcherOp { GIVEUP, RESET, UNWATCHEABLE, REMAP, MESSAGE, CREATE, DELETE, STATS, CHANGE, DIRTY, RECDIRTY } private class MyProcessAdapter extends ProcessAdapter { private WatcherOp myLastOp = null; private final List<String> myLines = newArrayList(); @Override public void processTerminated(ProcessEvent event) { LOG.warn("Watcher terminated with exit code " + event.getExitCode()); myProcessHandler = null; try { startupProcess(true); } catch (IOException e) { shutdownProcess(); LOG.warn("Watcher terminated and attempt to restart has failed. Exiting watching thread.", e); } } @Override public void onTextAvailable(ProcessEvent event, Key outputType) { if (outputType == ProcessOutputTypes.STDERR) { LOG.warn(event.getText().trim()); } if (outputType != ProcessOutputTypes.STDOUT) { return; } final String line = event.getText().trim(); if (LOG.isDebugEnabled()) { LOG.debug(">> " + line); } if (myLastOp == null) { final WatcherOp watcherOp; try { watcherOp = WatcherOp.valueOf(line); } catch (IllegalArgumentException e) { final String message = "Illegal watcher command: " + line; if (ApplicationManager.getApplication().isUnitTestMode()) LOG.debug(message); else LOG.error(message); return; } if (watcherOp == WatcherOp.GIVEUP) { notifyOnFailure(ApplicationBundle.message("watcher.gave.up"), null); myIsShuttingDown = true; } else if (watcherOp == WatcherOp.RESET) { reset(); } else { myLastOp = watcherOp; } } else if (myLastOp == WatcherOp.MESSAGE) { notifyOnFailure(line, NotificationListener.URL_OPENING_LISTENER); myLastOp = null; } else if (myLastOp == WatcherOp.REMAP || myLastOp == WatcherOp.UNWATCHEABLE) { if ("#".equals(line)) { if (myLastOp == WatcherOp.REMAP) { processRemap(); } else { mySettingRoots.decrementAndGet(); processUnwatchable(); } myLines.clear(); myLastOp = null; } else { myLines.add(line); } } else { String path = line.replace('\0', '\n'); // unescape processChange(path, myLastOp); myLastOp = null; } } private void processRemap() { Set<Pair<String, String>> pairs = newHashSet(); for (int i = 0; i < myLines.size() - 1; i += 2) { String pathA = preparePathForMapping(myLines.get(i)); String pathB = preparePathForMapping(myLines.get(i + 1)); pairs.add(Pair.create(pathA, pathB)); } myMapping = newArrayList(pairs); notifyOnEvent(); } private String preparePathForMapping(String path) { String localPath = FileUtil.toSystemDependentName(path); return localPath.endsWith(File.separator) ? localPath : localPath + File.separator; } private void processUnwatchable() { myManualWatchRoots = Collections.unmodifiableList(newArrayList(myLines)); notifyOnEvent(); } private void reset() { VirtualFile[] localRoots = myManagingFS.getLocalRoots(); synchronized (myLock) { for (VirtualFile root : localRoots) { myDirtyPaths.dirtyPathsRecursive.add(root.getPresentableUrl()); } } notifyOnEvent(); } private void processChange(String path, WatcherOp op) { if (SystemInfo.isWindows && op == WatcherOp.RECDIRTY && path.length() == 3 && Character.isLetter(path.charAt(0))) { VirtualFile root = LocalFileSystem.getInstance().findFileByPath(path); if (root != null) { synchronized (myLock) { myDirtyPaths.dirtyPathsRecursive.add(root.getPresentableUrl()); } } notifyOnEvent(); return; } boolean exactPath = op != WatcherOp.DIRTY && op != WatcherOp.RECDIRTY; Collection<String> paths = checkWatchable(path, exactPath, false); if (paths.isEmpty()) { if (LOG.isDebugEnabled()) { LOG.debug("Not watchable, filtered: " + path); } return; } synchronized (myLock) { switch (op) { case STATS: case CHANGE: myDirtyPaths.dirtyPaths.addAll(paths); break; case CREATE: case DELETE: for (String p : paths) { String parentPath = new File(p).getParent(); myDirtyPaths.dirtyPaths.add(parentPath != null ? parentPath : p); } break; case DIRTY: myDirtyPaths.dirtyDirectories.addAll(paths); break; case RECDIRTY: myDirtyPaths.dirtyPathsRecursive.addAll(paths); break; default: LOG.error("Unexpected op: " + op); } } notifyOnEvent(); } } /* test data and methods */ private volatile Runnable myNotifier = null; private void notifyOnEvent() { final Runnable notifier = myNotifier; if (notifier != null) { notifier.run(); } } @TestOnly public static Logger getLog() { return LOG; } @TestOnly public void startup(@Nullable final Runnable notifier) throws IOException { final Application app = ApplicationManager.getApplication(); assert app != null && app.isUnitTestMode() : app; myIsShuttingDown = false; myStartAttemptCount = 0; startupProcess(false); myNotifier = notifier; } @TestOnly public void shutdown() throws InterruptedException { final Application app = ApplicationManager.getApplication(); assert app != null && app.isUnitTestMode() : app; myNotifier = null; final MyProcessHandler processHandler = myProcessHandler; if (processHandler != null) { myIsShuttingDown = true; shutdownProcess(); long t = System.currentTimeMillis(); while (!processHandler.isProcessTerminated()) { if ((System.currentTimeMillis() - t) > 5000) { throw new InterruptedException("Timed out waiting watcher process to terminate"); } TimeoutUtil.sleep(100); } } } }
coalesce change file events in small frame, usually merge e.g. large copy file change notifications
platform/platform-impl/src/com/intellij/openapi/vfs/impl/local/FileWatcher.java
coalesce change file events in small frame, usually merge e.g. large copy file change notifications
<ide><path>latform/platform-impl/src/com/intellij/openapi/vfs/impl/local/FileWatcher.java <ide> <ide> private final Object myLock = new Object(); <ide> private DirtyPaths myDirtyPaths = new DirtyPaths(); <add> private final String[] myLastChangedPathes = new String[2]; <add> private int myLastChangedPathIndex; <ide> <ide> /** @deprecated use {@linkplain com.intellij.openapi.vfs.impl.local.LocalFileSystemImpl#getFileWatcher()} (to remove in IDEA 13) */ <ide> public static FileWatcher getInstance() { <ide> synchronized (myLock) { <ide> DirtyPaths dirtyPaths = myDirtyPaths; <ide> myDirtyPaths = new DirtyPaths(); <add> myLastChangedPathIndex = 0; <add> for(int i = 0; i < myLastChangedPathes.length; ++i) myLastChangedPathes[i] = null; <ide> return dirtyPaths; <ide> } <ide> } <ide> notifyOnEvent(); <ide> } <ide> <add> private int myChangeRequests, myFilteredRequests; <add> <ide> private void processChange(String path, WatcherOp op) { <ide> if (SystemInfo.isWindows && op == WatcherOp.RECDIRTY && path.length() == 3 && Character.isLetter(path.charAt(0))) { <ide> VirtualFile root = LocalFileSystem.getInstance().findFileByPath(path); <ide> return; <ide> } <ide> <add> if (op == WatcherOp.CHANGE) { <add> synchronized (myLock) { <add> ++myChangeRequests; <add> <add> // TODO: remove logging once finalized <add> if ((myChangeRequests & 0x3ff) == 0) LOG.info("Change requests:" + myChangeRequests + ", filtered:" + myFilteredRequests); <add> <add> for(int i = 0; i < myLastChangedPathes.length; ++i) { <add> int last = myLastChangedPathIndex - i - 1; <add> if (last < 0) last += myLastChangedPathes.length; <add> String lastChangedPath = myLastChangedPathes[last]; <add> if (lastChangedPath != null && lastChangedPath.equals(path)) { <add> ++myFilteredRequests; <add> return; <add> } <add> } <add> myLastChangedPathes[myLastChangedPathIndex ++] = path; <add> if (myLastChangedPathIndex == myLastChangedPathes.length) myLastChangedPathIndex = 0; <add> } <add> } <add> <ide> boolean exactPath = op != WatcherOp.DIRTY && op != WatcherOp.RECDIRTY; <ide> Collection<String> paths = checkWatchable(path, exactPath, false); <ide>
JavaScript
apache-2.0
99ccf377b45e68e862ec11931943087e18ac1293
0
implydata/plywood,implydata/plywood,implydata/plywood
var { expect } = require("chai"); var { WallTime } = require('chronoshift'); if (!WallTime.rules) { var tzData = require("chronoshift/lib/walltime/walltime-data.js"); WallTime.init(tzData.rules, tzData.zones); } var { druidRequesterFactory } = require('plywood-druid-requester'); var { mySqlRequesterFactory } = require('plywood-mysql-requester'); var plywood = require('../../build/plywood'); var { External, TimeRange, $, ply, basicExecutorFactory } = plywood; var utils = require('../utils'); var info = require('../info'); var druidRequester = druidRequesterFactory({ host: info.druidHost }); var mySqlRequester = mySqlRequesterFactory({ host: info.mySqlHost, database: info.mySqlDatabase, user: info.mySqlUser, password: info.mySqlPassword }); var attributes = [ { name: 'time', type: 'TIME' }, { name: 'sometimeLater', type: 'TIME' }, { name: 'channel', type: 'STRING' }, { name: 'page', type: 'STRING' }, { name: 'page_unique', special: 'unique' }, { name: 'user', type: 'STRING' }, { name: 'isNew', type: 'BOOLEAN' }, { name: 'isAnonymous', type: 'BOOLEAN' }, { name: 'commentLength', type: 'NUMBER' }, { name: 'metroCode', type: 'STRING' }, { name: 'cityName', type: 'STRING' }, { name: 'count', type: 'NUMBER' }, { name: 'delta', type: 'NUMBER' }, { name: 'deltaByTen', type: 'NUMBER' }, { name: 'added', type: 'NUMBER' }, { name: 'deleted', type: 'NUMBER' } ]; var druidExecutor = basicExecutorFactory({ datasets: { wiki: External.fromJS({ engine: 'druid', dataSource: 'wikipedia', timeAttribute: 'time', context: { timeout: 10000 }, attributes, filter: $('time').in(TimeRange.fromJS({ start: new Date("2015-09-12T00:00:00Z"), end: new Date("2015-09-13T00:00:00Z") })), druidVersion: info.druidVersion, requester: druidRequester }) } }); var mysqlExecutor = basicExecutorFactory({ datasets: { wiki: External.fromJS({ engine: 'mysql', table: 'wikipedia', attributes, requester: mySqlRequester }) } }); var equalityTest = utils.makeEqualityTest({ druid: druidExecutor, mysql: mysqlExecutor }); describe("Cross Functional", function() { this.timeout(10000); describe("filters", () => { it('works with a simple filter', equalityTest({ executorNames: ['druid', 'mysql'], expression: ply() .apply('wiki', '$wiki.filter($channel == en)') .apply('TotalAdded', '$wiki.sum($added)') })); it('works with == NULL filter', equalityTest({ executorNames: ['druid', 'mysql'], expression: ply() .apply('wiki', '$wiki.filter($cityName == null)') .apply('TotalAdded', '$wiki.sum($added)') })); it('works with != NULL filter', equalityTest({ executorNames: ['druid', 'mysql'], expression: ply() .apply('wiki', '$wiki.filter($cityName != null)') .apply('TotalAdded', '$wiki.sum($added)') })); it('works with contains filter', equalityTest({ executorNames: ['druid', 'mysql'], expression: ply() .apply('wiki', '$wiki.filter($cityName.contains("San"))') .apply('TotalAdded', '$wiki.sum($added)') })); }); describe("splits", () => { it('works with total', equalityTest({ executorNames: ['druid', 'mysql'], expression: ply() .apply('wiki', '$wiki') //.apply('RowCount', '$wiki.count()') // ToDo: make wikipedia data in MySQL rolled up .apply('TotalAdded', '$wiki.sum($added)') })); it('works with STRING split (sort on split)', equalityTest({ executorNames: ['druid', 'mysql'], expression: $('wiki') .split('$channel', 'Channel') .sort('$Channel', 'ascending') .limit(5) })); it('works with STRING split (sort on apply)', equalityTest({ executorNames: ['druid', 'mysql'], expression: $('wiki') .split('$channel', 'Channel') .apply('TotalAdded', '$wiki.sum($added)') .sort('$TotalAdded', 'descending') .limit(5) })); it('works with TIME split (timeBucket) (sort on split)'); it('works with TIME split (timeBucket) (sort on apply)'); it('works with TIME split (timePart) (sort on split)'); it('works with TIME split (timePart) (sort on apply)'); it('works with multi-dimensional split'); }); describe("applies", () => { it('works with all sorts of applies', equalityTest({ executorNames: ['druid', 'mysql'], expression: $('wiki') .split('$channel', 'Channel') .apply('TotalAdded', '$wiki.sum($added)') .apply('TokyoAdded', '$wiki.filter($cityName == Tokyo).sum($added)') .sort('$Channel', 'descending') .limit(50) })); }); });
test/functional/crossFunctional.mocha.js
var { expect } = require("chai"); var { WallTime } = require('chronoshift'); if (!WallTime.rules) { var tzData = require("chronoshift/lib/walltime/walltime-data.js"); WallTime.init(tzData.rules, tzData.zones); } var { druidRequesterFactory } = require('plywood-druid-requester'); var { mySqlRequesterFactory } = require('plywood-mysql-requester'); var plywood = require('../../build/plywood'); var { External, TimeRange, $, ply, basicExecutorFactory } = plywood; var utils = require('../utils'); var info = require('../info'); var druidRequester = druidRequesterFactory({ host: info.druidHost }); var mySqlRequester = mySqlRequesterFactory({ host: info.mySqlHost, database: info.mySqlDatabase, user: info.mySqlUser, password: info.mySqlPassword }); var attributes = [ { name: 'time', type: 'TIME' }, { name: 'sometimeLater', type: 'TIME' }, { name: 'channel', type: 'STRING' }, { name: 'page', type: 'STRING' }, { name: 'page_unique', special: 'unique' }, { name: 'user', type: 'STRING' }, { name: 'isNew', type: 'BOOLEAN' }, { name: 'isAnonymous', type: 'BOOLEAN' }, { name: 'commentLength', type: 'NUMBER' }, { name: 'metroCode', type: 'STRING' }, { name: 'cityName', type: 'STRING' }, { name: 'count', type: 'NUMBER' }, { name: 'delta', type: 'NUMBER' }, { name: 'deltaByTen', type: 'NUMBER' }, { name: 'added', type: 'NUMBER' }, { name: 'deleted', type: 'NUMBER' } ]; var druidExecutor = basicExecutorFactory({ datasets: { wiki: External.fromJS({ engine: 'druid', dataSource: 'wikipedia', timeAttribute: 'time', context: { timeout: 10000 }, attributes, filter: $('time').in(TimeRange.fromJS({ start: new Date("2015-09-12T00:00:00Z"), end: new Date("2015-09-13T00:00:00Z") })), druidVersion: info.druidVersion, requester: druidRequester }) } }); var mysqlExecutor = basicExecutorFactory({ datasets: { wiki: External.fromJS({ engine: 'mysql', table: 'wikipedia', attributes, requester: mySqlRequester }) } }); var equalityTest = utils.makeEqualityTest({ druid: druidExecutor, mysql: mysqlExecutor }); describe("Cross Functional", function() { this.timeout(10000); describe("filters", () => { it('works with a simple filter', equalityTest({ executorNames: ['druid', 'mysql'], expression: ply() .apply('wiki', '$wiki.filter($channel == en)') .apply('TotalAdded', '$wiki.sum($added)') })); it('works with an IS NULL filter', equalityTest({ executorNames: ['druid', 'mysql'], expression: ply() .apply('wiki', '$wiki.filter($cityName == null)') .apply('TotalAdded', '$wiki.sum($added)') })); it('works with contains filter', equalityTest({ executorNames: ['druid', 'mysql'], expression: ply() .apply('wiki', '$wiki.filter($cityName.contains("San"))') .apply('TotalAdded', '$wiki.sum($added)') })); }); describe("splits", () => { it('works with total', equalityTest({ executorNames: ['druid', 'mysql'], expression: ply() .apply('wiki', '$wiki') //.apply('RowCount', '$wiki.count()') // ToDo: make wikipedia data in MySQL rolled up .apply('TotalAdded', '$wiki.sum($added)') })); it('works with STRING split (sort on split)', equalityTest({ executorNames: ['druid', 'mysql'], expression: $('wiki') .split('$channel', 'Channel') .sort('$Channel', 'ascending') .limit(5) })); it('works with STRING split (sort on apply)', equalityTest({ executorNames: ['druid', 'mysql'], expression: $('wiki') .split('$channel', 'Channel') .apply('TotalAdded', '$wiki.sum($added)') .sort('$TotalAdded', 'descending') .limit(5) })); it('works with TIME split (timeBucket) (sort on split)'); it('works with TIME split (timeBucket) (sort on apply)'); it('works with TIME split (timePart) (sort on split)'); it('works with TIME split (timePart) (sort on apply)'); it('works with multi-dimensional split'); }); describe("applies", () => { it('works with all sorts of applies', equalityTest({ executorNames: ['druid', 'mysql'], expression: $('wiki') .split('$channel', 'Channel') .apply('TotalAdded', '$wiki.sum($added)') .apply('TokyoAdded', '$wiki.filter($cityName == Tokyo).sum($added)') .sort('$Channel', 'descending') .limit(50) })); }); });
not null test
test/functional/crossFunctional.mocha.js
not null test
<ide><path>est/functional/crossFunctional.mocha.js <ide> .apply('TotalAdded', '$wiki.sum($added)') <ide> })); <ide> <del> it('works with an IS NULL filter', equalityTest({ <add> it('works with == NULL filter', equalityTest({ <ide> executorNames: ['druid', 'mysql'], <ide> expression: ply() <ide> .apply('wiki', '$wiki.filter($cityName == null)') <add> .apply('TotalAdded', '$wiki.sum($added)') <add> })); <add> <add> it('works with != NULL filter', equalityTest({ <add> executorNames: ['druid', 'mysql'], <add> expression: ply() <add> .apply('wiki', '$wiki.filter($cityName != null)') <ide> .apply('TotalAdded', '$wiki.sum($added)') <ide> })); <ide>
Java
apache-2.0
2fc5b61d5935e7bdca7a69ef8d7bcbbbd0adbfad
0
androidx/androidx,AndroidX/androidx,androidx/androidx,androidx/androidx,AndroidX/androidx,androidx/androidx,aosp-mirror/platform_frameworks_support,androidx/androidx,aosp-mirror/platform_frameworks_support,AndroidX/androidx,AndroidX/androidx,AndroidX/androidx,androidx/androidx,androidx/androidx,aosp-mirror/platform_frameworks_support,androidx/androidx,aosp-mirror/platform_frameworks_support,androidx/androidx,AndroidX/androidx,AndroidX/androidx,AndroidX/androidx,androidx/androidx,aosp-mirror/platform_frameworks_support,AndroidX/androidx,AndroidX/androidx
/* * Copyright (C) 2015 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package android.support.v7.app; import android.content.Intent; import android.content.res.Configuration; import android.content.res.Resources; import android.os.Build; import android.os.Bundle; import android.support.annotation.CallSuper; import android.support.annotation.IdRes; import android.support.annotation.LayoutRes; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.annotation.StyleRes; import android.support.v4.app.ActivityCompat; import android.support.v4.app.FragmentActivity; import android.support.v4.app.NavUtils; import android.support.v4.app.TaskStackBuilder; import android.support.v4.view.KeyEventCompat; import android.support.v7.view.ActionMode; import android.support.v7.widget.TintResources; import android.support.v7.widget.Toolbar; import android.util.DisplayMetrics; import android.view.KeyEvent; import android.view.Menu; import android.view.MenuInflater; import android.view.View; import android.view.ViewGroup; /** * Base class for activities that use the * <a href="{@docRoot}tools/extras/support-library.html">support library</a> action bar features. * * <p>You can add an {@link android.support.v7.app.ActionBar} to your activity when running on API level 7 or higher * by extending this class for your activity and setting the activity theme to * {@link android.support.v7.appcompat.R.style#Theme_AppCompat Theme.AppCompat} or a similar theme. * * <div class="special reference"> * <h3>Developer Guides</h3> * * <p>For information about how to use the action bar, including how to add action items, navigation * modes and more, read the <a href="{@docRoot}guide/topics/ui/actionbar.html">Action * Bar</a> API guide.</p> * </div> */ public class AppCompatActivity extends FragmentActivity implements AppCompatCallback, TaskStackBuilder.SupportParentable, ActionBarDrawerToggle.DelegateProvider { private AppCompatDelegate mDelegate; private int mThemeId = 0; private boolean mEatKeyUpEvent; private Resources mResources; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { final AppCompatDelegate delegate = getDelegate(); delegate.installViewFactory(); delegate.onCreate(savedInstanceState); if (delegate.applyDayNight() && mThemeId != 0) { // If DayNight has been applied, we need to re-apply the theme for // the changes to take effect. On API 23+, we should bypass // setTheme(), which will no-op if the theme ID is identical to the // current theme ID. if (Build.VERSION.SDK_INT >= 23) { onApplyThemeResource(getTheme(), mThemeId, false); } else { setTheme(mThemeId); } } super.onCreate(savedInstanceState); } @Override public void setTheme(@StyleRes final int resid) { super.setTheme(resid); // Keep hold of the theme id so that we can re-set it later if needed mThemeId = resid; } @Override protected void onPostCreate(@Nullable Bundle savedInstanceState) { super.onPostCreate(savedInstanceState); getDelegate().onPostCreate(savedInstanceState); } /** * Support library version of {@link android.app.Activity#getActionBar}. * * <p>Retrieve a reference to this activity's ActionBar. * * @return The Activity's ActionBar, or null if it does not have one. */ @Nullable public ActionBar getSupportActionBar() { return getDelegate().getSupportActionBar(); } /** * Set a {@link android.widget.Toolbar Toolbar} to act as the * {@link android.support.v7.app.ActionBar} for this Activity window. * * <p>When set to a non-null value the {@link #getActionBar()} method will return * an {@link android.support.v7.app.ActionBar} object that can be used to control the given * toolbar as if it were a traditional window decor action bar. The toolbar's menu will be * populated with the Activity's options menu and the navigation button will be wired through * the standard {@link android.R.id#home home} menu select action.</p> * * <p>In order to use a Toolbar within the Activity's window content the application * must not request the window feature * {@link android.view.Window#FEATURE_ACTION_BAR FEATURE_SUPPORT_ACTION_BAR}.</p> * * @param toolbar Toolbar to set as the Activity's action bar, or {@code null} to clear it */ public void setSupportActionBar(@Nullable Toolbar toolbar) { getDelegate().setSupportActionBar(toolbar); } @Override public MenuInflater getMenuInflater() { return getDelegate().getMenuInflater(); } @Override public void setContentView(@LayoutRes int layoutResID) { getDelegate().setContentView(layoutResID); } @Override public void setContentView(View view) { getDelegate().setContentView(view); } @Override public void setContentView(View view, ViewGroup.LayoutParams params) { getDelegate().setContentView(view, params); } @Override public void addContentView(View view, ViewGroup.LayoutParams params) { getDelegate().addContentView(view, params); } @Override public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); getDelegate().onConfigurationChanged(newConfig); if (mResources != null) { // The real (and thus managed) resources object was already updated // by ResourcesManager, so pull the current metrics from there. final DisplayMetrics newMetrics = super.getResources().getDisplayMetrics(); mResources.updateConfiguration(newConfig, newMetrics); } } @Override protected void onStop() { super.onStop(); getDelegate().onStop(); } @Override protected void onPostResume() { super.onPostResume(); getDelegate().onPostResume(); } public View findViewById(@IdRes int id) { return getDelegate().findViewById(id); } @Override public final boolean onMenuItemSelected(int featureId, android.view.MenuItem item) { if (super.onMenuItemSelected(featureId, item)) { return true; } final ActionBar ab = getSupportActionBar(); if (item.getItemId() == android.R.id.home && ab != null && (ab.getDisplayOptions() & ActionBar.DISPLAY_HOME_AS_UP) != 0) { return onSupportNavigateUp(); } return false; } @Override protected void onDestroy() { super.onDestroy(); getDelegate().onDestroy(); } @Override protected void onTitleChanged(CharSequence title, int color) { super.onTitleChanged(title, color); getDelegate().setTitle(title); } /** * Enable extended support library window features. * <p> * This is a convenience for calling * {@link android.view.Window#requestFeature getWindow().requestFeature()}. * </p> * * @param featureId The desired feature as defined in * {@link android.view.Window} or {@link android.support.v4.view.WindowCompat}. * @return Returns true if the requested feature is supported and now enabled. * * @see android.app.Activity#requestWindowFeature * @see android.view.Window#requestFeature */ public boolean supportRequestWindowFeature(int featureId) { return getDelegate().requestWindowFeature(featureId); } @Override public void supportInvalidateOptionsMenu() { getDelegate().invalidateOptionsMenu(); } /** * @hide */ public void invalidateOptionsMenu() { getDelegate().invalidateOptionsMenu(); } /** * Notifies the Activity that a support action mode has been started. * Activity subclasses overriding this method should call the superclass implementation. * * @param mode The new action mode. */ @CallSuper public void onSupportActionModeStarted(@NonNull ActionMode mode) { } /** * Notifies the activity that a support action mode has finished. * Activity subclasses overriding this method should call the superclass implementation. * * @param mode The action mode that just finished. */ @CallSuper public void onSupportActionModeFinished(@NonNull ActionMode mode) { } /** * Called when a support action mode is being started for this window. Gives the * callback an opportunity to handle the action mode in its own unique and * beautiful way. If this method returns null the system can choose a way * to present the mode or choose not to start the mode at all. * * @param callback Callback to control the lifecycle of this action mode * @return The ActionMode that was started, or null if the system should present it */ @Nullable @Override public ActionMode onWindowStartingSupportActionMode(@NonNull ActionMode.Callback callback) { return null; } /** * Start an action mode. * * @param callback Callback that will manage lifecycle events for this context mode * @return The ContextMode that was started, or null if it was canceled */ @Nullable public ActionMode startSupportActionMode(@NonNull ActionMode.Callback callback) { return getDelegate().startSupportActionMode(callback); } /** * @deprecated Progress bars are no longer provided in AppCompat. */ @Deprecated public void setSupportProgressBarVisibility(boolean visible) { } /** * @deprecated Progress bars are no longer provided in AppCompat. */ @Deprecated public void setSupportProgressBarIndeterminateVisibility(boolean visible) { } /** * @deprecated Progress bars are no longer provided in AppCompat. */ @Deprecated public void setSupportProgressBarIndeterminate(boolean indeterminate) { } /** * @deprecated Progress bars are no longer provided in AppCompat. */ @Deprecated public void setSupportProgress(int progress) { } /** * Support version of {@link #onCreateNavigateUpTaskStack(android.app.TaskStackBuilder)}. * This method will be called on all platform versions. * * Define the synthetic task stack that will be generated during Up navigation from * a different task. * * <p>The default implementation of this method adds the parent chain of this activity * as specified in the manifest to the supplied {@link android.support.v4.app.TaskStackBuilder}. Applications * may choose to override this method to construct the desired task stack in a different * way.</p> * * <p>This method will be invoked by the default implementation of {@link #onNavigateUp()} * if {@link #shouldUpRecreateTask(android.content.Intent)} returns true when supplied with the intent * returned by {@link #getParentActivityIntent()}.</p> * * <p>Applications that wish to supply extra Intent parameters to the parent stack defined * by the manifest should override * {@link #onPrepareSupportNavigateUpTaskStack(android.support.v4.app.TaskStackBuilder)}.</p> * * @param builder An empty TaskStackBuilder - the application should add intents representing * the desired task stack */ public void onCreateSupportNavigateUpTaskStack(@NonNull TaskStackBuilder builder) { builder.addParentStack(this); } /** * Support version of {@link #onPrepareNavigateUpTaskStack(android.app.TaskStackBuilder)}. * This method will be called on all platform versions. * * Prepare the synthetic task stack that will be generated during Up navigation * from a different task. * * <p>This method receives the {@link android.support.v4.app.TaskStackBuilder} with the constructed series of * Intents as generated by {@link #onCreateSupportNavigateUpTaskStack(android.support.v4.app.TaskStackBuilder)}. * If any extra data should be added to these intents before launching the new task, * the application should override this method and add that data here.</p> * * @param builder A TaskStackBuilder that has been populated with Intents by * onCreateNavigateUpTaskStack. */ public void onPrepareSupportNavigateUpTaskStack(@NonNull TaskStackBuilder builder) { } /** * This method is called whenever the user chooses to navigate Up within your application's * activity hierarchy from the action bar. * * <p>If a parent was specified in the manifest for this activity or an activity-alias to it, * default Up navigation will be handled automatically. See * {@link #getSupportParentActivityIntent()} for how to specify the parent. If any activity * along the parent chain requires extra Intent arguments, the Activity subclass * should override the method {@link #onPrepareSupportNavigateUpTaskStack(android.support.v4.app.TaskStackBuilder)} * to supply those arguments.</p> * * <p>See <a href="{@docRoot}guide/topics/fundamentals/tasks-and-back-stack.html">Tasks and * Back Stack</a> from the developer guide and * <a href="{@docRoot}design/patterns/navigation.html">Navigation</a> from the design guide * for more information about navigating within your app.</p> * * <p>See the {@link android.support.v4.app.TaskStackBuilder} class and the Activity methods * {@link #getSupportParentActivityIntent()}, {@link #supportShouldUpRecreateTask(android.content.Intent)}, and * {@link #supportNavigateUpTo(android.content.Intent)} for help implementing custom Up navigation.</p> * * @return true if Up navigation completed successfully and this Activity was finished, * false otherwise. */ public boolean onSupportNavigateUp() { Intent upIntent = getSupportParentActivityIntent(); if (upIntent != null) { if (supportShouldUpRecreateTask(upIntent)) { TaskStackBuilder b = TaskStackBuilder.create(this); onCreateSupportNavigateUpTaskStack(b); onPrepareSupportNavigateUpTaskStack(b); b.startActivities(); try { ActivityCompat.finishAffinity(this); } catch (IllegalStateException e) { // This can only happen on 4.1+, when we don't have a parent or a result set. // In that case we should just finish(). finish(); } } else { // This activity is part of the application's task, so simply // navigate up to the hierarchical parent activity. supportNavigateUpTo(upIntent); } return true; } return false; } /** * Obtain an {@link android.content.Intent} that will launch an explicit target activity * specified by sourceActivity's {@link android.support.v4.app.NavUtils#PARENT_ACTIVITY} &lt;meta-data&gt; * element in the application's manifest. If the device is running * Jellybean or newer, the android:parentActivityName attribute will be preferred * if it is present. * * @return a new Intent targeting the defined parent activity of sourceActivity */ @Nullable public Intent getSupportParentActivityIntent() { return NavUtils.getParentActivityIntent(this); } /** * Returns true if sourceActivity should recreate the task when navigating 'up' * by using targetIntent. * * <p>If this method returns false the app can trivially call * {@link #supportNavigateUpTo(android.content.Intent)} using the same parameters to correctly perform * up navigation. If this method returns false, the app should synthesize a new task stack * by using {@link android.support.v4.app.TaskStackBuilder} or another similar mechanism to perform up navigation.</p> * * @param targetIntent An intent representing the target destination for up navigation * @return true if navigating up should recreate a new task stack, false if the same task * should be used for the destination */ public boolean supportShouldUpRecreateTask(@NonNull Intent targetIntent) { return NavUtils.shouldUpRecreateTask(this, targetIntent); } /** * Navigate from sourceActivity to the activity specified by upIntent, finishing sourceActivity * in the process. upIntent will have the flag {@link android.content.Intent#FLAG_ACTIVITY_CLEAR_TOP} set * by this method, along with any others required for proper up navigation as outlined * in the Android Design Guide. * * <p>This method should be used when performing up navigation from within the same task * as the destination. If up navigation should cross tasks in some cases, see * {@link #supportShouldUpRecreateTask(android.content.Intent)}.</p> * * @param upIntent An intent representing the target destination for up navigation */ public void supportNavigateUpTo(@NonNull Intent upIntent) { NavUtils.navigateUpTo(this, upIntent); } @Override public void onContentChanged() { // Call onSupportContentChanged() for legacy reasons onSupportContentChanged(); } /** * @deprecated Use {@link #onContentChanged()} instead. */ @Deprecated public void onSupportContentChanged() { } @Nullable @Override public ActionBarDrawerToggle.Delegate getDrawerToggleDelegate() { return getDelegate().getDrawerToggleDelegate(); } /** * {@inheritDoc} * * <p>Please note: AppCompat uses it's own feature id for the action bar: * {@link AppCompatDelegate#FEATURE_SUPPORT_ACTION_BAR FEATURE_SUPPORT_ACTION_BAR}.</p> */ @Override public boolean onMenuOpened(int featureId, Menu menu) { return super.onMenuOpened(featureId, menu); } /** * {@inheritDoc} * * <p>Please note: AppCompat uses it's own feature id for the action bar: * {@link AppCompatDelegate#FEATURE_SUPPORT_ACTION_BAR FEATURE_SUPPORT_ACTION_BAR}.</p> */ @Override public void onPanelClosed(int featureId, Menu menu) { super.onPanelClosed(featureId, menu); } @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); getDelegate().onSaveInstanceState(outState); } /** * @return The {@link AppCompatDelegate} being used by this Activity. */ @NonNull public AppCompatDelegate getDelegate() { if (mDelegate == null) { mDelegate = AppCompatDelegate.create(this, this); } return mDelegate; } @Override public boolean dispatchKeyEvent(KeyEvent event) { if (KeyEventCompat.isCtrlPressed(event) && event.getUnicodeChar(event.getMetaState() & ~KeyEvent.META_CTRL_MASK) == '<') { // Capture the Control-< and send focus to the ActionBar final int action = event.getAction(); if (action == KeyEvent.ACTION_DOWN) { final ActionBar actionBar = getSupportActionBar(); if (actionBar != null && actionBar.isShowing() && actionBar.requestFocus()) { mEatKeyUpEvent = true; return true; } } else if (action == KeyEvent.ACTION_UP && mEatKeyUpEvent) { mEatKeyUpEvent = false; return true; } } return super.dispatchKeyEvent(event); } @Override public Resources getResources() { if (mResources == null) { mResources = new TintResources(this, super.getResources()); } return mResources; } }
v7/appcompat/src/android/support/v7/app/AppCompatActivity.java
/* * Copyright (C) 2015 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package android.support.v7.app; import android.content.Intent; import android.content.res.Configuration; import android.content.res.Resources; import android.os.Build; import android.os.Bundle; import android.support.annotation.CallSuper; import android.support.annotation.IdRes; import android.support.annotation.LayoutRes; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.annotation.StyleRes; import android.support.v4.app.ActivityCompat; import android.support.v4.app.FragmentActivity; import android.support.v4.app.NavUtils; import android.support.v4.app.TaskStackBuilder; import android.support.v4.view.KeyEventCompat; import android.support.v7.view.ActionMode; import android.support.v7.widget.TintResources; import android.support.v7.widget.Toolbar; import android.util.DisplayMetrics; import android.view.KeyEvent; import android.view.Menu; import android.view.MenuInflater; import android.view.View; import android.view.ViewGroup; /** * Base class for activities that use the * <a href="{@docRoot}tools/extras/support-library.html">support library</a> action bar features. * * <p>You can add an {@link android.support.v7.app.ActionBar} to your activity when running on API level 7 or higher * by extending this class for your activity and setting the activity theme to * {@link android.support.v7.appcompat.R.style#Theme_AppCompat Theme.AppCompat} or a similar theme. * * <div class="special reference"> * <h3>Developer Guides</h3> * * <p>For information about how to use the action bar, including how to add action items, navigation * modes and more, read the <a href="{@docRoot}guide/topics/ui/actionbar.html">Action * Bar</a> API guide.</p> * </div> */ public class AppCompatActivity extends FragmentActivity implements AppCompatCallback, TaskStackBuilder.SupportParentable, ActionBarDrawerToggle.DelegateProvider { private AppCompatDelegate mDelegate; private int mThemeId = 0; private boolean mEatKeyUpEvent; private Resources mResources; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { final AppCompatDelegate delegate = getDelegate(); delegate.installViewFactory(); delegate.onCreate(savedInstanceState); if (delegate.applyDayNight() && mThemeId != 0) { // If DayNight has been applied, we need to re-apply the theme for // the changes to take effect. On API 23+, we should bypass // setTheme(), which will no-op if the theme ID is identical to the // current theme ID. if (Build.VERSION.SDK_INT >= 23) { onApplyThemeResource(getTheme(), mThemeId, false); } else { setTheme(mThemeId); } } super.onCreate(savedInstanceState); } @Override public void setTheme(@StyleRes final int resid) { super.setTheme(resid); // Keep hold of the theme id so that we can re-set it later if needed mThemeId = resid; } @Override protected void onPostCreate(@Nullable Bundle savedInstanceState) { super.onPostCreate(savedInstanceState); getDelegate().onPostCreate(savedInstanceState); } /** * Support library version of {@link android.app.Activity#getActionBar}. * * <p>Retrieve a reference to this activity's ActionBar. * * @return The Activity's ActionBar, or null if it does not have one. */ @Nullable public ActionBar getSupportActionBar() { return getDelegate().getSupportActionBar(); } /** * Set a {@link android.widget.Toolbar Toolbar} to act as the * {@link android.support.v7.app.ActionBar} for this Activity window. * * <p>When set to a non-null value the {@link #getActionBar()} method will return * an {@link android.support.v7.app.ActionBar} object that can be used to control the given * toolbar as if it were a traditional window decor action bar. The toolbar's menu will be * populated with the Activity's options menu and the navigation button will be wired through * the standard {@link android.R.id#home home} menu select action.</p> * * <p>In order to use a Toolbar within the Activity's window content the application * must not request the window feature * {@link android.view.Window#FEATURE_ACTION_BAR FEATURE_SUPPORT_ACTION_BAR}.</p> * * @param toolbar Toolbar to set as the Activity's action bar, or {@code null} to clear it */ public void setSupportActionBar(@Nullable Toolbar toolbar) { getDelegate().setSupportActionBar(toolbar); } @Override public MenuInflater getMenuInflater() { return getDelegate().getMenuInflater(); } @Override public void setContentView(@LayoutRes int layoutResID) { getDelegate().setContentView(layoutResID); } @Override public void setContentView(View view) { getDelegate().setContentView(view); } @Override public void setContentView(View view, ViewGroup.LayoutParams params) { getDelegate().setContentView(view, params); } @Override public void addContentView(View view, ViewGroup.LayoutParams params) { getDelegate().addContentView(view, params); } @Override public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); getDelegate().onConfigurationChanged(newConfig); if (mResources != null) { // The real (and thus managed) resources object was already updated // by ResourcesManager, so pull the current metrics from there. final DisplayMetrics newMetrics = super.getResources().getDisplayMetrics(); mResources.updateConfiguration(newConfig, newMetrics); } } @Override protected void onStop() { super.onStop(); getDelegate().onStop(); } @Override protected void onPostResume() { super.onPostResume(); getDelegate().onPostResume(); } @Nullable public View findViewById(@IdRes int id) { return getDelegate().findViewById(id); } @Override public final boolean onMenuItemSelected(int featureId, android.view.MenuItem item) { if (super.onMenuItemSelected(featureId, item)) { return true; } final ActionBar ab = getSupportActionBar(); if (item.getItemId() == android.R.id.home && ab != null && (ab.getDisplayOptions() & ActionBar.DISPLAY_HOME_AS_UP) != 0) { return onSupportNavigateUp(); } return false; } @Override protected void onDestroy() { super.onDestroy(); getDelegate().onDestroy(); } @Override protected void onTitleChanged(CharSequence title, int color) { super.onTitleChanged(title, color); getDelegate().setTitle(title); } /** * Enable extended support library window features. * <p> * This is a convenience for calling * {@link android.view.Window#requestFeature getWindow().requestFeature()}. * </p> * * @param featureId The desired feature as defined in * {@link android.view.Window} or {@link android.support.v4.view.WindowCompat}. * @return Returns true if the requested feature is supported and now enabled. * * @see android.app.Activity#requestWindowFeature * @see android.view.Window#requestFeature */ public boolean supportRequestWindowFeature(int featureId) { return getDelegate().requestWindowFeature(featureId); } @Override public void supportInvalidateOptionsMenu() { getDelegate().invalidateOptionsMenu(); } /** * @hide */ public void invalidateOptionsMenu() { getDelegate().invalidateOptionsMenu(); } /** * Notifies the Activity that a support action mode has been started. * Activity subclasses overriding this method should call the superclass implementation. * * @param mode The new action mode. */ @CallSuper public void onSupportActionModeStarted(@NonNull ActionMode mode) { } /** * Notifies the activity that a support action mode has finished. * Activity subclasses overriding this method should call the superclass implementation. * * @param mode The action mode that just finished. */ @CallSuper public void onSupportActionModeFinished(@NonNull ActionMode mode) { } /** * Called when a support action mode is being started for this window. Gives the * callback an opportunity to handle the action mode in its own unique and * beautiful way. If this method returns null the system can choose a way * to present the mode or choose not to start the mode at all. * * @param callback Callback to control the lifecycle of this action mode * @return The ActionMode that was started, or null if the system should present it */ @Nullable @Override public ActionMode onWindowStartingSupportActionMode(@NonNull ActionMode.Callback callback) { return null; } /** * Start an action mode. * * @param callback Callback that will manage lifecycle events for this context mode * @return The ContextMode that was started, or null if it was canceled */ @Nullable public ActionMode startSupportActionMode(@NonNull ActionMode.Callback callback) { return getDelegate().startSupportActionMode(callback); } /** * @deprecated Progress bars are no longer provided in AppCompat. */ @Deprecated public void setSupportProgressBarVisibility(boolean visible) { } /** * @deprecated Progress bars are no longer provided in AppCompat. */ @Deprecated public void setSupportProgressBarIndeterminateVisibility(boolean visible) { } /** * @deprecated Progress bars are no longer provided in AppCompat. */ @Deprecated public void setSupportProgressBarIndeterminate(boolean indeterminate) { } /** * @deprecated Progress bars are no longer provided in AppCompat. */ @Deprecated public void setSupportProgress(int progress) { } /** * Support version of {@link #onCreateNavigateUpTaskStack(android.app.TaskStackBuilder)}. * This method will be called on all platform versions. * * Define the synthetic task stack that will be generated during Up navigation from * a different task. * * <p>The default implementation of this method adds the parent chain of this activity * as specified in the manifest to the supplied {@link android.support.v4.app.TaskStackBuilder}. Applications * may choose to override this method to construct the desired task stack in a different * way.</p> * * <p>This method will be invoked by the default implementation of {@link #onNavigateUp()} * if {@link #shouldUpRecreateTask(android.content.Intent)} returns true when supplied with the intent * returned by {@link #getParentActivityIntent()}.</p> * * <p>Applications that wish to supply extra Intent parameters to the parent stack defined * by the manifest should override * {@link #onPrepareSupportNavigateUpTaskStack(android.support.v4.app.TaskStackBuilder)}.</p> * * @param builder An empty TaskStackBuilder - the application should add intents representing * the desired task stack */ public void onCreateSupportNavigateUpTaskStack(@NonNull TaskStackBuilder builder) { builder.addParentStack(this); } /** * Support version of {@link #onPrepareNavigateUpTaskStack(android.app.TaskStackBuilder)}. * This method will be called on all platform versions. * * Prepare the synthetic task stack that will be generated during Up navigation * from a different task. * * <p>This method receives the {@link android.support.v4.app.TaskStackBuilder} with the constructed series of * Intents as generated by {@link #onCreateSupportNavigateUpTaskStack(android.support.v4.app.TaskStackBuilder)}. * If any extra data should be added to these intents before launching the new task, * the application should override this method and add that data here.</p> * * @param builder A TaskStackBuilder that has been populated with Intents by * onCreateNavigateUpTaskStack. */ public void onPrepareSupportNavigateUpTaskStack(@NonNull TaskStackBuilder builder) { } /** * This method is called whenever the user chooses to navigate Up within your application's * activity hierarchy from the action bar. * * <p>If a parent was specified in the manifest for this activity or an activity-alias to it, * default Up navigation will be handled automatically. See * {@link #getSupportParentActivityIntent()} for how to specify the parent. If any activity * along the parent chain requires extra Intent arguments, the Activity subclass * should override the method {@link #onPrepareSupportNavigateUpTaskStack(android.support.v4.app.TaskStackBuilder)} * to supply those arguments.</p> * * <p>See <a href="{@docRoot}guide/topics/fundamentals/tasks-and-back-stack.html">Tasks and * Back Stack</a> from the developer guide and * <a href="{@docRoot}design/patterns/navigation.html">Navigation</a> from the design guide * for more information about navigating within your app.</p> * * <p>See the {@link android.support.v4.app.TaskStackBuilder} class and the Activity methods * {@link #getSupportParentActivityIntent()}, {@link #supportShouldUpRecreateTask(android.content.Intent)}, and * {@link #supportNavigateUpTo(android.content.Intent)} for help implementing custom Up navigation.</p> * * @return true if Up navigation completed successfully and this Activity was finished, * false otherwise. */ public boolean onSupportNavigateUp() { Intent upIntent = getSupportParentActivityIntent(); if (upIntent != null) { if (supportShouldUpRecreateTask(upIntent)) { TaskStackBuilder b = TaskStackBuilder.create(this); onCreateSupportNavigateUpTaskStack(b); onPrepareSupportNavigateUpTaskStack(b); b.startActivities(); try { ActivityCompat.finishAffinity(this); } catch (IllegalStateException e) { // This can only happen on 4.1+, when we don't have a parent or a result set. // In that case we should just finish(). finish(); } } else { // This activity is part of the application's task, so simply // navigate up to the hierarchical parent activity. supportNavigateUpTo(upIntent); } return true; } return false; } /** * Obtain an {@link android.content.Intent} that will launch an explicit target activity * specified by sourceActivity's {@link android.support.v4.app.NavUtils#PARENT_ACTIVITY} &lt;meta-data&gt; * element in the application's manifest. If the device is running * Jellybean or newer, the android:parentActivityName attribute will be preferred * if it is present. * * @return a new Intent targeting the defined parent activity of sourceActivity */ @Nullable public Intent getSupportParentActivityIntent() { return NavUtils.getParentActivityIntent(this); } /** * Returns true if sourceActivity should recreate the task when navigating 'up' * by using targetIntent. * * <p>If this method returns false the app can trivially call * {@link #supportNavigateUpTo(android.content.Intent)} using the same parameters to correctly perform * up navigation. If this method returns false, the app should synthesize a new task stack * by using {@link android.support.v4.app.TaskStackBuilder} or another similar mechanism to perform up navigation.</p> * * @param targetIntent An intent representing the target destination for up navigation * @return true if navigating up should recreate a new task stack, false if the same task * should be used for the destination */ public boolean supportShouldUpRecreateTask(@NonNull Intent targetIntent) { return NavUtils.shouldUpRecreateTask(this, targetIntent); } /** * Navigate from sourceActivity to the activity specified by upIntent, finishing sourceActivity * in the process. upIntent will have the flag {@link android.content.Intent#FLAG_ACTIVITY_CLEAR_TOP} set * by this method, along with any others required for proper up navigation as outlined * in the Android Design Guide. * * <p>This method should be used when performing up navigation from within the same task * as the destination. If up navigation should cross tasks in some cases, see * {@link #supportShouldUpRecreateTask(android.content.Intent)}.</p> * * @param upIntent An intent representing the target destination for up navigation */ public void supportNavigateUpTo(@NonNull Intent upIntent) { NavUtils.navigateUpTo(this, upIntent); } @Override public void onContentChanged() { // Call onSupportContentChanged() for legacy reasons onSupportContentChanged(); } /** * @deprecated Use {@link #onContentChanged()} instead. */ @Deprecated public void onSupportContentChanged() { } @Nullable @Override public ActionBarDrawerToggle.Delegate getDrawerToggleDelegate() { return getDelegate().getDrawerToggleDelegate(); } /** * {@inheritDoc} * * <p>Please note: AppCompat uses it's own feature id for the action bar: * {@link AppCompatDelegate#FEATURE_SUPPORT_ACTION_BAR FEATURE_SUPPORT_ACTION_BAR}.</p> */ @Override public boolean onMenuOpened(int featureId, Menu menu) { return super.onMenuOpened(featureId, menu); } /** * {@inheritDoc} * * <p>Please note: AppCompat uses it's own feature id for the action bar: * {@link AppCompatDelegate#FEATURE_SUPPORT_ACTION_BAR FEATURE_SUPPORT_ACTION_BAR}.</p> */ @Override public void onPanelClosed(int featureId, Menu menu) { super.onPanelClosed(featureId, menu); } @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); getDelegate().onSaveInstanceState(outState); } /** * @return The {@link AppCompatDelegate} being used by this Activity. */ @NonNull public AppCompatDelegate getDelegate() { if (mDelegate == null) { mDelegate = AppCompatDelegate.create(this, this); } return mDelegate; } @Override public boolean dispatchKeyEvent(KeyEvent event) { if (KeyEventCompat.isCtrlPressed(event) && event.getUnicodeChar(event.getMetaState() & ~KeyEvent.META_CTRL_MASK) == '<') { // Capture the Control-< and send focus to the ActionBar final int action = event.getAction(); if (action == KeyEvent.ACTION_DOWN) { final ActionBar actionBar = getSupportActionBar(); if (actionBar != null && actionBar.isShowing() && actionBar.requestFocus()) { mEatKeyUpEvent = true; return true; } } else if (action == KeyEvent.ACTION_UP && mEatKeyUpEvent) { mEatKeyUpEvent = false; return true; } } return super.dispatchKeyEvent(event); } @Override public Resources getResources() { if (mResources == null) { mResources = new TintResources(this, super.getResources()); } return mResources; } }
Remove @Nullable from AppCompatActivity#findViewById In practice if this really returns null then the developer messed up earlier. It's not reasonable to expect developers to null check findViewById, so make their linters happy by removing the annotation. Bug 27759646 Change-Id: I1ef0f1b91280b8b5836d30e36ef96fb5f2bcd3f3
v7/appcompat/src/android/support/v7/app/AppCompatActivity.java
Remove @Nullable from AppCompatActivity#findViewById
<ide><path>7/appcompat/src/android/support/v7/app/AppCompatActivity.java <ide> getDelegate().onPostResume(); <ide> } <ide> <del> @Nullable <ide> public View findViewById(@IdRes int id) { <ide> return getDelegate().findViewById(id); <ide> }
Java
mit
error: pathspec 'Easy/BestTimetoBuyandSellStock1.java' did not match any file(s) known to git
8917ced242e9c90379af9e1f4ab2f0e3ebd978a8
1
FreeTymeKiyan/LeetCode-Sol-Res,FreeTymeKiyan/LeetCode-Sol-Res,bssrdf/LeetCode-Sol-Res,bssrdf/LeetCode-Sol-Res
/** * Best Time to Buy and Sell Stock * Say you have an array for which the ith element is the price of a given stock on day i. * If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit. * Tags: Array Dynamic Programming * Similar Problems: (M) Maximum Subarray (M) Best Time to Buy and Sell Stock II (H) Best Time to Buy and Sell Stock III (H) Best Time to Buy and Sell Stock IV (M) Best Time to Buy and Sell Stock with Cooldown * O(n) time, O(1) space * @author chenshuna */ public class BestTimetoBuyandSellStock { public static int maxProfit(int[] prices) { if(prices == null || prices.length == 0 || prices.length == 1){ return 0; } int max = 0; int minPrice = prices[0]; for(int i = 0; i < prices.length; i++){ minPrice = Math.min(minPrice, prices[i]); max = Math.max(max, prices[i] - minPrice); } return max; } public static void main(String arg[]){ int[] prices = {2, 5, 8, 9, 1, 6}; System.out.print(maxProfit(prices)); } }
Easy/BestTimetoBuyandSellStock1.java
finished 121
Easy/BestTimetoBuyandSellStock1.java
finished 121
<ide><path>asy/BestTimetoBuyandSellStock1.java <add>/** <add> * Best Time to Buy and Sell Stock <add> * Say you have an array for which the ith element is the price of a given stock on day i. <add> * If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit. <add> * Tags: Array Dynamic Programming <add> * Similar Problems: (M) Maximum Subarray (M) Best Time to Buy and Sell Stock II (H) Best Time to Buy and Sell Stock III (H) Best Time to Buy and Sell Stock IV (M) Best Time to Buy and Sell Stock with Cooldown <add> * O(n) time, O(1) space <add> * @author chenshuna <add> */ <add> <add>public class BestTimetoBuyandSellStock { <add> public static int maxProfit(int[] prices) { <add> if(prices == null || prices.length == 0 || prices.length == 1){ <add> return 0; <add> } <add> int max = 0; <add> int minPrice = prices[0]; <add> for(int i = 0; i < prices.length; i++){ <add> minPrice = Math.min(minPrice, prices[i]); <add> max = Math.max(max, prices[i] - minPrice); <add> } <add> return max; <add> } <add> <add> public static void main(String arg[]){ <add> int[] prices = {2, 5, 8, 9, 1, 6}; <add> System.out.print(maxProfit(prices)); <add> } <add>}
Java
mit
5e4429bc172f9f6f27fff97773f29467d58b64a6
0
Pumahawk/AutomiAPI
package lexer; import java.io.BufferedReader; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import it.gandinolorenzo.lft.Automa; import it.gandinolorenzo.lft.Stato; public class UniLexer extends Lexer { private Map<String, Word> keyWords = new HashMap<>(); private String contenitoreNumero = ""; private String contenitoreIdentificatore = ""; private void keyToAutoma(Stato q, String key, Object endSeparator, Token t) { if(key == "") return; char c; Stato next, first = q; for(int i = 0; i < key.length(); i++) { c = key.charAt(i); next = new Stato(); q.addTransizione(c, next); q = next; } q.addTransizione(endSeparator, first, (cc) -> this.alertToken(t, (char)cc)); } private Automa generateAutoma() { Stato q0 = new Stato("q0"); Stato q1 = new Stato("q1"); Stato q2 = new Stato("q2: Inizio riconoscimento numero"); Stato qDiv = new Stato("q2: Inizio riconoscimento diviso"); q0.addTransizione(Pattern.SEPARATOR, q0); // Riconoscimento EOF q0.addTransizione((char) -1, q0, (c) -> this.alertToken(new Token(Tag.EOF))); // Riconoscimento ! not q0.addTransizione('!', q0, (c) -> this.alertToken(Token.not)); // Riconoscimento ( not q0.addTransizione('(', q0, (c) -> this.alertToken(Token.lpt)); // Riconoscimento ) not q0.addTransizione(')', q0, (c) -> this.alertToken(Token.rpt)); // Riconoscimento + not q0.addTransizione('+', q0, (c) -> this.alertToken(Token.plus)); // Riconoscimento - not q0.addTransizione('-', q0, (c) -> this.alertToken(Token.minus)); // Riconoscimento * not q0.addTransizione('*', q0, (c) -> this.alertToken(Token.mult)); // Riconoscimento / not q0.addTransizione('/', qDiv); qDiv.addTransizione(Pattern.NOT_MULT_DIV, q0, (c) -> this.alertToken(Token.div, (char) c)); //Riconoscimento commento su riga { Stato qCom = new Stato(); qDiv.addTransizione('/', qCom); qCom.addTransizione(Pattern.NOT_NEW_LINE, qCom); qCom.addTransizione('\n', q0); qCom.addTransizione((char) -1, q0, (c) -> this.alertToken(new Token(Tag.EOF))); } // Riconoscimento ; not q0.addTransizione(';', q0, (c) -> this.alertToken(Token.semicolon)); // Riconoscimento && end { Stato andS = new Stato(); q0.addTransizione('&', andS); andS.addTransizione('&', q0, (c) -> this.alertToken(Word.and)); } // Riconoscimento || { Stato orS = new Stato(); q0.addTransizione('|', orS); orS.addTransizione('|', q0, (c) -> this.alertToken(Word.or)); } // Riconoscimento <, <>, <= { Stato notEq = new Stato(); q0.addTransizione('<', notEq); notEq.addTransizione(Pattern.NOT_MAX_EQ, q0, (c) -> this.alertToken(Word.minus, (char)c)); notEq.addTransizione('>', q0, (c) -> this.alertToken(Word.ne)); notEq.addTransizione('=', q0, (c) -> this.alertToken(Word.le)); } // Riconoscimento =, == { Stato eqS = new Stato(); q0.addTransizione('=', eqS); eqS.addTransizione(Pattern.NOT_EQ, q0, (c) -> this.alertToken(Word.assign, (char)c)); eqS.addTransizione('=', q0, (c) -> this.alertToken(Word.eq)); } // Riconoscimento >, >= { Stato maxS = new Stato(); q0.addTransizione('>', maxS); maxS.addTransizione(Pattern.NOT_EQ, q0, (c) -> this.alertToken(Word.gt, (char)c)); maxS.addTransizione('=', q0, (c) -> this.alertToken(Word.ge)); } // Riconoscimento parole chiave keyWords.put("if", Word.iftok); keyWords.put("then", Word.then); keyWords.put("else", Word.elsetok); keyWords.put("for", Word.fortok); keyWords.put("do", Word.dotok); keyWords.put("print", Word.print); keyWords.put("read", Word.read); keyWords.put("begin", Word.begin); keyWords.put("end", Word.end); /* * * Parte sostitita dalla lista contente tutte le parole chiavi * * keyToAutoma(q0, "if", Pattern.SEPARATOR, Word.iftok); keyToAutoma(q0, "then", Pattern.SEPARATOR, Word.then); keyToAutoma(q0, "else", Pattern.SEPARATOR, Word.elsetok); keyToAutoma(q0, "for", Pattern.SEPARATOR, Word.fortok); keyToAutoma(q0, "do", Pattern.SEPARATOR, Word.dotok); keyToAutoma(q0, "print", Pattern.SEPARATOR, Word.print); keyToAutoma(q0, "read", Pattern.SEPARATOR, Word.read); keyToAutoma(q0, "begin", Pattern.SEPARATOR, Word.begin); keyToAutoma(q0, "end", Pattern.SEPARATOR, Word.end); keyToAutoma(q0, "<", Pattern.SEPARATOR, Word.lt); keyToAutoma(q0, ">", Pattern.SEPARATOR, Word.gt); keyToAutoma(q0, "=", Pattern.NOT_EQ, Word.assign); keyToAutoma(q0, "==", Pattern.SEPARATOR, Word.eq); keyToAutoma(q0, "<=", Pattern.SEPARATOR, Word.le); keyToAutoma(q0, "<>", Pattern.SEPARATOR, Word.ne); keyToAutoma(q0, ">=", Pattern.SEPARATOR, Word.ge); */ // Fine iconoscimento parole chiave //Riconoscimento numero q0.addTransizione(Pattern.NUMBER, q2, (c) -> contenitoreNumero += c); q2.addTransizione(Pattern.NUMBER, q2, (c) -> contenitoreNumero += c); q2.addTransizione(Pattern.NOT_NUMBER, q0, (c) -> { this.alertToken(new NumberTok(Integer.parseInt(contenitoreNumero)), (char) c); contenitoreNumero = ""; }); //Fine riconoscimento numero //Riconoscimento identificatore. Stato rId0 = new Stato("rId0"); Stato rId1 = new Stato("rId1"); q0.addTransizione(Pattern.LETTER, rId1, (c) -> contenitoreIdentificatore += c); q0.addTransizione('_', rId0, (c) -> contenitoreIdentificatore += c); rId0.addTransizione('_', rId0, (c) -> contenitoreIdentificatore += c); rId0.addTransizione(Pattern.LETTER, rId1, (c) -> contenitoreIdentificatore += c); rId0.addTransizione(Pattern.NUMBER, rId1, (c) -> contenitoreIdentificatore += c); rId1.addTransizione('_', rId1, (c) -> contenitoreIdentificatore += c); rId1.addTransizione(Pattern.NUMBER, rId1, (c) -> contenitoreIdentificatore += c); rId1.addTransizione(Pattern.LETTER, rId1, (c) -> contenitoreIdentificatore += c); rId1.addTransizione(Pattern.NON_IDENTIFICATORE, q0, (c) -> { if(keyWords.containsKey(contenitoreIdentificatore)) this.alertToken(keyWords.get(contenitoreIdentificatore)); else this.alertToken(new Word(Tag.ID, contenitoreIdentificatore)); addBuffer((char)c); contenitoreIdentificatore = ""; }); //Fine riconoscimento identificatore //Inizio riconoscimento commento Stato c1 = new Stato(); Stato c2 = new Stato(); Stato c3 = new Stato(); q0.addTransizione('/', c1); c1.addTransizione('*', c2); c2.addTransizione(Pattern.NOT_COM_PAT, c2); c2.addTransizione('/', c2); c2.addTransizione('*', c3); c3.addTransizione(Pattern.NOT_COM_PAT, c2); c3.addTransizione('/', q0); c3.addTransizione('*', c3); //Fine riconoscimento commento List<Stato> finali = new LinkedList<>(); finali.add(q0); Automa automa = new Automa(q0, finali); return automa; } public UniLexer(BufferedReader br) { super(null, br); Automa a = generateAutoma(); this.automa = a; this.stati.add(a.iniziale); } }
src/lexer/UniLexer.java
package lexer; import java.io.BufferedReader; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import it.gandinolorenzo.lft.Automa; import it.gandinolorenzo.lft.Stato; public class UniLexer extends Lexer { private Map<String, Word> keyWords = new HashMap<>(); private String contenitoreNumero = ""; private String contenitoreIdentificatore = ""; private void keyToAutoma(Stato q, String key, Object endSeparator, Token t) { if(key == "") return; char c; Stato next, first = q; for(int i = 0; i < key.length(); i++) { c = key.charAt(i); next = new Stato(); q.addTransizione(c, next); q = next; } q.addTransizione(endSeparator, first, (cc) -> this.alertToken(t, (char)cc)); } private Automa generateAutoma() { Stato q0 = new Stato("q0"); Stato q1 = new Stato("q1"); Stato q2 = new Stato("q2: Inizio riconoscimento numero"); Stato qDiv = new Stato("q2: Inizio riconoscimento diviso"); q0.addTransizione(Pattern.SEPARATOR, q0); // Riconoscimento EOF q0.addTransizione((char) -1, q0, (c) -> this.alertToken(new Token(Tag.EOF))); // Riconoscimento ! not q0.addTransizione('!', q0, (c) -> this.alertToken(Token.not)); // Riconoscimento ( not q0.addTransizione('(', q0, (c) -> this.alertToken(Token.lpt)); // Riconoscimento ) not q0.addTransizione(')', q0, (c) -> this.alertToken(Token.rpt)); // Riconoscimento + not q0.addTransizione('+', q0, (c) -> this.alertToken(Token.plus)); // Riconoscimento - not q0.addTransizione('-', q0, (c) -> this.alertToken(Token.minus)); // Riconoscimento * not q0.addTransizione('*', q0, (c) -> this.alertToken(Token.mult)); // Riconoscimento / not q0.addTransizione('/', qDiv); qDiv.addTransizione(Pattern.NOT_MULT_DIV, q0, (c) -> this.alertToken(Token.div, (char) c)); //Riconoscimento commento su riga { Stato qCom = new Stato(); qDiv.addTransizione('/', qCom); qCom.addTransizione(Pattern.NOT_NEW_LINE, qCom); qCom.addTransizione('\n', q0); qCom.addTransizione((char) -1, q0, (c) -> this.alertToken(new Token(Tag.EOF))); } // Riconoscimento ; not q0.addTransizione(';', q0, (c) -> this.alertToken(Token.semicolon)); // Riconoscimento && end { Stato andS = new Stato(); q0.addTransizione('&', andS); andS.addTransizione('&', q0, (c) -> this.alertToken(Word.and)); } // Riconoscimento || { Stato orS = new Stato(); q0.addTransizione('|', orS); orS.addTransizione('|', q0, (c) -> this.alertToken(Word.or)); } // Riconoscimento <, <>, <= { Stato notEq = new Stato(); q0.addTransizione('<', notEq); notEq.addTransizione(Pattern.NOT_MAX_EQ, q0, (c) -> this.alertToken(Word.minus, (char)c)); notEq.addTransizione('>', q0, (c) -> this.alertToken(Word.ne)); notEq.addTransizione('=', q0, (c) -> this.alertToken(Word.le)); } // Riconoscimento =, == { Stato eqS = new Stato(); q0.addTransizione('=', eqS); eqS.addTransizione(Pattern.NOT_EQ, q0, (c) -> this.alertToken(Word.assign, (char)c)); eqS.addTransizione('=', q0, (c) -> this.alertToken(Word.eq)); } // Riconoscimento >, >= { Stato maxS = new Stato(); q0.addTransizione('>', maxS); maxS.addTransizione(Pattern.NOT_EQ, q0, (c) -> this.alertToken(Word.gt, (char)c)); maxS.addTransizione('=', q0, (c) -> this.alertToken(Word.ge)); } // Riconoscimento parole chiave keyWords.put("if", Word.iftok); keyWords.put("then", Word.then); keyWords.put("else", Word.elsetok); keyWords.put("for", Word.fortok); keyWords.put("do", Word.dotok); keyWords.put("print", Word.print); keyWords.put("read", Word.read); keyWords.put("begin", Word.begin); keyWords.put("end", Word.end); /* * * Parte sostitita dalla lista contente tutte le parole chiavi * * keyToAutoma(q0, "if", Pattern.SEPARATOR, Word.iftok); keyToAutoma(q0, "then", Pattern.SEPARATOR, Word.then); keyToAutoma(q0, "else", Pattern.SEPARATOR, Word.elsetok); keyToAutoma(q0, "for", Pattern.SEPARATOR, Word.fortok); keyToAutoma(q0, "do", Pattern.SEPARATOR, Word.dotok); keyToAutoma(q0, "print", Pattern.SEPARATOR, Word.print); keyToAutoma(q0, "read", Pattern.SEPARATOR, Word.read); keyToAutoma(q0, "begin", Pattern.SEPARATOR, Word.begin); keyToAutoma(q0, "end", Pattern.SEPARATOR, Word.end); keyToAutoma(q0, "<", Pattern.SEPARATOR, Word.lt); keyToAutoma(q0, ">", Pattern.SEPARATOR, Word.gt); keyToAutoma(q0, "=", Pattern.NOT_EQ, Word.assign); keyToAutoma(q0, "==", Pattern.SEPARATOR, Word.eq); keyToAutoma(q0, "<=", Pattern.SEPARATOR, Word.le); keyToAutoma(q0, "<>", Pattern.SEPARATOR, Word.ne); keyToAutoma(q0, ">=", Pattern.SEPARATOR, Word.ge); */ // Fine iconoscimento parole chiave //Riconoscimento numero q0.addTransizione(Pattern.NUMBER, q2, (c) -> contenitoreNumero += c); q2.addTransizione(Pattern.NUMBER, q2, (c) -> contenitoreNumero += c); q2.addTransizione(Pattern.NOT_NUMBER, q0, (c) -> { this.alertToken(new NumberTok(Integer.parseInt(contenitoreNumero)), (char) c); contenitoreNumero = ""; }); //Fine riconoscimento numero //Riconoscimento identificatore. Stato rId0 = new Stato("rId0"); Stato rId1 = new Stato("rId1"); q0.addTransizione(Pattern.LETTER, rId1, (c) -> contenitoreIdentificatore += c); q0.addTransizione('_', rId0, (c) -> contenitoreIdentificatore += c); rId0.addTransizione('_', rId0, (c) -> contenitoreIdentificatore += c); rId0.addTransizione(Pattern.LETTER, rId1, (c) -> contenitoreIdentificatore += c); rId0.addTransizione(Pattern.NUMBER, rId1, (c) -> contenitoreIdentificatore += c); rId1.addTransizione('_', rId1, (c) -> contenitoreIdentificatore += c); rId1.addTransizione(Pattern.NUMBER, rId1, (c) -> contenitoreIdentificatore += c); rId1.addTransizione(Pattern.LETTER, rId1, (c) -> contenitoreIdentificatore += c); rId1.addTransizione(Pattern.NON_IDENTIFICATORE, q0, (c) -> { if(keyWords.containsKey(contenitoreIdentificatore)) this.alertToken(keyWords.get(contenitoreIdentificatore)); else this.alertToken(new Word(Tag.ID, contenitoreIdentificatore)); addBuffer((char)c); contenitoreIdentificatore = ""; }); //Fine riconoscimento identificatore //Inizio riconoscimento commento Stato c1 = new Stato(); Stato c2 = new Stato(); Stato c3 = new Stato(); q0.addTransizione('/', c1); c1.addTransizione('/', c1); c1.addTransizione('*', c2); c2.addTransizione(Pattern.NOT_COM_PAT, c2); c2.addTransizione('/', c2); c2.addTransizione('*', c3); c3.addTransizione(Pattern.NOT_COM_PAT, c2); c3.addTransizione('/', q0); c3.addTransizione('*', c3); //Fine riconoscimento commento List<Stato> finali = new LinkedList<>(); finali.add(q0); Automa automa = new Automa(q0, finali); return automa; } public UniLexer(BufferedReader br) { super(null, br); Automa a = generateAutoma(); this.automa = a; this.stati.add(a.iniziale); } }
Rimossa transizione sbagliata
src/lexer/UniLexer.java
Rimossa transizione sbagliata
<ide><path>rc/lexer/UniLexer.java <ide> <ide> q0.addTransizione('/', c1); <ide> <del> c1.addTransizione('/', c1); <ide> c1.addTransizione('*', c2); <ide> <ide> c2.addTransizione(Pattern.NOT_COM_PAT, c2);
Java
agpl-3.0
7c0d5bc7cf109d579b4b06361e0ddf8f98d822ea
0
PeterWithers/temp-to-delete1,KinshipSoftware/KinOathKinshipArchiver,KinshipSoftware/KinOathKinshipArchiver,PeterWithers/temp-to-delete1
package nl.mpi.kinnate.svg.relationlines; import java.awt.Point; import java.util.HashSet; import nl.mpi.kinnate.svg.EntitySvg; /** * Document : LineLookUpTable Created on : Sep 30, 2011, 3:24:55 PM * * @author Peter Withers */ public class LineLookUpTable { // this hashset keeps one line record for line part for each pair of entities, the line segments might be updated when an entity is dragged // todo: there will probably be multiple line parts for each pari of entities: start segment, end segment, main line and maybe some zig zag bits, even if these zig zag bits are not ued they probably should always be there for simplicity HashSet<LineRecord> lineRecords = new HashSet<LineRecord>(); protected LineLookUpTable() { } public void getIntersectsEntity() { } public void getOverlapsOtherLine() { } protected Point[] getLineDirected(Point[] undirectedLine) { // this method is not intended to handle diagonal lines Point[] lineDirected; if (undirectedLine[0].y == undirectedLine[1].y) { if (undirectedLine[0].x <= undirectedLine[1].x) { lineDirected = undirectedLine; } else { lineDirected = new Point[]{undirectedLine[1], undirectedLine[0]}; } } else if (undirectedLine[0].y <= undirectedLine[1].y) { lineDirected = undirectedLine; } else { lineDirected = new Point[]{undirectedLine[1], undirectedLine[0]}; } return lineDirected; } protected boolean intersectsPoint(Point entityPoint, Point[] relationLine) { // System.out.println("entityPoint:" + entityPoint); // System.out.println("segment: " + relationLine[0] + relationLine[1]); boolean startsBefore = relationLine[0].x <= entityPoint.x + EntitySvg.symbolSize; boolean endsBefore = relationLine[1].x <= entityPoint.x; boolean startsAbove = relationLine[0].y <= entityPoint.y + EntitySvg.symbolSize; boolean endsAbove = relationLine[1].y <= entityPoint.y; final boolean intersectsResult = startsBefore != endsBefore && startsAbove != endsAbove; // System.out.println("startsBefore: " + startsBefore); // System.out.println("endsBefore: " + endsBefore); // System.out.println("intersectsResult: " + intersectsResult); return (intersectsResult); } protected boolean intersects(Point[] horizontalLine, Point[] verticalLine) { Point[] horizontalLineDirected = getLineDirected(horizontalLine); boolean startsBefore = horizontalLineDirected[0].x < verticalLine[0].x; boolean endsBefore = horizontalLineDirected[1].x <= verticalLine[0].x; boolean startsAbove = verticalLine[0].y < horizontalLineDirected[0].y; boolean endsAbove = verticalLine[1].y < horizontalLineDirected[0].y; final boolean intersectsResult = startsBefore != endsBefore && startsAbove != endsAbove; return (intersectsResult); } protected boolean overlaps(Point[] lineA, Point[] lineB) { Point[] lineDirectedA = getLineDirected(lineA); Point[] lineDirectedB = getLineDirected(lineB); boolean verticalMatch = lineDirectedA[0].x == lineDirectedB[0].x && lineDirectedA[0].x == lineDirectedB[1].x && lineDirectedA[0].x == lineDirectedA[1].x; boolean horizontalMatch = lineDirectedA[0].y == lineDirectedB[0].y && lineDirectedA[0].y == lineDirectedB[1].y && lineDirectedA[0].y == lineDirectedA[1].y; // horizontalMatch int startA = lineDirectedA[0].x; int startB = lineDirectedB[0].x; int endA = lineDirectedA[1].x; int endB = lineDirectedB[1].x; if (verticalMatch) { // verticalMatch startA = lineDirectedA[0].y; startB = lineDirectedB[0].y; endA = lineDirectedA[1].y; endB = lineDirectedB[1].y; } boolean zeroLength = startA == endA || startB == endB; if (zeroLength) { // zero length lines don't count as a match return false; } if (horizontalMatch || verticalMatch) { // is lineA within lineB // is lineB within lineA if (startA <= startB && startA > endB) { // System.out.print(horizontalMatch + "||" + verticalMatch); // System.out.println(" x"); return true; } else if (startA >= startB && startA < endB) { // System.out.print(horizontalMatch + "||" + verticalMatch); // System.out.println(" y"); return true; } else if (startB <= startA && startB > endA) { // System.out.print(horizontalMatch + "||" + verticalMatch); // System.out.println(" z"); return true; } else if (startB >= startA && startB < endA) { // System.out.print(horizontalMatch + "||" + verticalMatch); // System.out.println(" w"); return true; } } return false; } boolean excludeFirstLastSegments = true; public void separateLinesOverlappingEntities(Point[] allEntityLocations) { int offset = 0; if (excludeFirstLastSegments) { offset = 1; } LineRecord[] lineRecordArray = lineRecords.toArray(new LineRecord[0]); for (int lineRecordCount = 0; lineRecordCount < lineRecordArray.length; lineRecordCount++) { // System.out.print("lineRecordCount: "+lineRecordCount); LineRecord lineRecordOuter = lineRecordArray[lineRecordCount]; for (int currentIndexA = 0 + offset; currentIndexA <= lineRecordOuter.getLastSegment() - offset; currentIndexA++) { Point[] currentSegmentA = lineRecordOuter.getSegment(currentIndexA); // System.out.print("[" + lineRecordCount + ":" + currentIndexA + "]"); for (Point entityLocation : allEntityLocations) { // System.out.println("entityLocation:" + entityLocation); if (intersectsPoint(entityLocation, currentSegmentA)) { // System.out.print(" intersects,"); // System.out.print("[" + entityLocation + "]"); lineRecordOuter.moveAside(currentIndexA, 6); } else { // System.out.print(","); } } } // System.out.println(""); } } public void separateOverlappingLines() { int offset = 0; if (excludeFirstLastSegments) { offset = 1; } LineRecord[] lineRecordArray = lineRecords.toArray(new LineRecord[0]); for (int lineRecordCount = 0; lineRecordCount < lineRecordArray.length; lineRecordCount++) { // System.out.print(lineRecordCount + ": "); LineRecord lineRecordOuter = lineRecordArray[lineRecordCount]; for (int currentIndexA = 0 + offset; currentIndexA <= lineRecordOuter.getLastSegment() - offset; currentIndexA++) { Point[] currentSegmentA = lineRecordOuter.getSegment(currentIndexA); // System.out.print("[a" + currentIndexA + "]"); for (int lineRecordInnerCount = lineRecordCount + 1; lineRecordInnerCount < lineRecordArray.length; lineRecordInnerCount++) { if (lineRecordCount != lineRecordInnerCount) { LineRecord lineRecordInner = lineRecordArray[lineRecordInnerCount]; if (lineRecordOuter.sharesSameGroup(lineRecordInner)) { // todo: hide lines that are overlapped by lines in the same group } else { for (int currentIndexB = 0 + offset; currentIndexB <= lineRecordInner.getLastSegment() - offset; currentIndexB++) { Point[] otherHorizontalLine = lineRecordInner.getSegment(currentIndexB); // System.out.print("[b" + currentIndexB + "]"); if (overlaps(currentSegmentA, otherHorizontalLine)) { // System.out.print(" overlaps,"); lineRecordInner.moveAside(currentIndexB, 6); } else { // System.out.print(","); } } } } } } // System.out.println(""); } } public void addLoops() { for (LineRecord lineRecordForLoops : lineRecords) { int currentHorizontal = lineRecordForLoops.getLastHorizontal(); while (currentHorizontal > -1) { Point[] currentHorizontalLine = lineRecordForLoops.getSegment(currentHorizontal); // System.out.println("currentHorizontal: " + currentHorizontal); for (LineRecord lineRecord : lineRecords) { if (lineRecord != lineRecordForLoops) { if (!lineRecord.sharesSameGroup(lineRecordForLoops)) { int currentVertical = lineRecord.getFirstVertical(); // System.out.println("currentVertical: " + currentVertical); while (currentVertical > -1) { Point[] currentVerticalLine = lineRecord.getSegment(currentVertical); if (intersects(currentHorizontalLine, currentVerticalLine)) { boolean isLeftHand = currentHorizontalLine[0].x > currentHorizontalLine[1].x; lineRecordForLoops.insertLoop(currentHorizontal, currentVerticalLine[0].x, isLeftHand); } currentVertical = lineRecord.getNextVertical(currentVertical); } } } } currentHorizontal = lineRecordForLoops.getPrevHorizontal(currentHorizontal); } lineRecordForLoops.sortLoops(); } } // protected Point[] getIntersections(LineRecord localLineRecord) { // HashSet<Point> intersectionPoints = new HashSet<Point>(); // for (LineRecord lineRecord : lineRecords) { // int currentHorizontal = lineRecord.getFirstHorizontal(); // while (currentHorizontal > -1) { // System.out.println("currentHorizontal: " + currentHorizontal); // currentHorizontal = lineRecord.getNextHorizontal(currentHorizontal); // } // // Point intersectionPoint = localLineRecord.getIntersection(lineRecord); // if (lineRecord != null) { // intersectionPoints.add(intersectionPoint); // } // } // return intersectionPoints.toArray(new Point[]{}); // } public void addRecord(LineRecord lineRecord) { lineRecords.add(lineRecord); } // public LineRecord adjustLineToObstructions(String lineIdString, ArrayList<Point> pointsList) { // LineRecord lineRecord = new LineRecord(lineIdString, pointsList); //// getIntersections(localLineRecord); //// //localLineRecord.insertLoop(3); // lineRecords.add(lineRecord); // return lineRecord; // } }
desktop/src/main/java/nl/mpi/kinnate/svg/relationlines/LineLookUpTable.java
package nl.mpi.kinnate.svg.relationlines; import java.awt.Point; import java.util.HashSet; import nl.mpi.kinnate.svg.EntitySvg; /** * Document : LineLookUpTable Created on : Sep 30, 2011, 3:24:55 PM * * @author Peter Withers */ public class LineLookUpTable { // this hashset keeps one line record for line part for each pair of entities, the line segments might be updated when an entity is dragged // todo: there will probably be multiple line parts for each pari of entities: start segment, end segment, main line and maybe some zig zag bits, even if these zig zag bits are not ued they probably should always be there for simplicity HashSet<LineRecord> lineRecords = new HashSet<LineRecord>(); protected LineLookUpTable() { } public void getIntersectsEntity() { } public void getOverlapsOtherLine() { } protected Point[] getLineDirected(Point[] undirectedLine) { // this method is not intended to handle diagonal lines Point[] lineDirected; if (undirectedLine[0].y == undirectedLine[1].y) { if (undirectedLine[0].x <= undirectedLine[1].x) { lineDirected = undirectedLine; } else { lineDirected = new Point[]{undirectedLine[1], undirectedLine[0]}; } } else if (undirectedLine[0].y <= undirectedLine[1].y) { lineDirected = undirectedLine; } else { lineDirected = new Point[]{undirectedLine[1], undirectedLine[0]}; } return lineDirected; } protected boolean intersectsPoint(Point entityPoint, Point[] relationLine) { System.out.println("entityPoint:" + entityPoint); System.out.println("segment: " + relationLine[0] + relationLine[1]); boolean startsBefore = relationLine[0].x <= entityPoint.x + EntitySvg.symbolSize; boolean endsBefore = relationLine[1].x <= entityPoint.x; boolean startsAbove = relationLine[0].y <= entityPoint.y + EntitySvg.symbolSize; boolean endsAbove = relationLine[1].y <= entityPoint.y; final boolean intersectsResult = startsBefore != endsBefore && startsAbove != endsAbove; System.out.println("startsBefore: " + startsBefore); System.out.println("endsBefore: " + endsBefore); System.out.println("intersectsResult: " + intersectsResult); return (intersectsResult); } protected boolean intersects(Point[] horizontalLine, Point[] verticalLine) { Point[] horizontalLineDirected = getLineDirected(horizontalLine); boolean startsBefore = horizontalLineDirected[0].x < verticalLine[0].x; boolean endsBefore = horizontalLineDirected[1].x <= verticalLine[0].x; boolean startsAbove = verticalLine[0].y < horizontalLineDirected[0].y; boolean endsAbove = verticalLine[1].y < horizontalLineDirected[0].y; final boolean intersectsResult = startsBefore != endsBefore && startsAbove != endsAbove; return (intersectsResult); } protected boolean overlaps(Point[] lineA, Point[] lineB) { Point[] lineDirectedA = getLineDirected(lineA); Point[] lineDirectedB = getLineDirected(lineB); boolean verticalMatch = lineDirectedA[0].x == lineDirectedB[0].x && lineDirectedA[0].x == lineDirectedB[1].x && lineDirectedA[0].x == lineDirectedA[1].x; boolean horizontalMatch = lineDirectedA[0].y == lineDirectedB[0].y && lineDirectedA[0].y == lineDirectedB[1].y && lineDirectedA[0].y == lineDirectedA[1].y; // horizontalMatch int startA = lineDirectedA[0].x; int startB = lineDirectedB[0].x; int endA = lineDirectedA[1].x; int endB = lineDirectedB[1].x; if (verticalMatch) { // verticalMatch startA = lineDirectedA[0].y; startB = lineDirectedB[0].y; endA = lineDirectedA[1].y; endB = lineDirectedB[1].y; } boolean zeroLength = startA == endA || startB == endB; if (zeroLength) { // zero length lines don't count as a match return false; } if (horizontalMatch || verticalMatch) { // is lineA within lineB // is lineB within lineA if (startA <= startB && startA > endB) { // System.out.print(horizontalMatch + "||" + verticalMatch); // System.out.println(" x"); return true; } else if (startA >= startB && startA < endB) { // System.out.print(horizontalMatch + "||" + verticalMatch); // System.out.println(" y"); return true; } else if (startB <= startA && startB > endA) { // System.out.print(horizontalMatch + "||" + verticalMatch); // System.out.println(" z"); return true; } else if (startB >= startA && startB < endA) { // System.out.print(horizontalMatch + "||" + verticalMatch); // System.out.println(" w"); return true; } } return false; } boolean excludeFirstLastSegments = true; public void separateLinesOverlappingEntities(Point[] allEntityLocations) { int offset = 0; if (excludeFirstLastSegments) { offset = 1; } LineRecord[] lineRecordArray = lineRecords.toArray(new LineRecord[0]); for (int lineRecordCount = 0; lineRecordCount < lineRecordArray.length; lineRecordCount++) { // System.out.print("lineRecordCount: "+lineRecordCount); LineRecord lineRecordOuter = lineRecordArray[lineRecordCount]; for (int currentIndexA = 0 + offset; currentIndexA <= lineRecordOuter.getLastSegment() - offset; currentIndexA++) { Point[] currentSegmentA = lineRecordOuter.getSegment(currentIndexA); System.out.print("[" + lineRecordCount + ":" + currentIndexA + "]"); for (Point entityLocation : allEntityLocations) { System.out.println("entityLocation:" + entityLocation); if (intersectsPoint(entityLocation, currentSegmentA)) { System.out.print(" intersects,"); // System.out.print("[" + entityLocation + "]"); lineRecordOuter.moveAside(currentIndexA, 6); } else { // System.out.print(","); } } } System.out.println(""); } } public void separateOverlappingLines() { int offset = 0; if (excludeFirstLastSegments) { offset = 1; } LineRecord[] lineRecordArray = lineRecords.toArray(new LineRecord[0]); for (int lineRecordCount = 0; lineRecordCount < lineRecordArray.length; lineRecordCount++) { // System.out.print(lineRecordCount + ": "); LineRecord lineRecordOuter = lineRecordArray[lineRecordCount]; for (int currentIndexA = 0 + offset; currentIndexA <= lineRecordOuter.getLastSegment() - offset; currentIndexA++) { Point[] currentSegmentA = lineRecordOuter.getSegment(currentIndexA); // System.out.print("[a" + currentIndexA + "]"); for (int lineRecordInnerCount = lineRecordCount + 1; lineRecordInnerCount < lineRecordArray.length; lineRecordInnerCount++) { if (lineRecordCount != lineRecordInnerCount) { LineRecord lineRecordInner = lineRecordArray[lineRecordInnerCount]; if (lineRecordOuter.sharesSameGroup(lineRecordInner)) { // todo: hide lines that are overlapped by lines in the same group } else { for (int currentIndexB = 0 + offset; currentIndexB <= lineRecordInner.getLastSegment() - offset; currentIndexB++) { Point[] otherHorizontalLine = lineRecordInner.getSegment(currentIndexB); // System.out.print("[b" + currentIndexB + "]"); if (overlaps(currentSegmentA, otherHorizontalLine)) { // System.out.print(" overlaps,"); lineRecordInner.moveAside(currentIndexB, 6); } else { // System.out.print(","); } } } } } } // System.out.println(""); } } public void addLoops() { for (LineRecord lineRecordForLoops : lineRecords) { int currentHorizontal = lineRecordForLoops.getLastHorizontal(); while (currentHorizontal > -1) { Point[] currentHorizontalLine = lineRecordForLoops.getSegment(currentHorizontal); // System.out.println("currentHorizontal: " + currentHorizontal); for (LineRecord lineRecord : lineRecords) { if (lineRecord != lineRecordForLoops) { if (!lineRecord.sharesSameGroup(lineRecordForLoops)) { int currentVertical = lineRecord.getFirstVertical(); // System.out.println("currentVertical: " + currentVertical); while (currentVertical > -1) { Point[] currentVerticalLine = lineRecord.getSegment(currentVertical); if (intersects(currentHorizontalLine, currentVerticalLine)) { boolean isLeftHand = currentHorizontalLine[0].x > currentHorizontalLine[1].x; lineRecordForLoops.insertLoop(currentHorizontal, currentVerticalLine[0].x, isLeftHand); } currentVertical = lineRecord.getNextVertical(currentVertical); } } } } currentHorizontal = lineRecordForLoops.getPrevHorizontal(currentHorizontal); } lineRecordForLoops.sortLoops(); } } // protected Point[] getIntersections(LineRecord localLineRecord) { // HashSet<Point> intersectionPoints = new HashSet<Point>(); // for (LineRecord lineRecord : lineRecords) { // int currentHorizontal = lineRecord.getFirstHorizontal(); // while (currentHorizontal > -1) { // System.out.println("currentHorizontal: " + currentHorizontal); // currentHorizontal = lineRecord.getNextHorizontal(currentHorizontal); // } // // Point intersectionPoint = localLineRecord.getIntersection(lineRecord); // if (lineRecord != null) { // intersectionPoints.add(intersectionPoint); // } // } // return intersectionPoints.toArray(new Point[]{}); // } public void addRecord(LineRecord lineRecord) { lineRecords.add(lineRecord); } // public LineRecord adjustLineToObstructions(String lineIdString, ArrayList<Point> pointsList) { // LineRecord lineRecord = new LineRecord(lineIdString, pointsList); //// getIntersections(localLineRecord); //// //localLineRecord.insertLoop(3); // lineRecords.add(lineRecord); // return lineRecord; // } }
Added collision detection between entities and relation lines and moved the relation lines accordingly. refs #1220 #1221
desktop/src/main/java/nl/mpi/kinnate/svg/relationlines/LineLookUpTable.java
Added collision detection between entities and relation lines and moved the relation lines accordingly. refs #1220 #1221
<ide><path>esktop/src/main/java/nl/mpi/kinnate/svg/relationlines/LineLookUpTable.java <ide> } <ide> <ide> protected boolean intersectsPoint(Point entityPoint, Point[] relationLine) { <del> System.out.println("entityPoint:" + entityPoint); <del> System.out.println("segment: " + relationLine[0] + relationLine[1]); <add>// System.out.println("entityPoint:" + entityPoint); <add>// System.out.println("segment: " + relationLine[0] + relationLine[1]); <ide> boolean startsBefore = relationLine[0].x <= entityPoint.x + EntitySvg.symbolSize; <ide> boolean endsBefore = relationLine[1].x <= entityPoint.x; <ide> boolean startsAbove = relationLine[0].y <= entityPoint.y + EntitySvg.symbolSize; <ide> boolean endsAbove = relationLine[1].y <= entityPoint.y; <ide> final boolean intersectsResult = startsBefore != endsBefore && startsAbove != endsAbove; <del> System.out.println("startsBefore: " + startsBefore); <del> System.out.println("endsBefore: " + endsBefore); <del> System.out.println("intersectsResult: " + intersectsResult); <add>// System.out.println("startsBefore: " + startsBefore); <add>// System.out.println("endsBefore: " + endsBefore); <add>// System.out.println("intersectsResult: " + intersectsResult); <ide> return (intersectsResult); <ide> } <ide> <ide> LineRecord lineRecordOuter = lineRecordArray[lineRecordCount]; <ide> for (int currentIndexA = 0 + offset; currentIndexA <= lineRecordOuter.getLastSegment() - offset; currentIndexA++) { <ide> Point[] currentSegmentA = lineRecordOuter.getSegment(currentIndexA); <del> System.out.print("[" + lineRecordCount + ":" + currentIndexA + "]"); <add>// System.out.print("[" + lineRecordCount + ":" + currentIndexA + "]"); <ide> for (Point entityLocation : allEntityLocations) { <del> System.out.println("entityLocation:" + entityLocation); <add>// System.out.println("entityLocation:" + entityLocation); <ide> if (intersectsPoint(entityLocation, currentSegmentA)) { <del> System.out.print(" intersects,"); <add>// System.out.print(" intersects,"); <ide> // System.out.print("[" + entityLocation + "]"); <ide> lineRecordOuter.moveAside(currentIndexA, 6); <ide> } else { <ide> } <ide> } <ide> } <del> System.out.println(""); <add>// System.out.println(""); <ide> } <ide> } <ide>
Java
bsd-2-clause
1d8d21042121ac328e0541f6636862452b52adad
0
Sethtroll/runelite,l2-/runelite,l2-/runelite,runelite/runelite,Sethtroll/runelite,runelite/runelite,runelite/runelite
/* * Copyright (c) 2018, Seth <http://github.com/sethtroll> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package net.runelite.client.plugins.agility; import java.awt.Dimension; import java.awt.Graphics2D; import java.time.Duration; import java.time.Instant; import javax.inject.Inject; import static net.runelite.api.MenuAction.RUNELITE_OVERLAY_CONFIG; import net.runelite.client.ui.overlay.Overlay; import static net.runelite.client.ui.overlay.OverlayManager.OPTION_CONFIGURE; import net.runelite.client.ui.overlay.OverlayMenuEntry; import net.runelite.client.ui.overlay.OverlayPosition; import net.runelite.client.ui.overlay.OverlayPriority; import net.runelite.client.ui.overlay.components.LineComponent; import net.runelite.client.ui.overlay.components.PanelComponent; class LapCounterOverlay extends Overlay { private final AgilityPlugin plugin; private final AgilityConfig config; private final PanelComponent panelComponent = new PanelComponent(); @Inject private LapCounterOverlay(AgilityPlugin plugin, AgilityConfig config) { super(plugin); setPosition(OverlayPosition.TOP_LEFT); setPriority(OverlayPriority.LOW); this.plugin = plugin; this.config = config; getMenuEntries().add(new OverlayMenuEntry(RUNELITE_OVERLAY_CONFIG, OPTION_CONFIGURE, "Agility overlay")); } @Override public Dimension render(Graphics2D graphics) { AgilitySession session = plugin.getSession(); if (!config.showLapCount() || session == null || session.getLastLapCompleted() == null || session.getCourse() == null) { return null; } Duration lapTimeout = Duration.ofMinutes(config.lapTimeout()); Duration sinceLap = Duration.between(session.getLastLapCompleted(), Instant.now()); if (sinceLap.compareTo(lapTimeout) >= 0) { // timeout session session.setLastLapCompleted(null); return null; } panelComponent.getChildren().clear(); panelComponent.getChildren().add(LineComponent.builder() .left("Total Laps:") .right(Integer.toString(session.getTotalLaps())) .build()); if (session.getLapsTillLevel() > 0) { panelComponent.getChildren().add(LineComponent.builder() .left("Laps until level:") .right(Integer.toString(session.getLapsTillLevel())) .build()); } return panelComponent.render(graphics); } }
runelite-client/src/main/java/net/runelite/client/plugins/agility/LapCounterOverlay.java
/* * Copyright (c) 2018, Seth <http://github.com/sethtroll> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package net.runelite.client.plugins.agility; import java.awt.Dimension; import java.awt.Graphics2D; import java.time.Duration; import java.time.Instant; import javax.inject.Inject; import static net.runelite.api.MenuAction.RUNELITE_OVERLAY_CONFIG; import net.runelite.client.ui.overlay.Overlay; import static net.runelite.client.ui.overlay.OverlayManager.OPTION_CONFIGURE; import net.runelite.client.ui.overlay.OverlayMenuEntry; import net.runelite.client.ui.overlay.OverlayPosition; import net.runelite.client.ui.overlay.OverlayPriority; import net.runelite.client.ui.overlay.components.LineComponent; import net.runelite.client.ui.overlay.components.PanelComponent; class LapCounterOverlay extends Overlay { private final AgilityPlugin plugin; private final AgilityConfig config; private final PanelComponent panelComponent = new PanelComponent(); @Inject private LapCounterOverlay(AgilityPlugin plugin, AgilityConfig config) { super(plugin); setPosition(OverlayPosition.TOP_LEFT); setPriority(OverlayPriority.LOW); this.plugin = plugin; this.config = config; getMenuEntries().add(new OverlayMenuEntry(RUNELITE_OVERLAY_CONFIG, OPTION_CONFIGURE, "Agility overlay")); } @Override public Dimension render(Graphics2D graphics) { AgilitySession session = plugin.getSession(); if (!config.showLapCount() || session == null || session.getLastLapCompleted() == null || session.getCourse() == null) { return null; } Duration lapTimeout = Duration.ofMinutes(config.lapTimeout()); Duration sinceLap = Duration.between(session.getLastLapCompleted(), Instant.now()); if (sinceLap.compareTo(lapTimeout) >= 0) { // timeout session session.setLastLapCompleted(null); return null; } panelComponent.getChildren().clear(); panelComponent.getChildren().add(LineComponent.builder() .left("Total Laps") .right(Integer.toString(session.getTotalLaps())) .build()); if (session.getLapsTillLevel() > 0) { panelComponent.getChildren().add(LineComponent.builder() .left("Laps till level") .right(Integer.toString(session.getLapsTillLevel())) .build()); } return panelComponent.render(graphics); } }
Update lap counter overlay strings for clarity. Removed slang "till'" from the lap counter overlay string and added colons to the end for cleanliness and aesthetic.
runelite-client/src/main/java/net/runelite/client/plugins/agility/LapCounterOverlay.java
Update lap counter overlay strings for clarity.
<ide><path>unelite-client/src/main/java/net/runelite/client/plugins/agility/LapCounterOverlay.java <ide> <ide> panelComponent.getChildren().clear(); <ide> panelComponent.getChildren().add(LineComponent.builder() <del> .left("Total Laps") <add> .left("Total Laps:") <ide> .right(Integer.toString(session.getTotalLaps())) <ide> .build()); <ide> <ide> if (session.getLapsTillLevel() > 0) <ide> { <ide> panelComponent.getChildren().add(LineComponent.builder() <del> .left("Laps till level") <add> .left("Laps until level:") <ide> .right(Integer.toString(session.getLapsTillLevel())) <ide> .build()); <ide> }
Java
epl-1.0
65605760cff9dff8efcdd1e8a49b61c60515b827
0
ELTE-Soft/txtUML,ELTE-Soft/txtUML,ELTE-Soft/txtUML,ELTE-Soft/txtUML
package hu.elte.txtuml.export.uml2; import java.io.File; import java.io.IOException; import java.util.List; import java.util.Set; import java.util.stream.Collectors; import java.util.stream.Stream; import org.eclipse.core.filesystem.EFS; import org.eclipse.core.filesystem.IFileStore; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IResource; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.NullProgressMonitor; import org.eclipse.emf.common.util.URI; import org.eclipse.emf.common.util.WrappedException; import org.eclipse.emf.ecore.resource.Resource; import org.eclipse.emf.ecore.resource.ResourceSet; import org.eclipse.emf.ecore.resource.impl.ResourceSetImpl; import org.eclipse.jdt.core.IJavaProject; import org.eclipse.jdt.core.IPackageFragment; import org.eclipse.jdt.core.JavaModelException; import org.eclipse.ui.IWorkbenchPage; import org.eclipse.ui.PartInitException; import org.eclipse.ui.PlatformUI; import org.eclipse.ui.ide.IDE; import org.eclipse.uml2.uml.Element; import org.eclipse.uml2.uml.Model; import hu.elte.txtuml.export.uml2.mapping.ModelMapCollector; import hu.elte.txtuml.export.uml2.mapping.ModelMapException; import hu.elte.txtuml.export.uml2.structural.ModelExporter; import hu.elte.txtuml.utils.eclipse.NotFoundException; import hu.elte.txtuml.utils.eclipse.PackageUtils; import hu.elte.txtuml.utils.eclipse.ProjectUtils; /** * This class is responsible for exporting Eclipse UML2 model generated from a * txtUML model. */ public class TxtUMLToUML2 { /** * Exports the txtUML model to a org.eclipse.uml2.uml.Model representation * * @param sourceProject * name of the source project, where the txtUML model can be find * @param packageName * fully qualified name of the txtUML model * @param outputDirectory * where the result model should be saved * @param folder * the target folder for generated model */ public static Model exportModel(String sourceProject, String packageName, String outputDirectory, ExportMode exportMode, String folder) throws JavaModelException, NotFoundException, IOException { return exportModel(sourceProject, packageName, URI.createPlatformResourceURI(outputDirectory, false), exportMode, folder); } /** * Exports the txtUML model to a org.eclipse.uml2.uml.Model representation * * @param sourceProject * name of the source project, where the txtUML model can be find * @param packageName * fully qualified name of the txtUML model * @param outputDirectory * where the result model should be saved * @param folder * the target folder for generated model */ public static Model exportModel(String sourceProject, String packageName, URI outputDirectory, ExportMode exportMode, String folder) throws NotFoundException, JavaModelException, IOException { Model model = exportModel(sourceProject, packageName, exportMode, folder); File file = new File(model.eResource().getURI().toFileString()); file.getParentFile().mkdirs(); model.eResource().save(null); IFile createdFile = ResourcesPlugin.getWorkspace().getRoot().findFilesForLocationURI(file.toURI())[0]; try { createdFile.refreshLocal(IResource.DEPTH_INFINITE, new NullProgressMonitor()); } catch (CoreException e) { throw new RuntimeException(e); } return model; } public static Model exportModel(String sourceProject, String packageName, ExportMode exportMode, String folder) throws NotFoundException, JavaModelException { IJavaProject javaProject = ProjectUtils.findJavaProject(sourceProject); IPackageFragment[] packageFragments = PackageUtils.findPackageFragments(javaProject, packageName); if (packageFragments.length == 0) { throw new NotFoundException("Cannot find package '" + packageName + "'"); } List<IPackageFragment> rootFragments = Stream.of(packageFragments) .filter(pf -> pf.getElementName().equals(packageName)).collect(Collectors.toList()); ModelExporter modelExporter = new ModelExporter(folder, exportMode); Model model = modelExporter.export(rootFragments); if (model == null) { throw new IllegalArgumentException("The selected package is not a txtUML model."); } ExporterCache cache = modelExporter.cache; Set<Element> unrooted = cache.floatingElements(); if (exportMode.isErrorHandler()) { unrooted.forEach(e -> e.destroy()); } else if (!unrooted.isEmpty()) { throw new IllegalStateException("Unrooted elements found in the exported model: " + unrooted); } ModelMapCollector collector = new ModelMapCollector(model.eResource().getURI()); cache.getMapping().forEach((s, e) -> collector.put(s, e)); try { URI destination = URI .createFileURI(rootFragments.get(0).getJavaProject().getProject().getLocation().toOSString()) .appendSegment(folder); String fileName = rootFragments.get(0).getElementName(); collector.save(destination, fileName); } catch (ModelMapException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } return model; } public static Model loadExportedModel(String uri) throws WrappedException { return loadExportedModel(URI.createPlatformResourceURI(uri, false)); } public static Model loadExportedModel(URI uri) throws WrappedException { ResourceSet resSet = new ResourceSetImpl(); Resource resource = resSet.getResource(uri, true); Model model = null; if (resource.getContents().size() != 0) model = (Model) resource.getContents().get(0); return model; } }
dev/plugins/hu.elte.txtuml.export.uml2/src/hu/elte/txtuml/export/uml2/TxtUMLToUML2.java
package hu.elte.txtuml.export.uml2; import java.io.File; import java.io.IOException; import java.util.List; import java.util.Set; import java.util.stream.Collectors; import java.util.stream.Stream; import org.eclipse.core.filesystem.EFS; import org.eclipse.core.filesystem.IFileStore; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IResource; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.NullProgressMonitor; import org.eclipse.emf.common.util.URI; import org.eclipse.emf.common.util.WrappedException; import org.eclipse.emf.ecore.resource.Resource; import org.eclipse.emf.ecore.resource.ResourceSet; import org.eclipse.emf.ecore.resource.impl.ResourceSetImpl; import org.eclipse.jdt.core.IJavaProject; import org.eclipse.jdt.core.IPackageFragment; import org.eclipse.jdt.core.JavaModelException; import org.eclipse.ui.IWorkbenchPage; import org.eclipse.ui.PartInitException; import org.eclipse.ui.PlatformUI; import org.eclipse.ui.ide.IDE; import org.eclipse.uml2.uml.Element; import org.eclipse.uml2.uml.Model; import hu.elte.txtuml.export.uml2.mapping.ModelMapCollector; import hu.elte.txtuml.export.uml2.mapping.ModelMapException; import hu.elte.txtuml.export.uml2.structural.ModelExporter; import hu.elte.txtuml.utils.eclipse.NotFoundException; import hu.elte.txtuml.utils.eclipse.PackageUtils; import hu.elte.txtuml.utils.eclipse.ProjectUtils; /** * This class is responsible for exporting Eclipse UML2 model generated from a * txtUML model. */ public class TxtUMLToUML2 { /** * Exports the txtUML model to a org.eclipse.uml2.uml.Model representation * * @param sourceProject * name of the source project, where the txtUML model can be find * @param packageName * fully qualified name of the txtUML model * @param outputDirectory * where the result model should be saved * @param folder * the target folder for generated model */ public static Model exportModel(String sourceProject, String packageName, String outputDirectory, ExportMode exportMode, String folder) throws JavaModelException, NotFoundException, IOException { return exportModel(sourceProject, packageName, URI.createPlatformResourceURI(outputDirectory, false), exportMode, folder); } /** * Exports the txtUML model to a org.eclipse.uml2.uml.Model representation * * @param sourceProject * name of the source project, where the txtUML model can be find * @param packageName * fully qualified name of the txtUML model * @param outputDirectory * where the result model should be saved * @param folder * the target folder for generated model */ public static Model exportModel(String sourceProject, String packageName, URI outputDirectory, ExportMode exportMode, String folder) throws NotFoundException, JavaModelException, IOException { Model model = exportModel(sourceProject, packageName, exportMode, folder); File file = new File(model.eResource().getURI().toFileString()); file.getParentFile().mkdirs(); model.eResource().save(null); IFile createdFile = ResourcesPlugin.getWorkspace().getRoot().findFilesForLocationURI(file.toURI())[0]; try { createdFile.refreshLocal(IResource.DEPTH_INFINITE, new NullProgressMonitor()); } catch (CoreException e) { throw new RuntimeException(e); } IFileStore fileStore = EFS.getLocalFileSystem().getStore(file.toURI()); if (PlatformUI.isWorkbenchRunning()) { IWorkbenchPage page = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage(); try { IDE.openEditorOnFileStore(page, fileStore); } catch (PartInitException e) { throw new RuntimeException(e); } } return model; } public static Model exportModel(String sourceProject, String packageName, ExportMode exportMode, String folder) throws NotFoundException, JavaModelException { IJavaProject javaProject = ProjectUtils.findJavaProject(sourceProject); IPackageFragment[] packageFragments = PackageUtils.findPackageFragments(javaProject, packageName); if (packageFragments.length == 0) { throw new NotFoundException("Cannot find package '" + packageName + "'"); } List<IPackageFragment> rootFragments = Stream.of(packageFragments) .filter(pf -> pf.getElementName().equals(packageName)).collect(Collectors.toList()); ModelExporter modelExporter = new ModelExporter(folder, exportMode); Model model = modelExporter.export(rootFragments); if (model == null) { throw new IllegalArgumentException("The selected package is not a txtUML model."); } ExporterCache cache = modelExporter.cache; Set<Element> unrooted = cache.floatingElements(); if (exportMode.isErrorHandler()) { unrooted.forEach(e -> e.destroy()); } else if (!unrooted.isEmpty()) { throw new IllegalStateException("Unrooted elements found in the exported model: " + unrooted); } ModelMapCollector collector = new ModelMapCollector(model.eResource().getURI()); cache.getMapping().forEach((s, e) -> collector.put(s, e)); try { URI destination = URI .createFileURI(rootFragments.get(0).getJavaProject().getProject().getLocation().toOSString()) .appendSegment(folder); String fileName = rootFragments.get(0).getElementName(); collector.save(destination, fileName); } catch (ModelMapException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } return model; } public static Model loadExportedModel(String uri) throws WrappedException { return loadExportedModel(URI.createPlatformResourceURI(uri, false)); } public static Model loadExportedModel(URI uri) throws WrappedException { ResourceSet resSet = new ResourceSetImpl(); Resource resource = resSet.getResource(uri, true); Model model = null; if (resource.getContents().size() != 0) model = (Model) resource.getContents().get(0); return model; } }
Removed the opening of the UML model.
dev/plugins/hu.elte.txtuml.export.uml2/src/hu/elte/txtuml/export/uml2/TxtUMLToUML2.java
Removed the opening of the UML model.
<ide><path>ev/plugins/hu.elte.txtuml.export.uml2/src/hu/elte/txtuml/export/uml2/TxtUMLToUML2.java <ide> throw new RuntimeException(e); <ide> } <ide> <del> IFileStore fileStore = EFS.getLocalFileSystem().getStore(file.toURI()); <del> if (PlatformUI.isWorkbenchRunning()) { <del> IWorkbenchPage page = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage(); <del> try { <del> IDE.openEditorOnFileStore(page, fileStore); <del> } catch (PartInitException e) { <del> throw new RuntimeException(e); <del> } <del> } <del> <ide> return model; <ide> } <ide>
Java
apache-2.0
ee7cd6c37f8e0074af7294ad561cf82faab34e68
0
scrutmydocs/scrutmydocs,scrutmydocs/scrutmydocs
package fr.issamax.essearch.action; import static org.elasticsearch.index.query.QueryBuilders.matchAllQuery; import static org.elasticsearch.index.query.QueryBuilders.queryString; import static fr.issamax.dao.elastic.factory.ESSearchProperties.*; import java.io.Serializable; import javax.faces.context.FacesContext; import org.elasticsearch.action.search.SearchResponse; import org.elasticsearch.action.search.SearchType; import org.elasticsearch.client.Client; import org.elasticsearch.index.query.QueryBuilder; import org.elasticsearch.search.SearchHit; import org.elasticsearch.search.SearchHits; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Component; import fr.issamax.essearch.data.Results; @Component("searchController") @Scope("session") public class SearchController implements Serializable { private static final long serialVersionUID = 1L; @Autowired protected Client esClient; protected String search; protected Results results; public void google() { try { QueryBuilder qb; if (search == null || search.trim().length() <= 0) { qb = matchAllQuery(); } else { qb = queryString(search); } SearchResponse searchHits = esClient.prepareSearch() .setIndices(INDEX_NAME) .setTypes(INDEX_TYPE_DOC) .setSearchType(SearchType.DFS_QUERY_THEN_FETCH) .setQuery(qb).setFrom(0).setSize(10) .addHighlightedField("name").addHighlightedField("file") .setHighlighterPreTags("<b>") .setHighlighterPostTags("</b>").execute().actionGet(); results = new Results(searchHits); } catch (Exception e) { e.printStackTrace(); } } public void imlucky() { try { QueryBuilder qb; if (search == null || search.trim().length() <= 0) { qb = matchAllQuery(); } else { qb = queryString(search); } SearchResponse searchResponse = esClient.prepareSearch() .setSearchType(SearchType.DFS_QUERY_THEN_FETCH) .setQuery(qb).setFrom(0).setSize(10) .addHighlightedField("name").addHighlightedField("file") .setHighlighterPreTags("<b>") .setHighlighterPostTags("</b>").execute().actionGet(); SearchHits hits = searchResponse.getHits(); if (hits != null && hits.getTotalHits() > 0) { SearchHit hit = hits.getAt(0); FacesContext.getCurrentInstance().getExternalContext().redirect("api/download/"+hit.getId()); } } catch (Exception e) { e.printStackTrace(); } } public void setSearch(String search) { this.search = search; } public String getSearch() { return search; } public Results getResults() { return results; } public void setResults(Results results) { this.results = results; } }
src/main/java/fr/issamax/essearch/action/SearchController.java
package fr.issamax.essearch.action; import static org.elasticsearch.index.query.QueryBuilders.matchAllQuery; import static org.elasticsearch.index.query.QueryBuilders.queryString; import static fr.issamax.dao.elastic.factory.ESSearchProperties.*; import java.io.Serializable; import javax.faces.context.FacesContext; import org.elasticsearch.action.search.SearchResponse; import org.elasticsearch.action.search.SearchType; import org.elasticsearch.client.Client; import org.elasticsearch.index.query.QueryBuilder; import org.elasticsearch.search.SearchHit; import org.elasticsearch.search.SearchHits; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Component; import fr.issamax.essearch.data.Results; @Component("searchController") @Scope("session") public class SearchController implements Serializable { private static final long serialVersionUID = 1L; @Autowired protected Client esClient; protected String search; protected Results results; public void google() { try { QueryBuilder qb; if (search == null || search.trim().length() <= 0) { qb = matchAllQuery(); } else { qb = queryString(search); } SearchResponse searchHits = esClient.prepareSearch() .setIndices(INDEX_NAME) .setSearchType(SearchType.DFS_QUERY_THEN_FETCH) .setQuery(qb).setFrom(0).setSize(10) .addHighlightedField("name").addHighlightedField("file") .setHighlighterPreTags("<b>") .setHighlighterPostTags("</b>").execute().actionGet(); results = new Results(searchHits); } catch (Exception e) { e.printStackTrace(); } } public void imlucky() { try { QueryBuilder qb; if (search == null || search.trim().length() <= 0) { qb = matchAllQuery(); } else { qb = queryString(search); } SearchResponse searchResponse = esClient.prepareSearch() .setSearchType(SearchType.DFS_QUERY_THEN_FETCH) .setQuery(qb).setFrom(0).setSize(10) .addHighlightedField("name").addHighlightedField("file") .setHighlighterPreTags("<b>") .setHighlighterPostTags("</b>").execute().actionGet(); SearchHits hits = searchResponse.getHits(); if (hits != null && hits.getTotalHits() > 0) { SearchHit hit = hits.getAt(0); FacesContext.getCurrentInstance().getExternalContext().redirect("api/download/"+hit.getId()); } } catch (Exception e) { e.printStackTrace(); } } public void setSearch(String search) { this.search = search; } public String getSearch() { return search; } public Results getResults() { return results; } public void setResults(Results results) { this.results = results; } }
We only search for docs and not folders !
src/main/java/fr/issamax/essearch/action/SearchController.java
We only search for docs and not folders !
<ide><path>rc/main/java/fr/issamax/essearch/action/SearchController.java <ide> <ide> SearchResponse searchHits = esClient.prepareSearch() <ide> .setIndices(INDEX_NAME) <add> .setTypes(INDEX_TYPE_DOC) <ide> .setSearchType(SearchType.DFS_QUERY_THEN_FETCH) <ide> .setQuery(qb).setFrom(0).setSize(10) <ide> .addHighlightedField("name").addHighlightedField("file")
Java
mit
6a3f2c40497ccbf999d4b6f84b638a1633469b0f
0
pablosaraiva/GoToBed
package pablosaraiva.gotobed; import java.lang.reflect.Field; import java.sql.*; import java.util.Set; import org.reflections.Reflections; import pablosaraiva.gotobed.annotations.DoNotSave; import pablosaraiva.gotobed.annotations.Sleeper; import pablosaraiva.gotobed.annotations.SleeperId; public class GoToBed { private BedProvider bedProvider; public GoToBed(BedProvider bedProvider) { this.bedProvider = bedProvider; Reflections reflections = new Reflections(); Set<Class<?>> sleeperClasses = reflections.getTypesAnnotatedWith(Sleeper.class); for (Class<?> clazz: sleeperClasses) { try { updateTable(clazz); } catch (SQLException e) { e.printStackTrace(); } } } public void sleep(Object obj) throws SQLException { if (hasId(obj)) { update(obj); } else { insert(obj); } } private void insert(Object obj) throws SQLException { Connection conn = bedProvider.getConnection(); StringBuilder sb = new StringBuilder(); sb.append("INSERT INTO "); sb.append(tableNameFor(obj.getClass())); sb.append("ID"); // for (Field f: obj.getClass().getDeclaredFields()) { // // } System.out.println("will insert"); conn.close(); } private void update(Object obj) { System.out.println("will update"); } private boolean hasId(Object obj) { for (Field f: obj.getClass().getDeclaredFields()) { f.setAccessible(true); if (f.isAnnotationPresent(SleeperId.class)) { try { f.setAccessible(true); Long id = (Long) f.get(obj); if (id != null && id > 0) { return true; } } catch (IllegalArgumentException | IllegalAccessException e) { e.printStackTrace(); } } f.setAccessible(false); } return false; } private void updateTable(Class<?> clazz) throws SQLException { if (existsTableForClass(clazz)) { updateTableColumnsForFlass(clazz); } else { createTableForClass(clazz); } } private void createTableForClass(Class<?> clazz) throws SQLException { StringBuilder sb = new StringBuilder(); sb.append("CREATE TABLE "); sb.append(tableNameFor(clazz)); sb.append("("); sb.append("ID BIGINT GENERATED BY DEFAULT AS IDENTITY (START WITH 1) PRIMARY KEY"); for (Field f: clazz.getDeclaredFields()) { if (isPersistableAndNotId(f)) { String columnType = getStringColumnTypeFor(f.getType()); sb.append(","); sb.append(columnNameFor(f)); sb.append(" "); sb.append(columnType); } } sb.append(")"); System.out.println(sb.toString()); Connection conn = bedProvider.getConnection(); Statement st = conn.createStatement(); st.execute(sb.toString()); conn.close(); } private String columnNameFor(Field f) { return f.getName().toUpperCase(); } private boolean isPersistableAndNotId(Field f) { if (f.isAnnotationPresent(SleeperId.class)) { return false; } else if (f.isAnnotationPresent(DoNotSave.class)) { return false; } else if (java.lang.reflect.Modifier.isStatic(f.getModifiers())) { return false; } else if (!persistenceIsImplementedForClass(f.getType())) { return false; } else { return true; } } private boolean persistenceIsImplementedForClass(Class<?> clazz) { String columnType = getStringColumnTypeFor(clazz); if ((columnType == null) || ("".equals(columnType))) { return false; } else { return true; } } private String getStringColumnTypeFor(Class<?> clazz) { if (clazz == String.class) { return "VARCHAR(128)"; } else if (clazz == Long.class || clazz == Long.TYPE) { return "BIGINT"; } else if (clazz == Integer.class || clazz == Integer.TYPE) { return "INT"; } else if (clazz == Boolean.class || clazz == Boolean.TYPE) { return "BOOLEAN"; } else if (clazz == java.util.Date.class) { return "DATE"; } else { return null; } } private String tableNameFor(Class<?> clazz) { return clazz.getSimpleName().toUpperCase(); } private void updateTableColumnsForFlass(Class<?> clazz) throws SQLException { for (Field f: clazz.getDeclaredFields()) { if (isPersistableAndNotId(f)) { if (!existsColumnFor(f)) { createColumnFor(f); } } } } private boolean existsColumnFor(Field f) throws SQLException { boolean exists; Connection conn = bedProvider.getConnection(); DatabaseMetaData metadata = conn.getMetaData(); ResultSet rs = metadata.getColumns(null, null, tableNameFor(f.getDeclaringClass()), columnNameFor(f)); if (rs.next()) { exists = true; } else { exists = false; } conn.close(); return exists; } private void createColumnFor(Field f) throws SQLException { StringBuilder sb = new StringBuilder(); sb.append("ALTER TABLE "); sb.append(tableNameFor(f.getDeclaringClass())); sb.append(" ADD "); sb.append(columnNameFor(f)); sb.append(" "); sb.append(getStringColumnTypeFor(f.getType())); System.out.println(sb.toString()); Connection conn = bedProvider.getConnection(); Statement st = conn.createStatement(); st.execute(sb.toString()); conn.close(); } private boolean existsTableForClass(Class<?> clazz) throws SQLException { boolean exists; Connection conn = bedProvider.getConnection(); DatabaseMetaData metadata = conn.getMetaData(); ResultSet rs = metadata.getTables(null, null, tableNameFor(clazz), null); if (rs.next()) { exists = true; } else { exists = false; } conn.close(); return exists; } }
src/pablosaraiva/gotobed/GoToBed.java
package pablosaraiva.gotobed; import java.lang.reflect.Field; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.Set; import org.reflections.Reflections; import pablosaraiva.gotobed.annotations.DoNotSave; import pablosaraiva.gotobed.annotations.Sleeper; import pablosaraiva.gotobed.annotations.SleeperId; public class GoToBed { private BedProvider bedProvider; public GoToBed(BedProvider bedProvider) { this.bedProvider = bedProvider; Reflections reflections = new Reflections(); Set<Class<?>> sleeperClasses = reflections.getTypesAnnotatedWith(Sleeper.class); for (Class<?> clazz: sleeperClasses) { try { updateTable(clazz); } catch (SQLException e) { e.printStackTrace(); } } } public void sleep(Object obj) throws SQLException { if (hasId(obj)) { update(obj); } else { insert(obj); } } private void insert(Object obj) throws SQLException { Connection conn = bedProvider.getConnection(); // StringBuilder sb = new StringBuilder(); // sb.append("INSERT INTO " ) System.out.println("will insert"); conn.close(); } private void update(Object obj) { System.out.println("will update"); } private boolean hasId(Object obj) { for (Field f: obj.getClass().getDeclaredFields()) { f.setAccessible(true); if (f.isAnnotationPresent(SleeperId.class)) { try { f.setAccessible(true); Long id = (Long) f.get(obj); if (id != null && id > 0) { return true; } } catch (IllegalArgumentException | IllegalAccessException e) { e.printStackTrace(); } } f.setAccessible(false); } return false; } private void updateTable(Class<?> clazz) throws SQLException { if (existsTableForClass(clazz)) { updateTableColumnsForFlass(clazz); } else { createTableForClass(clazz); } } private void createTableForClass(Class<?> clazz) throws SQLException { StringBuilder sb = new StringBuilder(); sb.append("CREATE TABLE "); sb.append(tableNameFor(clazz)); sb.append("("); sb.append("ID BIGINT GENERATED BY DEFAULT AS IDENTITY (START WITH 1) PRIMARY KEY"); for (Field f: clazz.getDeclaredFields()) { if (isPersistableAndNotId(f)) { String columnType = getStringColumnTypeFor(f.getType()); sb.append(","); sb.append(columnNameFor(f)); sb.append(" "); sb.append(columnType); } } sb.append(")"); System.out.println(sb.toString()); Connection conn = bedProvider.getConnection(); Statement st = conn.createStatement(); st.execute(sb.toString()); conn.close(); } private String columnNameFor(Field f) { return f.getName().toUpperCase(); } private boolean isPersistableAndNotId(Field f) { if (f.isAnnotationPresent(SleeperId.class)) { return false; } else if (f.isAnnotationPresent(DoNotSave.class)) { return false; } else if (java.lang.reflect.Modifier.isStatic(f.getModifiers())) { return false; } else if (!persistenceIsImplementedForClass(f.getType())) { return false; } else { return true; } } private boolean persistenceIsImplementedForClass(Class<?> clazz) { String columnType = getStringColumnTypeFor(clazz); if ((columnType == null) || ("".equals(columnType))) { return false; } else { return true; } } private String getStringColumnTypeFor(Class<?> clazz) { if (clazz == String.class) { return "VARCHAR(128)"; } else if (clazz == Long.class || clazz == Long.TYPE) { return "BIGINT"; } else if (clazz == Integer.class || clazz == Integer.TYPE) { return "INT"; } else if (clazz == Boolean.class || clazz == Boolean.TYPE) { return "BOOLEAN"; } else if (clazz == java.util.Date.class) { return "DATE"; } else { return null; } } private String tableNameFor(Class<?> clazz) { return clazz.getSimpleName().toUpperCase(); } private void updateTableColumnsForFlass(Class<?> clazz) throws SQLException { for (Field f: clazz.getDeclaredFields()) { if (isPersistableAndNotId(f)) { if (!existsColumnFor(f)) { createColumnFor(f); } } } } private boolean existsColumnFor(Field f) throws SQLException { boolean exists; Connection conn = bedProvider.getConnection(); Statement st = conn.createStatement(); ResultSet rs = st.executeQuery("SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = '"+tableNameFor(f.getDeclaringClass())+"' AND COLUMN_NAME = '"+columnNameFor(f)+"'"); if (rs.next()) { exists = true; } else { exists = false; } conn.close(); return exists; } private void createColumnFor(Field f) throws SQLException { StringBuilder sb = new StringBuilder(); sb.append("ALTER TABLE "); sb.append(tableNameFor(f.getDeclaringClass())); sb.append(" ADD "); sb.append(columnNameFor(f)); sb.append(" "); sb.append(getStringColumnTypeFor(f.getType())); System.out.println(sb.toString()); Connection conn = bedProvider.getConnection(); Statement st = conn.createStatement(); st.execute(sb.toString()); conn.close(); } private boolean existsTableForClass(Class<?> clazz) throws SQLException { boolean exists; Connection conn = bedProvider.getConnection(); Statement st = conn.createStatement(); ResultSet rs = st.executeQuery("SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = '"+tableNameFor(clazz)+"'"); if (rs.next()) { exists = true; } else { exists = false; } conn.close(); return exists; } }
Refactor for a better use of table metadata
src/pablosaraiva/gotobed/GoToBed.java
Refactor for a better use of table metadata
<ide><path>rc/pablosaraiva/gotobed/GoToBed.java <ide> package pablosaraiva.gotobed; <ide> <ide> import java.lang.reflect.Field; <del>import java.sql.Connection; <del>import java.sql.ResultSet; <del>import java.sql.SQLException; <del>import java.sql.Statement; <add>import java.sql.*; <ide> import java.util.Set; <ide> <ide> import org.reflections.Reflections; <ide> public class GoToBed { <ide> private BedProvider bedProvider; <ide> <del> public GoToBed(BedProvider bedProvider) { this.bedProvider = bedProvider; <add> public GoToBed(BedProvider bedProvider) { <add> this.bedProvider = bedProvider; <ide> <ide> Reflections reflections = new Reflections(); <ide> Set<Class<?>> sleeperClasses = reflections.getTypesAnnotatedWith(Sleeper.class); <ide> <ide> private void insert(Object obj) throws SQLException { <ide> Connection conn = bedProvider.getConnection(); <del>// StringBuilder sb = new StringBuilder(); <del>// sb.append("INSERT INTO " ) <add> StringBuilder sb = new StringBuilder(); <add> sb.append("INSERT INTO "); <add> sb.append(tableNameFor(obj.getClass())); <add> sb.append("ID"); <add>// for (Field f: obj.getClass().getDeclaredFields()) { <add>// <add>// } <ide> System.out.println("will insert"); <ide> conn.close(); <ide> } <ide> private boolean existsColumnFor(Field f) throws SQLException { <ide> boolean exists; <ide> Connection conn = bedProvider.getConnection(); <del> Statement st = conn.createStatement(); <del> ResultSet rs = st.executeQuery("SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = '"+tableNameFor(f.getDeclaringClass())+"' AND COLUMN_NAME = '"+columnNameFor(f)+"'"); <add> DatabaseMetaData metadata = conn.getMetaData(); <add> ResultSet rs = metadata.getColumns(null, null, tableNameFor(f.getDeclaringClass()), columnNameFor(f)); <ide> if (rs.next()) { <ide> exists = true; <ide> } else { <ide> private boolean existsTableForClass(Class<?> clazz) throws SQLException { <ide> boolean exists; <ide> Connection conn = bedProvider.getConnection(); <del> Statement st = conn.createStatement(); <del> ResultSet rs = st.executeQuery("SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = '"+tableNameFor(clazz)+"'"); <add> DatabaseMetaData metadata = conn.getMetaData(); <add> ResultSet rs = metadata.getTables(null, null, tableNameFor(clazz), null); <ide> if (rs.next()) { <ide> exists = true; <ide> } else {
Java
apache-2.0
6ebec471d94e134a6aa4bce1ed45f8f3f856e0e7
0
reportportal/commons-model
/* * Copyright 2021 EPAM Systems * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.epam.ta.reportportal.ws.model.launch.cluster; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import java.util.Map; /** * @author <a href="mailto:[email protected]">Ivan Budayeu</a> */ @JsonInclude(JsonInclude.Include.NON_NULL) public class ClusterInfoResource { @JsonProperty(value = "id") private Long id; @JsonProperty(value = "index") private Long index; @JsonProperty(value = "launchId") private Long launchId; @JsonProperty(value = "message") private String message; @JsonProperty(value = "metadata") private Map<String, Object> metadata; public ClusterInfoResource() { } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Long getIndex() { return index; } public void setIndex(Long index) { this.index = index; } public Long getLaunchId() { return launchId; } public void setLaunchId(Long launchId) { this.launchId = launchId; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } public Map<String, Object> getMetadata() { return metadata; } public void setMetadata(Map<String, Object> metadata) { this.metadata = metadata; } }
src/main/java/com/epam/ta/reportportal/ws/model/launch/cluster/ClusterInfoResource.java
/* * Copyright 2021 EPAM Systems * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.epam.ta.reportportal.ws.model.launch.cluster; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import java.util.Map; /** * @author <a href="mailto:[email protected]">Ivan Budayeu</a> */ @JsonInclude(JsonInclude.Include.NON_NULL) public class ClusterInfoResource { @JsonProperty(value = "id") private Long id; @JsonProperty(value = "launchId") private Long launchId; @JsonProperty(value = "message") private String message; @JsonProperty(value = "metadata") private Map<String, Object> metadata; public ClusterInfoResource() { } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Long getLaunchId() { return launchId; } public void setLaunchId(Long launchId) { this.launchId = launchId; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } public Map<String, Object> getMetadata() { return metadata; } public void setMetadata(Map<String, Object> metadata) { this.metadata = metadata; } }
EPMRPP-68949 || Cluster resource index (#305)
src/main/java/com/epam/ta/reportportal/ws/model/launch/cluster/ClusterInfoResource.java
EPMRPP-68949 || Cluster resource index (#305)
<ide><path>rc/main/java/com/epam/ta/reportportal/ws/model/launch/cluster/ClusterInfoResource.java <ide> @JsonProperty(value = "id") <ide> private Long id; <ide> <add> @JsonProperty(value = "index") <add> private Long index; <add> <ide> @JsonProperty(value = "launchId") <ide> private Long launchId; <ide> <ide> <ide> public void setId(Long id) { <ide> this.id = id; <add> } <add> <add> public Long getIndex() { <add> return index; <add> } <add> <add> public void setIndex(Long index) { <add> this.index = index; <ide> } <ide> <ide> public Long getLaunchId() {
Java
apache-2.0
error: pathspec 'java/vernacular/value/trunk/src/main/java/org/ppwcode/vernacular/value_III/ValueHelpers.java' did not match any file(s) known to git
59c93d9b8d1c23dfbc5f1e9f8e95dffc1134ec34
1
jandppw/ppwcode-recovered-from-google-code,jandppw/ppwcode-recovered-from-google-code,jandockx/ppwcode-recovered-from-google-code,jandppw/ppwcode-recovered-from-google-code,jandockx/ppwcode-recovered-from-google-code,jandockx/ppwcode-recovered-from-google-code,jandockx/ppwcode-recovered-from-google-code,jandppw/ppwcode-recovered-from-google-code,jandockx/ppwcode-recovered-from-google-code,jandppw/ppwcode-recovered-from-google-code,jandppw/ppwcode-recovered-from-google-code,jandockx/ppwcode-recovered-from-google-code
/*<license> Copyright 2004 - $Date$ by PeopleWare n.v.. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. </license>*/ package org.ppwcode.vernacular.value_III; import java.beans.PropertyEditor; import java.beans.PropertyEditorManager; /** * This class contains static convenience methods for working * with values. This methods do not use the {@link Value} * interface, because there are many classes in the outside * world that also use these patterns, that do not implement * these proprietary interfaces. * * @author Jan Dockx * @author PeopleWare n.v. */ public abstract class ValueHelpers { /*<section name="Meta Information">*/ //------------------------------------------------------------------ /** {@value} */ public static final String CVS_REVISION = "$Revision$"; //$NON-NLS-1$ /** {@value} */ public static final String CVS_DATE = "$Date$"; //$NON-NLS-1$ /** {@value} */ public static final String CVS_STATE = "$State$"; //$NON-NLS-1$ /** {@value} */ public static final String CVS_TAG = "$Name$"; //$NON-NLS-1$ /*</section>*/ /*<construction>*/ //------------------------------------------------------------------ private ValueHelpers() { // NOP } /*</construction>*/ /** * Is one value {@link Object#equals(java.lang.Object) equal} * to another, if <code>null</code> is also allowed as value * for a property. * * @return (one == null) * ? (other == null) * : one.equals(other); * * @idea (jand) move to ppw-util or toryt */ public static boolean eqn(final Object one, final Object other) { return (one == null) ? (other == null) : one.equals(other); } /** * Assert that <code>p</code> is needed at least to make * <code>result</code> <code>true</code>. * * @param p * A boolean expression that has to be <code>true</code> at least * to make <code>result</code> <code>true</code>. * @param result * The result to make <code>true</code>. * @return ! p ? ! result; */ public static boolean assertAtLeast(final boolean p, final boolean result) { return p || (!result); } /** * Register packages from this library as * path for {@link PropertyEditor PropertyEditors} with * the {@link PropertyEditorManager}. */ public static void registerPropertyEditors() { String[] oldPath = PropertyEditorManager.getEditorSearchPath(); String[] newPath = new String[oldPath.length + 1]; System.arraycopy(oldPath, 0, newPath, 0, oldPath.length); String currentPackageName = ValueHelpers.class.getPackage().getName(); newPath[newPath.length - 1] = currentPackageName; PropertyEditorManager.setEditorSearchPath(newPath); } }
java/vernacular/value/trunk/src/main/java/org/ppwcode/vernacular/value_III/ValueHelpers.java
name change, in line with ppwcode naming vernacular
java/vernacular/value/trunk/src/main/java/org/ppwcode/vernacular/value_III/ValueHelpers.java
name change, in line with ppwcode naming vernacular
<ide><path>ava/vernacular/value/trunk/src/main/java/org/ppwcode/vernacular/value_III/ValueHelpers.java <add>/*<license> <add>Copyright 2004 - $Date$ by PeopleWare n.v.. <add> <add>Licensed under the Apache License, Version 2.0 (the "License"); <add>you may not use this file except in compliance with the License. <add>You may obtain a copy of the License at <add> <add> http://www.apache.org/licenses/LICENSE-2.0 <add> <add>Unless required by applicable law or agreed to in writing, software <add>distributed under the License is distributed on an "AS IS" BASIS, <add>WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <add>See the License for the specific language governing permissions and <add>limitations under the License. <add></license>*/ <add> <add>package org.ppwcode.vernacular.value_III; <add> <add> <add>import java.beans.PropertyEditor; <add>import java.beans.PropertyEditorManager; <add> <add> <add>/** <add> * This class contains static convenience methods for working <add> * with values. This methods do not use the {@link Value} <add> * interface, because there are many classes in the outside <add> * world that also use these patterns, that do not implement <add> * these proprietary interfaces. <add> * <add> * @author Jan Dockx <add> * @author PeopleWare n.v. <add> */ <add>public abstract class ValueHelpers { <add> <add> /*<section name="Meta Information">*/ <add> //------------------------------------------------------------------ <add> <add> /** {@value} */ <add> public static final String CVS_REVISION = "$Revision$"; //$NON-NLS-1$ <add> /** {@value} */ <add> public static final String CVS_DATE = "$Date$"; //$NON-NLS-1$ <add> /** {@value} */ <add> public static final String CVS_STATE = "$State$"; //$NON-NLS-1$ <add> /** {@value} */ <add> public static final String CVS_TAG = "$Name$"; //$NON-NLS-1$ <add> <add> /*</section>*/ <add> <add> <add> <add> /*<construction>*/ <add> //------------------------------------------------------------------ <add> <add> private ValueHelpers() { <add> // NOP <add> } <add> <add> /*</construction>*/ <add> <add> <add> /** <add> * Is one value {@link Object#equals(java.lang.Object) equal} <add> * to another, if <code>null</code> is also allowed as value <add> * for a property. <add> * <add> * @return (one == null) <add> * ? (other == null) <add> * : one.equals(other); <add> * <add> * @idea (jand) move to ppw-util or toryt <add> */ <add> public static boolean eqn(final Object one, final Object other) { <add> return (one == null) ? (other == null) : one.equals(other); <add> } <add> <add> <add> /** <add> * Assert that <code>p</code> is needed at least to make <add> * <code>result</code> <code>true</code>. <add> * <add> * @param p <add> * A boolean expression that has to be <code>true</code> at least <add> * to make <code>result</code> <code>true</code>. <add> * @param result <add> * The result to make <code>true</code>. <add> * @return ! p ? ! result; <add> */ <add> public static boolean assertAtLeast(final boolean p, final boolean result) { <add> return p || (!result); <add> } <add> <add> /** <add> * Register packages from this library as <add> * path for {@link PropertyEditor PropertyEditors} with <add> * the {@link PropertyEditorManager}. <add> */ <add> public static void registerPropertyEditors() { <add> String[] oldPath = PropertyEditorManager.getEditorSearchPath(); <add> String[] newPath = new String[oldPath.length + 1]; <add> System.arraycopy(oldPath, 0, newPath, 0, oldPath.length); <add> String currentPackageName = ValueHelpers.class.getPackage().getName(); <add> newPath[newPath.length - 1] = currentPackageName; <add> PropertyEditorManager.setEditorSearchPath(newPath); <add> } <add> <add>}
Java
apache-2.0
2bdffe812d9cc2f4952cf203986cbde0e41311c5
0
Tony-Zhang03/hermes,lejingw/hermes,lejingw/hermes,lejingw/hermes,sdgdsffdsfff/hermes,fengshao0907/hermes,fengshao0907/hermes,sdgdsffdsfff/hermes,Tony-Zhang03/hermes,Tony-Zhang03/hermes,sdgdsffdsfff/hermes,lejingw/hermes,fengshao0907/hermes,sdgdsffdsfff/hermes,Tony-Zhang03/hermes,fengshao0907/hermes
package com.ctrip.hermes.metaserver.rest.resource; import io.confluent.kafka.schemaregistry.client.rest.RestService; import java.util.Map; import javax.inject.Singleton; import javax.ws.rs.DefaultValue; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.ws.rs.core.Response.Status; import org.apache.http.HttpResponse; import org.apache.http.client.fluent.Request; import org.apache.http.util.EntityUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.alibaba.fastjson.JSON; import com.ctrip.hermes.core.utils.PlexusComponentLocator; import com.ctrip.hermes.core.utils.StringUtils; import com.ctrip.hermes.meta.entity.Codec; import com.ctrip.hermes.metaserver.meta.MetaHolder; import com.ctrip.hermes.metaserver.rest.commons.RestException; @Path("/schema/register") @Singleton @Produces(MediaType.APPLICATION_JSON) public class SchemaRegisterResource { private static final Logger log = LoggerFactory.getLogger(SchemaRegisterResource.class); private MetaHolder m_metaHolder = PlexusComponentLocator.lookup(MetaHolder.class); @GET @Path("get") public Response getLatestSchemaBySubject(@QueryParam("subject") String subject) { if (StringUtils.isBlank(subject)) { throw new RestException("Subject is required.", Status.BAD_REQUEST); } Codec codec = m_metaHolder.getMeta().getCodecs().get("avro"); if (codec != null) { try { String url = codec.findProperty("schema.registry.url").getValue(); if (StringUtils.isBlank(url)) { throw new RestException("Can not find schema registry url in codec.", Status.INTERNAL_SERVER_ERROR); } url = String.format("%s/subjects/%s/versions/latest", url, subject); HttpResponse response = Request.Get(url).execute().returnResponse(); String json = EntityUtils.toString(response.getEntity()); return Response.status(response.getStatusLine().getStatusCode()).entity(json).build(); } catch (Exception e) { throw new RestException("Register schema failed.", e); } } return Response.status(Status.NOT_FOUND).entity("No avro codec was found!").build(); } @POST public Response registerSchema(String content) { @SuppressWarnings("unchecked") Map<String, String> m = JSON.parseObject(content, Map.class); if (StringUtils.isBlank(m.get("schema")) || StringUtils.isBlank(m.get("subject"))) { throw new RestException("Schema and subject is required.", Status.BAD_REQUEST); } Codec codec = m_metaHolder.getMeta().getCodecs().get("avro"); if (codec != null) { try { RestService restService = new RestService(codec.findProperty("schema.registry.url").getValue()); int id = restService.registerSchema(m.get("schema"), m.get("subject")); return Response.status(Status.OK).entity(id).build(); } catch (Exception e) { throw new RestException("Register schema failed.", e); } } log.warn("Register schema failed. Codec avro not found."); return Response.status(Status.NOT_FOUND).entity("No avro codec was found!").build(); } @GET public Response getSchemaById(@QueryParam("id") @DefaultValue("-1") int id) { Codec codec = m_metaHolder.getMeta().getCodecs().get("avro"); if (codec != null) { try { RestService restService = new RestService(codec.findProperty("schema.registry.url").getValue()); return Response.status(Status.OK).entity(restService.getId(id).getSchemaString()).build(); } catch (Exception e) { throw new RestException("Get schema string failed.", e); } } log.warn("Get schema string failed. Codec avro not found."); return Response.status(Status.NOT_FOUND).entity("No avro codec was found!").build(); } }
hermes-metaserver/src/main/java/com/ctrip/hermes/metaserver/rest/resource/SchemaRegisterResource.java
package com.ctrip.hermes.metaserver.rest.resource; import io.confluent.kafka.schemaregistry.client.rest.RestService; import java.util.Map; import javax.inject.Singleton; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.ws.rs.core.Response.Status; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.alibaba.fastjson.JSON; import com.ctrip.hermes.core.utils.PlexusComponentLocator; import com.ctrip.hermes.core.utils.StringUtils; import com.ctrip.hermes.meta.entity.Codec; import com.ctrip.hermes.metaserver.meta.MetaHolder; import com.ctrip.hermes.metaserver.rest.commons.RestException; @Path("/schema/register") @Singleton @Produces(MediaType.APPLICATION_JSON) public class SchemaRegisterResource { private static final Logger log = LoggerFactory.getLogger(SchemaRegisterResource.class); private MetaHolder m_metaHolder = PlexusComponentLocator.lookup(MetaHolder.class); @POST public Response registerSchema(String content) { @SuppressWarnings("unchecked") Map<String, String> m = JSON.parseObject(content, Map.class); if (StringUtils.isBlank(m.get("schema")) || StringUtils.isBlank(m.get("subject"))) { throw new RestException("Schema and subject is required.", Status.BAD_REQUEST); } Codec codec = m_metaHolder.getMeta().getCodecs().get("avro"); if (codec != null) { try { RestService restService = new RestService(codec.findProperty("schema.registry.url").getValue()); int id = restService.registerSchema(m.get("schema"), m.get("subject")); return Response.status(Status.OK).entity(id).build(); } catch (Exception e) { throw new RestException("Register schema failed.", e); } } log.warn("Register schema failed. Codec avro not found."); return Response.status(Status.NOT_FOUND).build(); } @GET public Response getSchemaById(@QueryParam("id") int id) { Codec codec = m_metaHolder.getMeta().getCodecs().get("avro"); if (codec != null) { try { RestService restService = new RestService(codec.findProperty("schema.registry.url").getValue()); return Response.status(Status.OK).entity(restService.getId(id).getSchemaString()).build(); } catch (Exception e) { throw new RestException("Get schema string failed.", e); } } log.warn("Get schema string failed. Codec avro not found."); return Response.status(Status.NOT_FOUND).build(); } }
add find schema api for meta-server
hermes-metaserver/src/main/java/com/ctrip/hermes/metaserver/rest/resource/SchemaRegisterResource.java
add find schema api for meta-server
<ide><path>ermes-metaserver/src/main/java/com/ctrip/hermes/metaserver/rest/resource/SchemaRegisterResource.java <ide> import java.util.Map; <ide> <ide> import javax.inject.Singleton; <add>import javax.ws.rs.DefaultValue; <ide> import javax.ws.rs.GET; <ide> import javax.ws.rs.POST; <ide> import javax.ws.rs.Path; <ide> import javax.ws.rs.core.Response; <ide> import javax.ws.rs.core.Response.Status; <ide> <add>import org.apache.http.HttpResponse; <add>import org.apache.http.client.fluent.Request; <add>import org.apache.http.util.EntityUtils; <ide> import org.slf4j.Logger; <ide> import org.slf4j.LoggerFactory; <ide> <ide> private static final Logger log = LoggerFactory.getLogger(SchemaRegisterResource.class); <ide> <ide> private MetaHolder m_metaHolder = PlexusComponentLocator.lookup(MetaHolder.class); <add> <add> @GET <add> @Path("get") <add> public Response getLatestSchemaBySubject(@QueryParam("subject") String subject) { <add> if (StringUtils.isBlank(subject)) { <add> throw new RestException("Subject is required.", Status.BAD_REQUEST); <add> } <add> Codec codec = m_metaHolder.getMeta().getCodecs().get("avro"); <add> if (codec != null) { <add> try { <add> String url = codec.findProperty("schema.registry.url").getValue(); <add> if (StringUtils.isBlank(url)) { <add> throw new RestException("Can not find schema registry url in codec.", Status.INTERNAL_SERVER_ERROR); <add> } <add> url = String.format("%s/subjects/%s/versions/latest", url, subject); <add> HttpResponse response = Request.Get(url).execute().returnResponse(); <add> String json = EntityUtils.toString(response.getEntity()); <add> return Response.status(response.getStatusLine().getStatusCode()).entity(json).build(); <add> } catch (Exception e) { <add> throw new RestException("Register schema failed.", e); <add> } <add> } <add> return Response.status(Status.NOT_FOUND).entity("No avro codec was found!").build(); <add> } <ide> <ide> @POST <ide> public Response registerSchema(String content) { <ide> } <ide> } <ide> log.warn("Register schema failed. Codec avro not found."); <del> return Response.status(Status.NOT_FOUND).build(); <add> return Response.status(Status.NOT_FOUND).entity("No avro codec was found!").build(); <ide> } <ide> <ide> @GET <del> public Response getSchemaById(@QueryParam("id") int id) { <add> public Response getSchemaById(@QueryParam("id") @DefaultValue("-1") int id) { <ide> Codec codec = m_metaHolder.getMeta().getCodecs().get("avro"); <ide> if (codec != null) { <ide> try { <ide> } <ide> } <ide> log.warn("Get schema string failed. Codec avro not found."); <del> return Response.status(Status.NOT_FOUND).build(); <add> return Response.status(Status.NOT_FOUND).entity("No avro codec was found!").build(); <ide> } <ide> }
Java
apache-2.0
1dae69b10c05336c49046bcab619c77f6e25d647
0
datastax/java-driver,datastax/java-driver
/* * Copyright DataStax, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.datastax.oss.driver.api.core.cql; import com.datastax.oss.driver.api.core.Cluster; import com.datastax.oss.driver.api.core.CqlIdentifier; import com.datastax.oss.driver.api.testinfra.CassandraRequirement; import com.datastax.oss.driver.api.testinfra.ccm.CcmRule; import com.datastax.oss.driver.api.testinfra.cluster.ClusterRule; import com.datastax.oss.driver.api.testinfra.cluster.ClusterUtils; import com.datastax.oss.driver.categories.ParallelizableTests; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.experimental.categories.Category; import org.junit.rules.TestName; import static org.assertj.core.api.Assertions.assertThat; @Category(ParallelizableTests.class) public class BoundStatementIT { @Rule public CcmRule ccm = CcmRule.getInstance(); @Rule public ClusterRule cluster = new ClusterRule(ccm, "request.page-size = 20"); @Rule public TestName name = new TestName(); private static final int VALUE = 7; @Before public void setupSchema() { // table with simple primary key, single cell. cluster .session() .execute( SimpleStatement.builder("CREATE TABLE IF NOT EXISTS test2 (k text primary key, v0 int)") .withConfigProfile(cluster.slowProfile()) .build()); } @Test(expected = IllegalStateException.class) public void should_not_allow_unset_value_when_protocol_less_than_v4() { try (Cluster<CqlSession> v3Cluster = ClusterUtils.newCluster(ccm, "protocol.version = V3")) { CqlIdentifier keyspace = cluster.keyspace(); CqlSession session = v3Cluster.connect(keyspace); PreparedStatement prepared = session.prepare("INSERT INTO test2 (k, v0) values (?, ?)"); BoundStatement boundStatement = prepared.boundStatementBuilder().setString(0, name.getMethodName()).unset(1).build(); session.execute(boundStatement); } } @Test @CassandraRequirement(min = "2.2") public void should_not_write_tombstone_if_value_is_implicitly_unset() { PreparedStatement prepared = cluster.session().prepare("INSERT INTO test2 (k, v0) values (?, ?)"); cluster.session().execute(prepared.bind(name.getMethodName(), VALUE)); BoundStatement boundStatement = prepared.boundStatementBuilder().setString(0, name.getMethodName()).build(); verifyUnset(boundStatement); } @Test @CassandraRequirement(min = "2.2") public void should_write_tombstone_if_value_is_explicitly_unset() { PreparedStatement prepared = cluster.session().prepare("INSERT INTO test2 (k, v0) values (?, ?)"); cluster.session().execute(prepared.bind(name.getMethodName(), VALUE)); BoundStatement boundStatement = prepared .boundStatementBuilder() .setString(0, name.getMethodName()) .setInt(1, VALUE + 1) // set initially, will be unset later .build(); verifyUnset(boundStatement.unset(1)); } @Test @CassandraRequirement(min = "2.2") public void should_write_tombstone_if_value_is_explicitly_unset_on_builder() { PreparedStatement prepared = cluster.session().prepare("INSERT INTO test2 (k, v0) values (?, ?)"); cluster.session().execute(prepared.bind(name.getMethodName(), VALUE)); BoundStatement boundStatement = prepared .boundStatementBuilder() .setString(0, name.getMethodName()) .setInt(1, VALUE + 1) // set initially, will be unset later .unset(1) .build(); verifyUnset(boundStatement); } @Test public void should_have_empty_result_definitions_for_update_query() { PreparedStatement prepared = cluster.session().prepare("INSERT INTO test2 (k, v0) values (?, ?)"); assertThat(prepared.getResultSetDefinitions()).hasSize(0); ResultSet rs = cluster.session().execute(prepared.bind(name.getMethodName(), VALUE)); assertThat(rs.getColumnDefinitions()).hasSize(0); } private void verifyUnset(BoundStatement boundStatement) { cluster.session().execute(boundStatement.unset(1)); // Verify that no tombstone was written by reading data back and ensuring initial value is retained. ResultSet result = cluster .session() .execute( SimpleStatement.builder("SELECT v0 from test2 where k = ?") .addPositionalValue(name.getMethodName()) .build()); Row row = result.iterator().next(); assertThat(row.getInt(0)).isEqualTo(VALUE); } }
integration-tests/src/test/java/com/datastax/oss/driver/api/core/cql/BoundStatementIT.java
/* * Copyright DataStax, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.datastax.oss.driver.api.core.cql; import com.datastax.oss.driver.api.core.Cluster; import com.datastax.oss.driver.api.core.CqlIdentifier; import com.datastax.oss.driver.api.testinfra.CassandraRequirement; import com.datastax.oss.driver.api.testinfra.ccm.CcmRule; import com.datastax.oss.driver.api.testinfra.cluster.ClusterRule; import com.datastax.oss.driver.api.testinfra.cluster.ClusterUtils; import com.datastax.oss.driver.categories.ParallelizableTests; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.experimental.categories.Category; import org.junit.rules.TestName; import static org.assertj.core.api.Assertions.assertThat; @Category(ParallelizableTests.class) public class BoundStatementIT { @Rule public CcmRule ccm = CcmRule.getInstance(); @Rule public ClusterRule cluster = new ClusterRule(ccm, "request.page-size = 20"); @Rule public TestName name = new TestName(); private static final int VALUE = 7; @Before public void setupSchema() { // table with simple primary key, single cell. cluster .session() .execute( SimpleStatement.builder("CREATE TABLE IF NOT EXISTS test2 (k text primary key, v0 int)") .withConfigProfile(cluster.slowProfile()) .build()); } @Test(expected = IllegalStateException.class) public void should_not_allow_unset_value_when_protocol_less_than_v4() { try (Cluster<CqlSession> v3Cluster = ClusterUtils.newCluster(ccm, "protocol.version = V3")) { CqlIdentifier keyspace = cluster.keyspace(); CqlSession session = v3Cluster.connect(keyspace); PreparedStatement prepared = session.prepare("INSERT INTO test2 (k, v0) values (?, ?)"); BoundStatement boundStatement = prepared.boundStatementBuilder().setString(0, name.getMethodName()).unset(1).build(); session.execute(boundStatement); } } @Test @CassandraRequirement(min = "2.2") public void should_not_write_tombstone_if_value_is_implicitly_unset() { PreparedStatement prepared = cluster.session().prepare("INSERT INTO test2 (k, v0) values (?, ?)"); cluster.session().execute(prepared.bind(name.getMethodName(), VALUE)); BoundStatement boundStatement = prepared.boundStatementBuilder().setString(0, name.getMethodName()).build(); verifyUnset(boundStatement); } @Test @CassandraRequirement(min = "2.2") public void should_write_tombstone_if_value_is_explicitly_unset() { PreparedStatement prepared = cluster.session().prepare("INSERT INTO test2 (k, v0) values (?, ?)"); cluster.session().execute(prepared.bind(name.getMethodName(), VALUE)); BoundStatement boundStatement = prepared .boundStatementBuilder() .setString(0, name.getMethodName()) .setInt(1, VALUE + 1) // set initially, will be unset later .build(); verifyUnset(boundStatement.unset(1)); } @Test @CassandraRequirement(min = "2.2") public void should_write_tombstone_if_value_is_explicitly_unset_on_builder() { PreparedStatement prepared = cluster.session().prepare("INSERT INTO test2 (k, v0) values (?, ?)"); cluster.session().execute(prepared.bind(name.getMethodName(), VALUE)); BoundStatement boundStatement = prepared .boundStatementBuilder() .setString(0, name.getMethodName()) .setInt(1, VALUE + 1) // set initially, will be unset later .unset(1) .build(); verifyUnset(boundStatement); } private void verifyUnset(BoundStatement boundStatement) { cluster.session().execute(boundStatement.unset(1)); // Verify that no tombstone was written by reading data back and ensuring initial value is retained. ResultSet result = cluster .session() .execute( SimpleStatement.builder("SELECT v0 from test2 where k = ?") .addPositionalValue(name.getMethodName()) .build()); Row row = result.iterator().next(); assertThat(row.getInt(0)).isEqualTo(VALUE); } }
Add integration test for prepared update queries
integration-tests/src/test/java/com/datastax/oss/driver/api/core/cql/BoundStatementIT.java
Add integration test for prepared update queries
<ide><path>ntegration-tests/src/test/java/com/datastax/oss/driver/api/core/cql/BoundStatementIT.java <ide> verifyUnset(boundStatement); <ide> } <ide> <add> @Test <add> public void should_have_empty_result_definitions_for_update_query() { <add> PreparedStatement prepared = <add> cluster.session().prepare("INSERT INTO test2 (k, v0) values (?, ?)"); <add> <add> assertThat(prepared.getResultSetDefinitions()).hasSize(0); <add> <add> ResultSet rs = cluster.session().execute(prepared.bind(name.getMethodName(), VALUE)); <add> assertThat(rs.getColumnDefinitions()).hasSize(0); <add> } <add> <ide> private void verifyUnset(BoundStatement boundStatement) { <ide> cluster.session().execute(boundStatement.unset(1)); <ide>
Java
mit
error: pathspec 'Heaters.java' did not match any file(s) known to git
5051b395a44eea9289680d9c0f6acc01fab09f6a
1
linnumberone/LeetCode
public class Solution { public int findRadius(int[] houses, int[] heaters) { Arrays.sort(houses); Arrays.sort(heaters); int radius = 0; int i = 0; for(int house : houses) { while(i < heaters.length - 1 && heaters[i + 1] + heaters[i] <= 2 * house) { i++; } radius = Math.max(radius, Math.abs(house - heaters[i])); } return radius; } }
Heaters.java
Create Heaters.java
Heaters.java
Create Heaters.java
<ide><path>eaters.java <add>public class Solution { <add> public int findRadius(int[] houses, int[] heaters) { <add> Arrays.sort(houses); <add> Arrays.sort(heaters); <add> <add> int radius = 0; <add> int i = 0; <add> for(int house : houses) { <add> while(i < heaters.length - 1 && heaters[i + 1] + heaters[i] <= 2 * house) { <add> i++; <add> } <add> radius = Math.max(radius, Math.abs(house - heaters[i])); <add> } <add> return radius; <add> } <add>}
Java
bsd-2-clause
dc84219abf06041f2e3e50b7e096cce11e4028de
0
TehSAUCE/imagej,TehSAUCE/imagej,TehSAUCE/imagej,biovoxxel/imagej,biovoxxel/imagej,biovoxxel/imagej
/* * #%L * ImageJ software for multidimensional image processing and analysis. * %% * Copyright (C) 2009 - 2013 Board of Regents of the University of * Wisconsin-Madison, Broad Institute of MIT and Harvard, and Max Planck * Institute of Molecular Cell Biology and Genetics. * %% * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * The views and conclusions contained in the software and documentation are * those of the authors and should not be interpreted as representing official * policies, either expressed or implied, of any organization. * #L% */ package imagej.ui; import imagej.module.Module; import imagej.module.ModuleItem; import imagej.plugin.AbstractPreprocessorPlugin; import imagej.plugin.PreprocessorPlugin; import org.scijava.Priority; import org.scijava.plugin.Parameter; import org.scijava.plugin.Plugin; /** * The UI preprocessor automatically populates module {@link UserInterface} * inputs with the {@link UIService}'s default UI instance, if compatible. * * @author Curtis Rueden */ @Plugin(type = PreprocessorPlugin.class, priority = Priority.VERY_HIGH_PRIORITY) public class UIPreprocessor extends AbstractPreprocessorPlugin { @Parameter(required = false) private UIService uiService; // -- ModuleProcessor methods -- @Override public void process(final Module module) { if (uiService == null) return; // no UI service available final UserInterface ui = uiService.getDefaultUI(); if (ui == null) return; // no default UI for (final ModuleItem<?> input : module.getInfo().inputs()) { if (!input.isAutoFill()) continue; // cannot auto-fill this input final Class<?> type = input.getType(); if (type.isAssignableFrom(ui.getClass())) { // input is a compatible UI final String name = input.getName(); module.setInput(name, ui); module.setResolved(name, true); } } } }
core/ui/src/main/java/imagej/ui/UIPreprocessor.java
/* * #%L * ImageJ software for multidimensional image processing and analysis. * %% * Copyright (C) 2009 - 2013 Board of Regents of the University of * Wisconsin-Madison, Broad Institute of MIT and Harvard, and Max Planck * Institute of Molecular Cell Biology and Genetics. * %% * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * The views and conclusions contained in the software and documentation are * those of the authors and should not be interpreted as representing official * policies, either expressed or implied, of any organization. * #L% */ package imagej.ui; import imagej.module.Module; import imagej.module.ModuleItem; import imagej.plugin.AbstractPreprocessorPlugin; import imagej.plugin.PreprocessorPlugin; import org.scijava.Priority; import org.scijava.plugin.Parameter; import org.scijava.plugin.Plugin; /** * The UI preprocessor automatically populates module {@link UserInterface} * inputs with the {@link UIService}'s default UI instance, if compatible. * * @author Curtis Rueden */ @Plugin(type = PreprocessorPlugin.class, priority = Priority.VERY_HIGH_PRIORITY) public class UIPreprocessor extends AbstractPreprocessorPlugin { @Parameter(required = false) private UIService uiService; // -- ModuleProcessor methods -- @Override public void process(final Module module) { if (uiService == null) return; // no UI service available final UserInterface ui = uiService.getDefaultUI(); for (final ModuleItem<?> input : module.getInfo().inputs()) { if (!input.isAutoFill()) continue; // cannot auto-fill this input final Class<?> type = input.getType(); if (type.isAssignableFrom(ui.getClass())) { // input is a compatible UI final String name = input.getName(); module.setInput(name, ui); module.setResolved(name, true); } } } }
UIPreprocessor: fix bug with null defaultUI
core/ui/src/main/java/imagej/ui/UIPreprocessor.java
UIPreprocessor: fix bug with null defaultUI
<ide><path>ore/ui/src/main/java/imagej/ui/UIPreprocessor.java <ide> if (uiService == null) return; // no UI service available <ide> <ide> final UserInterface ui = uiService.getDefaultUI(); <add> if (ui == null) return; // no default UI <add> <ide> for (final ModuleItem<?> input : module.getInfo().inputs()) { <ide> if (!input.isAutoFill()) continue; // cannot auto-fill this input <ide> final Class<?> type = input.getType();
Java
apache-2.0
a281fdd7b5e6b13b1e370557c3f269c6b1048d7c
0
apache/logging-log4j2,apache/logging-log4j2,apache/logging-log4j2
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache license, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the license for the specific language governing permissions and * limitations under the license. */ package org.apache.log4j; import java.util.Enumeration; import java.util.HashMap; import java.util.Map; import org.apache.log4j.helpers.NullEnumeration; import org.apache.log4j.legacy.core.ContextUtil; import org.apache.log4j.or.ObjectRenderer; import org.apache.log4j.or.RendererSupport; import org.apache.log4j.spi.HierarchyEventListener; import org.apache.log4j.spi.LoggerFactory; import org.apache.log4j.spi.LoggerRepository; import org.apache.log4j.spi.RepositorySelector; import org.apache.logging.log4j.spi.LoggerContext; import org.apache.logging.log4j.util.Strings; /** * */ public final class LogManager { /** * @deprecated This variable is for internal use only. It will * become package protected in future versions. * */ @Deprecated public static final String DEFAULT_CONFIGURATION_FILE = "log4j.properties"; /** * @deprecated This variable is for internal use only. It will * become private in future versions. * */ @Deprecated public static final String DEFAULT_CONFIGURATION_KEY = "log4j.configuration"; /** * @deprecated This variable is for internal use only. It will * become private in future versions. * */ @Deprecated public static final String CONFIGURATOR_CLASS_KEY = "log4j.configuratorClass"; /** * @deprecated This variable is for internal use only. It will * become private in future versions. */ @Deprecated public static final String DEFAULT_INIT_OVERRIDE_KEY = "log4j.defaultInitOverride"; static final String DEFAULT_XML_CONFIGURATION_FILE = "log4j.xml"; private static final LoggerRepository REPOSITORY = new Repository(); private static final boolean isLog4jCore; static { boolean core = false; try { if (Class.forName("org.apache.logging.log4j.core.LoggerContext") != null) { core = true; } } catch (Exception ex) { // Ignore the exception; } isLog4jCore = core; } public static Logger getRootLogger() { return Category.getInstance(PrivateManager.getContext(), Strings.EMPTY); } public static Logger getLogger(final String name) { return Category.getInstance(PrivateManager.getContext(), name); } public static Logger getLogger(final Class<?> clazz) { return Category.getInstance(PrivateManager.getContext(), clazz.getName()); } public static Logger getLogger(final String name, final LoggerFactory factory) { return Category.getInstance(PrivateManager.getContext(), name); } public static Logger exists(final String name) { final LoggerContext ctx = PrivateManager.getContext(); if (!ctx.hasLogger(name)) { return null; } return Logger.getLogger(name); } @SuppressWarnings("rawtypes") public static Enumeration getCurrentLoggers() { return NullEnumeration.getInstance(); } static void reconfigure() { if (isLog4jCore) { final LoggerContext ctx = PrivateManager.getContext(); ContextUtil.reconfigure(ctx); } } /** * No-op implementation. */ public static void shutdown() { } /** * No-op implementation. */ public static void resetConfiguration() { } /** * No-op implementation. * @param selector The RepositorySelector. * @param guard prevents calls at the incorrect time. * @throws IllegalArgumentException if a parameter is invalid. */ public static void setRepositorySelector(final RepositorySelector selector, final Object guard) throws IllegalArgumentException { } public static LoggerRepository getLoggerRepository() { return REPOSITORY; } /** * The Repository. */ private static class Repository implements LoggerRepository, RendererSupport { private final Map<Class<?>, ObjectRenderer> rendererMap = new HashMap<>(); @Override public Map<Class<?>, ObjectRenderer> getRendererMap() { return rendererMap; } @Override public void addHierarchyEventListener(final HierarchyEventListener listener) { } @Override public boolean isDisabled(final int level) { return false; } @Override public void setThreshold(final Level level) { } @Override public void setThreshold(final String val) { } @Override public void emitNoAppenderWarning(final Category cat) { } @Override public Level getThreshold() { return Level.OFF; } @Override public Logger getLogger(final String name) { return Category.getInstance(PrivateManager.getContext(), name); } @Override public Logger getLogger(final String name, final LoggerFactory factory) { return Category.getInstance(PrivateManager.getContext(), name); } @Override public Logger getRootLogger() { return Category.getRoot(PrivateManager.getContext()); } @Override public Logger exists(final String name) { return LogManager.exists(name); } @Override public void shutdown() { } @Override @SuppressWarnings("rawtypes") public Enumeration getCurrentLoggers() { return NullEnumeration.getInstance(); } @Override @SuppressWarnings("rawtypes") public Enumeration getCurrentCategories() { return NullEnumeration.getInstance(); } @Override public void fireAddAppenderEvent(final Category logger, final Appender appender) { } @Override public void resetConfiguration() { } } /** * Internal LogManager. */ private static class PrivateManager extends org.apache.logging.log4j.LogManager { private static final String FQCN = LogManager.class.getName(); public static LoggerContext getContext() { return getContext(FQCN, false); } public static org.apache.logging.log4j.Logger getLogger(final String name) { return getLogger(FQCN, name); } } }
log4j-1.2-api/src/main/java/org/apache/log4j/LogManager.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache license, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the license for the specific language governing permissions and * limitations under the license. */ package org.apache.log4j; import java.util.Enumeration; import java.util.HashMap; import java.util.Map; import org.apache.log4j.helpers.NullEnumeration; import org.apache.log4j.legacy.core.ContextUtil; import org.apache.log4j.or.ObjectRenderer; import org.apache.log4j.or.RendererSupport; import org.apache.log4j.spi.HierarchyEventListener; import org.apache.log4j.spi.LoggerFactory; import org.apache.log4j.spi.LoggerRepository; import org.apache.log4j.spi.RepositorySelector; import org.apache.logging.log4j.spi.LoggerContext; import org.apache.logging.log4j.util.Strings; /** * */ public final class LogManager { /** * @deprecated This variable is for internal use only. It will * become package protected in future versions. * */ @Deprecated public static final String DEFAULT_CONFIGURATION_FILE = "log4j.properties"; /** * @deprecated This variable is for internal use only. It will * become private in future versions. * */ @Deprecated public static final String DEFAULT_CONFIGURATION_KEY = "log4j.configuration"; /** * @deprecated This variable is for internal use only. It will * become private in future versions. * */ @Deprecated public static final String CONFIGURATOR_CLASS_KEY = "log4j.configuratorClass"; /** * @deprecated This variable is for internal use only. It will * become private in future versions. */ @Deprecated public static final String DEFAULT_INIT_OVERRIDE_KEY = "log4j.defaultInitOverride"; static final String DEFAULT_XML_CONFIGURATION_FILE = "log4j.xml"; private static final LoggerRepository REPOSITORY = new Repository(); private static final boolean isLog4jCore; static { boolean core = false; try { if (Class.forName("org.apache.logging.log4j.core.LoggerContext") != null) { core = true; } } catch (Exception ex) { // Ignore the exception; } isLog4jCore = core; } private LogManager() { } public static Logger getRootLogger() { return Category.getInstance(PrivateManager.getContext(), Strings.EMPTY); } public static Logger getLogger(final String name) { return Category.getInstance(PrivateManager.getContext(), name); } public static Logger getLogger(final Class<?> clazz) { return Category.getInstance(PrivateManager.getContext(), clazz.getName()); } public static Logger getLogger(final String name, final LoggerFactory factory) { return Category.getInstance(PrivateManager.getContext(), name); } public static Logger exists(final String name) { final LoggerContext ctx = PrivateManager.getContext(); if (!ctx.hasLogger(name)) { return null; } return Logger.getLogger(name); } @SuppressWarnings("rawtypes") public static Enumeration getCurrentLoggers() { return NullEnumeration.getInstance(); } static void reconfigure() { if (isLog4jCore) { final LoggerContext ctx = PrivateManager.getContext(); ContextUtil.reconfigure(ctx); } } /** * No-op implementation. */ public static void shutdown() { } /** * No-op implementation. */ public static void resetConfiguration() { } /** * No-op implementation. * @param selector The RepositorySelector. * @param guard prevents calls at the incorrect time. * @throws IllegalArgumentException if a parameter is invalid. */ public static void setRepositorySelector(final RepositorySelector selector, final Object guard) throws IllegalArgumentException { } public static LoggerRepository getLoggerRepository() { return REPOSITORY; } /** * The Repository. */ private static class Repository implements LoggerRepository, RendererSupport { private final Map<Class<?>, ObjectRenderer> rendererMap = new HashMap<>(); @Override public Map<Class<?>, ObjectRenderer> getRendererMap() { return rendererMap; } @Override public void addHierarchyEventListener(final HierarchyEventListener listener) { } @Override public boolean isDisabled(final int level) { return false; } @Override public void setThreshold(final Level level) { } @Override public void setThreshold(final String val) { } @Override public void emitNoAppenderWarning(final Category cat) { } @Override public Level getThreshold() { return Level.OFF; } @Override public Logger getLogger(final String name) { return Category.getInstance(PrivateManager.getContext(), name); } @Override public Logger getLogger(final String name, final LoggerFactory factory) { return Category.getInstance(PrivateManager.getContext(), name); } @Override public Logger getRootLogger() { return Category.getRoot(PrivateManager.getContext()); } @Override public Logger exists(final String name) { return LogManager.exists(name); } @Override public void shutdown() { } @Override @SuppressWarnings("rawtypes") public Enumeration getCurrentLoggers() { return NullEnumeration.getInstance(); } @Override @SuppressWarnings("rawtypes") public Enumeration getCurrentCategories() { return NullEnumeration.getInstance(); } @Override public void fireAddAppenderEvent(final Category logger, final Appender appender) { } @Override public void resetConfiguration() { } } /** * Internal LogManager. */ private static class PrivateManager extends org.apache.logging.log4j.LogManager { private static final String FQCN = LogManager.class.getName(); public static LoggerContext getContext() { return getContext(FQCN, false); } public static org.apache.logging.log4j.Logger getLogger(final String name) { return getLogger(FQCN, name); } } }
Log4j 1.2 bridge LogManager class default constructor should be public.
log4j-1.2-api/src/main/java/org/apache/log4j/LogManager.java
Log4j 1.2 bridge LogManager class default constructor should be public.
<ide><path>og4j-1.2-api/src/main/java/org/apache/log4j/LogManager.java <ide> isLog4jCore = core; <ide> } <ide> <del> private LogManager() { <del> } <del> <ide> public static Logger getRootLogger() { <ide> return Category.getInstance(PrivateManager.getContext(), Strings.EMPTY); <ide> }
Java
mit
dbebc54d26f1c98b6bc43af34f8115948e880198
0
FriedrichFroebel/oc_car-gui
import java.awt.event.FocusAdapter; import java.awt.event.FocusEvent; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.EventQueue; import java.awt.Font; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.FileReader; import java.io.InputStream; import java.io.InputStreamReader; import java.io.IOException; import java.io.OutputStream; import java.net.MalformedURLException; import java.net.URL; import java.text.DateFormat; import java.text.DecimalFormat; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Properties; import javax.swing.border.EmptyBorder; import javax.swing.ButtonGroup; import javax.swing.filechooser.FileNameExtensionFilter; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JFileChooser; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JPasswordField; import javax.swing.JRadioButton; import javax.swing.JSeparator; import javax.swing.JTextField; import javax.swing.SwingConstants; import org.apache.commons.io.FilenameUtils; import org.apache.commons.io.FileUtils; public class oc_car extends JFrame { //Programmversion zur Analyse fr eventuell verfgbares Update private static String version = "1.4"; //erweiterte Konsolenausgabe ist standardmig deaktiviert private static boolean debug = false; //Variablen, die von anderen Fenstern beeinflusst werden private static String loadpath = ""; private static boolean alleArten = true; private static boolean loadGPX = false; private static boolean savePW = false; //Konstanten int GPX_AbstandWP = 10; //nur jeder 10. Wegpunkt wird gespeichert int KML_AbstandWP = 10; //nur jeder 10. Wegpunkt wird gespeichert //Konfigurationswerte private static String ocUser = "User"; private static double Radius = 2; private static String Start = "Stuttgart"; private static String Ziel = "Mnchen"; private static int Arten = 1023; private static String Difficulty = "1-5"; private static String Terrain = "1-5"; //Einbinden einer Datei mit Konfigurationswerten ermglichen private Properties config = new Properties(); //Radius als String formatieren private static DecimalFormat df_radius = new DecimalFormat( "#.##"); //programminterne Daten private static String UUID = ""; private static String lngS = ""; private static String latS = ""; private static String lngZ = ""; private static String latZ = ""; //Koordinaten der Route private static String[] coords_list = new String[10000]; private static int anzahlAbfragen = 0; //gefundene Caches private static String[] caches = new String[10000]; private static int ohneDuplikate = 0; //E-Mail-Einstellungen private sendEmail email = new sendEmail(); private static String host = "smtp.gmail.com"; private static String port = "587"; private static String sender = "[email protected]"; private static String receiver = "[email protected]"; private static String password = ""; private static String subject = "oc_car - Die GPX-Datei fr Deine Route"; private static String body = "Die GPX-Datei fr Deine Route!"; private static boolean sendEmail = false; //GUI-Elemente, auf die zugegriffen werden muss private JPanel contentPane; private JTextField tfBenutzer; private JTextField tfStart; private JTextField tfZiel; private JTextField tfRadius; private JTextField tfSchwierigkeitsbereich; private JTextField tfTerrainbereich; private JTextField tfMailserver; private JTextField tfAbsender; private JTextField tfEmpfaenger; private JTextField tfBetreff; private JTextField tfMailtext; private JRadioButton rdtbnAlle; private JRadioButton rdtbnAuswaehlen; private JTextField tfPort; private JLabel lblFortschritt = new JLabel("");; //Anwendung starten public static void main(String[] args) { try { if (!args[0].equals(" ")) { debug = true; } } catch (ArrayIndexOutOfBoundsException e) { //do nothing } EventQueue.invokeLater(new Runnable() { public void run() { try { oc_car mainframe = new oc_car(); mainframe.setVisible(true); } catch (Exception e) { e.printStackTrace(); } } }); } //Frame erstellen public oc_car() { setResizable(false); setTitle("Opencaching.de - Caches entlang einer Route"); //Titel setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //Aktion beim Drcken des X setBounds(100, 100, 564, 393); //Position und Abmessungen contentPane = new JPanel(); contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); setContentPane(contentPane); contentPane.setLayout(null); //Beschriftungen bei Textfeldern fr Routenabfrage JLabel lblBenutzer = new JLabel("Benutzer:"); lblBenutzer.setHorizontalAlignment(SwingConstants.RIGHT); lblBenutzer.setBounds(10, 10, 180, 15); contentPane.add(lblBenutzer); JLabel lblStart = new JLabel("Start:"); lblStart.setHorizontalAlignment(SwingConstants.RIGHT); lblStart.setBounds(10, 32, 180, 15); contentPane.add(lblStart); JLabel lblZiel = new JLabel("Ziel:"); lblZiel.setHorizontalAlignment(SwingConstants.RIGHT); lblZiel.setBounds(10, 54, 180, 15); contentPane.add(lblZiel); JLabel lblRadius = new JLabel("Radius (in km):"); lblRadius.setHorizontalAlignment(SwingConstants.RIGHT); lblRadius.setBounds(10, 76, 180, 15); contentPane.add(lblRadius); JLabel lblCachearten = new JLabel("Cachearten:"); lblCachearten.setHorizontalAlignment(SwingConstants.RIGHT); lblCachearten.setBounds(10, 98, 180, 15); contentPane.add(lblCachearten); JLabel lblSchwierigkeitsbereich = new JLabel("Schwierigkeitsbereich:"); lblSchwierigkeitsbereich.setHorizontalAlignment(SwingConstants.RIGHT); lblSchwierigkeitsbereich.setBounds(10, 123, 180, 15); contentPane.add(lblSchwierigkeitsbereich); JLabel lblTerrainbereich = new JLabel("Terrainbereich:"); lblTerrainbereich.setHorizontalAlignment(SwingConstants.RIGHT); lblTerrainbereich.setBounds(10, 145, 180, 15); contentPane.add(lblTerrainbereich); //Textfelder fr Routenabfrage tfBenutzer = new JTextField(); tfBenutzer.addFocusListener(new FocusAdapter() { @Override public void focusGained(FocusEvent arg0) { tfBenutzer.selectAll(); } @Override public void focusLost(FocusEvent arg0) { if (!tfBenutzer.getText().equals("")) { ocUser = tfBenutzer.getText(); writeConfig(); } else { //tfBenutzer.setText(ocUser); } } }); tfBenutzer.setBounds(196, 8, 150, 20); contentPane.add(tfBenutzer); tfBenutzer.setColumns(10); tfStart = new JTextField(); tfStart.addFocusListener(new FocusAdapter() { @Override public void focusGained(FocusEvent e) { tfStart.selectAll(); } @Override public void focusLost(FocusEvent e) { if (!tfStart.getText().equals("")) { Start = tfStart.getText(); writeConfig(); } else { //tfStart.setText(Start); } } }); tfStart.setColumns(10); tfStart.setBounds(196, 30, 150, 20); contentPane.add(tfStart); tfZiel = new JTextField(); tfZiel.addFocusListener(new FocusAdapter() { @Override public void focusGained(FocusEvent e) { tfZiel.selectAll(); } @Override public void focusLost(FocusEvent e) { if (!tfZiel.getText().equals("")) { Ziel = tfZiel.getText(); writeConfig(); } else { //tfZiel.setText(Ziel); } } }); tfZiel.setColumns(10); tfZiel.setBounds(196, 52, 150, 20); contentPane.add(tfZiel); tfRadius = new JTextField(); tfRadius.addFocusListener(new FocusAdapter() { @Override public void focusGained(FocusEvent e) { tfRadius.selectAll(); } @Override public void focusLost(FocusEvent e) { try { Radius = Double.parseDouble(tfRadius.getText()); } catch (NumberFormatException ex) { tfRadius.setText(df_radius.format(Radius)); if (debug) ex.printStackTrace(); } writeConfig(); } }); tfRadius.setColumns(10); tfRadius.setBounds(196, 74, 100, 20); contentPane.add(tfRadius); tfSchwierigkeitsbereich = new JTextField(); tfSchwierigkeitsbereich.addFocusListener(new FocusAdapter() { @Override public void focusGained(FocusEvent e) { tfSchwierigkeitsbereich.selectAll(); } @Override public void focusLost(FocusEvent e) { if (!tfSchwierigkeitsbereich.getText().equals("")) { int minus = 0; String string = tfSchwierigkeitsbereich.getText(); while ((string.charAt(minus) != '-') && (minus < string.length() - 1)) { minus += 1; } try { Double.parseDouble(string.substring(0,minus)); Double.parseDouble(string.substring(minus+1,string.length())); Difficulty = string; } catch (NumberFormatException ex) { tfSchwierigkeitsbereich.setText(Difficulty); if (debug) ex.printStackTrace(); } } } }); tfSchwierigkeitsbereich.setColumns(10); tfSchwierigkeitsbereich.setBounds(196, 121, 100, 20); contentPane.add(tfSchwierigkeitsbereich); tfTerrainbereich = new JTextField(); tfTerrainbereich.addFocusListener(new FocusAdapter() { @Override public void focusGained(FocusEvent e) { tfTerrainbereich.selectAll(); } @Override public void focusLost(FocusEvent e) { if (!tfTerrainbereich.getText().equals("")) { int minus = 0; String string = tfTerrainbereich.getText(); while ((string.charAt(minus) != '-') && (minus < string.length() - 1)) { minus += 1; } try { Double.parseDouble(string.substring(0,minus)); Double.parseDouble(string.substring(minus+1,string.length())); Terrain = string; } catch (NumberFormatException ex) { tfTerrainbereich.setText(Terrain); if (debug) ex.printStackTrace(); } } } }); tfTerrainbereich.setColumns(10); tfTerrainbereich.setBounds(196, 143, 100, 20); contentPane.add(tfTerrainbereich); //Radiobuttons fr Auswahl der Cachearten JRadioButton rdbtnAlle = new JRadioButton("alle"); rdbtnAlle.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent arg0) { alleArten = true; } }); rdbtnAlle.setBounds(196, 96, 65, 23); contentPane.add(rdbtnAlle); JRadioButton rdbtnAuswaehlen = new JRadioButton("ausw\u00E4hlen"); rdbtnAuswaehlen.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent arg0) { try { arten_choose artenwahl = new arten_choose(); artenwahl.setVisible(true); } catch (Exception e) { e.printStackTrace(); } if (Arten != 0) { alleArten = false; writeConfig(); } else { alleArten = true; Arten = 1023; writeConfig(); rdtbnAlle.setSelected(true); } } }); rdbtnAuswaehlen.setBounds(260, 96, 120, 23); contentPane.add(rdbtnAuswaehlen); //Radiobuttons gruppieren, damit nur einer ausgewhlt werden kann ButtonGroup arten = new ButtonGroup(); arten.add(rdbtnAlle); arten.add(rdbtnAuswaehlen); //Beschriftung, wenn GPX-Route geladen JLabel lblGpxGeladen = new JLabel("Route geladen"); lblGpxGeladen.setFont(new Font("Tahoma", Font.ITALIC, 11)); lblGpxGeladen.setHorizontalAlignment(SwingConstants.CENTER); lblGpxGeladen.setBounds(364, 54, 170, 15); contentPane.add(lblGpxGeladen); lblGpxGeladen.setVisible(false); //GPX-Route laden via JFileChooser JButton btnGpxRouteLaden = new JButton("GPX-Route laden"); btnGpxRouteLaden.addKeyListener(new KeyAdapter() { @Override public void keyPressed(KeyEvent arg0) { if (arg0.getKeyCode() == KeyEvent.VK_ENTER) { //Enter-Taste gedrckt JFileChooser gpxeingabe = new JFileChooser(); FileNameExtensionFilter gpx = new FileNameExtensionFilter("GPX-Dateien", "gpx", "GPX"); gpxeingabe.setFileFilter(gpx); if (loadpath.equals("")) { File f = new File(System.getProperty("user.home") + File.separator + "occar"); gpxeingabe.setCurrentDirectory(f); } else { File f = new File(loadpath); gpxeingabe.setCurrentDirectory(f); } int option = gpxeingabe.showOpenDialog(null); if (option == JFileChooser.APPROVE_OPTION) { String pfadEingabe = gpxeingabe.getSelectedFile().getAbsolutePath(); if (FilenameUtils.getExtension(pfadEingabe).toUpperCase().equals("GPX")) { //System.out.println(pfadEingabe); loadpath = pfadEingabe; loadGPX = true; lblGpxGeladen.setVisible(true); } else { javax.swing.JOptionPane.showMessageDialog(null, "Dateiendung ist nicht GPX, sondern \"" + FilenameUtils.getExtension(pfadEingabe) + "\".", "Fehlerhafte Dateiendung", JOptionPane.WARNING_MESSAGE); } } } } }); btnGpxRouteLaden.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { JFileChooser gpxeingabe = new JFileChooser(); //Dateibrowser //nur GPX-Dateien erlauben FileNameExtensionFilter gpx = new FileNameExtensionFilter("GPX-Dateien", "gpx", "GPX"); gpxeingabe.setFileFilter(gpx); if (loadpath.equals("")) { //bisher noch keine (gltige) GPX-Datei geladen File f = new File(System.getProperty("user.home") + File.separator + "occar"); gpxeingabe.setCurrentDirectory(f); } else { //bereits einmal GPX-Datei geladen File f = new File(loadpath); gpxeingabe.setCurrentDirectory(f); } int option = gpxeingabe.showOpenDialog(null); //wenn Datei ausgewhlt worden ist if (option == JFileChooser.APPROVE_OPTION) { //Pfad ermitteln String pfadEingabe = gpxeingabe.getSelectedFile().getAbsolutePath(); //Dateiendung prfen if (FilenameUtils.getExtension(pfadEingabe).toUpperCase().equals("GPX")) { if (debug) System.out.println(pfadEingabe); loadpath = pfadEingabe; loadGPX = true; lblGpxGeladen.setVisible(true); //Info anzeigen } else { javax.swing.JOptionPane.showMessageDialog(null, "Dateiendung ist nicht GPX, sondern \"" + FilenameUtils.getExtension(pfadEingabe) + "\".", "Fehlerhafte Dateiendung", JOptionPane.WARNING_MESSAGE); } } } }); btnGpxRouteLaden.setBounds(364, 28, 170, 23); contentPane.add(btnGpxRouteLaden); //Trennstrich zwischen Routenkonfiguration und E-Mail-Einstellungen JSeparator sepAllgemeinMail = new JSeparator(); sepAllgemeinMail.setBounds(10, 170, 534, 2); contentPane.add(sepAllgemeinMail); //Beschriftungen bei Textfeldern fr E-Mail-Versand JLabel lblMailserver = new JLabel("E-Mail-Server:"); lblMailserver.setHorizontalAlignment(SwingConstants.RIGHT); lblMailserver.setBounds(10, 181, 100, 14); contentPane.add(lblMailserver); JLabel lblPort = new JLabel("Port:"); lblPort.setHorizontalAlignment(SwingConstants.RIGHT); lblPort.setBounds(275, 181, 100, 14); contentPane.add(lblPort); JLabel lblAbsender = new JLabel("Absender:"); lblAbsender.setHorizontalAlignment(SwingConstants.RIGHT); lblAbsender.setBounds(10, 209, 100, 14); contentPane.add(lblAbsender); JLabel lblEmpfaenger = new JLabel("Empf\u00E4nger:"); lblEmpfaenger.setHorizontalAlignment(SwingConstants.RIGHT); lblEmpfaenger.setBounds(275, 209, 100, 14); contentPane.add(lblEmpfaenger); JLabel lblBetreff = new JLabel("Betreff:"); lblBetreff.setHorizontalAlignment(SwingConstants.RIGHT); lblBetreff.setBounds(10, 237, 100, 14); contentPane.add(lblBetreff); JLabel lblMailtext = new JLabel("E-Mail-Text:"); lblMailtext.setHorizontalAlignment(SwingConstants.RIGHT); lblMailtext.setBounds(10, 265, 100, 14); contentPane.add(lblMailtext); //Textfelder fr E-Mail-Versand tfMailserver = new JTextField(); tfMailserver.addFocusListener(new FocusAdapter() { @Override public void focusGained(FocusEvent e) { tfMailserver.selectAll(); } @Override public void focusLost(FocusEvent e) { host = tfMailserver.getText(); writeConfig(); } }); tfMailserver.setBounds(113, 179, 165, 20); contentPane.add(tfMailserver); tfMailserver.setColumns(10); tfAbsender = new JTextField(); tfAbsender.addFocusListener(new FocusAdapter() { @Override public void focusGained(FocusEvent e) { tfAbsender.selectAll(); } @Override public void focusLost(FocusEvent e) { sender = tfAbsender.getText(); writeConfig(); } }); tfAbsender.setBounds(113, 207, 165, 20); contentPane.add(tfAbsender); tfAbsender.setColumns(10); tfEmpfaenger = new JTextField(); tfEmpfaenger.addFocusListener(new FocusAdapter() { @Override public void focusGained(FocusEvent e) { tfEmpfaenger.selectAll(); } @Override public void focusLost(FocusEvent e) { receiver = tfEmpfaenger.getText(); writeConfig(); } }); tfEmpfaenger.setColumns(10); tfEmpfaenger.setBounds(378, 207, 165, 20); contentPane.add(tfEmpfaenger); tfBetreff = new JTextField(); tfBetreff.addFocusListener(new FocusAdapter() { @Override public void focusGained(FocusEvent e) { tfBetreff.selectAll(); } @Override public void focusLost(FocusEvent e) { subject = tfBetreff.getText(); writeConfig(); } }); tfBetreff.setBounds(113, 235, 431, 20); contentPane.add(tfBetreff); tfBetreff.setColumns(10); tfMailtext = new JTextField(); tfMailtext.addFocusListener(new FocusAdapter() { @Override public void focusGained(FocusEvent e) { tfMailtext.selectAll(); } @Override public void focusLost(FocusEvent e) { body = tfMailtext.getText(); writeConfig(); } }); tfMailtext.setBounds(113, 263, 431, 20); contentPane.add(tfMailtext); tfMailtext.setColumns(10); tfPort = new JTextField(); tfPort.addFocusListener(new FocusAdapter() { @Override public void focusGained(FocusEvent arg0) { tfPort.selectAll(); } @Override public void focusLost(FocusEvent e) { try { port = Integer.toString(Integer.parseInt(tfPort.getText())); } catch (NumberFormatException ex) { tfPort.setText(port); if (debug) ex.printStackTrace(); } writeConfig(); } }); tfPort.setBounds(378, 179, 120, 20); contentPane.add(tfPort); tfPort.setColumns(10); JLabel lblPasswort = new JLabel("Passwort:"); lblPasswort.setHorizontalAlignment(SwingConstants.RIGHT); lblPasswort.setBounds(10, 293, 100, 14); contentPane.add(lblPasswort); JPasswordField pfPassword = new JPasswordField(); pfPassword.setBounds(113, 291, 120, 20); contentPane.add(pfPassword); //Trennstrich zwischen E-Mail-Einstellungen und Meldungslabel JSeparator sepMailProgress = new JSeparator(); sepMailProgress.setBounds(10, 318, 534, 2); contentPane.add(sepMailProgress); //Meldungslabel lblFortschritt.setHorizontalAlignment(SwingConstants.CENTER); lblFortschritt.setBounds(10, 327, 534, 20); contentPane.add(lblFortschritt); //Button zum Starten der Suche JButton btnStartSuche = new JButton("Caches suchen"); btnStartSuche.addKeyListener(new KeyAdapter() { @Override public void keyPressed(KeyEvent e) { if (e.getKeyCode() == KeyEvent.VK_ENTER) { if (rdtbnAlle.isSelected()) { alleArten = true; } else { alleArten = false; } try { char[] input = pfPassword.getPassword(); String temp = ""; for (int i = 0; i < pfPassword.getPassword().length; i++) { temp += input[i]; } password = temp; } catch (ArrayIndexOutOfBoundsException ex) { if (debug) System.out.println("Kein Passwort angegeben"); } sucheStarten(); lblGpxGeladen.setVisible(false); loadGPX = false; if (!savePW) { password = ""; } writeConfig(); } } }); btnStartSuche.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent arg0) { //Passwort ermitteln try { char[] input = pfPassword.getPassword(); String temp = ""; for (int i = 0; i < pfPassword.getPassword().length; i++) { temp += input[i]; } password = temp; } catch (ArrayIndexOutOfBoundsException e) { if (debug) System.out.println("Kein Passwort angegeben"); } sucheStarten(); //Suche durch Funktionsaufruf starten lblGpxGeladen.setVisible(false); //eventuelll sichtbares Label deaktivieren loadGPX = false; //keine GPX-Datei mehr geladen if (!savePW) { //wenn Passwort nicht gespeichert werden soll password = ""; //Passwortvariable leeren } writeConfig(); //evtl. vorhandenes Passwort in Konfiguration schreiben } }); btnStartSuche.setBounds(364, 119, 170, 23); contentPane.add(btnStartSuche); //Passwort speichern? JCheckBox boxSavePW = new JCheckBox("Passwort speichern"); boxSavePW.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent arg0) { if (boxSavePW.isSelected()) { //wenn mit Maus geklickt und Box selektiert savePW = true; //Passwort speichern } else { savePW = false; } } }); boxSavePW.setBounds(249, 289, 170, 22); contentPane.add(boxSavePW); //E-Mail versenden? JCheckBox boxSendEmail = new JCheckBox("E-Mail senden"); boxSendEmail.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent arg0) { if (boxSendEmail.isSelected()) { sendEmail = true; } else { sendEmail = false; } System.out.println(sendEmail); } }); boxSendEmail.setBounds(364, 72, 170, 25); contentPane.add(boxSendEmail); checkNewVersion(); //auf neue Version prfen readConfig(); //Konfigurationsdatei lesen printInitialConfig(); //Konfiguration ausgeben //einen Radiobutton entsprechend der Konfiguration vorbelegen if (Arten == 1023) { rdbtnAlle.setSelected(true); alleArten = true; } else { rdtbnAuswaehlen.setSelected(true); alleArten = false; } //Checkbox zur Passwortspeicherung entsprechend der Konfiguration einstellen if (password.equals("")) { boxSavePW.setSelected(false); savePW = false; } else { boxSavePW.setSelected(true); savePW = true; pfPassword.setText(password); } //Checkbox zum E-Mail-Versand entsprechend der Konfiguration einstellen if (sendEmail) { boxSendEmail.setSelected(true); } else { boxSendEmail.setSelected(false); } } //Zahlenwert fr Cachearten erhalten (in Klasse arten_choose verwendet) public int getCachearten() { return Arten; } //Zahlenwert fr Cachearten setzen (in Klasse arten_choose verwendet) public void setCachearten(int cachearten) { oc_car.Arten = cachearten; } //Parameter in Konfigurationsdatei schreiben private boolean writeConfig() { try { //Parameter fr Routenabfrage config.setProperty("ocUser", ocUser); config.setProperty("Radius", df_radius.format(Radius)); config.setProperty("Start", Start); config.setProperty("Ziel", Ziel); config.setProperty("Arten", Integer.toString(Arten)); config.setProperty("Difficulty", Difficulty); config.setProperty("Terrain", Terrain); //Parameter fr E-Mail-Versand config.setProperty("host", host); config.setProperty("port", port); config.setProperty("sender", sender); config.setProperty("receiver", receiver); config.setProperty("subject", subject); config.setProperty("body", body); config.setProperty("sendEmail", Boolean.toString(sendEmail)); if (savePW) { config.setProperty("password", password); } else { config.setProperty("password", ""); } //in XML-Datei schreiben File f = new File(System.getProperty("user.home") + File.separator + "occar" + File.separator + "occar_config.xml"); OutputStream o = new FileOutputStream(f); config.storeToXML(o, "Config-Datei fr oc_car-gui"); } catch (IOException e) { if (debug) e.printStackTrace(); return false; } return true; } //Parameter aus Konfiguration lesen private boolean readConfig() { InputStream s = null; try { //Dateipfad zusammensetzen File f = new File(System.getProperty("user.home") + File.separator + "occar" + File.separator + "occar_config.xml"); if (!f.exists()) { //wenn Datei nicht existiert writeConfig(); //Datei mit Inhalt erstellen } else { //Datei existiert //aus XML-Datei lesen s = new FileInputStream(f); config.loadFromXML(s); //Parameter fr Routenabfrage ocUser = config.getProperty("ocUser", "User"); Radius = Double.parseDouble(config.getProperty("Radius", "2")); Start = config.getProperty("Start", "Stuttgart"); Ziel = config.getProperty("Ziel", "Mnchen"); Arten = Integer.parseInt(config.getProperty("Arten", "1023")); Difficulty = config.getProperty("Difficulty", "1-5"); Terrain = config.getProperty("Terrain", "1-5"); //Parameter fr E-Mail-Versand host = config.getProperty("host", "smtp.gmail.com"); port = config.getProperty("port", "587"); sender = config.getProperty("sender", "[email protected]"); receiver = config.getProperty("receiver", "[email protected]"); subject = config.getProperty("subject", "oc_car - Die GPX-Datei fr Deine Route"); body = config.getProperty("body", "Die GPX-Datei fr Deine Route!"); sendEmail = Boolean.parseBoolean(config.getProperty("sendEmail", "false")); password = config.getProperty("password", ""); System.out.println(password); } } catch (IOException e) { if (debug) e.printStackTrace(); return false; } return true; } //am Programmbeginn Daten aus Konfigurationsdatei in die Textfelder schreiben private void printInitialConfig() { tfBenutzer.setText(ocUser); tfStart.setText(Start); tfZiel.setText(Ziel); tfRadius.setText(df_radius.format(Radius)); tfSchwierigkeitsbereich.setText(Difficulty); tfTerrainbereich.setText(Terrain); tfMailserver.setText(host); tfAbsender.setText(sender); tfEmpfaenger.setText(receiver); tfBetreff.setText(subject); tfMailtext.setText(body); tfPort.setText(port); } //Opencaching.de Benutzer-ID ermitteln private boolean getUUID() { URL url; InputStream is = null; BufferedReader br; String line = ""; try { url = new URL("http://www.opencaching.de/okapi/services/users/by_username?username=" + ocUser + "&fields=uuid&consumer_key=8YV657YqzqDcVC3QC9wM"); is = url.openStream(); br = new BufferedReader(new InputStreamReader(is)); line = br.readLine(); //Antwort speichern (nur eine Zeile zurckgeliefert) is.close(); } catch (MalformedURLException e) { if (debug) e.printStackTrace(); return false; } catch (IOException e) { javax.swing.JOptionPane.showMessageDialog(null, "Benutzer nicht gefunden!\nBitte Aufrufparameter prfen!", "Ungltiger Benutzername", JOptionPane.INFORMATION_MESSAGE); if (debug) System.out.println("Benutzer nicht gefunden! Bitte Aufrufparameter prfen!"); if (debug) System.out.println(line); return false; } if (debug) System.out.println(line); try { //Rckgabestring auf String "uuid" berprfen if (!line.substring(2,6).equals("uuid")) return false; } catch (StringIndexOutOfBoundsException e) { if (debug) e.printStackTrace(); return false; } UUID = line.substring(9,line.length() - 2); //Benutzer-ID extrahieren if (debug) System.out.println("Benutzer wurde gefunden."); return true; } //Koordinaten des Startpunktes ermitteln private boolean getCoordsOfStart() { URL url; InputStream is = null; BufferedReader br; String line = ""; String Start_mod = ""; //Umlaute, Leerzeichen ersetzen; ungltige Zeichen entfernen for (int i = 0; i < Start.length(); i++) { switch (Start.charAt(i)) { case ' ': Start_mod += "+"; break; case '': case '': Start_mod += "ae"; break; case '': case '': Start_mod += "oe"; break; case '': case '': Start_mod += "ue"; break; case '': Start_mod += "ss"; break; default: if ((((Start.charAt(i) >= 'A') && Start.charAt(i) <= 'Z')) || ((Start.charAt(i) >= 'a') && (Start.charAt(i) <= 'z')) || ((Start.charAt(i) >= '0') && (Start.charAt(i) <= '9'))) { Start_mod += Start.charAt(i); }; } } if (debug) System.out.println(Start_mod); try { url = new URL("http://nominatim.openstreetmap.org/search?q=" + Start_mod + "&format=json"); is = url.openStream(); br = new BufferedReader(new InputStreamReader(is)); line = br.readLine(); is.close(); } catch (MalformedURLException e) { if (debug) e.printStackTrace(); return false; } catch (IOException e) { if (debug) e.printStackTrace(); if (debug) System.out.println(line); return false; } if (debug) System.out.println(line); try { int i = 0; boolean gefunden = false; //nach erstem Auftauchen des "lat"-Strings suchen while (i < line.length() && !gefunden) { if (line.substring(i, i + 6).equals("lat\":\"")) { gefunden = true; } else { i++; } } int j = i + 7; //Ende der lat-Koordinate suchen while (line.charAt(j) != '"') { j++; } latS = line.substring(i + 6, j); int k = j + 9; //Ende der lng-Koordinate suchen while (line.charAt(k) != '"') { k++; } lngS = line.substring(j+9, k); } catch (StringIndexOutOfBoundsException e) { if (debug) e.printStackTrace(); return false; } if (debug) System.out.println(latS + "," + lngS); return true; } private boolean getCoordsOfZiel() { URL url; InputStream is = null; BufferedReader br; String line = ""; String Ziel_mod = ""; for (int i = 0; i < Ziel.length(); i++) { switch (Ziel.charAt(i)) { case ' ': Ziel_mod += "+"; break; case '': case '': Ziel_mod += "ae"; break; case '': case '': Ziel_mod += "oe"; break; case '': case '': Ziel_mod += "ue"; break; case '': Ziel_mod += "ss"; break; default: if ((((Ziel.charAt(i) >= 'A') && Ziel.charAt(i) <= 'Z')) || ((Ziel.charAt(i) >= 'a') && (Ziel.charAt(i) <= 'z')) || ((Ziel.charAt(i) >= '0') && (Ziel.charAt(i) <= '9'))) { Ziel_mod += Ziel.charAt(i); }; } } if (debug) System.out.println(Ziel_mod); try { url = new URL("http://nominatim.openstreetmap.org/search?q=" + Ziel_mod + "&format=json"); is = url.openStream(); // throws an IOException br = new BufferedReader(new InputStreamReader(is)); line = br.readLine(); is.close(); } catch (MalformedURLException e) { if (debug) e.printStackTrace(); return false; } catch (IOException e) { if (debug) e.printStackTrace(); return false; } if (debug) System.out.println(line); try { int i = 0; boolean gefunden = false; while (i < line.length() && !gefunden) { if (line.substring(i, i + 6).equals("lat\":\"")) { gefunden = true; } else { i++; } } int j = i + 7; while (line.charAt(j) != '"') { j++; } latZ = line.substring(i + 6, j); int k = j + 9; while (line.charAt(k) != '"') { k++; } lngZ = line.substring(j+9, k); } catch (StringIndexOutOfBoundsException e) { if (debug) e.printStackTrace(); return false; } if (debug) System.out.println(latZ + "," + lngZ); return true; } //KML-Route herunterladen private boolean downloadKMLRoute() { try { //Route berechnen und in Datei herunterladen URL url = new URL("http://www.yournavigation.org/api/1.0/gosmore.php?flat=" + latS + "&flon=" + lngS + "&tlat=" + latZ + "&tlon=" + lngZ + "&v=motorcar&fast=1"); File file = new File(System.getProperty("user.home") + File.separator + "occar" + File.separator + "route.kml"); if (file.exists()) { file.delete(); //eventuell existierende Datei gleichen Namens lschen } FileUtils.copyURLToFile(url, file, 0, 0); //Datei speichern } catch (MalformedURLException e) { if (debug) e.printStackTrace(); return false; } catch (IOException e) { if (debug) e.printStackTrace(); return false; } return true; } //Routenkoordinaten aus KML-Datei auslesen private boolean KML2Array() { int stelleImArray = 0; try { BufferedReader br = new BufferedReader(new FileReader(System.getProperty("user.home") + File.separator + "occar" + File.separator + "route.kml")); String line = br.readLine(); int anzahlZeilen = 0; while (line != null) { //solange noch nicht Dateiende erreicht if (line.charAt(0) != '<' && line.charAt(0) != ' ') { //linksbndige Zeile suchen if (anzahlZeilen % KML_AbstandWP == 0) { //nur jede X. Zeile im Array speichern coords_list[stelleImArray] = line; stelleImArray++; } anzahlZeilen++; } line = br.readLine(); //neue Zeile lesen } br.close(); } catch (IOException e) { if (debug) e.printStackTrace(); return false; } catch (ArrayIndexOutOfBoundsException e) { if (debug) e.printStackTrace(); return false; } if (debug) { System.out.println(stelleImArray); /*for (int i = 0; i < stelleImArray; i++) { System.out.println(coords_list[i]); }*/ } anzahlAbfragen = stelleImArray; return true; } //Routenkoordinaten aus GPX-Datei auslesen private boolean GPX2Array() { int stelleImArray = 0; try { BufferedReader br = new BufferedReader(new FileReader(loadpath)); String line = br.readLine(); int anzahlZeilen = 0; while (line != null) { //solange noch nicht Dateiende erreicht int startpunkt = 0; for (int i = 0; i < line.length() - 8; i++) { if (line.substring(i, i+9).equals("trkpt lat")) { //nach Trackpoint suchen if (anzahlZeilen % GPX_AbstandWP == 0) { //nur jeden X. Trackpoint im Array speichern startpunkt = i + 12; int endpunkt = startpunkt; //Ende des 2. Koordinatenpaarelements suchen while (!line.substring(endpunkt, endpunkt+7).equals("\" lon=\"")) { endpunkt++; } String teil2 = line.substring(startpunkt-1, endpunkt); //System.out.println(teil2); endpunkt += 6; startpunkt = endpunkt; //Ende des 1. Koordinatenpaarelements suchen while ((!line.substring(endpunkt, endpunkt+3).equals("\"/>"))) { endpunkt++; } String teil1 = line.substring(startpunkt + 1, endpunkt); //System.out.println(teil1); coords_list[stelleImArray] = teil1 + "," + teil2; stelleImArray++; } anzahlZeilen++; } } line = br.readLine(); //nchste Zeile lesen } br.close(); } catch (IOException e) { if (debug) e.printStackTrace(); return false; } catch (ArrayIndexOutOfBoundsException e) { if (debug) e.printStackTrace(); return false; } catch (StringIndexOutOfBoundsException e) { if (debug) e.printStackTrace(); return false; } if (debug) { System.out.println(stelleImArray); /*for (int i = 0; i < stelleImArray; i++) { System.out.println(coords_list[i]); }*/ } anzahlAbfragen = stelleImArray; return true; } //Radius berprfen private boolean checkRadius() { if (Radius < 0.1) { //Radius gro genug javax.swing.JOptionPane.showMessageDialog(null, "Der eingegebene Radius ist zu klein!"); return false; } if (Radius > 10) { //Radius klein genug javax.swing.JOptionPane.showMessageDialog(null, "Der eingegebene Radius ist zu gro!"); return false; } return true; } //Caches entlang der Route suchen private boolean requestCaches() { //Fortschrittsframe aktivieren progressBar progress = new progressBar(); progress.setVisible(true); String arten = ""; //gewnschte Cachearten auslesen if (!alleArten) { //bitweiser Vergleich mit entsprechender Maske if ((Arten & (1<<0)) == (1<<0)) { if (arten.equals("")) { arten += "Traditional"; } else { arten += "|Traditional"; } } if ((Arten & (1<<1)) == (1<<1)) { if (arten.equals("")) { arten += "Multi"; } else { arten += "|Multi"; } } if ((Arten & (1<<2)) == (1<<2)) { if (arten.equals("")) { arten += "Quiz"; } else { arten += "|Quiz"; } } if ((Arten & (1<<3)) == (1<<3)) { if (arten.equals("")) { arten += "Virtual"; } else { arten += "|Virtual"; } } if ((Arten & (1<<4)) == (1<<4)) { if (arten.equals("")) { arten += "Event"; } else { arten += "|Event"; } } if ((Arten & (1<<5)) == (1<<5)) { if (arten.equals("")) { arten += "Webcam"; } else { arten += "|Webcam"; } } if ((Arten & (1<<6)) == (1<<6)) { if (arten.equals("")) { arten += "Moving"; } else { arten += "|Moving"; } } if ((Arten & (1<<7)) == (1<<7)) { if (arten.equals("")) { arten += "Math/Physics"; } else { arten += "|Math/Physics"; } } if ((Arten & (1<<8)) == (1<<8)) { if (arten.equals("")) { arten += "Drive-In"; } else { arten += "|Drive-In"; } } if ((Arten & (1<<9)) == (1<<9)) { if (arten.equals("")) { arten += "Other"; } else { arten += "|Other"; } } } int stelleImArray = 0; String[] alle = new String[anzahlAbfragen]; for (int i = 0; i < anzahlAbfragen; i++) { URL url; InputStream is = null; BufferedReader br; String line = ""; //die Koordinaten werden genau verkehrt herum gespeichert und mssen umgedreht werden int j = 0; String coords_fehler = coords_list[i]; while (coords_fehler.charAt(j) != ',') { j++; } String coords = coords_fehler.substring(j+1, coords_fehler.length()) + "|" + coords_fehler.substring(0, j); //System.out.println(coords); try { //Abfrage durchfhren (Mittelpunkt-Suche mit Radius) if (alleArten) { url = new URL("http://www.opencaching.de/okapi/services/caches/search/nearest?center=" + coords + "&radius=" + df_radius.format(Radius) + "&difficulty=" + Difficulty + "&terrain=" + Terrain + "&status=Available&consumer_key=8YV657YqzqDcVC3QC9wM"); } else { url = new URL("http://www.opencaching.de/okapi/services/caches/search/nearest?center=" + coords + "&radius=" + df_radius.format(Radius) + "&type=" + arten + "&difficulty=" + Difficulty + "&terrain=" + Terrain + "&status=Available&consumer_key=8YV657YqzqDcVC3QC9wM"); } //System.out.println(url); is = url.openStream(); br = new BufferedReader(new InputStreamReader(is)); line = br.readLine(); is.close(); } catch (MalformedURLException e) { if (debug) e.printStackTrace(); return false; } catch (IOException e) { if (debug) e.printStackTrace(); return false; } //System.out.println(line); //Fortschritt progress.updatebar((100 * i) / anzahlAbfragen); //prfen, ob Dose gefunden if (line.length() < 30) { //keine Dose in diesem Bereich } else { String a = line.substring(13, line.length() - 16); String b = a.replace("\"", ""); //Anfhrungszeichen durch Leerzeichen ersetzen b = b.replace(",", " "); //Kommas durch Leerzeichen ersetzen alle[stelleImArray] = b; //Ergebnis der Abfrage zum Array hinzufgen stelleImArray++; } } if (debug) { for (int i = 0; i < stelleImArray; i++) { System.out.println(alle[i]); } System.out.println("---"); } //Duplikate filtern und OC-Codes feldweise in Array schreiben ohneDuplikate = 0; for (int i = 0; i < stelleImArray; i++) { int startpunkt = 0; int endpunkt = 0; String aktuell = alle[i]; //System.out.println(aktuell); while (endpunkt < aktuell.length()) { if (aktuell.charAt(endpunkt) == ' ') { if (ohneDuplikate == 0) { caches[0] = aktuell.substring(startpunkt, endpunkt); startpunkt = endpunkt + 1; ohneDuplikate++; } else { String teilstring = aktuell.substring(startpunkt, endpunkt); boolean schon_vorhanden = false; for (int j = 0; j < ohneDuplikate; j++) { if (teilstring.equals(caches[j])) { schon_vorhanden = true; startpunkt = endpunkt + 1; } } if (!schon_vorhanden) { caches[ohneDuplikate] = teilstring; startpunkt = endpunkt + 1; ohneDuplikate++; } } } endpunkt++; } String teilstring = aktuell.substring(startpunkt, endpunkt); boolean schon_vorhanden = false; for (int j = 0; j < ohneDuplikate; j++) { if (teilstring.equals(caches[j])) { schon_vorhanden = true; startpunkt = endpunkt + 1; } } if (!schon_vorhanden) { caches[ohneDuplikate] = teilstring; startpunkt = endpunkt + 1; ohneDuplikate++; } } if (debug) System.out.println("Gefundene Listings ohne Duplikate: " + ohneDuplikate); if (debug) { for (int i = 0; i < ohneDuplikate; i++) { System.out.print(caches[i] + " , "); } } progress.dispose(); //Fortschrittsframe schlieen return true; } //GPX-Dateien mit den gefundenen und gefilterten Caches herunterladen private boolean downloadCaches() { int anzahlAufrufe = ohneDuplikate / 500 + 1; int ende = 0; if (ohneDuplikate < 500) { ende = ohneDuplikate; } else { ende = 500; } for (int i = 0; i < anzahlAufrufe; i++) { String codes_aufruf = caches[i*500]; for (int j = i * 500 + 1; j < ende; j++) { codes_aufruf = codes_aufruf + "|" + caches[j]; } DateFormat dateFormat = new SimpleDateFormat("yyyyMMdd-HHmmss"); Date date = new Date(); String outputFile = dateFormat.format(date) + "PQ.gpx"; if (debug) System.out.println(codes_aufruf); try { URL url = new URL("http://www.opencaching.de/okapi/services/caches/formatters/gpx?cache_codes=" + codes_aufruf + "&consumer_key=8YV657YqzqDcVC3QC9wM&ns_ground=true&latest_logs=true&mark_found=true&user_uuid=" + UUID); File file = new File(System.getProperty("user.home") + File.separator + "occar" + File.separator + outputFile); FileUtils.copyURLToFile(url, file, 0, 0); } catch (MalformedURLException e) { if (debug) e.printStackTrace(); return false; } catch (IOException e) { if (debug) e.printStackTrace(); return false; } if (sendEmail) { //E-Mail-Versand gewnscht boolean erfolg = false; erfolg = email.sendMailWithAttachment(host, port, sender, receiver, password, outputFile, subject, body, debug); if (erfolg) { lblFortschritt.setText("Die Datei(en) wurden im Verzeichnis abgelegt und per E-Mail versendet."); } else { lblFortschritt.setText("Fehler beim Versenden der Datei(en)! Passwort prfen!"); } } else { //kein E-Mail-Versand gewnscht lblFortschritt.setText("Die Datei " + outputFile + " wurde gespeichert!"); } if (ende < ohneDuplikate) { if ((ende + 500) < ohneDuplikate) { ende += 500; } else { ende = ohneDuplikate; } } } return true; } //auf neue Programmversion prfen private boolean checkNewVersion() { URL url; InputStream is = null; BufferedReader br; String line = ""; try { //Dateiinhalt der Versionsdatei von Github ermitteln url = new URL("https://raw.githubusercontent.com/FriedrichFroebel/oc_car-gui/master/version"); is = url.openStream(); br = new BufferedReader(new InputStreamReader(is)); line = br.readLine(); if (debug) System.out.println("Inhalt Versionscheck: " + line); is.close(); } catch (MalformedURLException e) { if (debug) e.printStackTrace(); return false; } catch (IOException e) { if (debug) e.printStackTrace(); return false; } if (!line.equals(version)) { //Zeileninhalt stimmt nicht mit Versionsangabe des Programms berein //Information anzeigen javax.swing.JOptionPane.showMessageDialog(null, "Neue Version verfgbar:\n" + "https://github.com/FriedrichFroebel/oc_car-gui/releases", "Versionshinweis", JOptionPane.INFORMATION_MESSAGE); return true; } else { if (debug) System.out.println("Es wird bereits die aktuellste Version verwendet."); } return false; } //Aufruf der einzelnen Elemente der Suche private boolean sucheStarten() { if (debug) System.out.println(System.getProperty("user.home")); /* * die eigentlich wichtigen Schritte * nur bei Gltigkeit des vorhergehenden wird der nchste ausgefhrt * sonst bricht das Programm ab und gibt bei aktivierter Debug-Flag * eine Hinweismeldung aus, wo der Fehler aufgetreten ist */ if (getUUID()) { if (loadGPX) { if (GPX2Array()) { if (checkRadius()) { if (requestCaches()) { if (!downloadCaches()) { if (debug) System.out.println("Abbruch: downloadCaches()"); } } else { if (debug) System.out.println("Abbruch: requestCaches()"); } } else { if (debug) System.out.println("Abbruch: checkRadius()"); } } else { if (debug) System.out.println("Abbruch: GPX2Array()"); } } else { if (getCoordsOfStart() && getCoordsOfZiel()) { if (downloadKMLRoute()) { if (KML2Array()) { if (checkRadius()) { if (requestCaches()) { if (!downloadCaches()) { if (debug) System.out.println("Abbruch: downloadCaches()"); return false; } } else { if (debug) System.out.println("Abbruch: requestCaches()"); return false; } } else { if (debug) System.out.println("Abbruch: checkRadius()"); return false; } } else { if (debug) System.out.println("Abbruch: KML2Array()"); return false; } } else { if (debug) System.out.println("Abbruch: downloadKMLRoute()"); return false; } } else { if (debug) System.out.println("Abbruch: getCoords()"); return false; } } } else { if (debug) System.out.println("Abbruch: getUUID()"); return false; } return true; } }
src/oc_car.java
import java.awt.event.FocusAdapter; import java.awt.event.FocusEvent; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.EventQueue; import java.awt.Font; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.FileReader; import java.io.InputStream; import java.io.InputStreamReader; import java.io.IOException; import java.io.OutputStream; import java.net.MalformedURLException; import java.net.URL; import java.text.DateFormat; import java.text.DecimalFormat; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Properties; import javax.swing.border.EmptyBorder; import javax.swing.ButtonGroup; import javax.swing.filechooser.FileNameExtensionFilter; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JFileChooser; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JPasswordField; import javax.swing.JRadioButton; import javax.swing.JSeparator; import javax.swing.JTextField; import javax.swing.SwingConstants; import org.apache.commons.io.FilenameUtils; import org.apache.commons.io.FileUtils; public class oc_car extends JFrame { //Programmversion zur Analyse fr eventuell verfgbares Update private static String version = "1.3"; //erweiterte Konsolenausgabe ist standardmig deaktiviert private static boolean debug = false; //Variablen, die von anderen Fenstern beeinflusst werden private static String loadpath = ""; private static boolean alleArten = true; private static boolean loadGPX = false; private static boolean savePW = false; //Konfigurationswerte private static String ocUser = "User"; private static double Radius = 2; private static String Start = "Stuttgart"; private static String Ziel = "Mnchen"; private static int Arten = 1023; private static String Difficulty = "1-5"; private static String Terrain = "1-5"; //Einbinden einer Datei mit Konfigurationswerten ermglichen private Properties config = new Properties(); //Radius als String formatieren private static DecimalFormat df_radius = new DecimalFormat( "#.##"); //programminterne Daten private static String UUID = ""; private static String lngS = ""; private static String latS = ""; private static String lngZ = ""; private static String latZ = ""; //Koordinaten der Route private static String[] coords_list = new String[10000]; private static int anzahlAbfragen = 0; //gefundene Caches private static String[] caches = new String[10000]; private static int ohneDuplikate = 0; //E-Mail-Einstellungen private sendEmail email = new sendEmail(); private static String host = "smtp.gmail.com"; private static String port = "587"; private static String sender = "[email protected]"; private static String receiver = "[email protected]"; private static String password = ""; private static String subject = "oc_car - Die GPX-Datei fr Deine Route"; private static String body = "Die GPX-Datei fr Deine Route!"; private static boolean sendEmail = false; //GUI-Elemente, auf die zugegriffen werden muss private JPanel contentPane; private JTextField tfBenutzer; private JTextField tfStart; private JTextField tfZiel; private JTextField tfRadius; private JTextField tfSchwierigkeitsbereich; private JTextField tfTerrainbereich; private JTextField tfMailserver; private JTextField tfAbsender; private JTextField tfEmpfaenger; private JTextField tfBetreff; private JTextField tfMailtext; private JRadioButton rdtbnAlle; private JRadioButton rdtbnAuswaehlen; private JTextField tfPort; private JLabel lblFortschritt = new JLabel("");; //Anwendung starten public static void main(String[] args) { try { if (!args[0].equals(" ")) { debug = true; } } catch (ArrayIndexOutOfBoundsException e) { //do nothing } EventQueue.invokeLater(new Runnable() { public void run() { try { oc_car mainframe = new oc_car(); mainframe.setVisible(true); } catch (Exception e) { e.printStackTrace(); } } }); } //Frame erstellen public oc_car() { setResizable(false); setTitle("Opencaching.de - Caches entlang einer Route"); //Titel setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //Aktion beim Drcken des X setBounds(100, 100, 564, 393); //Position und Abmessungen contentPane = new JPanel(); contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); setContentPane(contentPane); contentPane.setLayout(null); //Beschriftungen bei Textfeldern fr Routenabfrage JLabel lblBenutzer = new JLabel("Benutzer:"); lblBenutzer.setHorizontalAlignment(SwingConstants.RIGHT); lblBenutzer.setBounds(10, 10, 180, 15); contentPane.add(lblBenutzer); JLabel lblStart = new JLabel("Start:"); lblStart.setHorizontalAlignment(SwingConstants.RIGHT); lblStart.setBounds(10, 32, 180, 15); contentPane.add(lblStart); JLabel lblZiel = new JLabel("Ziel:"); lblZiel.setHorizontalAlignment(SwingConstants.RIGHT); lblZiel.setBounds(10, 54, 180, 15); contentPane.add(lblZiel); JLabel lblRadius = new JLabel("Radius (in km):"); lblRadius.setHorizontalAlignment(SwingConstants.RIGHT); lblRadius.setBounds(10, 76, 180, 15); contentPane.add(lblRadius); JLabel lblCachearten = new JLabel("Cachearten:"); lblCachearten.setHorizontalAlignment(SwingConstants.RIGHT); lblCachearten.setBounds(10, 98, 180, 15); contentPane.add(lblCachearten); JLabel lblSchwierigkeitsbereich = new JLabel("Schwierigkeitsbereich:"); lblSchwierigkeitsbereich.setHorizontalAlignment(SwingConstants.RIGHT); lblSchwierigkeitsbereich.setBounds(10, 123, 180, 15); contentPane.add(lblSchwierigkeitsbereich); JLabel lblTerrainbereich = new JLabel("Terrainbereich:"); lblTerrainbereich.setHorizontalAlignment(SwingConstants.RIGHT); lblTerrainbereich.setBounds(10, 145, 180, 15); contentPane.add(lblTerrainbereich); //Textfelder fr Routenabfrage tfBenutzer = new JTextField(); tfBenutzer.addFocusListener(new FocusAdapter() { @Override public void focusGained(FocusEvent arg0) { tfBenutzer.selectAll(); } @Override public void focusLost(FocusEvent arg0) { ocUser = tfBenutzer.getText(); writeConfig(); } }); tfBenutzer.setBounds(196, 8, 150, 20); contentPane.add(tfBenutzer); tfBenutzer.setColumns(10); tfStart = new JTextField(); tfStart.addFocusListener(new FocusAdapter() { @Override public void focusGained(FocusEvent e) { tfStart.selectAll(); } @Override public void focusLost(FocusEvent e) { Start = tfStart.getText(); writeConfig(); } }); tfStart.setColumns(10); tfStart.setBounds(196, 30, 150, 20); contentPane.add(tfStart); tfZiel = new JTextField(); tfZiel.addFocusListener(new FocusAdapter() { @Override public void focusGained(FocusEvent e) { tfZiel.selectAll(); } @Override public void focusLost(FocusEvent e) { Ziel = tfZiel.getText(); writeConfig(); } }); tfZiel.setColumns(10); tfZiel.setBounds(196, 52, 150, 20); contentPane.add(tfZiel); tfRadius = new JTextField(); tfRadius.addFocusListener(new FocusAdapter() { @Override public void focusGained(FocusEvent e) { tfRadius.selectAll(); } @Override public void focusLost(FocusEvent e) { try { Radius = Double.parseDouble(tfRadius.getText()); } catch (NumberFormatException ex) { tfRadius.setText(df_radius.format(Radius)); if (debug) ex.printStackTrace(); } writeConfig(); } }); tfRadius.setColumns(10); tfRadius.setBounds(196, 74, 100, 20); contentPane.add(tfRadius); tfSchwierigkeitsbereich = new JTextField(); tfSchwierigkeitsbereich.addFocusListener(new FocusAdapter() { @Override public void focusGained(FocusEvent e) { tfSchwierigkeitsbereich.selectAll(); } @Override public void focusLost(FocusEvent e) { Difficulty = tfSchwierigkeitsbereich.getText(); writeConfig(); } }); tfSchwierigkeitsbereich.setColumns(10); tfSchwierigkeitsbereich.setBounds(196, 121, 100, 20); contentPane.add(tfSchwierigkeitsbereich); tfTerrainbereich = new JTextField(); tfTerrainbereich.addFocusListener(new FocusAdapter() { @Override public void focusGained(FocusEvent e) { tfTerrainbereich.selectAll(); } @Override public void focusLost(FocusEvent e) { Terrain = tfTerrainbereich.getText(); writeConfig(); } }); tfTerrainbereich.setColumns(10); tfTerrainbereich.setBounds(196, 143, 100, 20); contentPane.add(tfTerrainbereich); //Radiobuttons fr Auswahl der Cachearten JRadioButton rdbtnAlle = new JRadioButton("alle"); rdbtnAlle.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent arg0) { alleArten = true; } }); rdbtnAlle.setBounds(196, 96, 65, 23); contentPane.add(rdbtnAlle); JRadioButton rdbtnAuswaehlen = new JRadioButton("ausw\u00E4hlen"); rdbtnAuswaehlen.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent arg0) { try { arten_choose artenwahl = new arten_choose(); artenwahl.setVisible(true); } catch (Exception e) { e.printStackTrace(); } writeConfig(); alleArten = false; } }); rdbtnAuswaehlen.setBounds(260, 96, 120, 23); contentPane.add(rdbtnAuswaehlen); //Radiobuttons gruppieren, damit nur einer ausgewhlt werden kann ButtonGroup arten = new ButtonGroup(); arten.add(rdbtnAlle); arten.add(rdbtnAuswaehlen); //Beschriftung, wenn GPX-Route geladen JLabel lblGpxGeladen = new JLabel("Route geladen"); lblGpxGeladen.setFont(new Font("Tahoma", Font.ITALIC, 11)); lblGpxGeladen.setHorizontalAlignment(SwingConstants.CENTER); lblGpxGeladen.setBounds(364, 54, 170, 15); contentPane.add(lblGpxGeladen); lblGpxGeladen.setVisible(false); //GPX-Route laden via JFileChooser JButton btnGpxRouteLaden = new JButton("GPX-Route laden"); btnGpxRouteLaden.addKeyListener(new KeyAdapter() { @Override public void keyPressed(KeyEvent arg0) { if (arg0.getKeyCode() == KeyEvent.VK_ENTER) { //Enter-Taste gedrckt JFileChooser gpxeingabe = new JFileChooser(); FileNameExtensionFilter gpx = new FileNameExtensionFilter("GPX-Dateien", "gpx", "GPX"); gpxeingabe.setFileFilter(gpx); if (loadpath.equals("")) { File f = new File(System.getProperty("user.home") + File.separator + "occar"); gpxeingabe.setCurrentDirectory(f); } else { File f = new File(loadpath); gpxeingabe.setCurrentDirectory(f); } int option = gpxeingabe.showOpenDialog(null); if (option == JFileChooser.APPROVE_OPTION) { String pfadEingabe = gpxeingabe.getSelectedFile().getAbsolutePath(); if (FilenameUtils.getExtension(pfadEingabe).toUpperCase().equals("GPX")) { //System.out.println(pfadEingabe); loadpath = pfadEingabe; loadGPX = true; lblGpxGeladen.setVisible(true); } else { javax.swing.JOptionPane.showMessageDialog(null, "Dateiendung ist nicht GPX, sondern \"" + FilenameUtils.getExtension(pfadEingabe) + "\".", "Fehlerhafte Dateiendung", JOptionPane.WARNING_MESSAGE); } } } } }); btnGpxRouteLaden.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { JFileChooser gpxeingabe = new JFileChooser(); //Dateibrowser //nur GPX-Dateien erlauben FileNameExtensionFilter gpx = new FileNameExtensionFilter("GPX-Dateien", "gpx", "GPX"); gpxeingabe.setFileFilter(gpx); if (loadpath.equals("")) { //bisher noch keine (gltige) GPX-Datei geladen File f = new File(System.getProperty("user.home") + File.separator + "occar"); gpxeingabe.setCurrentDirectory(f); } else { //bereits einmal GPX-Datei geladen File f = new File(loadpath); gpxeingabe.setCurrentDirectory(f); } int option = gpxeingabe.showOpenDialog(null); //wenn Datei ausgewhlt worden ist if (option == JFileChooser.APPROVE_OPTION) { //Pfad ermitteln String pfadEingabe = gpxeingabe.getSelectedFile().getAbsolutePath(); //Dateiendung prfen if (FilenameUtils.getExtension(pfadEingabe).toUpperCase().equals("GPX")) { if (debug) System.out.println(pfadEingabe); loadpath = pfadEingabe; loadGPX = true; lblGpxGeladen.setVisible(true); //Info anzeigen } else { javax.swing.JOptionPane.showMessageDialog(null, "Dateiendung ist nicht GPX, sondern \"" + FilenameUtils.getExtension(pfadEingabe) + "\".", "Fehlerhafte Dateiendung", JOptionPane.WARNING_MESSAGE); } } } }); btnGpxRouteLaden.setBounds(364, 28, 170, 23); contentPane.add(btnGpxRouteLaden); //Trennstrich zwischen Routenkonfiguration und E-Mail-Einstellungen JSeparator sepAllgemeinMail = new JSeparator(); sepAllgemeinMail.setBounds(10, 170, 534, 2); contentPane.add(sepAllgemeinMail); //Beschriftungen bei Textfeldern fr E-Mail-Versand JLabel lblMailserver = new JLabel("E-Mail-Server:"); lblMailserver.setHorizontalAlignment(SwingConstants.RIGHT); lblMailserver.setBounds(10, 181, 100, 14); contentPane.add(lblMailserver); JLabel lblPort = new JLabel("Port:"); lblPort.setHorizontalAlignment(SwingConstants.RIGHT); lblPort.setBounds(275, 181, 100, 14); contentPane.add(lblPort); JLabel lblAbsender = new JLabel("Absender:"); lblAbsender.setHorizontalAlignment(SwingConstants.RIGHT); lblAbsender.setBounds(10, 209, 100, 14); contentPane.add(lblAbsender); JLabel lblEmpfaenger = new JLabel("Empf\u00E4nger:"); lblEmpfaenger.setHorizontalAlignment(SwingConstants.RIGHT); lblEmpfaenger.setBounds(275, 209, 100, 14); contentPane.add(lblEmpfaenger); JLabel lblBetreff = new JLabel("Betreff:"); lblBetreff.setHorizontalAlignment(SwingConstants.RIGHT); lblBetreff.setBounds(10, 237, 100, 14); contentPane.add(lblBetreff); JLabel lblMailtext = new JLabel("E-Mail-Text:"); lblMailtext.setHorizontalAlignment(SwingConstants.RIGHT); lblMailtext.setBounds(10, 265, 100, 14); contentPane.add(lblMailtext); //Textfelder fr E-Mail-Versand tfMailserver = new JTextField(); tfMailserver.addFocusListener(new FocusAdapter() { @Override public void focusGained(FocusEvent e) { tfMailserver.selectAll(); } @Override public void focusLost(FocusEvent e) { host = tfMailserver.getText(); writeConfig(); } }); tfMailserver.setBounds(113, 179, 165, 20); contentPane.add(tfMailserver); tfMailserver.setColumns(10); tfAbsender = new JTextField(); tfAbsender.addFocusListener(new FocusAdapter() { @Override public void focusGained(FocusEvent e) { tfAbsender.selectAll(); } @Override public void focusLost(FocusEvent e) { sender = tfAbsender.getText(); writeConfig(); } }); tfAbsender.setBounds(113, 207, 165, 20); contentPane.add(tfAbsender); tfAbsender.setColumns(10); tfEmpfaenger = new JTextField(); tfEmpfaenger.addFocusListener(new FocusAdapter() { @Override public void focusGained(FocusEvent e) { tfEmpfaenger.selectAll(); } @Override public void focusLost(FocusEvent e) { receiver = tfEmpfaenger.getText(); writeConfig(); } }); tfEmpfaenger.setColumns(10); tfEmpfaenger.setBounds(378, 207, 165, 20); contentPane.add(tfEmpfaenger); tfBetreff = new JTextField(); tfBetreff.addFocusListener(new FocusAdapter() { @Override public void focusGained(FocusEvent e) { tfBetreff.selectAll(); } @Override public void focusLost(FocusEvent e) { subject = tfBetreff.getText(); writeConfig(); } }); tfBetreff.setBounds(113, 235, 431, 20); contentPane.add(tfBetreff); tfBetreff.setColumns(10); tfMailtext = new JTextField(); tfMailtext.addFocusListener(new FocusAdapter() { @Override public void focusGained(FocusEvent e) { tfMailtext.selectAll(); } @Override public void focusLost(FocusEvent e) { body = tfMailtext.getText(); writeConfig(); } }); tfMailtext.setBounds(113, 263, 431, 20); contentPane.add(tfMailtext); tfMailtext.setColumns(10); tfPort = new JTextField(); tfPort.addFocusListener(new FocusAdapter() { @Override public void focusGained(FocusEvent arg0) { tfPort.selectAll(); } @Override public void focusLost(FocusEvent e) { try { port = Integer.toString(Integer.parseInt(tfPort.getText())); } catch (NumberFormatException ex) { tfPort.setText(port); if (debug) ex.printStackTrace(); } writeConfig(); } }); tfPort.setBounds(378, 179, 120, 20); contentPane.add(tfPort); tfPort.setColumns(10); JLabel lblPasswort = new JLabel("Passwort:"); lblPasswort.setHorizontalAlignment(SwingConstants.RIGHT); lblPasswort.setBounds(10, 293, 100, 14); contentPane.add(lblPasswort); JPasswordField pfPassword = new JPasswordField(); pfPassword.setBounds(113, 291, 120, 20); contentPane.add(pfPassword); //Trennstrich zwischen E-Mail-Einstellungen und Meldungslabel JSeparator sepMailProgress = new JSeparator(); sepMailProgress.setBounds(10, 318, 534, 2); contentPane.add(sepMailProgress); //Meldungslabel lblFortschritt.setHorizontalAlignment(SwingConstants.CENTER); lblFortschritt.setBounds(10, 327, 534, 20); contentPane.add(lblFortschritt); //Button zum Starten der Suche JButton btnStartSuche = new JButton("Caches suchen"); btnStartSuche.addKeyListener(new KeyAdapter() { @Override public void keyPressed(KeyEvent e) { if (e.getKeyCode() == KeyEvent.VK_ENTER) { if (rdtbnAlle.isSelected()) { alleArten = true; } else { alleArten = false; } try { char[] input = pfPassword.getPassword(); String temp = ""; for (int i = 0; i < pfPassword.getPassword().length; i++) { temp += input[i]; } password = temp; } catch (ArrayIndexOutOfBoundsException ex) { if (debug) System.out.println("Kein Passwort angegeben"); } sucheStarten(); lblGpxGeladen.setVisible(false); loadGPX = false; if (!savePW) { password = ""; } writeConfig(); } } }); btnStartSuche.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent arg0) { //Passwort ermitteln try { char[] input = pfPassword.getPassword(); String temp = ""; for (int i = 0; i < pfPassword.getPassword().length; i++) { temp += input[i]; } password = temp; } catch (ArrayIndexOutOfBoundsException e) { if (debug) System.out.println("Kein Passwort angegeben"); } sucheStarten(); //Suche durch Funktionsaufruf starten lblGpxGeladen.setVisible(false); //eventuelll sichtbares Label deaktivieren loadGPX = false; //keine GPX-Datei mehr geladen if (!savePW) { //wenn Passwort nicht gespeichert werden soll password = ""; //Passwortvariable leeren } writeConfig(); //evtl. vorhandenes Passwort in Konfiguration schreiben } }); btnStartSuche.setBounds(364, 119, 170, 23); contentPane.add(btnStartSuche); //Passwort speichern? JCheckBox boxSavePW = new JCheckBox("Passwort speichern"); boxSavePW.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent arg0) { if (boxSavePW.isSelected()) { //wenn mit Maus geklickt und Box selektiert savePW = true; //Passwort speichern } else { savePW = false; } } }); boxSavePW.setBounds(249, 289, 170, 22); contentPane.add(boxSavePW); //E-Mail versenden? JCheckBox boxSendEmail = new JCheckBox("E-Mail senden"); boxSendEmail.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent arg0) { if (boxSendEmail.isSelected()) { sendEmail = true; } else { sendEmail = false; } System.out.println(sendEmail); } }); boxSendEmail.setBounds(364, 72, 170, 25); contentPane.add(boxSendEmail); checkNewVersion(); //auf neue Version prfen readConfig(); //Konfigurationsdatei lesen printInitialConfig(); //Konfiguration ausgeben //einen Radiobutton entsprechend der Konfiguration vorbelegen if (Arten == 1023) { rdbtnAlle.setSelected(true); alleArten = true; } else { rdtbnAuswaehlen.setSelected(true); alleArten = false; } //Checkbox zur Passwortspeicherung entsprechend der Konfiguration einstellen if (password.equals("")) { boxSavePW.setSelected(false); savePW = false; } else { boxSavePW.setSelected(true); savePW = true; pfPassword.setText(password); } //Checkbox zum E-Mail-Versand entsprechend der Konfiguration einstellen if (sendEmail) { boxSendEmail.setSelected(true); } else { boxSendEmail.setSelected(false); } } //Zahlenwert fr Cachearten erhalten (in Klasse arten_choose verwendet) public int getCachearten() { return Arten; } //Zahlenwert fr Cachearten setzen (in Klasse arten_choose verwendet) public void setCachearten(int cachearten) { oc_car.Arten = cachearten; } //Parameter in Konfigurationsdatei schreiben private boolean writeConfig() { try { //Parameter fr Routenabfrage config.setProperty("ocUser", ocUser); config.setProperty("Radius", df_radius.format(Radius)); config.setProperty("Start", Start); config.setProperty("Ziel", Ziel); config.setProperty("Arten", Integer.toString(Arten)); config.setProperty("Difficulty", Difficulty); config.setProperty("Terrain", Terrain); //Parameter fr E-Mail-Versand config.setProperty("host", host); config.setProperty("port", port); config.setProperty("sender", sender); config.setProperty("receiver", receiver); config.setProperty("subject", subject); config.setProperty("body", body); config.setProperty("sendEmail", Boolean.toString(sendEmail)); if (savePW) { config.setProperty("password", password); } else { config.setProperty("password", ""); } //in XML-Datei schreiben File f = new File(System.getProperty("user.home") + File.separator + "occar" + File.separator + "occar_config.xml"); OutputStream o = new FileOutputStream(f); config.storeToXML(o, "Config-Datei fr oc_car-gui"); } catch (IOException e) { if (debug) e.printStackTrace(); return false; } return true; } //Parameter aus Konfiguration lesen private boolean readConfig() { InputStream s = null; try { //Dateipfad zusammensetzen File f = new File(System.getProperty("user.home") + File.separator + "occar" + File.separator + "occar_config.xml"); if (!f.exists()) { //wenn Datei nicht existiert writeConfig(); //Datei mit Inhalt erstellen } else { //Datei existiert //aus XML-Datei lesen s = new FileInputStream(f); config.loadFromXML(s); //Parameter fr Routenabfrage ocUser = config.getProperty("ocUser", "User"); Radius = Double.parseDouble(config.getProperty("Radius", "2")); Start = config.getProperty("Start", "Stuttgart"); Ziel = config.getProperty("Ziel", "Mnchen"); Arten = Integer.parseInt(config.getProperty("Arten", "1023")); Difficulty = config.getProperty("Difficulty", "1-5"); Terrain = config.getProperty("Terrain", "1-5"); //Parameter fr E-Mail-Versand host = config.getProperty("host", "smtp.gmail.com"); port = config.getProperty("port", "587"); sender = config.getProperty("sender", "[email protected]"); receiver = config.getProperty("receiver", "[email protected]"); subject = config.getProperty("subject", "oc_car - Die GPX-Datei fr Deine Route"); body = config.getProperty("body", "Die GPX-Datei fr Deine Route!"); sendEmail = Boolean.parseBoolean(config.getProperty("sendEmail", "false")); password = config.getProperty("password", ""); System.out.println(password); } } catch (IOException e) { if (debug) e.printStackTrace(); return false; } return true; } //am Programmbeginn Daten aus Konfigurationsdatei in die Textfelder schreiben private void printInitialConfig() { tfBenutzer.setText(ocUser); tfStart.setText(Start); tfZiel.setText(Ziel); tfRadius.setText(df_radius.format(Radius)); tfSchwierigkeitsbereich.setText(Difficulty); tfTerrainbereich.setText(Terrain); tfMailserver.setText(host); tfAbsender.setText(sender); tfEmpfaenger.setText(receiver); tfBetreff.setText(subject); tfMailtext.setText(body); tfPort.setText(port); } //Opencaching.de Benutzer-ID ermitteln private boolean getUUID() { URL url; InputStream is = null; BufferedReader br; String line = ""; try { url = new URL("http://www.opencaching.de/okapi/services/users/by_username?username=" + ocUser + "&fields=uuid&consumer_key=8YV657YqzqDcVC3QC9wM"); is = url.openStream(); br = new BufferedReader(new InputStreamReader(is)); line = br.readLine(); //Antwort speichern (nur eine Zeile zurckgeliefert) is.close(); } catch (MalformedURLException e) { if (debug) e.printStackTrace(); return false; } catch (IOException e) { javax.swing.JOptionPane.showMessageDialog(null, "Benutzer nicht gefunden!\nBitte Aufrufparameter prfen!", "Ungltiger Benutzername", JOptionPane.INFORMATION_MESSAGE); if (debug) System.out.println("Benutzer nicht gefunden! Bitte Aufrufparameter prfen!"); if (debug) System.out.println(line); return false; } if (debug) System.out.println(line); try { //Rckgabestring auf String "uuid" berprfen if (!line.substring(2,6).equals("uuid")) return false; } catch (StringIndexOutOfBoundsException e) { if (debug) e.printStackTrace(); return false; } UUID = line.substring(9,line.length() - 2); //Benutzer-ID extrahieren if (debug) System.out.println("Benutzer wurde gefunden."); return true; } //Koordinaten des Startpunktes ermitteln private boolean getCoordsOfStart() { URL url; InputStream is = null; BufferedReader br; String line = ""; String Start_mod = ""; //Umlaute, Leerzeichen ersetzen; ungltige Zeichen entfernen for (int i = 0; i < Start.length(); i++) { switch (Start.charAt(i)) { case ' ': Start_mod += "+"; break; case '': case '': Start_mod += "ae"; break; case '': case '': Start_mod += "oe"; break; case '': case '': Start_mod += "ue"; break; case '': Start_mod += "ss"; break; default: if ((((Start.charAt(i) >= 'A') && Start.charAt(i) <= 'Z')) || ((Start.charAt(i) >= 'a') && (Start.charAt(i) <= 'z')) || ((Start.charAt(i) >= '0') && (Start.charAt(i) <= '9'))) { Start_mod += Start.charAt(i); }; } } if (debug) System.out.println(Start_mod); try { url = new URL("http://nominatim.openstreetmap.org/search?q=" + Start_mod + "&format=json"); is = url.openStream(); br = new BufferedReader(new InputStreamReader(is)); line = br.readLine(); is.close(); } catch (MalformedURLException e) { if (debug) e.printStackTrace(); return false; } catch (IOException e) { if (debug) e.printStackTrace(); if (debug) System.out.println(line); return false; } if (debug) System.out.println(line); try { int i = 0; boolean gefunden = false; //nach erstem Auftauchen des "lat"-Strings suchen while (i < line.length() && !gefunden) { if (line.substring(i, i + 6).equals("lat\":\"")) { gefunden = true; } else { i++; } } int j = i + 7; //Ende der lat-Koordinate suchen while (line.charAt(j) != '"') { j++; } latS = line.substring(i + 6, j); int k = j + 9; //Ende der lng-Koordinate suchen while (line.charAt(k) != '"') { k++; } lngS = line.substring(j+9, k); } catch (StringIndexOutOfBoundsException e) { if (debug) e.printStackTrace(); return false; } if (debug) System.out.println(latS + "," + lngS); return true; } private boolean getCoordsOfZiel() { URL url; InputStream is = null; BufferedReader br; String line = ""; String Ziel_mod = ""; for (int i = 0; i < Ziel.length(); i++) { switch (Ziel.charAt(i)) { case ' ': Ziel_mod += "+"; break; case '': case '': Ziel_mod += "ae"; break; case '': case '': Ziel_mod += "oe"; break; case '': case '': Ziel_mod += "ue"; break; case '': Ziel_mod += "ss"; break; default: if ((((Ziel.charAt(i) >= 'A') && Ziel.charAt(i) <= 'Z')) || ((Ziel.charAt(i) >= 'a') && (Ziel.charAt(i) <= 'z')) || ((Ziel.charAt(i) >= '0') && (Ziel.charAt(i) <= '9'))) { Ziel_mod += Ziel.charAt(i); }; } } if (debug) System.out.println(Ziel_mod); try { url = new URL("http://nominatim.openstreetmap.org/search?q=" + Ziel_mod + "&format=json"); is = url.openStream(); // throws an IOException br = new BufferedReader(new InputStreamReader(is)); line = br.readLine(); is.close(); } catch (MalformedURLException e) { if (debug) e.printStackTrace(); return false; } catch (IOException e) { if (debug) e.printStackTrace(); return false; } if (debug) System.out.println(line); try { int i = 0; boolean gefunden = false; while (i < line.length() && !gefunden) { if (line.substring(i, i + 6).equals("lat\":\"")) { gefunden = true; } else { i++; } } int j = i + 7; while (line.charAt(j) != '"') { j++; } latZ = line.substring(i + 6, j); int k = j + 9; while (line.charAt(k) != '"') { k++; } lngZ = line.substring(j+9, k); } catch (StringIndexOutOfBoundsException e) { if (debug) e.printStackTrace(); return false; } if (debug) System.out.println(latZ + "," + lngZ); return true; } //KML-Route herunterladen private boolean downloadKMLRoute() { try { //Route berechnen und in Datei herunterladen URL url = new URL("http://www.yournavigation.org/api/1.0/gosmore.php?flat=" + latS + "&flon=" + lngS + "&tlat=" + latZ + "&tlon=" + lngZ + "&v=motorcar&fast=1"); File file = new File(System.getProperty("user.home") + File.separator + "occar" + File.separator + "route.kml"); if (file.exists()) { file.delete(); //eventuell existierende Datei gleichen Namens lschen } FileUtils.copyURLToFile(url, file, 0, 0); //Datei speichern } catch (MalformedURLException e) { if (debug) e.printStackTrace(); return false; } catch (IOException e) { if (debug) e.printStackTrace(); return false; } return true; } //Routenkoordinaten aus KML-Datei auslesen private boolean KML2Array() { int stelleImArray = 0; try { BufferedReader br = new BufferedReader(new FileReader(System.getProperty("user.home") + File.separator + "occar" + File.separator + "route.kml")); String line = br.readLine(); int anzahlZeilen = 0; while (line != null) { //solange noch nicht Dateiende erreicht if (line.charAt(0) != '<' && line.charAt(0) != ' ') { //linksbndige Zeile suchen if (anzahlZeilen % 10 == 0) { //nur jede 10. Zeile im Array speichern coords_list[stelleImArray] = line; stelleImArray++; } anzahlZeilen++; } line = br.readLine(); //neue Zeile lesen } br.close(); } catch (IOException e) { if (debug) e.printStackTrace(); return false; } catch (ArrayIndexOutOfBoundsException e) { if (debug) e.printStackTrace(); return false; } if (debug) { System.out.println(stelleImArray); /*for (int i = 0; i < stelleImArray; i++) { System.out.println(coords_list[i]); }*/ } anzahlAbfragen = stelleImArray; return true; } //Routenkoordinaten aus GPX-Datei auslesen private boolean GPX2Array() { int stelleImArray = 0; try { BufferedReader br = new BufferedReader(new FileReader(loadpath)); String line = br.readLine(); int anzahlZeilen = 0; while (line != null) { //solange noch nicht Dateiende erreicht int startpunkt = 0; for (int i = 0; i < line.length() - 8; i++) { if (line.substring(i, i+9).equals("trkpt lat")) { //nach Trackpoint suchen if (anzahlZeilen % 10 == 0) { //nur jeden 10. Trackpoint im Array speichern startpunkt = i + 12; int endpunkt = startpunkt; //Ende des 2. Koordinatenpaarelements suchen while (!line.substring(endpunkt, endpunkt+7).equals("\" lon=\"")) { endpunkt++; } String teil2 = line.substring(startpunkt-1, endpunkt); //System.out.println(teil2); endpunkt += 6; startpunkt = endpunkt; //Ende des 1. Koordinatenpaarelements suchen while ((!line.substring(endpunkt, endpunkt+3).equals("\"/>"))) { endpunkt++; } String teil1 = line.substring(startpunkt + 1, endpunkt); //System.out.println(teil1); coords_list[stelleImArray] = teil1 + "," + teil2; stelleImArray++; } anzahlZeilen++; } } line = br.readLine(); //nchste Zeile lesen } br.close(); } catch (IOException e) { if (debug) e.printStackTrace(); return false; } catch (ArrayIndexOutOfBoundsException e) { if (debug) e.printStackTrace(); return false; } catch (StringIndexOutOfBoundsException e) { if (debug) e.printStackTrace(); return false; } if (debug) { System.out.println(stelleImArray); /*for (int i = 0; i < stelleImArray; i++) { System.out.println(coords_list[i]); }*/ } anzahlAbfragen = stelleImArray; return true; } //Radius berprfen private boolean checkRadius() { if (Radius < 0.1) { //Radius gro genug javax.swing.JOptionPane.showMessageDialog(null, "Der eingegebene Radius ist zu klein!"); return false; } if (Radius > 10) { //Radius klein genug javax.swing.JOptionPane.showMessageDialog(null, "Der eingegebene Radius ist zu gro!"); return false; } return true; } //Caches entlang der Route suchen private boolean requestCaches() { //Fortschrittsframe aktivieren progressBar progress = new progressBar(); progress.setVisible(true); String arten = ""; //gewnschte Cachearten auslesen if (!alleArten) { //bitweiser Vergleich mit entsprechender Maske if ((Arten & (1<<0)) == (1<<0)) { if (arten.equals("")) { arten += "Traditional"; } else { arten += "|Traditional"; } } if ((Arten & (1<<1)) == (1<<1)) { if (arten.equals("")) { arten += "Multi"; } else { arten += "|Multi"; } } if ((Arten & (1<<2)) == (1<<2)) { if (arten.equals("")) { arten += "Quiz"; } else { arten += "|Quiz"; } } if ((Arten & (1<<3)) == (1<<3)) { if (arten.equals("")) { arten += "Virtual"; } else { arten += "|Virtual"; } } if ((Arten & (1<<4)) == (1<<4)) { if (arten.equals("")) { arten += "Event"; } else { arten += "|Event"; } } if ((Arten & (1<<5)) == (1<<5)) { if (arten.equals("")) { arten += "Webcam"; } else { arten += "|Webcam"; } } if ((Arten & (1<<6)) == (1<<6)) { if (arten.equals("")) { arten += "Moving"; } else { arten += "|Moving"; } } if ((Arten & (1<<7)) == (1<<7)) { if (arten.equals("")) { arten += "Math/Physics"; } else { arten += "|Math/Physics"; } } if ((Arten & (1<<8)) == (1<<8)) { if (arten.equals("")) { arten += "Drive-In"; } else { arten += "|Drive-In"; } } if ((Arten & (1<<9)) == (1<<9)) { if (arten.equals("")) { arten += "Other"; } else { arten += "|Other"; } } } int stelleImArray = 0; String[] alle = new String[anzahlAbfragen]; for (int i = 0; i < anzahlAbfragen; i++) { URL url; InputStream is = null; BufferedReader br; String line = ""; //die Koordinaten werden genau verkehrt herum gespeichert und mssen umgedreht werden int j = 0; String coords_fehler = coords_list[i]; while (coords_fehler.charAt(j) != ',') { j++; } String coords = coords_fehler.substring(j+1, coords_fehler.length()) + "|" + coords_fehler.substring(0, j); //System.out.println(coords); try { //Abfrage durchfhren (Mittelpunkt-Suche mit Radius) if (alleArten) { url = new URL("http://www.opencaching.de/okapi/services/caches/search/nearest?center=" + coords + "&radius=" + df_radius.format(Radius) + "&difficulty=" + Difficulty + "&terrain=" + Terrain + "&status=Available&consumer_key=8YV657YqzqDcVC3QC9wM"); } else { url = new URL("http://www.opencaching.de/okapi/services/caches/search/nearest?center=" + coords + "&radius=" + df_radius.format(Radius) + "&type=" + arten + "&difficulty=" + Difficulty + "&terrain=" + Terrain + "&status=Available&consumer_key=8YV657YqzqDcVC3QC9wM"); } //System.out.println(url); is = url.openStream(); br = new BufferedReader(new InputStreamReader(is)); line = br.readLine(); is.close(); } catch (MalformedURLException e) { if (debug) e.printStackTrace(); return false; } catch (IOException e) { if (debug) e.printStackTrace(); return false; } //System.out.println(line); //Fortschritt progress.updatebar((100 * i) / anzahlAbfragen); //prfen, ob Dose gefunden if (line.length() < 30) { //keine Dose in diesem Bereich } else { String a = line.substring(13, line.length() - 16); String b = a.replace("\"", ""); //Anfhrungszeichen durch Leerzeichen ersetzen b = b.replace(",", " "); //Kommas durch Leerzeichen ersetzen alle[stelleImArray] = b; //Ergebnis der Abfrage zum Array hinzufgen stelleImArray++; } } if (debug) { for (int i = 0; i < stelleImArray; i++) { System.out.println(alle[i]); } System.out.println("---"); } //Duplikate filtern und OC-Codes feldweise in Array schreiben ohneDuplikate = 0; for (int i = 0; i < stelleImArray; i++) { int startpunkt = 0; int endpunkt = 0; String aktuell = alle[i]; //System.out.println(aktuell); while (endpunkt < aktuell.length()) { if (aktuell.charAt(endpunkt) == ' ') { if (ohneDuplikate == 0) { caches[0] = aktuell.substring(startpunkt, endpunkt); startpunkt = endpunkt + 1; ohneDuplikate++; } else { String teilstring = aktuell.substring(startpunkt, endpunkt); boolean schon_vorhanden = false; for (int j = 0; j < ohneDuplikate; j++) { if (teilstring.equals(caches[j])) { schon_vorhanden = true; startpunkt = endpunkt + 1; } } if (!schon_vorhanden) { caches[ohneDuplikate] = teilstring; startpunkt = endpunkt + 1; ohneDuplikate++; } } } endpunkt++; } String teilstring = aktuell.substring(startpunkt, endpunkt); boolean schon_vorhanden = false; for (int j = 0; j < ohneDuplikate; j++) { if (teilstring.equals(caches[j])) { schon_vorhanden = true; startpunkt = endpunkt + 1; } } if (!schon_vorhanden) { caches[ohneDuplikate] = teilstring; startpunkt = endpunkt + 1; ohneDuplikate++; } } if (debug) System.out.println("Gefundene Listings ohne Duplikate: " + ohneDuplikate); if (debug) { for (int i = 0; i < ohneDuplikate; i++) { System.out.print(caches[i] + " , "); } } progress.dispose(); //Fortschrittsframe schlieen return true; } //GPX-Dateien mit den gefundenen und gefilterten Caches herunterladen private boolean downloadCaches() { int anzahlAufrufe = ohneDuplikate / 500 + 1; int ende = 0; if (ohneDuplikate < 500) { ende = ohneDuplikate; } else { ende = 500; } for (int i = 0; i < anzahlAufrufe; i++) { String codes_aufruf = caches[i*500]; for (int j = i * 500 + 1; j < ende; j++) { codes_aufruf = codes_aufruf + "|" + caches[j]; } DateFormat dateFormat = new SimpleDateFormat("yyyyMMdd-HHmmss"); Date date = new Date(); String outputFile = dateFormat.format(date) + "PQ.gpx"; if (debug) System.out.println(codes_aufruf); try { URL url = new URL("http://www.opencaching.de/okapi/services/caches/formatters/gpx?cache_codes=" + codes_aufruf + "&consumer_key=8YV657YqzqDcVC3QC9wM&ns_ground=true&latest_logs=true&mark_found=true&user_uuid=" + UUID); File file = new File(System.getProperty("user.home") + File.separator + "occar" + File.separator + outputFile); FileUtils.copyURLToFile(url, file, 0, 0); } catch (MalformedURLException e) { if (debug) e.printStackTrace(); return false; } catch (IOException e) { if (debug) e.printStackTrace(); return false; } if (sendEmail) { //E-Mail-Versand gewnscht boolean erfolg = false; erfolg = email.sendMailWithAttachment(host, port, sender, receiver, password, outputFile, subject, body, debug); if (erfolg) { lblFortschritt.setText("Die Datei(en) wurden im Verzeichnis abgelegt und per E-Mail versendet."); } else { lblFortschritt.setText("Fehler beim Versenden der Datei(en)! Passwort prfen!"); } } else { //kein E-Mail-Versand gewnscht lblFortschritt.setText("Die Datei " + outputFile + " wurde gespeichert!"); } if (ende < ohneDuplikate) { if ((ende + 500) < ohneDuplikate) { ende += 500; } else { ende = ohneDuplikate; } } } return true; } //auf neue Programmversion prfen private boolean checkNewVersion() { URL url; InputStream is = null; BufferedReader br; String line = ""; try { //Dateiinhalt der Versionsdatei von Github ermitteln url = new URL("https://raw.githubusercontent.com/FriedrichFroebel/oc_car-gui/master/version"); is = url.openStream(); br = new BufferedReader(new InputStreamReader(is)); line = br.readLine(); if (debug) System.out.println("Inhalt Versionscheck: " + line); is.close(); } catch (MalformedURLException e) { if (debug) e.printStackTrace(); return false; } catch (IOException e) { if (debug) e.printStackTrace(); return false; } if (!line.equals(version)) { //Zeileninhalt stimmt nicht mit Versionsangabe des Programms berein //Information anzeigen javax.swing.JOptionPane.showMessageDialog(null, "Neue Version verfgbar:\n" + "https://github.com/FriedrichFroebel/oc_car-gui/releases", "Versionshinweis", JOptionPane.INFORMATION_MESSAGE); return true; } else { if (debug) System.out.println("Es wird bereits die aktuellste Version verwendet."); } return false; } //Aufruf der einzelnen Elemente der Suche private boolean sucheStarten() { if (debug) System.out.println(System.getProperty("user.home")); /* * die eigentlich wichtigen Schritte * nur bei Gltigkeit des vorhergehenden wird der nchste ausgefhrt * sonst bricht das Programm ab und gibt bei aktivierter Debug-Flag * eine Hinweismeldung aus, wo der Fehler aufgetreten ist */ if (getUUID()) { if (getCoordsOfStart() && getCoordsOfZiel()) { if (loadGPX) { if (GPX2Array()) { if (checkRadius()) { if (requestCaches()) { if (!downloadCaches()) { if (debug) System.out.println("Abbruch: downloadCaches()"); } } else { if (debug) System.out.println("Abbruch: requestCaches()"); } } else { if (debug) System.out.println("Abbruch: checkRadius()"); } } else { if (debug) System.out.println("Abbruch: GPX2Array()"); } } else { if (downloadKMLRoute()) { if (KML2Array()) { if (checkRadius()) { if (requestCaches()) { if (!downloadCaches()) { if (debug) System.out.println("Abbruch: downloadCaches()"); return false; } } else { if (debug) System.out.println("Abbruch: requestCaches()"); return false; } } else { if (debug) System.out.println("Abbruch: checkRadius()"); return false; } } else { if (debug) System.out.println("Abbruch: KML2Array()"); return false; } } else { if (debug) System.out.println("Abbruch: downloadKMLRoute()"); return false; } } } else { if (debug) System.out.println("Abbruch: getCoords()"); return false; } } else { if (debug) System.out.println("Abbruch: getUUID()"); return false; } return true; } }
Laden von GPX korrigiert; erweiterte Prüfung der Eingabeparameter
src/oc_car.java
Laden von GPX korrigiert; erweiterte Prüfung der Eingabeparameter
<ide><path>rc/oc_car.java <ide> public class oc_car extends JFrame { <ide> <ide> //Programmversion zur Analyse fr eventuell verfgbares Update <del> private static String version = "1.3"; <add> private static String version = "1.4"; <ide> <ide> //erweiterte Konsolenausgabe ist standardmig deaktiviert <ide> private static boolean debug = false; <ide> private static boolean alleArten = true; <ide> private static boolean loadGPX = false; <ide> private static boolean savePW = false; <add> <add> //Konstanten <add> int GPX_AbstandWP = 10; //nur jeder 10. Wegpunkt wird gespeichert <add> int KML_AbstandWP = 10; //nur jeder 10. Wegpunkt wird gespeichert <ide> <ide> //Konfigurationswerte <ide> private static String ocUser = "User"; <ide> } <ide> @Override <ide> public void focusLost(FocusEvent arg0) { <del> ocUser = tfBenutzer.getText(); <del> writeConfig(); <add> if (!tfBenutzer.getText().equals("")) { <add> ocUser = tfBenutzer.getText(); <add> writeConfig(); <add> } else { <add> //tfBenutzer.setText(ocUser); <add> } <ide> } <ide> }); <ide> tfBenutzer.setBounds(196, 8, 150, 20); <ide> } <ide> @Override <ide> public void focusLost(FocusEvent e) { <del> Start = tfStart.getText(); <del> writeConfig(); <add> if (!tfStart.getText().equals("")) { <add> Start = tfStart.getText(); <add> writeConfig(); <add> } else { <add> //tfStart.setText(Start); <add> } <ide> } <ide> }); <ide> tfStart.setColumns(10); <ide> } <ide> @Override <ide> public void focusLost(FocusEvent e) { <del> Ziel = tfZiel.getText(); <del> writeConfig(); <add> if (!tfZiel.getText().equals("")) { <add> Ziel = tfZiel.getText(); <add> writeConfig(); <add> } else { <add> //tfZiel.setText(Ziel); <add> } <ide> } <ide> }); <ide> tfZiel.setColumns(10); <ide> } <ide> @Override <ide> public void focusLost(FocusEvent e) { <del> Difficulty = tfSchwierigkeitsbereich.getText(); <del> writeConfig(); <add> if (!tfSchwierigkeitsbereich.getText().equals("")) { <add> int minus = 0; <add> String string = tfSchwierigkeitsbereich.getText(); <add> while ((string.charAt(minus) != '-') && (minus < string.length() - 1)) { <add> minus += 1; <add> } <add> try { <add> Double.parseDouble(string.substring(0,minus)); <add> Double.parseDouble(string.substring(minus+1,string.length())); <add> Difficulty = string; <add> } catch (NumberFormatException ex) { <add> tfSchwierigkeitsbereich.setText(Difficulty); <add> if (debug) ex.printStackTrace(); <add> } <add> } <ide> } <ide> }); <ide> tfSchwierigkeitsbereich.setColumns(10); <ide> } <ide> @Override <ide> public void focusLost(FocusEvent e) { <del> Terrain = tfTerrainbereich.getText(); <del> writeConfig(); <add> if (!tfTerrainbereich.getText().equals("")) { <add> int minus = 0; <add> String string = tfTerrainbereich.getText(); <add> while ((string.charAt(minus) != '-') && (minus < string.length() - 1)) { <add> minus += 1; <add> } <add> try { <add> Double.parseDouble(string.substring(0,minus)); <add> Double.parseDouble(string.substring(minus+1,string.length())); <add> Terrain = string; <add> } catch (NumberFormatException ex) { <add> tfTerrainbereich.setText(Terrain); <add> if (debug) ex.printStackTrace(); <add> } <add> } <ide> } <ide> }); <ide> tfTerrainbereich.setColumns(10); <ide> } catch (Exception e) { <ide> e.printStackTrace(); <ide> } <del> writeConfig(); <del> alleArten = false; <add> if (Arten != 0) { <add> alleArten = false; <add> writeConfig(); <add> } else { <add> alleArten = true; <add> Arten = 1023; <add> writeConfig(); <add> rdtbnAlle.setSelected(true); <add> } <ide> } <ide> }); <ide> rdbtnAuswaehlen.setBounds(260, 96, 120, 23); <ide> <ide> while (line != null) { //solange noch nicht Dateiende erreicht <ide> if (line.charAt(0) != '<' && line.charAt(0) != ' ') { //linksbndige Zeile suchen <del> if (anzahlZeilen % 10 == 0) { //nur jede 10. Zeile im Array speichern <add> if (anzahlZeilen % KML_AbstandWP == 0) { //nur jede X. Zeile im Array speichern <ide> coords_list[stelleImArray] = line; <ide> stelleImArray++; <ide> } <ide> <ide> for (int i = 0; i < line.length() - 8; i++) { <ide> if (line.substring(i, i+9).equals("trkpt lat")) { //nach Trackpoint suchen <del> if (anzahlZeilen % 10 == 0) { //nur jeden 10. Trackpoint im Array speichern <add> if (anzahlZeilen % GPX_AbstandWP == 0) { //nur jeden X. Trackpoint im Array speichern <ide> startpunkt = i + 12; <ide> int endpunkt = startpunkt; <ide> //Ende des 2. Koordinatenpaarelements suchen <ide> * eine Hinweismeldung aus, wo der Fehler aufgetreten ist <ide> */ <ide> if (getUUID()) { <del> if (getCoordsOfStart() && getCoordsOfZiel()) { <del> if (loadGPX) { <del> if (GPX2Array()) { <del> if (checkRadius()) { <del> if (requestCaches()) { <del> if (!downloadCaches()) { <del> if (debug) System.out.println("Abbruch: downloadCaches()"); <del> } <del> } else { <del> if (debug) System.out.println("Abbruch: requestCaches()"); <add> if (loadGPX) { <add> if (GPX2Array()) { <add> if (checkRadius()) { <add> if (requestCaches()) { <add> if (!downloadCaches()) { <add> if (debug) System.out.println("Abbruch: downloadCaches()"); <ide> } <ide> } else { <del> if (debug) System.out.println("Abbruch: checkRadius()"); <add> if (debug) System.out.println("Abbruch: requestCaches()"); <ide> } <ide> } else { <del> if (debug) System.out.println("Abbruch: GPX2Array()"); <add> if (debug) System.out.println("Abbruch: checkRadius()"); <ide> } <ide> } else { <add> if (debug) System.out.println("Abbruch: GPX2Array()"); <add> } <add> } else { <add> if (getCoordsOfStart() && getCoordsOfZiel()) { <ide> if (downloadKMLRoute()) { <ide> if (KML2Array()) { <ide> if (checkRadius()) { <ide> if (debug) System.out.println("Abbruch: downloadKMLRoute()"); <ide> return false; <ide> } <del> } <del> } else { <del> if (debug) System.out.println("Abbruch: getCoords()"); <del> return false; <add> } else { <add> if (debug) System.out.println("Abbruch: getCoords()"); <add> return false; <add> } <ide> } <ide> } else { <ide> if (debug) System.out.println("Abbruch: getUUID()");
JavaScript
mit
42a38199496fb57b3274158518cbe6755245b5d4
0
dwpdigitaltech/dwp-portfolio,LandRegistry/digital-portfolio,LandRegistry/digital-portfolio,dwpdigitaltech/dwp-portfolio
{ "id":10, "name":"Real Time Earnings", "description": "Allows benefit processing staff to get real time employment information about a claimant so that claims can be processed more accurately.", "theme": "Fraud & Debt", "location": "Leeds", "phase":"beta", "facing":"internal", "sro":"John Fundry", "service_man":"TBC", "phase-history":{ "discovery": [ {"label":"Completed", "date": "September 2014"} ], "alpha": [ {"label":"Completed", "date": "December 2014"} ], "beta": [ {"label":"Started", "date": "January 2015"}, {"label":"Private Beta", "date": "February 2016"}, {"label":"Public Beta Predicted", "date": "April 2016"} ] }, "priority":"Top" }
lib/projects/real-time-earnings.js
{ "id":10, "name":"Real Time Earnings", "description": "Allows benefit processing staff to get real time employment information about a claimant so that claims can be processed more accurately.", "theme": "Fraud & Debt", "location": "Leeds", "phase":"beta", "facing":"internal", "sro":"", "phase-history":{ "discovery": [ {"label":"Completed", "date": "Sep 2014"} ], "alpha": [ {"label":"Completed", "date": "Dec 2014"} ], "beta": [ {"label":"Started", "date": "Jan 2015"} ] }, "priority":"Top" }
Update real-time-earnings.js
lib/projects/real-time-earnings.js
Update real-time-earnings.js
<ide><path>ib/projects/real-time-earnings.js <ide> "location": "Leeds", <ide> "phase":"beta", <ide> "facing":"internal", <del> "sro":"", <add> "sro":"John Fundry", <add> "service_man":"TBC", <ide> "phase-history":{ <ide> "discovery": [ <del> {"label":"Completed", "date": "Sep 2014"} <add> {"label":"Completed", "date": "September 2014"} <ide> ], <ide> "alpha": [ <del> {"label":"Completed", "date": "Dec 2014"} <add> {"label":"Completed", "date": "December 2014"} <ide> ], <ide> "beta": [ <del> {"label":"Started", "date": "Jan 2015"} <add> {"label":"Started", "date": "January 2015"}, <add> {"label":"Private Beta", "date": "February 2016"}, <add> {"label":"Public Beta Predicted", "date": "April 2016"} <ide> ] <ide> }, <ide> "priority":"Top"
Java
mit
7b1267ca58bfe769fee31d7d48a194b61e48e7dc
0
bknopper/TSPEvolutionaryAlgorithmsDemo,bknopper/TSPEvolutionaryAlgorithmsDemo,bknopper/TSPEvolutionaryAlgorithmsDemo,bknopper/TSPEvolutionaryAlgorithmsDemo
/* * Copyright 2013 (C) NCIM Groep * * Created on : * Author : Bas W. Knopper * * This class is used for the JavaOne Demo on 09/24/2013 * for the following session: * * Evolutionary Algorithms: The Key to Solving Complex Java Puzzles [BOF2913] * */ package nl.ncim.javaone.tsp.ea; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Random; import nl.ncim.javaone.tsp.gui.JavaOneTSPDemo; import nl.ncim.javaone.tsp.util.TSPUtils; public class Algorithm { /** * Our connection to the demo (view) */ private JavaOneTSPDemo view; /** * Population of the algorithm */ private List<CandidateSolution> population = new ArrayList<CandidateSolution>(); /** * Thread in which the algorithm runs */ private Thread algorithmThread; /** * Probability with which a new child mutates */ private int mutationProbability; /** * Size of the population (as given by the GUI) */ private int populationSize; /** * number of generations to run max. */ private int nrOfGenerations; /** * When this fitness threshold is reached the algorithm can be stopped */ private int fitnessThreshold; /** * Number of parents to be selected for reproduction (each generation) */ private int parentSelectionSize; /** * Pool of CandidateSolution from which a number of parents will be selected for reproduction (each generation) */ private int parentPoolSize; /** * Constructor for the Evolutionary Algorithm * * @param view * @param mutationProbability * @param populationSize * @param nrOfGenerations * @param fitnessThreshold * @param parentSelectionSize * @param parentPoolSize */ public Algorithm(JavaOneTSPDemo view, int mutationProbability, int populationSize, int nrOfGenerations, int fitnessThreshold, int parentSelectionSize, int parentPoolSize) { this.view = view; this.mutationProbability = mutationProbability; this.populationSize = populationSize; this.nrOfGenerations = nrOfGenerations; this.fitnessThreshold = fitnessThreshold; this.parentSelectionSize = parentSelectionSize; this.parentPoolSize = parentPoolSize; } /** * Starts the algorithm using the settings given through the * constructor. */ public void startAlgorithm() { /* let the algorithm run in a Thread */ algorithmThread = new Thread(new Runnable() { public void run() { population = initialisation(); /* * implemented a Comparable for CandidateSolution * using its fitness. So best fitness (lowest) * first. */ Collections.sort(population); CandidateSolution bestCandidateSolution = population.get(0); int generations = 0; /* show the current best candidate solution on the demo screen */ view.showLastGeneration(bestCandidateSolution, generations); /* start the iterative part of the algorithm */ while(generations != nrOfGenerations && population.get(0).getFitness() > fitnessThreshold) { /* Select the parents for reproduction */ List<CandidateSolution> parents = parentSelection(); /* Let the selected parents reproduce (recombine) */ for(int i = 0; i < parents.size(); i += 2) { CandidateSolution parent1 = parents.get(i); CandidateSolution parent2 = parents.get(i + 1); List<CandidateSolution> children = parent1.recombine(parent2); /* * let the children mutate with probability mutationProbability * and add them to the population */ for(CandidateSolution child : children) { /* probability to mutate */ if(new Random().nextInt(101) <= mutationProbability) { child.mutate(); } population.add(child); } } /* * Since evaluation of candidate solutions is done within * the CandidateSolution itself, there is no need to evaluate * seperately here (although that is a part of the Evolutionary * Algorithm) */ /* * Survivor selection: which individuals (CandidateSolutions) * progress to the next generation */ selectSurvivors(); /* Sort the population so that the best candidates are up front */ Collections.sort(population); generations++; view.showLastGeneration(population.get(0), generations); /* * Sleep, so the Thread can be interrupted if needed * and to make the progression of the algorithm easy * on the eyes on the demo screen */ try { Thread.sleep(1); } catch(InterruptedException e) { view.reset(); return; } } /* we're done here */ view.done(); } }); /* start the above defined algorithm */ algorithmThread.start(); } /** * Selects the survivors by removing the worst candidate * solutions from the list, so we have the original * population size again */ private void selectSurvivors() { /* Sort the population so that the best candidates are up front */ Collections.sort(population); /* * cut back the population to the original size by dropping the worst * candidates */ population = new ArrayList<CandidateSolution>(population.subList(0, populationSize)); } /** * Select the x best candidate solutions from a randomly selected * pool from the population * * @return parents a list of the chosen parents */ private List<CandidateSolution> parentSelection() { List<CandidateSolution> tempPopulation = new ArrayList<CandidateSolution>(population); List<CandidateSolution> randomCandidates = new ArrayList<CandidateSolution>(); Random random = new Random(); for(int i = 0; i <= parentPoolSize; i++) { /* select a random candidate solution from the temp population */ int randomlySelectedIndex = random.nextInt(tempPopulation.size()); CandidateSolution randomSelection = tempPopulation.get(randomlySelectedIndex); randomCandidates.add(randomSelection); /* delete the candidate from the temp population, so we can't pick it again */ tempPopulation.remove(randomlySelectedIndex); } /* Sort the population so that the best candidates are up front */ Collections.sort(randomCandidates); /* * return a list with size parentSelectionSize with the best * CandidateSolutions */ return randomCandidates.subList(0, parentSelectionSize); } private List<CandidateSolution> initialisation() { /* initialize population list of CandidateSolutions */ List<CandidateSolution> populationTemp = new ArrayList<CandidateSolution>(); /* create a populationSize amount of random CandidateSolutions (routes) */ for(int i = 0; i < populationSize; i++) { CandidateSolution candidateSolution = new CandidateSolution(TSPUtils.getBaseCity(), TSPUtils.getRandomizedCities()); populationTemp.add(candidateSolution); } return populationTemp; } private void printPopulation() { /* * for (CandidateSolution candidateSolution : population) { * * System.out.println("CandidateSolution added to population: " + * candidateSolution.toString()); } * * System.out.println("Population size: " + population.size()); */ } /** * Stops the algorithm */ public void stopAlgorithm() { algorithmThread.interrupt(); } }
JavaOneTSPDemo/src/main/java/nl/ncim/javaone/tsp/ea/Algorithm.java
/* * Copyright 2013 (C) NCIM Groep * * Created on : * Author : Bas W. Knopper * * This class is used for the JavaOne Demo on 09/24/2013 * for the following session: * * Evolutionary Algorithms: The Key to Solving Complex Java Puzzles [BOF2913] * */ package nl.ncim.javaone.tsp.ea; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Random; import nl.ncim.javaone.tsp.gui.JavaOneTSPDemo; import nl.ncim.javaone.tsp.util.TSPUtils; public class Algorithm { /** * Our connection to the demo (view) */ private JavaOneTSPDemo view; /** * Population of the algorithm */ private List<CandidateSolution> population = new ArrayList<CandidateSolution>(); /** * Thread in which the algorithm runs */ private Thread algorithmThread; /** * Probability with which a new child mutates */ private int mutationProbability; /** * Size of the population (as given by the GUI) */ private int populationSize; /** * number of generations to run max. */ private int nrOfGenerations; /** * When this fitness threshold is reached the algorithm can be stopped */ private int fitnessThreshold; /** * Number of parents to be selected for reproduction (each generation) */ private int parentSelectionSize; /** * Pool of CandidateSolution from which a number of parents will be selected for reproduction (each generation) */ private int parentPoolSize; /** * Constructor for the Evolutionary Algorithm * * @param view * @param mutationProbability * @param populationSize * @param nrOfGenerations * @param fitnessThreshold * @param parentSelectionSize * @param parentPoolSize */ public Algorithm(JavaOneTSPDemo view, int mutationProbability, int populationSize, int nrOfGenerations, int fitnessThreshold, int parentSelectionSize, int parentPoolSize) { this.view = view; this.mutationProbability = mutationProbability; this.populationSize = populationSize; this.nrOfGenerations = nrOfGenerations; this.fitnessThreshold = fitnessThreshold; this.parentSelectionSize = parentSelectionSize; this.parentPoolSize = parentPoolSize; } /** * Starts the algorithm using the settings given through the * constructor. */ public void startAlgorithm() { /* let the algorithm run in a Thread */ algorithmThread = new Thread(new Runnable() { public void run() { population = initialisation(); /* * implemented a Comparable for CandidateSolution * using its fitness. So best fitness (lowest) * first. */ Collections.sort(population); CandidateSolution bestCandidateSolution = population.get(0); int generations = 0; /* show the current best candidate solution on the demo screen */ view.showLastGeneration(bestCandidateSolution, generations); /* start the iterative part of the algorithm */ while(generations != nrOfGenerations && population.get(0).getFitness() > fitnessThreshold) { /* Select the parents for reproduction */ List<CandidateSolution> parents = parentSelection(); /* Let the selected parents reproduce (recombine) */ for(int i = 0; i < parents.size(); i += 2) { CandidateSolution parent1 = parents.get(i); CandidateSolution parent2 = parents.get(i + 1); List<CandidateSolution> children = parent1.recombine(parent2); /* * let the children mutate with probability mutationProbability * and add them to the population */ for(CandidateSolution child : children) { /* probability to mutate */ if(new Random().nextInt(101) <= mutationProbability) { child.mutate(); } population.add(child); } } /* * Since evaluation of candidate solutions is done within * the CandidateSolution itself, there is no need to evaluate * seperately here (although that is a part of the Evolutionary * Algorithm) */ /* * Survivor selection: which individuals (CandidateSolutions) * progress to the next generation */ selectSurvivors(); /* Sort the population so that the best candidates are up front */ Collections.sort(population); generations++; view.showLastGeneration(population.get(0), generations); /* * Sleep, so the Thread can be interrupted if needed * and to make the progression of the algorithm easy * on the eyes on the demo screen */ try { Thread.sleep(1); } catch(InterruptedException e) { view.reset(); return; } } /* we're done here */ view.done(); } }); /* start the above defined algorithm */ algorithmThread.start(); } /** * Selects the survivors by removing the worst candidate * solutions from the list, so we have the original * population size again */ private void selectSurvivors() { /* Sort the population so that the best candidates are up front */ Collections.sort(population); /* * cut back the population to the original size by dropping the worst * candidates */ population = new ArrayList<CandidateSolution>(population.subList(0, populationSize)); } /** * Select the x best candidate solutions from the population * * @param nrParentsToBeSelected * the number of parents to be selected * @return parents a list of the chosen parents */ private List<CandidateSolution> parentSelection() { List<CandidateSolution> randomCandidates = new ArrayList<CandidateSolution>(); Random random = new Random(); for(int i = 0; i <= parentPoolSize; i++) { int randomlySelectedIndex = random.nextInt(population.size()); CandidateSolution randomSelection = population.get(randomlySelectedIndex); randomCandidates.add(randomSelection); } /* Sort the population so that the best candidates are up front */ Collections.sort(randomCandidates); /* * return a list with size parentSelectionSize with the best * CandidateSolutions */ return randomCandidates.subList(0, parentSelectionSize); } private List<CandidateSolution> initialisation() { /* initialize population list of CandidateSolutions */ List<CandidateSolution> populationTemp = new ArrayList<CandidateSolution>(); /* create a populationSize amount of random CandidateSolutions (routes) */ for(int i = 0; i < populationSize; i++) { CandidateSolution candidateSolution = new CandidateSolution(TSPUtils.getBaseCity(), TSPUtils.getRandomizedCities()); populationTemp.add(candidateSolution); } return populationTemp; } private void printPopulation() { /* * for (CandidateSolution candidateSolution : population) { * * System.out.println("CandidateSolution added to population: " + * candidateSolution.toString()); } * * System.out.println("Population size: " + population.size()); */ } /** * Stops the algorithm */ public void stopAlgorithm() { algorithmThread.interrupt(); } }
Prevented duplicate parents in parenSelection method
JavaOneTSPDemo/src/main/java/nl/ncim/javaone/tsp/ea/Algorithm.java
Prevented duplicate parents in parenSelection method
<ide><path>avaOneTSPDemo/src/main/java/nl/ncim/javaone/tsp/ea/Algorithm.java <ide> } <ide> <ide> /** <del> * Select the x best candidate solutions from the population <add> * Select the x best candidate solutions from a randomly selected <add> * pool from the population <ide> * <del> * @param nrParentsToBeSelected <del> * the number of parents to be selected <ide> * @return parents a list of the chosen parents <ide> */ <ide> private List<CandidateSolution> parentSelection() <ide> { <ide> <add> List<CandidateSolution> tempPopulation = new ArrayList<CandidateSolution>(population); <ide> List<CandidateSolution> randomCandidates = new ArrayList<CandidateSolution>(); <ide> <ide> Random random = new Random(); <ide> for(int i = 0; i <= parentPoolSize; i++) <ide> { <del> int randomlySelectedIndex = random.nextInt(population.size()); <del> CandidateSolution randomSelection = population.get(randomlySelectedIndex); <add> <add> /* select a random candidate solution from the temp population */ <add> int randomlySelectedIndex = random.nextInt(tempPopulation.size()); <add> CandidateSolution randomSelection = tempPopulation.get(randomlySelectedIndex); <add> <add> <ide> randomCandidates.add(randomSelection); <add> <add> /* delete the candidate from the temp population, so we can't pick it again */ <add> tempPopulation.remove(randomlySelectedIndex); <ide> } <ide> <ide> /* Sort the population so that the best candidates are up front */
Java
apache-2.0
47ad75575b1e10b2a65e1165e4c7ffde42c1d142
0
SyncFree/SwiftCloud,SyncFree/SwiftCloud,SyncFree/SwiftCloud,SyncFree/SwiftCloud
package swift.application.filesystem.fuse; import java.io.File; import java.io.IOException; import java.nio.BufferOverflowException; import java.nio.ByteBuffer; import java.nio.CharBuffer; import java.util.Collection; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import swift.application.filesystem.Filesystem; import swift.application.filesystem.FilesystemBasic; import swift.application.filesystem.IFile; import swift.client.SwiftImpl; import swift.crdt.DirectoryTxnLocal; import swift.crdt.DirectoryVersioned; import swift.crdt.interfaces.CachePolicy; import swift.crdt.interfaces.IsolationLevel; import swift.crdt.interfaces.Swift; import swift.crdt.interfaces.TxnHandle; import swift.dc.DCConstants; import swift.dc.DCSequencerServer; import swift.dc.DCServer; import swift.exceptions.NetworkException; import swift.exceptions.NoSuchObjectException; import swift.exceptions.VersionNotFoundException; import swift.exceptions.WrongTypeException; import swift.utils.Pair; import sys.Sys; import fuse.Errno; import fuse.Filesystem3; import fuse.FuseDirFiller; import fuse.FuseException; import fuse.FuseFtypeConstants; import fuse.FuseGetattrSetter; import fuse.FuseMount; import fuse.FuseOpenSetter; import fuse.FuseSizeSetter; import fuse.FuseStatfsSetter; import fuse.XattrLister; import fuse.XattrSupport; /** * FUSE-J: Java bindings for FUSE (Filesystem in Userspace by Miklos Szeredi * ([email protected])) * * The interface description of Fuse says: * * The file system operations: * * Most of these should work very similarly to the well known UNIX file system * operations. Exceptions are: * * - All operations should return the error value (errno) by either: - throwing * a fuse.FuseException with a errno field of the exception set to the desired * fuse.Errno.E* value. - returning an integer value taken from fuse.Errno.E* * constants. this is supposed to be less expensive in terms of CPU cycles and * should only be used for very frequent errors (for example ENOENT). * * - getdir() is the opendir(), readdir(), ..., closedir() sequence in one call. * * - There is no create() operation, mknod() will be called for creation of all * non directory, non symlink nodes. * * - open() No creation, or trunctation flags (O_CREAT, O_EXCL, O_TRUNC) will be * passed to open(). Open should only check if the operation is permitted for * the given flags. * * - read(), write(), release() are are passed a filehandle that is returned * from open() in addition to a pathname. The offset of the read and write is * passed as the last argument, the number of bytes read/writen is returned * through the java.nio.ByteBuffer object * * - release() is called when an open file has: 1) all file descriptors closed * 2) all memory mappings unmapped This call need only be implemented if this * information is required. * * - flush() called when a file is closed (can be called multiple times for each * dup-ed filehandle) * * - fsync() called when file data should be synced (with a flag to sync only * data but not metadata) * */ public class FilesystemFuse implements Filesystem3, XattrSupport { private static final Log log = LogFactory.getLog(FilesystemFuse.class); protected static Swift server; protected Filesystem fs; private static final int MODE = 0777; private static final int BLOCK_SIZE = 512; private static final int NAME_LENGTH = 1024; protected static final String ROOT = "test"; public FilesystemFuse(Filesystem fs) { this.fs = fs; } @Override public int chmod(String path, int mode) throws FuseException { // No model implemented log.info("chmod for " + path); return Errno.EROFS; } @Override public int chown(String path, int uid, int gid) throws FuseException { // No ownership model implemented log.info("chown for " + path); return Errno.EROFS; } @Override public int flush(String path, Object fileHandle) throws FuseException { String remotePath = getRemotePath(path); log.info("flush for " + path); synchronized (this) { TxnHandle txn = null; try { txn = server.beginTxn(IsolationLevel.SNAPSHOT_ISOLATION, CachePolicy.STRICTLY_MOST_RECENT, false); IFile f = (IFile) fileHandle; File fstub = new File(remotePath); fs.updateFile(txn, fstub.getName(), fstub.getParent(), f); txn.commit(); return 0; } catch (NetworkException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (WrongTypeException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (NoSuchObjectException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (VersionNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } txn.rollback(); } return Errno.EROFS; } @Override public int fsync(String path, Object fileHandle, boolean isDatasync) throws FuseException { String remotePath = getRemotePath(path); log.info("flush for " + remotePath); synchronized (this) { TxnHandle txn = null; try { txn = server.beginTxn(IsolationLevel.SNAPSHOT_ISOLATION, CachePolicy.STRICTLY_MOST_RECENT, false); IFile f = (IFile) fileHandle; File fstub = new File(remotePath); fs.updateFile(txn, fstub.getName(), fstub.getParent(), f); txn.commit(); txn = server.beginTxn(IsolationLevel.SNAPSHOT_ISOLATION, CachePolicy.STRICTLY_MOST_RECENT, false); fileHandle = fs.readFile(txn, fstub.getName(), fstub.getParent()); txn.commit(); return 0; } catch (NetworkException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (WrongTypeException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (NoSuchObjectException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (VersionNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } txn.rollback(); } return Errno.EROFS; } @Override public int getattr(String path, FuseGetattrSetter getattrSetter) throws FuseException { String remotePath = getRemotePath(path); File fstub = new File(remotePath); log.info("getattr for " + remotePath); int time = (int) (System.currentTimeMillis() / 1000L); synchronized (this) { TxnHandle txn = null; try { txn = server.beginTxn(IsolationLevel.SNAPSHOT_ISOLATION, CachePolicy.STRICTLY_MOST_RECENT, true); if ("/".equals(path)) { DirectoryTxnLocal root = fs.getDirectory(txn, "/" + ROOT); getattrSetter.set(root.hashCode(), FuseFtypeConstants.TYPE_DIR | MODE, 1, 0, 0, 0, root.getValue() .size() * NAME_LENGTH, (root.getValue().size() * NAME_LENGTH + BLOCK_SIZE - 1) / BLOCK_SIZE, time, time, time); } else if (fs.isDirectory(txn, fstub.getName(), fstub.getParent())) { DirectoryTxnLocal dir = fs.getDirectory(txn, remotePath); getattrSetter.set(dir.hashCode(), FuseFtypeConstants.TYPE_DIR | MODE, 1, 0, 0, 0, dir.getValue() .size() * NAME_LENGTH, (dir.getValue().size() * NAME_LENGTH + BLOCK_SIZE - 1) / BLOCK_SIZE, time, time, time); } else if (fs.isFile(txn, fstub.getName(), fstub.getParent())) { IFile f = fs.readFile(txn, fstub.getName(), fstub.getParent()); getattrSetter.set(fstub.hashCode(), FuseFtypeConstants.TYPE_FILE | MODE, 1, 0, 0, 0, f.getSize(), (f.getSize() + BLOCK_SIZE - 1) / BLOCK_SIZE, time, time, time); } else { txn.rollback(); return Errno.ENOENT; } txn.commit(); return 0; } catch (NetworkException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (WrongTypeException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (NoSuchObjectException e) { e.printStackTrace(); } catch (VersionNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } txn.rollback(); } return Errno.ENOENT; } @Override public int getdir(String path, FuseDirFiller filler) throws FuseException { String remotePath = getRemotePath(path); log.info("getdir for " + remotePath); synchronized (this) { TxnHandle txn = null; try { txn = server.beginTxn(IsolationLevel.SNAPSHOT_ISOLATION, CachePolicy.STRICTLY_MOST_RECENT, true); DirectoryTxnLocal dir = fs.getDirectory(txn, remotePath); Collection<Pair<String, Class<?>>> c = dir.getValue(); for (Pair<String, Class<?>> entry : c) { String name = entry.getFirst(); // TODO This needs to be adapted for links and permissions int mode = MODE; int ftype = FuseFtypeConstants.TYPE_FILE; if (entry.getSecond().equals(DirectoryVersioned.class)) { ftype = FuseFtypeConstants.TYPE_DIR; } filler.add(name, entry.hashCode(), ftype | mode); } txn.commit(); return 0; } catch (NetworkException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (WrongTypeException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (NoSuchObjectException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (VersionNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } txn.rollback(); } return Errno.EROFS; } @Override public int link(String from, String to) throws FuseException { // FIXME Links are future work... log.info("link from " + from + " to " + to); return Errno.EROFS; } @Override public int mkdir(String path, int mode) throws FuseException { String remotePath = getRemotePath(path); log.info("mkdir for " + remotePath); synchronized (this) { TxnHandle txn = null; try { txn = server.beginTxn(IsolationLevel.SNAPSHOT_ISOLATION, CachePolicy.STRICTLY_MOST_RECENT, false); File f = new File(remotePath); log.info("creating dir " + f.getName() + " in parentdir " + f.getParent()); fs.createDirectory(txn, f.getName(), f.getParent()); txn.commit(); return 0; } catch (NetworkException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (WrongTypeException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (NoSuchObjectException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (VersionNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } txn.rollback(); } return Errno.EROFS; } private String getRemotePath(String path) { if ("/".equals(path)) { return "/" + ROOT; } return "/" + ROOT + path; } @Override public int mknod(String path, int mode, int rdev) throws FuseException { String remotePath = getRemotePath(path); log.info("mknod for " + remotePath); synchronized (this) { TxnHandle txn = null; try { txn = server.beginTxn(IsolationLevel.SNAPSHOT_ISOLATION, CachePolicy.STRICTLY_MOST_RECENT, false); File f = new File(remotePath); log.info("creating file " + f.getName() + " in parentdir " + f.getParent()); fs.createFile(txn, f.getName(), f.getParent()); txn.commit(); return 0; } catch (NetworkException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (WrongTypeException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (NoSuchObjectException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (VersionNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } txn.rollback(); } return Errno.EROFS; } @Override public int open(String path, int flags, FuseOpenSetter openSetter) throws FuseException { String remotePath = getRemotePath(path); log.info("open for " + remotePath); synchronized (this) { TxnHandle txn = null; try { txn = server.beginTxn(IsolationLevel.SNAPSHOT_ISOLATION, CachePolicy.STRICTLY_MOST_RECENT, true); File fstub = new File(remotePath); if (fstub.isDirectory()) { txn.rollback(); throw new FuseException().initErrno(FuseException.EISDIR); } log.info("opening file " + fstub.getName() + " in parentdir " + fstub.getParent()); IFile f = fs.readFile(txn, fstub.getName(), fstub.getParent()); txn.commit(); openSetter.setFh(f); return 0; } catch (NetworkException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (WrongTypeException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (NoSuchObjectException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (VersionNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } txn.rollback(); } return Errno.EROFS; } @Override public int read(String path, Object fh, ByteBuffer buf, long offset) throws FuseException { String remotePath = getRemotePath(path); log.info("read for " + remotePath); if (fh instanceof IFile) { IFile f = (IFile) fh; f.read(buf, offset); return 0; } return Errno.EBADF; } @Override public int readlink(String path, CharBuffer link) throws FuseException { // TODO Auto-generated method stub log.info("readlink for " + path); return Errno.EROFS; } @Override public int release(String path, Object fileHandle, int flags) throws FuseException { // No action required here log.info("release for " + path); return 0; } @Override public int rename(String from, String to) throws FuseException { // TODO Auto-generated method stub log.info("rename from " + from + " to " + to); return Errno.EROFS; } @Override public int rmdir(String path) throws FuseException { String remotePath = getRemotePath(path); log.info("rmdir for " + remotePath); synchronized (this) { TxnHandle txn = null; try { txn = server.beginTxn(IsolationLevel.SNAPSHOT_ISOLATION, CachePolicy.STRICTLY_MOST_RECENT, false); File f = new File(remotePath); fs.removeDirectory(txn, f.getName(), f.getParent()); txn.commit(); return 0; } catch (NetworkException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (WrongTypeException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (NoSuchObjectException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (VersionNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } txn.rollback(); } return Errno.EROFS; } @Override public int statfs(FuseStatfsSetter arg0) throws FuseException { // TODO Auto-generated method stub log.info("statfs called"); return 0; } @Override public int symlink(String from, String to) throws FuseException { // FIXME Future work... log.info("symlink from " + from + " to " + to); return Errno.EROFS; } @Override public int truncate(String path, long mode) throws FuseException { // TODO Auto-generated method stub log.info("truncate for " + path); return 0; } @Override public int unlink(String path) throws FuseException { String remotePath = getRemotePath(path); log.info("Unlink for " + remotePath); synchronized (this) { TxnHandle txn = null; try { txn = server.beginTxn(IsolationLevel.SNAPSHOT_ISOLATION, CachePolicy.STRICTLY_MOST_RECENT, false); File f = new File(remotePath); fs.removeFile(txn, f.getName(), f.getParent()); txn.commit(); return 0; } catch (NetworkException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (WrongTypeException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (NoSuchObjectException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (VersionNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } txn.rollback(); } return Errno.EROFS; } @Override public int utime(String path, int atime, int mtime) throws FuseException { // Modification times are not supported yet.... log.info("Utime for " + path); return 0; } @Override public int write(String path, Object fh, boolean isWritepage, ByteBuffer buf, long offset) throws FuseException { String remotePath = getRemotePath(path); log.info("write for " + remotePath); if (fh instanceof IFile) { IFile f = (IFile) fh; while (buf.remaining() > 0) { int pos = buf.position(); f.update(buf, offset); offset += buf.position() - pos; } } return 0; } // // XattrSupport implementation /** * This method will be called to get the value of the extended attribute * * @param path * the path to file or directory containing extended attribute * @param name * the name of the extended attribute * @param dst * a ByteBuffer that should be filled with the value of the * extended attribute * @return 0 if Ok or errno when error * @throws fuse.FuseException * an alternative to returning errno is to throw this exception * with errno initialized * @throws java.nio.BufferOverflowException * should be thrown to indicate that the given <code>dst</code> * ByteBuffer is not large enough to hold the attribute's value. * After that <code>getxattr()</code> method will be called * again with a larger buffer. */ public int getxattr(String path, String name, ByteBuffer dst, int position) throws FuseException, BufferOverflowException { log.info("getxattr " + name + " for " + path); return Errno.ENOATTR; } /** * This method can be called to query for the size of the extended attribute * * @param path * the path to file or directory containing extended attribute * @param name * the name of the extended attribute * @param sizeSetter * a callback interface that should be used to set the * attribute's size * @return 0 if Ok or errno when error * @throws fuse.FuseException * an alternative to returning errno is to throw this exception * with errno initialized */ public int getxattrsize(String path, String name, FuseSizeSetter sizeSetter) throws FuseException { log.info("getxattrsize " + name + " for " + path); return Errno.ENOATTR; } /** * This method will be called to get the list of extended attribute names * * @param path * the path to file or directory containing extended attributes * @param lister * a callback interface that should be used to list the attribute * names * @return 0 if Ok or errno when error * @throws fuse.FuseException * an alternative to returning errno is to throw this exception * with errno initialized */ public int listxattr(String path, XattrLister lister) throws FuseException { log.info("listxattr for " + path); return Errno.ENOATTR; } /** * This method will be called to remove the extended attribute * * @param path * the path to file or directory containing extended attributes * @param name * the name of the extended attribute * @return 0 if Ok or errno when error * @throws fuse.FuseException * an alternative to returning errno is to throw this exception * with errno initialized */ public int removexattr(String path, String name) throws FuseException { log.info("removexattr " + name + " for " + path); return Errno.ENOATTR; } /** * This method will be called to set the value of an extended attribute * * @param path * the path to file or directory containing extended attributes * @param name * the name of the extended attribute * @param value * the value of the extended attribute * @param flags * parameter can be used to refine the semantics of the * operation. * <p> * <code>XATTR_CREATE</code> specifies a pure create, which * should fail with <code>Errno.EEXIST</code> if the named * attribute exists already. * <p> * <code>XATTR_REPLACE</code> specifies a pure replace operation, * which should fail with <code>Errno.ENOATTR</code> if the named * attribute does not already exist. * <p> * By default (no flags), the extended attribute will be created * if need be, or will simply replace the value if the attribute * exists. * @return 0 if Ok or errno when error * @throws fuse.FuseException * an alternative to returning errno is to throw this exception * with errno initialized */ public int setxattr(String path, String name, ByteBuffer value, int flags, int position) throws FuseException { log.info("setxattr " + name + " for " + path); return Errno.ENOATTR; } public static void initServerInfrastructure(String sequencerName, String scoutName) { DCSequencerServer.main(new String[] { "-name", sequencerName }); try { Thread.sleep(500); } catch (InterruptedException e) { // do nothing } DCServer.main(new String[] { sequencerName }); try { Thread.sleep(500); } catch (InterruptedException e) { // do nothing } Sys.init(); server = SwiftImpl.newInstance(scoutName, DCConstants.SURROGATE_PORT); } public static void main(String[] args) { log.info("setting up servers"); initServerInfrastructure("localhost", "localhost"); try { log.info("getting root directory"); TxnHandle txn = server.beginTxn(IsolationLevel.SNAPSHOT_ISOLATION, CachePolicy.STRICTLY_MOST_RECENT, false); // create a root directory // FIXME make this part of arguments Filesystem fs = new FilesystemBasic(txn, ROOT, "DIR"); txn.commit(); log.info("mounting filesystem"); FuseMount.mount(args, new FilesystemFuse(fs), log); } catch (Exception e) { e.printStackTrace(); } finally { log.info("exiting"); } } }
src/swift/application/filesystem/fuse/FilesystemFuse.java
package swift.application.filesystem.fuse; import java.io.File; import java.io.IOException; import java.nio.BufferOverflowException; import java.nio.ByteBuffer; import java.nio.CharBuffer; import java.util.Collection; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import swift.application.filesystem.Filesystem; import swift.application.filesystem.FilesystemBasic; import swift.application.filesystem.IFile; import swift.client.SwiftImpl; import swift.crdt.DirectoryTxnLocal; import swift.crdt.DirectoryVersioned; import swift.crdt.interfaces.CachePolicy; import swift.crdt.interfaces.IsolationLevel; import swift.crdt.interfaces.Swift; import swift.crdt.interfaces.TxnHandle; import swift.dc.DCConstants; import swift.dc.DCSequencerServer; import swift.dc.DCServer; import swift.exceptions.NetworkException; import swift.exceptions.NoSuchObjectException; import swift.exceptions.VersionNotFoundException; import swift.exceptions.WrongTypeException; import swift.utils.Pair; import sys.Sys; import fuse.Errno; import fuse.Filesystem3; import fuse.FuseDirFiller; import fuse.FuseException; import fuse.FuseFtypeConstants; import fuse.FuseGetattrSetter; import fuse.FuseMount; import fuse.FuseOpenSetter; import fuse.FuseSizeSetter; import fuse.FuseStatfsSetter; import fuse.XattrLister; import fuse.XattrSupport; /** * FUSE-J: Java bindings for FUSE (Filesystem in Userspace by Miklos Szeredi * ([email protected])) * * The interface description of Fuse says: * * The file system operations: * * Most of these should work very similarly to the well known UNIX file system * operations. Exceptions are: * * - All operations should return the error value (errno) by either: - throwing * a fuse.FuseException with a errno field of the exception set to the desired * fuse.Errno.E* value. - returning an integer value taken from fuse.Errno.E* * constants. this is supposed to be less expensive in terms of CPU cycles and * should only be used for very frequent errors (for example ENOENT). * * - getdir() is the opendir(), readdir(), ..., closedir() sequence in one call. * * - There is no create() operation, mknod() will be called for creation of all * non directory, non symlink nodes. * * - open() No creation, or trunctation flags (O_CREAT, O_EXCL, O_TRUNC) will be * passed to open(). Open should only check if the operation is permitted for * the given flags. * * - read(), write(), release() are are passed a filehandle that is returned * from open() in addition to a pathname. The offset of the read and write is * passed as the last argument, the number of bytes read/writen is returned * through the java.nio.ByteBuffer object * * - release() is called when an open file has: 1) all file descriptors closed * 2) all memory mappings unmapped This call need only be implemented if this * information is required. * * - flush() called when a file is closed (can be called multiple times for each * dup-ed filehandle) * * - fsync() called when file data should be synced (with a flag to sync only * data but not metadata) * */ public class FilesystemFuse implements Filesystem3, XattrSupport { private static final Log log = LogFactory.getLog(FilesystemFuse.class); protected static Swift server; protected final Filesystem fs; private static final int MODE = 0777; private static final int BLOCK_SIZE = 512; private static final int NAME_LENGTH = 1024; protected static final String ROOT = "test"; public FilesystemFuse(Filesystem fs) { this.fs = fs; } @Override public int chmod(String path, int mode) throws FuseException { // No model implemented log.info("chmod for " + path); return Errno.EROFS; } @Override public int chown(String path, int uid, int gid) throws FuseException { // No ownership model implemented log.info("chown for " + path); return Errno.EROFS; } @Override public int flush(String path, Object fileHandle) throws FuseException { String remotePath = getRemotePath(path); log.info("flush for " + path); synchronized (this) { TxnHandle txn = null; try { txn = server.beginTxn(IsolationLevel.SNAPSHOT_ISOLATION, CachePolicy.STRICTLY_MOST_RECENT, false); IFile f = (IFile) fileHandle; File fstub = new File(remotePath); fs.updateFile(txn, fstub.getName(), fstub.getParent(), f); txn.commit(); return 0; } catch (NetworkException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (WrongTypeException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (NoSuchObjectException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (VersionNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } txn.rollback(); } return Errno.EROFS; } @Override public int fsync(String path, Object fileHandle, boolean isDatasync) throws FuseException { String remotePath = getRemotePath(path); log.info("flush for " + remotePath); synchronized (this) { TxnHandle txn = null; try { txn = server.beginTxn(IsolationLevel.SNAPSHOT_ISOLATION, CachePolicy.STRICTLY_MOST_RECENT, false); IFile f = (IFile) fileHandle; File fstub = new File(remotePath); fs.updateFile(txn, fstub.getName(), fstub.getParent(), f); txn.commit(); txn = server.beginTxn(IsolationLevel.SNAPSHOT_ISOLATION, CachePolicy.STRICTLY_MOST_RECENT, false); fileHandle = fs.readFile(txn, fstub.getName(), fstub.getParent()); txn.commit(); return 0; } catch (NetworkException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (WrongTypeException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (NoSuchObjectException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (VersionNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } txn.rollback(); } return Errno.EROFS; } @Override public int getattr(String path, FuseGetattrSetter getattrSetter) throws FuseException { String remotePath = getRemotePath(path); File fstub = new File(remotePath); log.info("getattr for " + remotePath); int time = (int) (System.currentTimeMillis() / 1000L); synchronized (this) { TxnHandle txn = null; try { txn = server.beginTxn(IsolationLevel.SNAPSHOT_ISOLATION, CachePolicy.STRICTLY_MOST_RECENT, true); if ("/".equals(path)) { DirectoryTxnLocal root = fs.getDirectory(txn, "/" + ROOT); getattrSetter.set(root.hashCode(), FuseFtypeConstants.TYPE_DIR | MODE, 1, 0, 0, 0, root.getValue() .size() * NAME_LENGTH, (root.getValue().size() * NAME_LENGTH + BLOCK_SIZE - 1) / BLOCK_SIZE, time, time, time); } else if (fs.isDirectory(txn, fstub.getName(), fstub.getParent())) { DirectoryTxnLocal dir = fs.getDirectory(txn, remotePath); getattrSetter.set(dir.hashCode(), FuseFtypeConstants.TYPE_DIR | MODE, 1, 0, 0, 0, dir.getValue() .size() * NAME_LENGTH, (dir.getValue().size() * NAME_LENGTH + BLOCK_SIZE - 1) / BLOCK_SIZE, time, time, time); } else if (fs.isFile(txn, fstub.getName(), fstub.getParent())) { IFile f = fs.readFile(txn, fstub.getName(), fstub.getParent()); getattrSetter.set(fstub.hashCode(), FuseFtypeConstants.TYPE_FILE | MODE, 1, 0, 0, 0, f.getSize(), (f.getSize() + BLOCK_SIZE - 1) / BLOCK_SIZE, time, time, time); } else { txn.rollback(); return Errno.ENOENT; } txn.commit(); return 0; } catch (NetworkException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (WrongTypeException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (NoSuchObjectException e) { e.printStackTrace(); } catch (VersionNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } txn.rollback(); } return Errno.ENOENT; } @Override public int getdir(String path, FuseDirFiller filler) throws FuseException { String remotePath = getRemotePath(path); log.info("getdir for " + remotePath); synchronized (this) { TxnHandle txn = null; try { txn = server.beginTxn(IsolationLevel.SNAPSHOT_ISOLATION, CachePolicy.STRICTLY_MOST_RECENT, true); DirectoryTxnLocal dir = fs.getDirectory(txn, remotePath); Collection<Pair<String, Class<?>>> c = dir.getValue(); for (Pair<String, Class<?>> entry : c) { String name = entry.getFirst(); // TODO This needs to be adapted for links and permissions int mode = MODE; int ftype = FuseFtypeConstants.TYPE_FILE; if (entry.getSecond().equals(DirectoryVersioned.class)) { ftype = FuseFtypeConstants.TYPE_DIR; } filler.add(name, entry.hashCode(), ftype | mode); } txn.commit(); return 0; } catch (NetworkException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (WrongTypeException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (NoSuchObjectException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (VersionNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } txn.rollback(); } return Errno.EROFS; } @Override public int link(String from, String to) throws FuseException { // FIXME Links are future work... log.info("link from " + from + " to " + to); return Errno.EROFS; } @Override public int mkdir(String path, int mode) throws FuseException { String remotePath = getRemotePath(path); log.info("mkdir for " + remotePath); synchronized (this) { TxnHandle txn = null; try { txn = server.beginTxn(IsolationLevel.SNAPSHOT_ISOLATION, CachePolicy.STRICTLY_MOST_RECENT, false); File f = new File(remotePath); log.info("creating dir " + f.getName() + " in parentdir " + f.getParent()); fs.createDirectory(txn, f.getName(), f.getParent()); txn.commit(); return 0; } catch (NetworkException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (WrongTypeException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (NoSuchObjectException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (VersionNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } txn.rollback(); } return Errno.EROFS; } private String getRemotePath(String path) { if ("/".equals(path)) { return "/" + ROOT; } return "/" + ROOT + path; } @Override public int mknod(String path, int mode, int rdev) throws FuseException { String remotePath = getRemotePath(path); log.info("mknod for " + remotePath); synchronized (this) { TxnHandle txn = null; try { txn = server.beginTxn(IsolationLevel.SNAPSHOT_ISOLATION, CachePolicy.STRICTLY_MOST_RECENT, false); File f = new File(remotePath); log.info("creating file " + f.getName() + " in parentdir " + f.getParent()); fs.createFile(txn, f.getName(), f.getParent()); txn.commit(); return 0; } catch (NetworkException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (WrongTypeException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (NoSuchObjectException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (VersionNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } txn.rollback(); } return Errno.EROFS; } @Override public int open(String path, int flags, FuseOpenSetter openSetter) throws FuseException { String remotePath = getRemotePath(path); log.info("open for " + remotePath); synchronized (this) { TxnHandle txn = null; try { txn = server.beginTxn(IsolationLevel.SNAPSHOT_ISOLATION, CachePolicy.STRICTLY_MOST_RECENT, true); File fstub = new File(remotePath); if (fstub.isDirectory()) { txn.rollback(); throw new FuseException().initErrno(FuseException.EISDIR); } log.info("opening file " + fstub.getName() + " in parentdir " + fstub.getParent()); IFile f = fs.readFile(txn, fstub.getName(), fstub.getParent()); txn.commit(); openSetter.setFh(f); return 0; } catch (NetworkException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (WrongTypeException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (NoSuchObjectException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (VersionNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } txn.rollback(); } return Errno.EROFS; } @Override public int read(String path, Object fh, ByteBuffer buf, long offset) throws FuseException { String remotePath = getRemotePath(path); log.info("read for " + remotePath); if (fh instanceof IFile) { IFile f = (IFile) fh; f.read(buf, offset); return 0; } return Errno.EBADF; } @Override public int readlink(String path, CharBuffer link) throws FuseException { // TODO Auto-generated method stub log.info("readlink for " + path); return Errno.EROFS; } @Override public int release(String path, Object fileHandle, int flags) throws FuseException { // No action required here log.info("release for " + path); return 0; } @Override public int rename(String from, String to) throws FuseException { // TODO Auto-generated method stub log.info("rename from " + from + " to " + to); return Errno.EROFS; } @Override public int rmdir(String path) throws FuseException { String remotePath = getRemotePath(path); log.info("rmdir for " + remotePath); synchronized (this) { TxnHandle txn = null; try { txn = server.beginTxn(IsolationLevel.SNAPSHOT_ISOLATION, CachePolicy.STRICTLY_MOST_RECENT, false); File f = new File(remotePath); fs.removeDirectory(txn, f.getName(), f.getParent()); txn.commit(); return 0; } catch (NetworkException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (WrongTypeException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (NoSuchObjectException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (VersionNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } txn.rollback(); } return Errno.EROFS; } @Override public int statfs(FuseStatfsSetter arg0) throws FuseException { // TODO Auto-generated method stub log.info("statfs called"); return 0; } @Override public int symlink(String from, String to) throws FuseException { // FIXME Future work... log.info("symlink from " + from + " to " + to); return Errno.EROFS; } @Override public int truncate(String path, long mode) throws FuseException { // TODO Auto-generated method stub log.info("truncate for " + path); return 0; } @Override public int unlink(String path) throws FuseException { String remotePath = getRemotePath(path); log.info("Unlink for " + remotePath); synchronized (this) { TxnHandle txn = null; try { txn = server.beginTxn(IsolationLevel.SNAPSHOT_ISOLATION, CachePolicy.STRICTLY_MOST_RECENT, false); File f = new File(remotePath); fs.removeFile(txn, f.getName(), f.getParent()); txn.commit(); return 0; } catch (NetworkException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (WrongTypeException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (NoSuchObjectException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (VersionNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } txn.rollback(); } return Errno.EROFS; } @Override public int utime(String path, int atime, int mtime) throws FuseException { // Modification times are not supported yet.... log.info("Utime for " + path); return 0; } @Override public int write(String path, Object fh, boolean isWritepage, ByteBuffer buf, long offset) throws FuseException { String remotePath = getRemotePath(path); log.info("write for " + remotePath); if (fh instanceof IFile) { IFile f = (IFile) fh; while (buf.remaining() > 0) { int pos = buf.position(); f.update(buf, offset); offset += buf.position() - pos; } } return 0; } // // XattrSupport implementation /** * This method will be called to get the value of the extended attribute * * @param path * the path to file or directory containing extended attribute * @param name * the name of the extended attribute * @param dst * a ByteBuffer that should be filled with the value of the * extended attribute * @return 0 if Ok or errno when error * @throws fuse.FuseException * an alternative to returning errno is to throw this exception * with errno initialized * @throws java.nio.BufferOverflowException * should be thrown to indicate that the given <code>dst</code> * ByteBuffer is not large enough to hold the attribute's value. * After that <code>getxattr()</code> method will be called * again with a larger buffer. */ public int getxattr(String path, String name, ByteBuffer dst, int position) throws FuseException, BufferOverflowException { log.info("getxattr " + name + " for " + path); return Errno.ENOATTR; } /** * This method can be called to query for the size of the extended attribute * * @param path * the path to file or directory containing extended attribute * @param name * the name of the extended attribute * @param sizeSetter * a callback interface that should be used to set the * attribute's size * @return 0 if Ok or errno when error * @throws fuse.FuseException * an alternative to returning errno is to throw this exception * with errno initialized */ public int getxattrsize(String path, String name, FuseSizeSetter sizeSetter) throws FuseException { log.info("getxattrsize " + name + " for " + path); return Errno.ENOATTR; } /** * This method will be called to get the list of extended attribute names * * @param path * the path to file or directory containing extended attributes * @param lister * a callback interface that should be used to list the attribute * names * @return 0 if Ok or errno when error * @throws fuse.FuseException * an alternative to returning errno is to throw this exception * with errno initialized */ public int listxattr(String path, XattrLister lister) throws FuseException { log.info("listxattr for " + path); return Errno.ENOATTR; } /** * This method will be called to remove the extended attribute * * @param path * the path to file or directory containing extended attributes * @param name * the name of the extended attribute * @return 0 if Ok or errno when error * @throws fuse.FuseException * an alternative to returning errno is to throw this exception * with errno initialized */ public int removexattr(String path, String name) throws FuseException { log.info("removexattr " + name + " for " + path); return Errno.ENOATTR; } /** * This method will be called to set the value of an extended attribute * * @param path * the path to file or directory containing extended attributes * @param name * the name of the extended attribute * @param value * the value of the extended attribute * @param flags * parameter can be used to refine the semantics of the * operation. * <p> * <code>XATTR_CREATE</code> specifies a pure create, which * should fail with <code>Errno.EEXIST</code> if the named * attribute exists already. * <p> * <code>XATTR_REPLACE</code> specifies a pure replace operation, * which should fail with <code>Errno.ENOATTR</code> if the named * attribute does not already exist. * <p> * By default (no flags), the extended attribute will be created * if need be, or will simply replace the value if the attribute * exists. * @return 0 if Ok or errno when error * @throws fuse.FuseException * an alternative to returning errno is to throw this exception * with errno initialized */ public int setxattr(String path, String name, ByteBuffer value, int flags, int position) throws FuseException { log.info("setxattr " + name + " for " + path); return Errno.ENOATTR; } public static void initServerInfrastructure(String sequencerName, String scoutName) { DCSequencerServer.main(new String[] { "-name", sequencerName }); try { Thread.sleep(500); } catch (InterruptedException e) { // do nothing } DCServer.main(new String[] { sequencerName }); try { Thread.sleep(500); } catch (InterruptedException e) { // do nothing } Sys.init(); server = SwiftImpl.newInstance(scoutName, DCConstants.SURROGATE_PORT); } public static void main(String[] args) { log.info("setting up servers"); initServerInfrastructure("localhost", "localhost"); try { log.info("getting root directory"); TxnHandle txn = server.beginTxn(IsolationLevel.SNAPSHOT_ISOLATION, CachePolicy.STRICTLY_MOST_RECENT, false); // create a root directory // FIXME make this part of arguments Filesystem fs = new FilesystemBasic(txn, ROOT, "DIR"); txn.commit(); log.info("mounting filesystem"); FuseMount.mount(args, new FilesystemFuse(fs), log); } catch (Exception e) { e.printStackTrace(); } finally { log.info("exiting"); } } }
compatibility with remote interface of Sérgio git-svn-id: 12b4b70d94dc3d7bb244948a4de5adf9a227d930@1551 049c2a90-bdf1-4f83-8191-3719d539f8e0
src/swift/application/filesystem/fuse/FilesystemFuse.java
compatibility with remote interface of Sérgio
<ide><path>rc/swift/application/filesystem/fuse/FilesystemFuse.java <ide> private static final Log log = LogFactory.getLog(FilesystemFuse.class); <ide> protected static Swift server; <ide> <del> protected final Filesystem fs; <add> protected Filesystem fs; <ide> private static final int MODE = 0777; <ide> private static final int BLOCK_SIZE = 512; <ide> private static final int NAME_LENGTH = 1024;
Java
mit
02555642aa7efee6e7d8625ce994ae6e8883d1c6
0
sormuras/bach,sormuras/bach
/* * Bach - Java Shell Builder * Copyright (C) 2020 Christian Stein * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import java.io.File; import java.io.IOException; import java.io.PrintWriter; import java.io.StringWriter; import java.io.UncheckedIOException; import java.lang.System.Logger.Level; import java.lang.System.Logger; import java.lang.module.ModuleDescriptor.Requires; import java.lang.module.ModuleDescriptor.Version; import java.lang.module.ModuleDescriptor; import java.lang.module.ModuleFinder; import java.lang.module.ModuleReference; import java.lang.reflect.Array; import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse.BodyHandlers; import java.net.http.HttpResponse; import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; import java.nio.file.CopyOption; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.StandardCopyOption; import java.nio.file.attribute.FileTime; import java.text.MessageFormat; import java.text.SimpleDateFormat; import java.time.Duration; import java.time.Instant; import java.time.ZoneOffset; import java.time.format.DateTimeFormatter; import java.time.temporal.ChronoUnit; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.ResourceBundle; import java.util.Set; import java.util.StringJoiner; import java.util.TreeMap; import java.util.TreeSet; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.function.Consumer; import java.util.function.Function; import java.util.function.Predicate; import java.util.function.Supplier; import java.util.function.UnaryOperator; import java.util.regex.Pattern; import java.util.spi.ToolProvider; import java.util.stream.Collectors; import java.util.stream.Stream; public class Bach { public static final Version VERSION = Version.parse("11.0-ea"); public static final Path BUILD_JAVA = Path.of(".bach/src/Build.java"); public static final Path WORKSPACE = Path.of(".bach/workspace"); public static void main(String... args) { Main.main(args); } public static Optional<Path> findCustomBuildProgram() { return Files.exists(BUILD_JAVA) ? Optional.of(BUILD_JAVA) : Optional.empty(); } public static Bach of() { return of(Path.of("")); } public static Bach of(Path directory) { return of(Project.newProject(directory).build()); } public static Bach of(UnaryOperator<Project.Builder> operator) { return of(operator.apply(Project.newProject(Path.of(""))).build()); } public static Bach of(Project project) { return new Bach(project, HttpClient.newBuilder()::build); } private final Logbook logbook; private final Project project; private final Supplier<HttpClient> httpClient; public Bach(Project project, Supplier<HttpClient> httpClient) { this(Logbook.ofSystem(), project, httpClient); } private Bach(Logbook logbook, Project project, Supplier<HttpClient> httpClient) { this.logbook = Objects.requireNonNull(logbook, "logbook"); this.project = Objects.requireNonNull(project, "project"); this.httpClient = Functions.memoize(httpClient); logbook.log(Level.TRACE, "Initialized " + toString()); logbook.log(Level.DEBUG, project.toTitleAndVersion()); } public Logger getLogger() { return logbook; } public Project getProject() { return project; } public HttpClient getHttpClient() { return httpClient.get(); } public Summary build() { var summary = new Summary(this); try { execute(buildSequence()); } finally { summary.writeMarkdown(project.base().workspace("summary.md"), true); } return summary; } private Task buildSequence() { var tasks = new ArrayList<Task>(); tasks.add(new Task.ResolveMissingModules()); for (var realm : project.structure().realms()) { tasks.add(realm.javac()); for (var unit : realm.units()) tasks.addAll(unit.tasks()); tasks.addAll(realm.tasks()); } return Task.sequence("Build Sequence", tasks); } private void execute(Task task) { var label = task.getLabel(); var tasks = task.getList(); if (tasks.isEmpty()) { logbook.log(Level.TRACE, "* {0}", label); try { if (logbook.isDryRun()) return; task.execute(this); } catch (Throwable throwable) { var message = "Task execution failed"; logbook.log(Level.ERROR, message, throwable); throw new Error(message, throwable); } finally { logbook.log(Level.DEBUG, task.getOut().toString().strip()); logbook.log(Level.WARNING, task.getErr().toString().strip()); } return; } logbook.log(Level.TRACE, "+ {0}", label); var start = System.currentTimeMillis(); for (var sub : tasks) execute(sub); var duration = System.currentTimeMillis() - start; logbook.log(Level.TRACE, "= {0} took {1} ms", label, duration); } private void execute(ToolProvider tool, PrintWriter out, PrintWriter err, String... args) { var call = (tool.name() + ' ' + String.join(" ", args)).trim(); logbook.log(Level.DEBUG, call); var code = tool.run(out, err, args); if (code != 0) throw new AssertionError("Tool run exit code: " + code + "\n\t" + call); } public String toString() { return "Bach.java " + VERSION; } public interface Call { String toLabel(); ToolProvider toProvider(); String[] toArguments(); default Task toTask() { return new Task.RunTool(toLabel(), toProvider(), toArguments()); } class Arguments { private final List<String> list = new ArrayList<>(); public Arguments add(Object argument) { list.add(argument.toString()); return this; } public Arguments add(String key, Object value) { return add(key).add(value); } public Arguments add(String key, Object first, Object second) { return add(key).add(first).add(second); } public Arguments add(Arguments arguments) { list.addAll(arguments.list); return this; } public String[] toStringArray() { return list.toArray(String[]::new); } } final class Context { private final String realm; private final String module; public Context(String realm, String module) { this.realm = realm; this.module = module; } public String realm() { return realm; } public String module() { return module; } } interface Tuner { void tune(Call call, Context context); } } static class Main { public static void main(String... args) { if (Bach.findCustomBuildProgram().isPresent()) { System.err.println("Custom build program execution not supported, yet."); return; } Bach.of().build().assertSuccessful(); } } public static final class Project { public static Builder newProject(Path directory) { return ModulesWalker.walk(directory); } public static Builder newProject(String title, String version) { return new Builder().title(title).version(Version.parse(version)); } public static void tuner(Call call, @SuppressWarnings("unused") Call.Context context) { if (call instanceof GenericModuleSourceFilesConsumer) { var consumer = (GenericModuleSourceFilesConsumer<?>) call; consumer.setCharacterEncodingUsedBySourceFiles("UTF-8"); } if (call instanceof Javac) { var javac = (Javac) call; javac.setGenerateMetadataForMethodParameters(true); javac.setTerminateCompilationIfWarningsOccur(true); javac.getAdditionalArguments().add("-X" + "lint"); } if (call instanceof Javadoc) { var javadoc = (Javadoc) call; javadoc.getAdditionalArguments().add("-locale", "en"); } if (call instanceof Jlink) { var jlink = (Jlink) call; jlink.getAdditionalArguments().add("--compress", "2"); jlink.getAdditionalArguments().add("--strip-debug"); jlink.getAdditionalArguments().add("--no-header-files"); jlink.getAdditionalArguments().add("--no-man-pages"); } } private final Base base; private final Info info; private final Structure structure; public Project(Base base, Info info, Structure structure) { this.base = Objects.requireNonNull(base, "base"); this.info = Objects.requireNonNull(info, "info"); this.structure = Objects.requireNonNull(structure, "structure"); } public Base base() { return base; } public Info info() { return info; } public Structure structure() { return structure; } public String toString() { return new StringJoiner(", ", Project.class.getSimpleName() + "[", "]") .add("base=" + base) .add("info=" + info) .add("structure=" + structure) .toString(); } public List<String> toStrings() { var list = new ArrayList<String>(); list.add("Project"); list.add("\ttitle: " + info.title()); list.add("\tversion: " + info.version()); list.add("\trealms: " + structure.realms().size()); list.add("\tunits: " + structure.units().count()); for (var realm : structure.realms()) { list.add("\tRealm " + realm.name()); list.add("\t\tjavac: " + String.format("%.77s...", realm.javac().getLabel())); list.add("\t\ttasks: " + realm.tasks().size()); for (var unit : realm.units()) { list.add("\t\tUnit " + unit.name()); list.add("\t\t\ttasks: " + unit.tasks().size()); var module = unit.descriptor(); list.add("\t\t\tModule Descriptor " + module.toNameAndVersion()); list.add("\t\t\t\tmain: " + module.mainClass().orElse("-")); list.add("\t\t\t\trequires: " + new TreeSet<>(module.requires())); } } return list; } public String toTitleAndVersion() { return info.title() + ' ' + info.version(); } public Set<String> toDeclaredModuleNames() { return structure.units().map(Unit::name).collect(Collectors.toCollection(TreeSet::new)); } public Set<String> toRequiredModuleNames() { return Modules.required(structure.units().map(Unit::descriptor)); } public static final class Base { public static Base of() { return of(Path.of("")); } public static Base of(Path directory) { return new Base(directory, directory.resolve(Bach.WORKSPACE)); } private final Path directory; private final Path workspace; Base(Path directory, Path workspace) { this.directory = Objects.requireNonNull(directory, "directory"); this.workspace = Objects.requireNonNull(workspace, "workspace"); } public Path directory() { return directory; } public Path workspace() { return workspace; } public Path path(String first, String... more) { return directory.resolve(Path.of(first, more)); } public Path workspace(String first, String... more) { return workspace.resolve(Path.of(first, more)); } public Path api() { return workspace("api"); } public Path classes(String realm) { return workspace("classes", realm); } public Path classes(String realm, String module) { return workspace("classes", realm, module); } public Path image() { return workspace("image"); } public Path modules(String realm) { return workspace("modules", realm); } } public static final class Info { private final String title; private final Version version; public Info(String title, Version version) { this.title = Objects.requireNonNull(title, "title"); this.version = Objects.requireNonNull(version, "version"); } public String title() { return title; } public Version version() { return version; } public String toString() { return new StringJoiner(", ", Info.class.getSimpleName() + "[", "]") .add("title='" + title + "'") .add("version=" + version) .toString(); } } public static final class Structure { private final Library library; private final List<Realm> realms; public Structure(Library library, List<Realm> realms) { this.library = library; this.realms = List.copyOf(Objects.requireNonNull(realms, "realms")); } public Library library() { return library; } public List<Realm> realms() { return realms; } public Stream<Unit> units() { return realms.stream().flatMap(realm -> realm.units().stream()); } } public static final class Library { public static Library of() { return of(new ModulesMap()); } public static Library of(Map<String, String> map) { return new Library(Set.of(), map::get); } private final Set<String> required; private final UnaryOperator<String> lookup; public Library(Set<String> required, UnaryOperator<String> lookup) { this.required = required; this.lookup = lookup; } public Set<String> required() { return required; } public UnaryOperator<String> lookup() { return lookup; } } public static final class Realm { private final String name; private final List<Unit> units; private final Task javac; private final List<Task> tasks; public Realm(String name, List<Unit> units, Task javac, List<Task> tasks) { this.name = Objects.requireNonNull(name, "name"); this.units = List.copyOf(Objects.requireNonNull(units, "units")); this.javac = Objects.requireNonNull(javac, "javac"); this.tasks = List.copyOf(Objects.requireNonNull(tasks, "tasks")); } public String name() { return name; } public List<Unit> units() { return units; } public Task javac() { return javac; } public List<Task> tasks() { return tasks; } } public static final class Unit { private final ModuleDescriptor descriptor; private final List<Task> tasks; public Unit(ModuleDescriptor descriptor, List<Task> tasks) { this.descriptor = Objects.requireNonNull(descriptor, "descriptor"); this.tasks = List.copyOf(Objects.requireNonNull(tasks, "tasks")); } public ModuleDescriptor descriptor() { return descriptor; } public List<Task> tasks() { return tasks; } public String name() { return descriptor.name(); } } public static class Builder { private Base base = Base.of(); private String title = "Project Title"; private Version version = Version.parse("1-ea"); private Structure structure = new Structure(Library.of(), List.of()); public Project build() { var info = new Info(title, version); return new Project(base, info, structure); } public Builder base(Base base) { this.base = base; return this; } public Builder title(String title) { this.title = title; return this; } public Builder version(Version version) { this.version = version; return this; } public Builder structure(Structure structure) { this.structure = structure; return this; } } } public static class Summary { private final Bach bach; private final Logbook logbook; public Summary(Bach bach) { this.bach = bach; this.logbook = (Logbook) bach.getLogger(); } public void assertSuccessful() { var entries = logbook.entries(Level.WARNING).collect(Collectors.toList()); if (entries.isEmpty()) return; var lines = new StringJoiner(System.lineSeparator()); lines.add(String.format("Collected %d error(s)", entries.size())); for (var entry : entries) lines.add("\t- " + entry.message()); lines.add(""); lines.add(String.join(System.lineSeparator(), toMarkdown())); var error = new AssertionError(lines.toString()); for (var entry : entries) if (entry.exception() != null) error.addSuppressed(entry.exception()); throw error; } public void writeMarkdown(Path file, boolean createCopyWithTimestamp) { var markdown = toMarkdown(); try { Files.createDirectories(file.getParent()); Files.write(file, markdown); if (createCopyWithTimestamp) { @SuppressWarnings("SpellCheckingInspection") var pattern = "yyyyMMdd_HHmmss"; var formatter = DateTimeFormatter.ofPattern(pattern).withZone(ZoneOffset.UTC); var timestamp = formatter.format(Instant.now().truncatedTo(ChronoUnit.SECONDS)); var summaries = Files.createDirectories(file.resolveSibling("summaries")); Files.copy(file, summaries.resolve("summary-" + timestamp + ".md")); } } catch (Exception e) { throw new RuntimeException(e); } } public List<String> toMarkdown() { var md = new ArrayList<String>(); md.add("# Summary for " + bach.getProject().toTitleAndVersion()); md.addAll(projectDescription()); md.addAll(logbookEntries()); return md; } private List<String> projectDescription() { var md = new ArrayList<String>(); var project = bach.getProject(); md.add(""); md.add("## Project"); md.add("- title: " + project.info().title()); md.add("- version: " + project.info().version()); md.add(""); md.add("```text"); md.addAll(project.toStrings()); md.add("```"); return md; } private List<String> logbookEntries() { var md = new ArrayList<String>(); md.add(""); md.add("## Logbook"); for (var entry : logbook.entries(Level.ALL).collect(Collectors.toList())) { md.add("- " + entry.level()); var one = entry.message().lines().count() == 1; md.add((one ? "`" : "```text\n") + entry.message() + (one ? "`" : "\n```")); } return md; } } public static class Task { public static Task sequence(String label, Task... tasks) { return sequence(label, List.of(tasks)); } public static Task sequence(String label, List<Task> tasks) { return new Task(label, tasks); } private final String label; private final List<Task> list; private final StringWriter out; private final StringWriter err; public Task() { this("", List.of()); } public Task(String label, List<Task> list) { Objects.requireNonNull(label, "label"); this.label = label.isBlank() ? getClass().getSimpleName() : label; this.list = List.copyOf(Objects.requireNonNull(list, "list")); this.out = new StringWriter(); this.err = new StringWriter(); } public String getLabel() { return label; } public List<Task> getList() { return list; } public StringWriter getOut() { return out; } public StringWriter getErr() { return err; } public String toString() { return new StringJoiner(", ", Task.class.getSimpleName() + "[", "]") .add("label='" + label + "'") .add("list.size=" + list.size()) .toString(); } public void execute(Bach bach) throws Exception {} public static class RunTool extends Task { private final ToolProvider tool; private final String[] args; public RunTool(String label, ToolProvider tool, String... args) { super(label, List.of()); this.tool = tool; this.args = args; } public void execute(Bach bach) { bach.execute(tool, new PrintWriter(getOut()), new PrintWriter(getErr()), args); } } public static class CreateDirectories extends Task { private final Path directory; public CreateDirectories(Path directory) { super("Create directories " + directory.toUri(), List.of()); this.directory = directory; } public void execute(Bach bach) throws Exception { Files.createDirectories(directory); } } public static class DeleteDirectories extends Task { private final Path directory; public DeleteDirectories(Path directory) { super("Delete directory " + directory, List.of()); this.directory = directory; } public void execute(Bach bach) throws Exception { if (Files.notExists(directory)) return; try (var stream = Files.walk(directory)) { var paths = stream.sorted((p, q) -> -p.compareTo(q)); for (var path : paths.toArray(Path[]::new)) Files.deleteIfExists(path); } } } public static class ResolveMissingModules extends Task { public ResolveMissingModules() { super("Resolve missing modules", List.of()); } public void execute(Bach bach) { var project = bach.getProject(); var library = project.structure().library(); var lib = project.base().directory().resolve("lib"); class Transporter implements Consumer<Set<String>> { public void accept(Set<String> modules) { var resources = new Resources(bach.getHttpClient()); for (var module : modules) { var raw = library.lookup().apply(module); if (raw == null) continue; try { var uri = URI.create(raw); var name = module + ".jar"; var file = resources.copy(uri, lib.resolve(name)); var size = Files.size(file); bach.getLogger().log(Level.INFO, "{0} ({1} bytes) << {2}", file, size, uri); } catch (Exception e) { throw new Error("Resolve module '" + module + "' failed: " + raw +"\n\t" + e, e); } } } } var declared = project.toDeclaredModuleNames(); var required = project.toRequiredModuleNames(); var resolver = new ModulesResolver(new Path[] {lib}, declared, new Transporter()); resolver.resolve(required); resolver.resolve(library.required()); } } } public static abstract class AbstractCallBuilder implements Call { public static boolean assigned(Object object) { if (object == null) return false; if (object instanceof Number) return ((Number) object).intValue() != 0; if (object instanceof String) return !((String) object).isEmpty(); if (object instanceof Optional) return ((Optional<?>) object).isPresent(); if (object instanceof Collection) return !((Collection<?>) object).isEmpty(); if (object.getClass().isArray()) return Array.getLength(object) != 0; return true; } public static String join(Collection<Path> paths) { return paths.stream().map(Path::toString).collect(Collectors.joining(File.pathSeparator)); } public static String joinPaths(Collection<String> paths) { return String.join(File.pathSeparator, paths); } private final String name; private final Arguments additionalArguments = new Arguments(); public AbstractCallBuilder(String name) { this.name = name; } public Arguments getAdditionalArguments() { return additionalArguments; } public ToolProvider toProvider() { return ToolProvider.findFirst(name).orElseThrow(); } public String[] toArguments() { var arguments = new Arguments(); arguments(arguments); return arguments.add(getAdditionalArguments()).toStringArray(); } protected void arguments(Arguments arguments) {} } @SuppressWarnings("unchecked") public static abstract class GenericModuleSourceFilesConsumer<T> extends AbstractCallBuilder { private Path destinationDirectory; private String characterEncodingUsedBySourceFiles; private Set<String> modules; public GenericModuleSourceFilesConsumer(String name) { super(name); } protected void arguments(Arguments arguments) { var destination = getDestinationDirectory(); if (assigned(destination)) arguments.add("-d", destination); var encoding = getCharacterEncodingUsedBySourceFiles(); if (assigned(encoding)) arguments.add("-encoding", encoding); var modules = getModules(); if (assigned(modules)) arguments.add("--module", String.join(",", new TreeSet<>(modules))); } public Path getDestinationDirectory() { return destinationDirectory; } public T setDestinationDirectory(Path directory) { this.destinationDirectory = directory; return (T) this; } public String getCharacterEncodingUsedBySourceFiles() { return characterEncodingUsedBySourceFiles; } public T setCharacterEncodingUsedBySourceFiles(String encoding) { this.characterEncodingUsedBySourceFiles = encoding; return (T) this; } public Set<String> getModules() { return modules; } public T setModules(Set<String> modules) { this.modules = modules; return (T) this; } } public static class Jar extends AbstractCallBuilder { public Jar() { super("jar"); } public String toLabel() { return "Operate on JAR file"; } } public static class Javac extends GenericModuleSourceFilesConsumer<Javac> { private Version versionOfModulesThatAreBeingCompiled; private Collection<String> patternsWhereToFindSourceFiles; private Map<String, Collection<Path>> pathsWhereToFindSourceFiles; private Map<String, Collection<Path>> pathsWhereToFindMoreAssetsPerModule; private Collection<Path> pathsWhereToFindApplicationModules; private int compileForVirtualMachineVersion; private boolean enablePreviewLanguageFeatures; private boolean generateMetadataForMethodParameters; private boolean outputMessagesAboutWhatTheCompilerIsDoing; private boolean outputSourceLocationsOfDeprecatedUsages; private boolean terminateCompilationIfWarningsOccur; public Javac() { super("javac"); } public String toLabel() { return "Compile module(s): " + getModules(); } protected void arguments(Arguments arguments) { super.arguments(arguments); var version = getVersionOfModulesThatAreBeingCompiled(); if (assigned(version)) arguments.add("--module-version", version); var patterns = getPatternsWhereToFindSourceFiles(); if (assigned(patterns)) arguments.add("--module-source-path", joinPaths(patterns)); var specific = getPathsWhereToFindSourceFiles(); if (assigned(specific)) for (var entry : specific.entrySet()) arguments.add("--module-source-path", entry.getKey() + '=' + join(entry.getValue())); var patches = getPathsWhereToFindMoreAssetsPerModule(); if (assigned(patches)) for (var patch : patches.entrySet()) arguments.add("--patch-module", patch.getKey() + '=' + join(patch.getValue())); var modulePath = getPathsWhereToFindApplicationModules(); if (assigned(modulePath)) arguments.add("--module-path", join(modulePath)); var release = getCompileForVirtualMachineVersion(); if (assigned(release)) arguments.add("--release", release); if (isEnablePreviewLanguageFeatures()) arguments.add("--enable-preview"); if (isGenerateMetadataForMethodParameters()) arguments.add("-parameters"); if (isOutputSourceLocationsOfDeprecatedUsages()) arguments.add("-deprecation"); if (isOutputMessagesAboutWhatTheCompilerIsDoing()) arguments.add("-verbose"); if (isTerminateCompilationIfWarningsOccur()) arguments.add("-Werror"); } public Version getVersionOfModulesThatAreBeingCompiled() { return versionOfModulesThatAreBeingCompiled; } public Javac setVersionOfModulesThatAreBeingCompiled( Version versionOfModulesThatAreBeingCompiled) { this.versionOfModulesThatAreBeingCompiled = versionOfModulesThatAreBeingCompiled; return this; } public Collection<String> getPatternsWhereToFindSourceFiles() { return patternsWhereToFindSourceFiles; } public Javac setPatternsWhereToFindSourceFiles(Collection<String> patterns) { this.patternsWhereToFindSourceFiles = patterns; return this; } public Map<String, Collection<Path>> getPathsWhereToFindSourceFiles() { return pathsWhereToFindSourceFiles; } public Javac setPathsWhereToFindSourceFiles(Map<String, Collection<Path>> map) { this.pathsWhereToFindSourceFiles = map; return this; } public Map<String, Collection<Path>> getPathsWhereToFindMoreAssetsPerModule() { return pathsWhereToFindMoreAssetsPerModule; } public Javac setPathsWhereToFindMoreAssetsPerModule(Map<String, Collection<Path>> map) { this.pathsWhereToFindMoreAssetsPerModule = map; return this; } public Collection<Path> getPathsWhereToFindApplicationModules() { return pathsWhereToFindApplicationModules; } public Javac setPathsWhereToFindApplicationModules( Collection<Path> pathsWhereToFindApplicationModules) { this.pathsWhereToFindApplicationModules = pathsWhereToFindApplicationModules; return this; } public int getCompileForVirtualMachineVersion() { return compileForVirtualMachineVersion; } public Javac setCompileForVirtualMachineVersion(int release) { this.compileForVirtualMachineVersion = release; return this; } public boolean isEnablePreviewLanguageFeatures() { return enablePreviewLanguageFeatures; } public Javac setEnablePreviewLanguageFeatures(boolean preview) { this.enablePreviewLanguageFeatures = preview; return this; } public boolean isGenerateMetadataForMethodParameters() { return generateMetadataForMethodParameters; } public Javac setGenerateMetadataForMethodParameters(boolean parameters) { this.generateMetadataForMethodParameters = parameters; return this; } public boolean isOutputMessagesAboutWhatTheCompilerIsDoing() { return outputMessagesAboutWhatTheCompilerIsDoing; } public Javac setOutputMessagesAboutWhatTheCompilerIsDoing(boolean verbose) { this.outputMessagesAboutWhatTheCompilerIsDoing = verbose; return this; } public boolean isOutputSourceLocationsOfDeprecatedUsages() { return outputSourceLocationsOfDeprecatedUsages; } public Javac setOutputSourceLocationsOfDeprecatedUsages(boolean deprecation) { this.outputSourceLocationsOfDeprecatedUsages = deprecation; return this; } public boolean isTerminateCompilationIfWarningsOccur() { return terminateCompilationIfWarningsOccur; } public Javac setTerminateCompilationIfWarningsOccur(boolean error) { this.terminateCompilationIfWarningsOccur = error; return this; } } public static class Javadoc extends GenericModuleSourceFilesConsumer<Javadoc> { private Collection<String> patternsWhereToFindSourceFiles; private Map<String, Collection<Path>> pathsWhereToFindSourceFiles; private Map<String, Collection<Path>> pathsWhereToFindMoreAssetsPerModule; private Collection<Path> pathsWhereToFindApplicationModules; private String characterEncodingUsedBySourceFiles; private int compileForVirtualMachineVersion; private boolean enablePreviewLanguageFeatures; private boolean outputMessagesAboutWhatJavadocIsDoing; private boolean shutOffDisplayingStatusMessages; public Javadoc() { super("javadoc"); } public String toLabel() { return "Generate API documentation for " + getModules(); } protected void arguments(Arguments arguments) { super.arguments(arguments); var patterns = getPatternsWhereToFindSourceFiles(); if (assigned(patterns)) arguments.add("--module-source-path", joinPaths(patterns)); var specific = getPathsWhereToFindSourceFiles(); if (assigned(specific)) for (var entry : specific.entrySet()) arguments.add("--module-source-path", entry.getKey() + '=' + join(entry.getValue())); var patches = getPathsWhereToFindMoreAssetsPerModule(); if (assigned(patches)) for (var patch : patches.entrySet()) arguments.add("--patch-module", patch.getKey() + '=' + join(patch.getValue())); var modulePath = getPathsWhereToFindApplicationModules(); if (assigned(modulePath)) arguments.add("--module-path", join(modulePath)); var encoding = getCharacterEncodingUsedBySourceFiles(); if (assigned(encoding)) arguments.add("-encoding", encoding); var release = getCompileForVirtualMachineVersion(); if (assigned(release)) arguments.add("--release", release); if (isEnablePreviewLanguageFeatures()) arguments.add("--enable-preview"); if (isOutputMessagesAboutWhatJavadocIsDoing()) arguments.add("-verbose"); if (isShutOffDisplayingStatusMessages()) arguments.add("-quiet"); } public Collection<String> getPatternsWhereToFindSourceFiles() { return patternsWhereToFindSourceFiles; } public Javadoc setPatternsWhereToFindSourceFiles(Collection<String> patterns) { this.patternsWhereToFindSourceFiles = patterns; return this; } public Map<String, Collection<Path>> getPathsWhereToFindSourceFiles() { return pathsWhereToFindSourceFiles; } public Javadoc setPathsWhereToFindSourceFiles(Map<String, Collection<Path>> map) { this.pathsWhereToFindSourceFiles = map; return this; } public Map<String, Collection<Path>> getPathsWhereToFindMoreAssetsPerModule() { return pathsWhereToFindMoreAssetsPerModule; } public Javadoc setPathsWhereToFindMoreAssetsPerModule(Map<String, Collection<Path>> map) { this.pathsWhereToFindMoreAssetsPerModule = map; return this; } public Collection<Path> getPathsWhereToFindApplicationModules() { return pathsWhereToFindApplicationModules; } public Javadoc setPathsWhereToFindApplicationModules(Collection<Path> paths) { this.pathsWhereToFindApplicationModules = paths; return this; } public String getCharacterEncodingUsedBySourceFiles() { return characterEncodingUsedBySourceFiles; } public Javadoc setCharacterEncodingUsedBySourceFiles(String encoding) { this.characterEncodingUsedBySourceFiles = encoding; return this; } public int getCompileForVirtualMachineVersion() { return compileForVirtualMachineVersion; } public Javadoc setCompileForVirtualMachineVersion(int release) { this.compileForVirtualMachineVersion = release; return this; } public boolean isEnablePreviewLanguageFeatures() { return enablePreviewLanguageFeatures; } public Javadoc setEnablePreviewLanguageFeatures(boolean preview) { this.enablePreviewLanguageFeatures = preview; return this; } public boolean isOutputMessagesAboutWhatJavadocIsDoing() { return outputMessagesAboutWhatJavadocIsDoing; } public Javadoc setOutputMessagesAboutWhatJavadocIsDoing(boolean verbose) { this.outputMessagesAboutWhatJavadocIsDoing = verbose; return this; } public boolean isShutOffDisplayingStatusMessages() { return shutOffDisplayingStatusMessages; } public Javadoc setShutOffDisplayingStatusMessages(boolean quiet) { this.shutOffDisplayingStatusMessages = quiet; return this; } } public static class Jlink extends AbstractCallBuilder { private Path locationOfTheGeneratedRuntimeImage; private Set<String> modules; public Jlink() { super("jlink"); } public String toLabel() { return "Create a custom runtime image with dependencies for " + getModules(); } protected void arguments(Arguments arguments) { var output = getLocationOfTheGeneratedRuntimeImage(); if (assigned(output)) arguments.add("--output", output); var modules = getModules(); if (assigned(modules)) arguments.add("--add-modules", String.join(",", new TreeSet<>(modules))); } public Path getLocationOfTheGeneratedRuntimeImage() { return locationOfTheGeneratedRuntimeImage; } public Jlink setLocationOfTheGeneratedRuntimeImage(Path output) { this.locationOfTheGeneratedRuntimeImage = output; return this; } public Set<String> getModules() { return modules; } public Jlink setModules(Set<String> modules) { this.modules = modules; return this; } } public static class Functions { public static <T> Supplier<T> memoize(Supplier<T> supplier) { Objects.requireNonNull(supplier, "supplier"); class CachingSupplier implements Supplier<T> { Supplier<T> delegate = this::initialize; boolean initialized = false; public T get() { return delegate.get(); } private synchronized T initialize() { if (initialized) return delegate.get(); T value = supplier.get(); delegate = () -> value; initialized = true; return value; } } return new CachingSupplier(); } private Functions() {} } public static class Logbook implements System.Logger { public static Logbook ofSystem() { var debug = Boolean.getBoolean("ebug") || "".equals(System.getProperty("ebug")); var dryRun = Boolean.getBoolean("ry-run") || "".equals(System.getProperty("ry-run")); return new Logbook(System.out::println, debug, dryRun); } private final Consumer<String> consumer; private final boolean debug; private final boolean dryRun; private final Collection<Entry> entries; public Logbook(Consumer<String> consumer, boolean debug, boolean dryRun) { this.consumer = consumer; this.debug = debug; this.dryRun = dryRun; this.entries = new ConcurrentLinkedQueue<>(); } public boolean isDebug() { return debug; } public boolean isDryRun() { return dryRun; } public String getName() { return "Logbook"; } public boolean isLoggable(Level level) { if (level == Level.ALL) return isDebug(); if (level == Level.OFF) return isDryRun(); return true; } public void log(Level level, ResourceBundle bundle, String message, Throwable thrown) { if (message == null || message.isBlank()) return; var entry = new Entry(level, message, thrown); if (debug) consumer.accept(entry.toString()); entries.add(entry); } public void log(Level level, ResourceBundle bundle, String pattern, Object... arguments) { var message = arguments == null ? pattern : MessageFormat.format(pattern, arguments); log(level, bundle, message, (Throwable) null); } public Stream<Entry> entries(Level threshold) { return entries.stream().filter(entry -> entry.level.getSeverity() >= threshold.getSeverity()); } public List<String> messages() { return lines(entry -> entry.message); } public List<String> lines(Function<Entry, String> mapper) { return entries.stream().map(mapper).collect(Collectors.toList()); } public static final class Entry { private final Level level; private final String message; private final Throwable exception; public Entry(Level level, String message, Throwable exception) { this.level = level; this.message = message; this.exception = exception; } public Level level() { return level; } public String message() { return message; } public Throwable exception() { return exception; } public String toString() { var exceptionMessage = exception == null ? "" : " -> " + exception; return String.format("%c|%s%s", level.name().charAt(0), message, exceptionMessage); } } } public static class Modules { interface Patterns { Pattern NAME = Pattern.compile( "(?:module)" // key word + "\\s+([\\w.]+)" // module name + "(?:\\s*/\\*.*\\*/\\s*)?" // optional multi-line comment + "\\s*\\{"); // end marker Pattern REQUIRES = Pattern.compile( "(?:requires)" // key word + "(?:\\s+[\\w.]+)?" // optional modifiers + "\\s+([\\w.]+)" // module name + "(?:\\s*/\\*\\s*([\\w.\\-+]+)\\s*\\*/\\s*)?" // optional '/*' version '*/' + "\\s*;"); // end marker } public static Optional<String> findMainClass(Path info, String module) { var main = Path.of(module.replace('.', '/'), "Main.java"); var exists = Files.isRegularFile(info.resolveSibling(main)); return exists ? Optional.of(module + '.' + "Main") : Optional.empty(); } public static Optional<String> findMainModule(Stream<ModuleDescriptor> descriptors) { var mains = descriptors.filter(d -> d.mainClass().isPresent()).collect(Collectors.toList()); return mains.size() == 1 ? Optional.of(mains.get(0).name()) : Optional.empty(); } public static ModuleDescriptor describe(Path info) { try { var module = describe(Files.readString(info)); var temporary = module.build(); findMainClass(info, temporary.name()).ifPresent(module::mainClass); return module.build(); } catch (IOException e) { throw new UncheckedIOException("Describe failed", e); } } public static ModuleDescriptor.Builder describe(String source) { var nameMatcher = Patterns.NAME.matcher(source); if (!nameMatcher.find()) throw new IllegalArgumentException("Expected Java module source unit, but got: " + source); var name = nameMatcher.group(1).trim(); var builder = ModuleDescriptor.newModule(name); var requiresMatcher = Patterns.REQUIRES.matcher(source); while (requiresMatcher.find()) { var requiredName = requiresMatcher.group(1); Optional.ofNullable(requiresMatcher.group(2)) .ifPresentOrElse( version -> builder.requires(Set.of(), requiredName, Version.parse(version)), () -> builder.requires(requiredName)); } return builder; } public static String modulePatternForm(Path info, String module) { var pattern = info.normalize().getParent().toString().replace(module, "*"); if (pattern.equals("*")) return "."; if (pattern.endsWith("*")) return pattern.substring(0, pattern.length() - 2); if (pattern.startsWith("*")) return "." + File.separator + pattern; return pattern; } public static Set<String> declared(ModuleFinder finder) { return declared(finder.findAll().stream().map(ModuleReference::descriptor)); } public static Set<String> declared(Stream<ModuleDescriptor> descriptors) { return descriptors.map(ModuleDescriptor::name).collect(Collectors.toCollection(TreeSet::new)); } public static Set<String> required(ModuleFinder finder) { return required(finder.findAll().stream().map(ModuleReference::descriptor)); } public static Set<String> required(Stream<ModuleDescriptor> descriptors) { return descriptors .map(ModuleDescriptor::requires) .flatMap(Set::stream) .filter(requires -> !requires.modifiers().contains(Requires.Modifier.MANDATED)) .filter(requires -> !requires.modifiers().contains(Requires.Modifier.SYNTHETIC)) .map(Requires::name) .collect(Collectors.toCollection(TreeSet::new)); } private Modules() {} } public static class ModulesMap extends TreeMap<String, String> { private static final long serialVersionUID = -7978021121082640440L; public ModulesMap() { put("junit", "https://repo.maven.apache.org/maven2/junit/junit/4.13/junit-4.13.jar"); put( "net.bytebuddy", "https://repo.maven.apache.org/maven2/net/bytebuddy/byte-buddy/1.10.10/byte-buddy-1.10.10.jar"); put( "net.bytebuddy.agent", "https://repo.maven.apache.org/maven2/net/bytebuddy/byte-buddy-agent/1.10.10/byte-buddy-agent-1.10.10.jar"); put( "org.apiguardian.api", "https://repo.maven.apache.org/maven2/org/apiguardian/apiguardian-api/1.1.0/apiguardian-api-1.1.0.jar"); put( "org.assertj.core", "https://repo.maven.apache.org/maven2/org/assertj/assertj-core/3.16.1/assertj-core-3.16.1.jar"); put( "org.hamcrest", "https://repo.maven.apache.org/maven2/org/hamcrest/hamcrest/2.2/hamcrest-2.2.jar"); put( "org.junit.jupiter", "https://repo.maven.apache.org/maven2/org/junit/jupiter/junit-jupiter/5.7.0-M1/junit-jupiter-5.7.0-M1.jar"); put( "org.junit.jupiter.api", "https://repo.maven.apache.org/maven2/org/junit/jupiter/junit-jupiter-api/5.7.0-M1/junit-jupiter-api-5.7.0-M1.jar"); put( "org.junit.jupiter.engine", "https://repo.maven.apache.org/maven2/org/junit/jupiter/junit-jupiter-engine/5.7.0-M1/junit-jupiter-engine-5.7.0-M1.jar"); put( "org.junit.jupiter.params", "https://repo.maven.apache.org/maven2/org/junit/jupiter/junit-jupiter-params/5.7.0-M1/junit-jupiter-params-5.7.0-M1.jar"); put( "org.junit.platform.commons", "https://repo.maven.apache.org/maven2/org/junit/platform/junit-platform-commons/1.7.0-M1/junit-platform-commons-1.7.0-M1.jar"); put( "org.junit.platform.console", "https://repo.maven.apache.org/maven2/org/junit/platform/junit-platform-console/1.7.0-M1/junit-platform-console-1.7.0-M1.jar"); put( "org.junit.platform.engine", "https://repo.maven.apache.org/maven2/org/junit/platform/junit-platform-engine/1.7.0-M1/junit-platform-engine-1.7.0-M1.jar"); put( "org.junit.platform.launcher", "https://repo.maven.apache.org/maven2/org/junit/platform/junit-platform-launcher/1.7.0-M1/junit-platform-launcher-1.7.0-M1.jar"); put( "org.junit.platform.reporting", "https://repo.maven.apache.org/maven2/org/junit/platform/junit-platform-reporting/1.7.0-M1/junit-platform-reporting-1.7.0-M1.jar"); put( "org.junit.platform.testkit", "https://repo.maven.apache.org/maven2/org/junit/platform/junit-platform-testkit/1.7.0-M1/junit-platform-testkit-1.7.0-M1.jar"); put( "org.junit.vintage.engine", "https://repo.maven.apache.org/maven2/org/junit/vintage/junit-vintage-engine/5.7.0-M1/junit-vintage-engine-5.7.0-M1.jar"); put( "org.objectweb.asm", "https://repo.maven.apache.org/maven2/org/ow2/asm/asm/8.0.1/asm-8.0.1.jar"); put( "org.objectweb.asm.commons", "https://repo.maven.apache.org/maven2/org/ow2/asm/asm-commons/8.0.1/asm-commons-8.0.1.jar"); put( "org.objectweb.asm.tree", "https://repo.maven.apache.org/maven2/org/ow2/asm/asm-tree/8.0.1/asm-tree-8.0.1.jar"); put( "org.objectweb.asm.tree.analysis", "https://repo.maven.apache.org/maven2/org/ow2/asm/asm-analysis/8.0.1/asm-analysis-8.0.1.jar"); put( "org.objectweb.asm.util", "https://repo.maven.apache.org/maven2/org/ow2/asm/asm-util/8.0.1/asm-util-8.0.1.jar"); put( "org.opentest4j", "https://repo.maven.apache.org/maven2/org/opentest4j/opentest4j/1.2.0/opentest4j-1.2.0.jar"); } } public static class ModulesResolver { private final Path[] paths; private final Set<String> declared; private final Consumer<Set<String>> transporter; private final Set<String> system; public ModulesResolver(Path[] paths, Set<String> declared, Consumer<Set<String>> transporter) { this.paths = paths; this.declared = new TreeSet<>(declared); this.transporter = transporter; this.system = Modules.declared(ModuleFinder.ofSystem()); } public void resolve(Set<String> required) { resolveModules(required); resolveLibraryModules(); } public void resolveModules(Set<String> required) { var missing = missing(required); if (missing.isEmpty()) return; transporter.accept(missing); var unresolved = missing(required); if (unresolved.isEmpty()) return; throw new IllegalStateException("Unresolved modules: " + unresolved); } public void resolveLibraryModules() { do { var missing = missing(Modules.required(ModuleFinder.of(paths))); if (missing.isEmpty()) return; resolveModules(missing); } while (true); } Set<String> missing(Set<String> required) { var missing = new TreeSet<>(required); missing.removeAll(declared); if (required.isEmpty()) return Set.of(); missing.removeAll(system); if (required.isEmpty()) return Set.of(); var library = Modules.declared(ModuleFinder.of(paths)); missing.removeAll(library); return missing; } } public static class ModulesWalker { public static Project.Builder walk(Path directory) { return walk(Project.Base.of(directory), Project::tuner); } public static Project.Builder walk(Project.Base base, Call.Tuner tuner) { var moduleInfoFiles = Paths.find(List.of(base.directory()), Paths::isModuleInfoJavaFile); if (moduleInfoFiles.isEmpty()) throw new IllegalStateException("No module found: " + base); var walker = new ModulesWalker(base, moduleInfoFiles, tuner); return walker.walkAndCreateUnnamedRealm(); } private final Project.Base base; private final List<Path> moduleInfoFiles; private final Call.Tuner tuner; public ModulesWalker(Project.Base base, List<Path> moduleInfoFiles, Call.Tuner tuner) { this.base = base; this.moduleInfoFiles = moduleInfoFiles; this.tuner = tuner; } public Project.Builder walkAndCreateUnnamedRealm() { var moduleNames = new TreeSet<String>(); var moduleSourcePathPatterns = new TreeSet<String>(); var units = new ArrayList<Project.Unit>(); var javadocCommentFound = false; for (var info : moduleInfoFiles) { javadocCommentFound = javadocCommentFound || Paths.isJavadocCommentAvailable(info); var descriptor = Modules.describe(info); var module = descriptor.name(); moduleNames.add(module); moduleSourcePathPatterns.add(Modules.modulePatternForm(info, descriptor.name())); var classes = base.classes("", module); var modules = base.modules(""); var jar = modules.resolve(module + ".jar"); var context = new Call.Context("", module); var jarCreate = new Jar(); var jarCreateArgs = jarCreate.getAdditionalArguments(); jarCreateArgs.add("--create").add("--file", jar); descriptor.mainClass().ifPresent(main -> jarCreateArgs.add("--main-class", main)); jarCreateArgs.add("-C", classes, "."); tuner.tune(jarCreate, context); var jarDescribe = new Jar(); jarDescribe.getAdditionalArguments().add("--describe-module").add("--file", jar); tuner.tune(jarDescribe, context); var task = Task.sequence( "Create modular JAR file " + jar.getFileName(), new Task.CreateDirectories(jar.getParent()), jarCreate.toTask(), jarDescribe.toTask()); units.add(new Project.Unit(descriptor, List.of(task))); } var context = new Call.Context("", null); var javac = new Javac() .setModules(moduleNames) .setPatternsWhereToFindSourceFiles(moduleSourcePathPatterns) .setDestinationDirectory(base.classes("")); tuner.tune(javac, context); var tasks = new ArrayList<Task>(); if (javadocCommentFound) { var javadoc = new Javadoc() .setDestinationDirectory(base.api()) .setModules(moduleNames) .setPatternsWhereToFindSourceFiles(moduleSourcePathPatterns); tuner.tune(javadoc, context); tasks.add(javadoc.toTask()); } var mainModule = Modules.findMainModule(units.stream().map(Project.Unit::descriptor)); if (mainModule.isPresent()) { var jlink = new Jlink().setModules(moduleNames).setLocationOfTheGeneratedRuntimeImage(base.image()); var launcher = Path.of(mainModule.get().replace('.', '/')).getFileName().toString(); var arguments = jlink.getAdditionalArguments(); arguments.add("--module-path", base.modules("")); arguments.add("--launcher", launcher + '=' + mainModule.get()); tuner.tune(jlink, context); tasks.add( Task.sequence( String.format("Create custom runtime image with '%s' as launcher", launcher), new Task.DeleteDirectories(base.image()), jlink.toTask())); } var realm = new Project.Realm("", units, javac.toTask(), tasks); var directoryName = base.directory().toAbsolutePath().getFileName(); return new Project.Builder() .base(base) .title("Project " + Optional.ofNullable(directoryName).map(Path::toString).orElse("?")) .structure(new Project.Structure(Project.Library.of(), List.of(realm))); } } public static class Paths { public static boolean isEmpty(Path path) { try { if (Files.isRegularFile(path)) return Files.size(path) == 0L; try (var stream = Files.list(path)) { return stream.findAny().isEmpty(); } } catch (IOException e) { throw new UncheckedIOException(e); } } public static boolean isJavadocCommentAvailable(Path path) { try { return Files.readString(path).contains("/**"); } catch (IOException e) { throw new UncheckedIOException(e); } } public static boolean isModuleInfoJavaFile(Path path) { return Files.isRegularFile(path) && path.getFileName().toString().equals("module-info.java"); } public static List<Path> find(Collection<Path> roots, Predicate<Path> filter) { var files = new TreeSet<Path>(); for (var root : roots) { try (var stream = Files.walk(root)) { stream.filter(filter).forEach(files::add); } catch (Exception e) { throw new Error("Walk directory '" + root + "' failed: " + e, e); } } return List.copyOf(files); } private Paths() {} } public static class Resources { private final HttpClient client; public Resources(HttpClient client) { this.client = client; } public HttpResponse<Void> head(URI uri, int timeout) throws Exception { var nobody = HttpRequest.BodyPublishers.noBody(); var duration = Duration.ofSeconds(timeout); var request = HttpRequest.newBuilder(uri).method("HEAD", nobody).timeout(duration).build(); return client.send(request, BodyHandlers.discarding()); } public Path copy(URI uri, Path file) throws Exception { return copy(uri, file, StandardCopyOption.COPY_ATTRIBUTES); } public Path copy(URI uri, Path file, CopyOption... options) throws Exception { var request = HttpRequest.newBuilder(uri).GET(); if (Files.exists(file) && Files.getFileStore(file).supportsFileAttributeView("user")) { var etagBytes = (byte[]) Files.getAttribute(file, "user:etag"); var etag = StandardCharsets.UTF_8.decode(ByteBuffer.wrap(etagBytes)).toString(); request.setHeader("If-None-Match", etag); } var directory = file.getParent(); if (directory != null) Files.createDirectories(directory); var handler = BodyHandlers.ofFile(file); var response = client.send(request.build(), handler); if (response.statusCode() == 200) { if (Set.of(options).contains(StandardCopyOption.COPY_ATTRIBUTES)) { var etagHeader = response.headers().firstValue("etag"); if (etagHeader.isPresent() && Files.getFileStore(file).supportsFileAttributeView("user")) { var etag = StandardCharsets.UTF_8.encode(etagHeader.get()); Files.setAttribute(file, "user:etag", etag); } var lastModifiedHeader = response.headers().firstValue("last-modified"); if (lastModifiedHeader.isPresent()) { @SuppressWarnings("SpellCheckingInspection") var format = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz", Locale.US); var current = System.currentTimeMillis(); var millis = format.parse(lastModifiedHeader.get()).getTime(); // 0 means "unknown" var fileTime = FileTime.fromMillis(millis == 0 ? current : millis); Files.setLastModifiedTime(file, fileTime); } } return file; } if (response.statusCode() == 304 /*Not Modified*/) return file; Files.deleteIfExists(file); throw new IllegalStateException("Copy " + uri + " failed: response=" + response); } public String read(URI uri) throws Exception { var request = HttpRequest.newBuilder(uri).GET(); return client.send(request.build(), BodyHandlers.ofString()).body(); } } }
.bach/src/Bach.java
/* * Bach - Java Shell Builder * Copyright (C) 2020 Christian Stein * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import java.io.File; import java.io.IOException; import java.io.PrintWriter; import java.io.StringWriter; import java.io.UncheckedIOException; import java.lang.System.Logger.Level; import java.lang.System.Logger; import java.lang.module.ModuleDescriptor.Requires; import java.lang.module.ModuleDescriptor.Version; import java.lang.module.ModuleDescriptor; import java.lang.module.ModuleFinder; import java.lang.module.ModuleReference; import java.lang.reflect.Array; import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse.BodyHandlers; import java.net.http.HttpResponse; import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; import java.nio.file.CopyOption; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.StandardCopyOption; import java.nio.file.attribute.FileTime; import java.text.MessageFormat; import java.text.SimpleDateFormat; import java.time.Duration; import java.time.Instant; import java.time.ZoneOffset; import java.time.format.DateTimeFormatter; import java.time.temporal.ChronoUnit; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.ResourceBundle; import java.util.Set; import java.util.StringJoiner; import java.util.TreeMap; import java.util.TreeSet; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.function.Consumer; import java.util.function.Function; import java.util.function.Predicate; import java.util.function.Supplier; import java.util.function.UnaryOperator; import java.util.regex.Pattern; import java.util.spi.ToolProvider; import java.util.stream.Collectors; import java.util.stream.Stream; public class Bach { public static final Version VERSION = Version.parse("11.0-ea"); public static final Path BUILD_JAVA = Path.of(".bach/src/Build.java"); public static final Path WORKSPACE = Path.of(".bach/workspace"); public static void main(String... args) { Main.main(args); } public static Optional<Path> findCustomBuildProgram() { return Files.exists(BUILD_JAVA) ? Optional.of(BUILD_JAVA) : Optional.empty(); } public static Bach of() { return of(Path.of("")); } public static Bach of(Path directory) { return of(Project.newProject(directory).build()); } public static Bach of(UnaryOperator<Project.Builder> operator) { return of(operator.apply(Project.newProject(Path.of(""))).build()); } public static Bach of(Project project) { return new Bach(project, HttpClient.newBuilder()::build); } private final Logbook logbook; private final Project project; private final Supplier<HttpClient> httpClient; public Bach(Project project, Supplier<HttpClient> httpClient) { this(Logbook.ofSystem(), project, httpClient); } private Bach(Logbook logbook, Project project, Supplier<HttpClient> httpClient) { this.logbook = Objects.requireNonNull(logbook, "logbook"); this.project = Objects.requireNonNull(project, "project"); this.httpClient = Functions.memoize(httpClient); logbook.log(Level.TRACE, "Initialized " + toString()); logbook.log(Level.DEBUG, project.toTitleAndVersion()); } public Logger getLogger() { return logbook; } public Project getProject() { return project; } public HttpClient getHttpClient() { return httpClient.get(); } public Summary build() { var summary = new Summary(this); try { execute(buildSequence()); } finally { summary.writeMarkdown(project.base().workspace("summary.md"), true); } return summary; } private Task buildSequence() { var tasks = new ArrayList<Task>(); tasks.add(new Task.ResolveMissingModules()); for (var realm : project.structure().realms()) { tasks.add(realm.javac()); for (var unit : realm.units()) tasks.addAll(unit.tasks()); tasks.addAll(realm.tasks()); } return Task.sequence("Build Sequence", tasks); } private void execute(Task task) { var label = task.getLabel(); var tasks = task.getList(); if (tasks.isEmpty()) { logbook.log(Level.TRACE, "* {0}", label); try { if (logbook.isDryRun()) return; task.execute(this); } catch (Throwable throwable) { var message = "Task execution failed"; logbook.log(Level.ERROR, message, throwable); throw new Error(message, throwable); } finally { logbook.log(Level.DEBUG, task.getOut().toString().strip()); logbook.log(Level.WARNING, task.getErr().toString().strip()); } return; } logbook.log(Level.TRACE, "+ {0}", label); var start = System.currentTimeMillis(); for (var sub : tasks) execute(sub); var duration = System.currentTimeMillis() - start; logbook.log(Level.TRACE, "= {0} took {1} ms", label, duration); } private void execute(ToolProvider tool, PrintWriter out, PrintWriter err, String... args) { var call = (tool.name() + ' ' + String.join(" ", args)).trim(); logbook.log(Level.DEBUG, call); var code = tool.run(out, err, args); if (code != 0) throw new AssertionError("Tool run exit code: " + code + "\n\t" + call); } public String toString() { return "Bach.java " + VERSION; } public interface Call { String toLabel(); ToolProvider toProvider(); String[] toArguments(); default Task toTask() { return new Task.RunTool(toLabel(), toProvider(), toArguments()); } class Arguments { private final List<String> list = new ArrayList<>(); public Arguments add(Object argument) { list.add(argument.toString()); return this; } public Arguments add(String key, Object value) { return add(key).add(value); } public Arguments add(String key, Object first, Object second) { return add(key).add(first).add(second); } public Arguments add(Arguments arguments) { list.addAll(arguments.list); return this; } public String[] toStringArray() { return list.toArray(String[]::new); } } final class Context { private final String realm; private final String module; public Context(String realm, String module) { this.realm = realm; this.module = module; } public String realm() { return realm; } public String module() { return module; } } interface Tuner { void tune(Call call, Context context); } } static class Main { public static void main(String... args) { if (Bach.findCustomBuildProgram().isPresent()) { System.err.println("Custom build program execution not supported, yet."); return; } Bach.of().build().assertSuccessful(); } } public static final class Project { public static Builder newProject(Path directory) { return new Builder().base(Base.of(directory)).walk(); } public static Builder newProject(String title, String version) { return new Builder().title(title).version(Version.parse(version)); } static void tuner(Call call, @SuppressWarnings("unused") Call.Context context) { if (call instanceof GenericModuleSourceFilesConsumer) { var consumer = (GenericModuleSourceFilesConsumer<?>) call; consumer.setCharacterEncodingUsedBySourceFiles("UTF-8"); } if (call instanceof Javac) { var javac = (Javac) call; javac.setGenerateMetadataForMethodParameters(true); javac.setTerminateCompilationIfWarningsOccur(true); javac.getAdditionalArguments().add("-X" + "lint"); } if (call instanceof Javadoc) { var javadoc = (Javadoc) call; javadoc.getAdditionalArguments().add("-locale", "en"); } if (call instanceof Jlink) { var jlink = (Jlink) call; jlink.getAdditionalArguments().add("--compress", "2"); jlink.getAdditionalArguments().add("--strip-debug"); jlink.getAdditionalArguments().add("--no-header-files"); jlink.getAdditionalArguments().add("--no-man-pages"); } } private final Base base; private final Info info; private final Structure structure; public Project(Base base, Info info, Structure structure) { this.base = Objects.requireNonNull(base, "base"); this.info = Objects.requireNonNull(info, "info"); this.structure = Objects.requireNonNull(structure, "structure"); } public Base base() { return base; } public Info info() { return info; } public Structure structure() { return structure; } public String toString() { return new StringJoiner(", ", Project.class.getSimpleName() + "[", "]") .add("base=" + base) .add("info=" + info) .add("structure=" + structure) .toString(); } public List<String> toStrings() { var list = new ArrayList<String>(); list.add("Project"); list.add("\ttitle: " + info.title()); list.add("\tversion: " + info.version()); list.add("\trealms: " + structure.realms().size()); list.add("\tunits: " + structure.units().count()); for (var realm : structure.realms()) { list.add("\tRealm " + realm.name()); list.add("\t\tjavac: " + String.format("%.77s...", realm.javac().getLabel())); list.add("\t\ttasks: " + realm.tasks().size()); for (var unit : realm.units()) { list.add("\t\tUnit " + unit.name()); list.add("\t\t\ttasks: " + unit.tasks().size()); var module = unit.descriptor(); list.add("\t\t\tModule Descriptor " + module.toNameAndVersion()); list.add("\t\t\t\tmain: " + module.mainClass().orElse("-")); list.add("\t\t\t\trequires: " + new TreeSet<>(module.requires())); } } return list; } public String toTitleAndVersion() { return info.title() + ' ' + info.version(); } public Set<String> toDeclaredModuleNames() { return structure.units().map(Unit::name).collect(Collectors.toCollection(TreeSet::new)); } public Set<String> toRequiredModuleNames() { return Modules.required(structure.units().map(Unit::descriptor)); } public static final class Base { public static Base of() { return of(Path.of("")); } public static Base of(Path directory) { return new Base(directory, directory.resolve(Bach.WORKSPACE)); } private final Path directory; private final Path workspace; Base(Path directory, Path workspace) { this.directory = Objects.requireNonNull(directory, "directory"); this.workspace = Objects.requireNonNull(workspace, "workspace"); } public Path directory() { return directory; } public Path workspace() { return workspace; } public Path path(String first, String... more) { return directory.resolve(Path.of(first, more)); } public Path workspace(String first, String... more) { return workspace.resolve(Path.of(first, more)); } public Path api() { return workspace("api"); } public Path classes(String realm) { return workspace("classes", realm); } public Path classes(String realm, String module) { return workspace("classes", realm, module); } public Path image() { return workspace("image"); } public Path modules(String realm) { return workspace("modules", realm); } } public static final class Info { private final String title; private final Version version; public Info(String title, Version version) { this.title = Objects.requireNonNull(title, "title"); this.version = Objects.requireNonNull(version, "version"); } public String title() { return title; } public Version version() { return version; } public String toString() { return new StringJoiner(", ", Info.class.getSimpleName() + "[", "]") .add("title='" + title + "'") .add("version=" + version) .toString(); } } public static final class Structure { private final Library library; private final List<Realm> realms; public Structure(Library library, List<Realm> realms) { this.library = library; this.realms = List.copyOf(Objects.requireNonNull(realms, "realms")); } public Library library() { return library; } public List<Realm> realms() { return realms; } public Stream<Unit> units() { return realms.stream().flatMap(realm -> realm.units().stream()); } } public static final class Library { public static Library of() { return of(new ModulesMap()); } public static Library of(Map<String, String> map) { return new Library(Set.of(), map::get); } private final Set<String> required; private final UnaryOperator<String> lookup; public Library(Set<String> required, UnaryOperator<String> lookup) { this.required = required; this.lookup = lookup; } public Set<String> required() { return required; } public UnaryOperator<String> lookup() { return lookup; } } public static final class Realm { private final String name; private final List<Unit> units; private final Task javac; private final List<Task> tasks; public Realm(String name, List<Unit> units, Task javac, List<Task> tasks) { this.name = Objects.requireNonNull(name, "name"); this.units = List.copyOf(Objects.requireNonNull(units, "units")); this.javac = Objects.requireNonNull(javac, "javac"); this.tasks = List.copyOf(Objects.requireNonNull(tasks, "tasks")); } public String name() { return name; } public List<Unit> units() { return units; } public Task javac() { return javac; } public List<Task> tasks() { return tasks; } } public static final class Unit { private final ModuleDescriptor descriptor; private final List<Task> tasks; public Unit(ModuleDescriptor descriptor, List<Task> tasks) { this.descriptor = Objects.requireNonNull(descriptor, "descriptor"); this.tasks = List.copyOf(Objects.requireNonNull(tasks, "tasks")); } public ModuleDescriptor descriptor() { return descriptor; } public List<Task> tasks() { return tasks; } public String name() { return descriptor.name(); } } public static class Builder { private Base base = Base.of(); private String title = "Project Title"; private Version version = Version.parse("1-ea"); private Structure structure = new Structure(Library.of(), List.of()); public Project build() { var info = new Info(title, version); return new Project(base, info, structure); } public Builder base(Base base) { this.base = base; return this; } public Builder title(String title) { this.title = title; return this; } public Builder version(Version version) { this.version = version; return this; } public Builder structure(Structure structure) { this.structure = structure; return this; } public Builder walk() { return walk(Project::tuner); } public Builder walk(Call.Tuner tuner) { var moduleInfoFiles = Paths.find(List.of(base.directory()), Paths::isModuleInfoJavaFile); if (moduleInfoFiles.isEmpty()) throw new IllegalStateException("No module found: " + base); return walkUnnamedRealm(moduleInfoFiles, tuner); } public Builder walkUnnamedRealm(List<Path> moduleInfoFiles, Call.Tuner tuner) { var moduleNames = new TreeSet<String>(); var moduleSourcePathPatterns = new TreeSet<String>(); var units = new ArrayList<Unit>(); var javadocCommentFound = false; for (var info : moduleInfoFiles) { javadocCommentFound = javadocCommentFound || Paths.isJavadocCommentAvailable(info); var descriptor = Modules.describe(info); var module = descriptor.name(); moduleNames.add(module); moduleSourcePathPatterns.add(Modules.modulePatternForm(info, descriptor.name())); var classes = base.classes("", module); var modules = base.modules(""); var jar = modules.resolve(module + ".jar"); var context = new Call.Context("", module); var jarCreate = new Jar(); var jarCreateArgs = jarCreate.getAdditionalArguments(); jarCreateArgs.add("--create").add("--file", jar); descriptor.mainClass().ifPresent(main -> jarCreateArgs.add("--main-class", main)); jarCreateArgs.add("-C", classes, "."); tuner.tune(jarCreate, context); var jarDescribe = new Jar(); jarDescribe.getAdditionalArguments().add("--describe-module").add("--file", jar); tuner.tune(jarDescribe, context); var task = Task.sequence( "Create modular JAR file " + jar.getFileName(), new Task.CreateDirectories(jar.getParent()), jarCreate.toTask(), jarDescribe.toTask()); units.add(new Unit(descriptor, List.of(task))); } var context = new Call.Context("", null); var javac = new Javac() .setModules(moduleNames) .setPatternsWhereToFindSourceFiles(moduleSourcePathPatterns) .setDestinationDirectory(base.classes("")); tuner.tune(javac, context); var tasks = new ArrayList<Task>(); if (javadocCommentFound) { var javadoc = new Javadoc() .setDestinationDirectory(base.api()) .setModules(moduleNames) .setPatternsWhereToFindSourceFiles(moduleSourcePathPatterns); tuner.tune(javadoc, context); tasks.add(javadoc.toTask()); } var mainModule = Modules.findMainModule(units.stream().map(Unit::descriptor)); if (mainModule.isPresent()) { var jlink = new Jlink().setModules(moduleNames).setLocationOfTheGeneratedRuntimeImage(base.image()); var launcher = Path.of(mainModule.get().replace('.', '/')).getFileName().toString(); var arguments = jlink.getAdditionalArguments(); arguments.add("--module-path", base.modules("")); arguments.add("--launcher", launcher + '=' + mainModule.get()); tuner.tune(jlink, context); tasks.add( Task.sequence( String.format("Create custom runtime image with '%s' as launcher", launcher), new Task.DeleteDirectories(base.image()), jlink.toTask())); } var realm = new Realm("", units, javac.toTask(), tasks); var directoryName = base.directory().toAbsolutePath().getFileName(); return title("Project " + Optional.ofNullable(directoryName).map(Path::toString).orElse("?")) .structure(new Structure(Library.of(), List.of(realm))); } } } public static class Summary { private final Bach bach; private final Logbook logbook; public Summary(Bach bach) { this.bach = bach; this.logbook = (Logbook) bach.getLogger(); } public void assertSuccessful() { var entries = logbook.entries(Level.WARNING).collect(Collectors.toList()); if (entries.isEmpty()) return; var lines = new StringJoiner(System.lineSeparator()); lines.add(String.format("Collected %d error(s)", entries.size())); for (var entry : entries) lines.add("\t- " + entry.message()); lines.add(""); lines.add(String.join(System.lineSeparator(), toMarkdown())); var error = new AssertionError(lines.toString()); for (var entry : entries) if (entry.exception() != null) error.addSuppressed(entry.exception()); throw error; } public void writeMarkdown(Path file, boolean createCopyWithTimestamp) { var markdown = toMarkdown(); try { Files.createDirectories(file.getParent()); Files.write(file, markdown); if (createCopyWithTimestamp) { @SuppressWarnings("SpellCheckingInspection") var pattern = "yyyyMMdd_HHmmss"; var formatter = DateTimeFormatter.ofPattern(pattern).withZone(ZoneOffset.UTC); var timestamp = formatter.format(Instant.now().truncatedTo(ChronoUnit.SECONDS)); var summaries = Files.createDirectories(file.resolveSibling("summaries")); Files.copy(file, summaries.resolve("summary-" + timestamp + ".md")); } } catch (Exception e) { throw new RuntimeException(e); } } public List<String> toMarkdown() { var md = new ArrayList<String>(); md.add("# Summary for " + bach.getProject().toTitleAndVersion()); md.addAll(projectDescription()); md.addAll(logbookEntries()); return md; } private List<String> projectDescription() { var md = new ArrayList<String>(); var project = bach.getProject(); md.add(""); md.add("## Project"); md.add("- title: " + project.info().title()); md.add("- version: " + project.info().version()); md.add(""); md.add("```text"); md.addAll(project.toStrings()); md.add("```"); return md; } private List<String> logbookEntries() { var md = new ArrayList<String>(); md.add(""); md.add("## Logbook"); for (var entry : logbook.entries(Level.ALL).collect(Collectors.toList())) { md.add("- " + entry.level()); var one = entry.message().lines().count() == 1; md.add((one ? "`" : "```text\n") + entry.message() + (one ? "`" : "\n```")); } return md; } } public static class Task { public static Task sequence(String label, Task... tasks) { return sequence(label, List.of(tasks)); } public static Task sequence(String label, List<Task> tasks) { return new Task(label, tasks); } private final String label; private final List<Task> list; private final StringWriter out; private final StringWriter err; public Task() { this("", List.of()); } public Task(String label, List<Task> list) { Objects.requireNonNull(label, "label"); this.label = label.isBlank() ? getClass().getSimpleName() : label; this.list = List.copyOf(Objects.requireNonNull(list, "list")); this.out = new StringWriter(); this.err = new StringWriter(); } public String getLabel() { return label; } public List<Task> getList() { return list; } public StringWriter getOut() { return out; } public StringWriter getErr() { return err; } public String toString() { return new StringJoiner(", ", Task.class.getSimpleName() + "[", "]") .add("label='" + label + "'") .add("list.size=" + list.size()) .toString(); } public void execute(Bach bach) throws Exception {} public static class RunTool extends Task { private final ToolProvider tool; private final String[] args; public RunTool(String label, ToolProvider tool, String... args) { super(label, List.of()); this.tool = tool; this.args = args; } public void execute(Bach bach) { bach.execute(tool, new PrintWriter(getOut()), new PrintWriter(getErr()), args); } } public static class CreateDirectories extends Task { private final Path directory; public CreateDirectories(Path directory) { super("Create directories " + directory.toUri(), List.of()); this.directory = directory; } public void execute(Bach bach) throws Exception { Files.createDirectories(directory); } } public static class DeleteDirectories extends Task { private final Path directory; public DeleteDirectories(Path directory) { super("Delete directory " + directory, List.of()); this.directory = directory; } public void execute(Bach bach) throws Exception { if (Files.notExists(directory)) return; try (var stream = Files.walk(directory)) { var paths = stream.sorted((p, q) -> -p.compareTo(q)); for (var path : paths.toArray(Path[]::new)) Files.deleteIfExists(path); } } } public static class ResolveMissingModules extends Task { public ResolveMissingModules() { super("Resolve missing modules", List.of()); } public void execute(Bach bach) { var project = bach.getProject(); var library = project.structure().library(); var lib = project.base().directory().resolve("lib"); class Transporter implements Consumer<Set<String>> { public void accept(Set<String> modules) { var resources = new Resources(bach.getHttpClient()); for (var module : modules) { var raw = library.lookup().apply(module); if (raw == null) continue; try { var uri = URI.create(raw); var name = module + ".jar"; var file = resources.copy(uri, lib.resolve(name)); var size = Files.size(file); bach.getLogger().log(Level.INFO, "{0} ({1} bytes) << {2}", file, size, uri); } catch (Exception e) { throw new Error("Resolve module '" + module + "' failed: " + raw +"\n\t" + e, e); } } } } var declared = project.toDeclaredModuleNames(); var required = project.toRequiredModuleNames(); var resolver = new ModulesResolver(new Path[] {lib}, declared, new Transporter()); resolver.resolve(required); resolver.resolve(library.required()); } } } public static abstract class AbstractCallBuilder implements Call { public static boolean assigned(Object object) { if (object == null) return false; if (object instanceof Number) return ((Number) object).intValue() != 0; if (object instanceof String) return !((String) object).isEmpty(); if (object instanceof Optional) return ((Optional<?>) object).isPresent(); if (object instanceof Collection) return !((Collection<?>) object).isEmpty(); if (object.getClass().isArray()) return Array.getLength(object) != 0; return true; } public static String join(Collection<Path> paths) { return paths.stream().map(Path::toString).collect(Collectors.joining(File.pathSeparator)); } public static String joinPaths(Collection<String> paths) { return String.join(File.pathSeparator, paths); } private final String name; private final Arguments additionalArguments = new Arguments(); public AbstractCallBuilder(String name) { this.name = name; } public Arguments getAdditionalArguments() { return additionalArguments; } public ToolProvider toProvider() { return ToolProvider.findFirst(name).orElseThrow(); } public String[] toArguments() { var arguments = new Arguments(); arguments(arguments); return arguments.add(getAdditionalArguments()).toStringArray(); } protected void arguments(Arguments arguments) {} } @SuppressWarnings("unchecked") public static abstract class GenericModuleSourceFilesConsumer<T> extends AbstractCallBuilder { private Path destinationDirectory; private String characterEncodingUsedBySourceFiles; private Set<String> modules; public GenericModuleSourceFilesConsumer(String name) { super(name); } protected void arguments(Arguments arguments) { var destination = getDestinationDirectory(); if (assigned(destination)) arguments.add("-d", destination); var encoding = getCharacterEncodingUsedBySourceFiles(); if (assigned(encoding)) arguments.add("-encoding", encoding); var modules = getModules(); if (assigned(modules)) arguments.add("--module", String.join(",", new TreeSet<>(modules))); } public Path getDestinationDirectory() { return destinationDirectory; } public T setDestinationDirectory(Path directory) { this.destinationDirectory = directory; return (T) this; } public String getCharacterEncodingUsedBySourceFiles() { return characterEncodingUsedBySourceFiles; } public T setCharacterEncodingUsedBySourceFiles(String encoding) { this.characterEncodingUsedBySourceFiles = encoding; return (T) this; } public Set<String> getModules() { return modules; } public T setModules(Set<String> modules) { this.modules = modules; return (T) this; } } public static class Jar extends AbstractCallBuilder { public Jar() { super("jar"); } public String toLabel() { return "Operate on JAR file"; } } public static class Javac extends GenericModuleSourceFilesConsumer<Javac> { private Version versionOfModulesThatAreBeingCompiled; private Collection<String> patternsWhereToFindSourceFiles; private Map<String, Collection<Path>> pathsWhereToFindSourceFiles; private Map<String, Collection<Path>> pathsWhereToFindMoreAssetsPerModule; private Collection<Path> pathsWhereToFindApplicationModules; private int compileForVirtualMachineVersion; private boolean enablePreviewLanguageFeatures; private boolean generateMetadataForMethodParameters; private boolean outputMessagesAboutWhatTheCompilerIsDoing; private boolean outputSourceLocationsOfDeprecatedUsages; private boolean terminateCompilationIfWarningsOccur; public Javac() { super("javac"); } public String toLabel() { return "Compile module(s): " + getModules(); } protected void arguments(Arguments arguments) { super.arguments(arguments); var version = getVersionOfModulesThatAreBeingCompiled(); if (assigned(version)) arguments.add("--module-version", version); var patterns = getPatternsWhereToFindSourceFiles(); if (assigned(patterns)) arguments.add("--module-source-path", joinPaths(patterns)); var specific = getPathsWhereToFindSourceFiles(); if (assigned(specific)) for (var entry : specific.entrySet()) arguments.add("--module-source-path", entry.getKey() + '=' + join(entry.getValue())); var patches = getPathsWhereToFindMoreAssetsPerModule(); if (assigned(patches)) for (var patch : patches.entrySet()) arguments.add("--patch-module", patch.getKey() + '=' + join(patch.getValue())); var modulePath = getPathsWhereToFindApplicationModules(); if (assigned(modulePath)) arguments.add("--module-path", join(modulePath)); var release = getCompileForVirtualMachineVersion(); if (assigned(release)) arguments.add("--release", release); if (isEnablePreviewLanguageFeatures()) arguments.add("--enable-preview"); if (isGenerateMetadataForMethodParameters()) arguments.add("-parameters"); if (isOutputSourceLocationsOfDeprecatedUsages()) arguments.add("-deprecation"); if (isOutputMessagesAboutWhatTheCompilerIsDoing()) arguments.add("-verbose"); if (isTerminateCompilationIfWarningsOccur()) arguments.add("-Werror"); } public Version getVersionOfModulesThatAreBeingCompiled() { return versionOfModulesThatAreBeingCompiled; } public Javac setVersionOfModulesThatAreBeingCompiled( Version versionOfModulesThatAreBeingCompiled) { this.versionOfModulesThatAreBeingCompiled = versionOfModulesThatAreBeingCompiled; return this; } public Collection<String> getPatternsWhereToFindSourceFiles() { return patternsWhereToFindSourceFiles; } public Javac setPatternsWhereToFindSourceFiles(Collection<String> patterns) { this.patternsWhereToFindSourceFiles = patterns; return this; } public Map<String, Collection<Path>> getPathsWhereToFindSourceFiles() { return pathsWhereToFindSourceFiles; } public Javac setPathsWhereToFindSourceFiles(Map<String, Collection<Path>> map) { this.pathsWhereToFindSourceFiles = map; return this; } public Map<String, Collection<Path>> getPathsWhereToFindMoreAssetsPerModule() { return pathsWhereToFindMoreAssetsPerModule; } public Javac setPathsWhereToFindMoreAssetsPerModule(Map<String, Collection<Path>> map) { this.pathsWhereToFindMoreAssetsPerModule = map; return this; } public Collection<Path> getPathsWhereToFindApplicationModules() { return pathsWhereToFindApplicationModules; } public Javac setPathsWhereToFindApplicationModules( Collection<Path> pathsWhereToFindApplicationModules) { this.pathsWhereToFindApplicationModules = pathsWhereToFindApplicationModules; return this; } public int getCompileForVirtualMachineVersion() { return compileForVirtualMachineVersion; } public Javac setCompileForVirtualMachineVersion(int release) { this.compileForVirtualMachineVersion = release; return this; } public boolean isEnablePreviewLanguageFeatures() { return enablePreviewLanguageFeatures; } public Javac setEnablePreviewLanguageFeatures(boolean preview) { this.enablePreviewLanguageFeatures = preview; return this; } public boolean isGenerateMetadataForMethodParameters() { return generateMetadataForMethodParameters; } public Javac setGenerateMetadataForMethodParameters(boolean parameters) { this.generateMetadataForMethodParameters = parameters; return this; } public boolean isOutputMessagesAboutWhatTheCompilerIsDoing() { return outputMessagesAboutWhatTheCompilerIsDoing; } public Javac setOutputMessagesAboutWhatTheCompilerIsDoing(boolean verbose) { this.outputMessagesAboutWhatTheCompilerIsDoing = verbose; return this; } public boolean isOutputSourceLocationsOfDeprecatedUsages() { return outputSourceLocationsOfDeprecatedUsages; } public Javac setOutputSourceLocationsOfDeprecatedUsages(boolean deprecation) { this.outputSourceLocationsOfDeprecatedUsages = deprecation; return this; } public boolean isTerminateCompilationIfWarningsOccur() { return terminateCompilationIfWarningsOccur; } public Javac setTerminateCompilationIfWarningsOccur(boolean error) { this.terminateCompilationIfWarningsOccur = error; return this; } } public static class Javadoc extends GenericModuleSourceFilesConsumer<Javadoc> { private Collection<String> patternsWhereToFindSourceFiles; private Map<String, Collection<Path>> pathsWhereToFindSourceFiles; private Map<String, Collection<Path>> pathsWhereToFindMoreAssetsPerModule; private Collection<Path> pathsWhereToFindApplicationModules; private String characterEncodingUsedBySourceFiles; private int compileForVirtualMachineVersion; private boolean enablePreviewLanguageFeatures; private boolean outputMessagesAboutWhatJavadocIsDoing; private boolean shutOffDisplayingStatusMessages; public Javadoc() { super("javadoc"); } public String toLabel() { return "Generate API documentation for " + getModules(); } protected void arguments(Arguments arguments) { super.arguments(arguments); var patterns = getPatternsWhereToFindSourceFiles(); if (assigned(patterns)) arguments.add("--module-source-path", joinPaths(patterns)); var specific = getPathsWhereToFindSourceFiles(); if (assigned(specific)) for (var entry : specific.entrySet()) arguments.add("--module-source-path", entry.getKey() + '=' + join(entry.getValue())); var patches = getPathsWhereToFindMoreAssetsPerModule(); if (assigned(patches)) for (var patch : patches.entrySet()) arguments.add("--patch-module", patch.getKey() + '=' + join(patch.getValue())); var modulePath = getPathsWhereToFindApplicationModules(); if (assigned(modulePath)) arguments.add("--module-path", join(modulePath)); var encoding = getCharacterEncodingUsedBySourceFiles(); if (assigned(encoding)) arguments.add("-encoding", encoding); var release = getCompileForVirtualMachineVersion(); if (assigned(release)) arguments.add("--release", release); if (isEnablePreviewLanguageFeatures()) arguments.add("--enable-preview"); if (isOutputMessagesAboutWhatJavadocIsDoing()) arguments.add("-verbose"); if (isShutOffDisplayingStatusMessages()) arguments.add("-quiet"); } public Collection<String> getPatternsWhereToFindSourceFiles() { return patternsWhereToFindSourceFiles; } public Javadoc setPatternsWhereToFindSourceFiles(Collection<String> patterns) { this.patternsWhereToFindSourceFiles = patterns; return this; } public Map<String, Collection<Path>> getPathsWhereToFindSourceFiles() { return pathsWhereToFindSourceFiles; } public Javadoc setPathsWhereToFindSourceFiles(Map<String, Collection<Path>> map) { this.pathsWhereToFindSourceFiles = map; return this; } public Map<String, Collection<Path>> getPathsWhereToFindMoreAssetsPerModule() { return pathsWhereToFindMoreAssetsPerModule; } public Javadoc setPathsWhereToFindMoreAssetsPerModule(Map<String, Collection<Path>> map) { this.pathsWhereToFindMoreAssetsPerModule = map; return this; } public Collection<Path> getPathsWhereToFindApplicationModules() { return pathsWhereToFindApplicationModules; } public Javadoc setPathsWhereToFindApplicationModules(Collection<Path> paths) { this.pathsWhereToFindApplicationModules = paths; return this; } public String getCharacterEncodingUsedBySourceFiles() { return characterEncodingUsedBySourceFiles; } public Javadoc setCharacterEncodingUsedBySourceFiles(String encoding) { this.characterEncodingUsedBySourceFiles = encoding; return this; } public int getCompileForVirtualMachineVersion() { return compileForVirtualMachineVersion; } public Javadoc setCompileForVirtualMachineVersion(int release) { this.compileForVirtualMachineVersion = release; return this; } public boolean isEnablePreviewLanguageFeatures() { return enablePreviewLanguageFeatures; } public Javadoc setEnablePreviewLanguageFeatures(boolean preview) { this.enablePreviewLanguageFeatures = preview; return this; } public boolean isOutputMessagesAboutWhatJavadocIsDoing() { return outputMessagesAboutWhatJavadocIsDoing; } public Javadoc setOutputMessagesAboutWhatJavadocIsDoing(boolean verbose) { this.outputMessagesAboutWhatJavadocIsDoing = verbose; return this; } public boolean isShutOffDisplayingStatusMessages() { return shutOffDisplayingStatusMessages; } public Javadoc setShutOffDisplayingStatusMessages(boolean quiet) { this.shutOffDisplayingStatusMessages = quiet; return this; } } public static class Jlink extends AbstractCallBuilder { private Path locationOfTheGeneratedRuntimeImage; private Set<String> modules; public Jlink() { super("jlink"); } public String toLabel() { return "Create a custom runtime image with dependencies for " + getModules(); } protected void arguments(Arguments arguments) { var output = getLocationOfTheGeneratedRuntimeImage(); if (assigned(output)) arguments.add("--output", output); var modules = getModules(); if (assigned(modules)) arguments.add("--add-modules", String.join(",", new TreeSet<>(modules))); } public Path getLocationOfTheGeneratedRuntimeImage() { return locationOfTheGeneratedRuntimeImage; } public Jlink setLocationOfTheGeneratedRuntimeImage(Path output) { this.locationOfTheGeneratedRuntimeImage = output; return this; } public Set<String> getModules() { return modules; } public Jlink setModules(Set<String> modules) { this.modules = modules; return this; } } public static class Functions { public static <T> Supplier<T> memoize(Supplier<T> supplier) { Objects.requireNonNull(supplier, "supplier"); class CachingSupplier implements Supplier<T> { Supplier<T> delegate = this::initialize; boolean initialized = false; public T get() { return delegate.get(); } private synchronized T initialize() { if (initialized) return delegate.get(); T value = supplier.get(); delegate = () -> value; initialized = true; return value; } } return new CachingSupplier(); } private Functions() {} } public static class Logbook implements System.Logger { public static Logbook ofSystem() { var debug = Boolean.getBoolean("ebug") || "".equals(System.getProperty("ebug")); var dryRun = Boolean.getBoolean("ry-run") || "".equals(System.getProperty("ry-run")); return new Logbook(System.out::println, debug, dryRun); } private final Consumer<String> consumer; private final boolean debug; private final boolean dryRun; private final Collection<Entry> entries; public Logbook(Consumer<String> consumer, boolean debug, boolean dryRun) { this.consumer = consumer; this.debug = debug; this.dryRun = dryRun; this.entries = new ConcurrentLinkedQueue<>(); } public boolean isDebug() { return debug; } public boolean isDryRun() { return dryRun; } public String getName() { return "Logbook"; } public boolean isLoggable(Level level) { if (level == Level.ALL) return isDebug(); if (level == Level.OFF) return isDryRun(); return true; } public void log(Level level, ResourceBundle bundle, String message, Throwable thrown) { if (message == null || message.isBlank()) return; var entry = new Entry(level, message, thrown); if (debug) consumer.accept(entry.toString()); entries.add(entry); } public void log(Level level, ResourceBundle bundle, String pattern, Object... arguments) { var message = arguments == null ? pattern : MessageFormat.format(pattern, arguments); log(level, bundle, message, (Throwable) null); } public Stream<Entry> entries(Level threshold) { return entries.stream().filter(entry -> entry.level.getSeverity() >= threshold.getSeverity()); } public List<String> messages() { return lines(entry -> entry.message); } public List<String> lines(Function<Entry, String> mapper) { return entries.stream().map(mapper).collect(Collectors.toList()); } public static final class Entry { private final Level level; private final String message; private final Throwable exception; public Entry(Level level, String message, Throwable exception) { this.level = level; this.message = message; this.exception = exception; } public Level level() { return level; } public String message() { return message; } public Throwable exception() { return exception; } public String toString() { var exceptionMessage = exception == null ? "" : " -> " + exception; return String.format("%c|%s%s", level.name().charAt(0), message, exceptionMessage); } } } public static class Modules { interface Patterns { Pattern NAME = Pattern.compile( "(?:module)" // key word + "\\s+([\\w.]+)" // module name + "(?:\\s*/\\*.*\\*/\\s*)?" // optional multi-line comment + "\\s*\\{"); // end marker Pattern REQUIRES = Pattern.compile( "(?:requires)" // key word + "(?:\\s+[\\w.]+)?" // optional modifiers + "\\s+([\\w.]+)" // module name + "(?:\\s*/\\*\\s*([\\w.\\-+]+)\\s*\\*/\\s*)?" // optional '/*' version '*/' + "\\s*;"); // end marker } public static Optional<String> findMainClass(Path info, String module) { var main = Path.of(module.replace('.', '/'), "Main.java"); var exists = Files.isRegularFile(info.resolveSibling(main)); return exists ? Optional.of(module + '.' + "Main") : Optional.empty(); } public static Optional<String> findMainModule(Stream<ModuleDescriptor> descriptors) { var mains = descriptors.filter(d -> d.mainClass().isPresent()).collect(Collectors.toList()); return mains.size() == 1 ? Optional.of(mains.get(0).name()) : Optional.empty(); } public static ModuleDescriptor describe(Path info) { try { var module = describe(Files.readString(info)); var temporary = module.build(); findMainClass(info, temporary.name()).ifPresent(module::mainClass); return module.build(); } catch (IOException e) { throw new UncheckedIOException("Describe failed", e); } } public static ModuleDescriptor.Builder describe(String source) { var nameMatcher = Patterns.NAME.matcher(source); if (!nameMatcher.find()) throw new IllegalArgumentException("Expected Java module source unit, but got: " + source); var name = nameMatcher.group(1).trim(); var builder = ModuleDescriptor.newModule(name); var requiresMatcher = Patterns.REQUIRES.matcher(source); while (requiresMatcher.find()) { var requiredName = requiresMatcher.group(1); Optional.ofNullable(requiresMatcher.group(2)) .ifPresentOrElse( version -> builder.requires(Set.of(), requiredName, Version.parse(version)), () -> builder.requires(requiredName)); } return builder; } public static String modulePatternForm(Path info, String module) { var pattern = info.normalize().getParent().toString().replace(module, "*"); if (pattern.equals("*")) return "."; if (pattern.endsWith("*")) return pattern.substring(0, pattern.length() - 2); if (pattern.startsWith("*")) return "." + File.separator + pattern; return pattern; } public static Set<String> declared(ModuleFinder finder) { return declared(finder.findAll().stream().map(ModuleReference::descriptor)); } public static Set<String> declared(Stream<ModuleDescriptor> descriptors) { return descriptors.map(ModuleDescriptor::name).collect(Collectors.toCollection(TreeSet::new)); } public static Set<String> required(ModuleFinder finder) { return required(finder.findAll().stream().map(ModuleReference::descriptor)); } public static Set<String> required(Stream<ModuleDescriptor> descriptors) { return descriptors .map(ModuleDescriptor::requires) .flatMap(Set::stream) .filter(requires -> !requires.modifiers().contains(Requires.Modifier.MANDATED)) .filter(requires -> !requires.modifiers().contains(Requires.Modifier.SYNTHETIC)) .map(Requires::name) .collect(Collectors.toCollection(TreeSet::new)); } private Modules() {} } public static class ModulesMap extends TreeMap<String, String> { private static final long serialVersionUID = -7978021121082640440L; public ModulesMap() { put("junit", "https://repo.maven.apache.org/maven2/junit/junit/4.13/junit-4.13.jar"); put( "net.bytebuddy", "https://repo.maven.apache.org/maven2/net/bytebuddy/byte-buddy/1.10.10/byte-buddy-1.10.10.jar"); put( "net.bytebuddy.agent", "https://repo.maven.apache.org/maven2/net/bytebuddy/byte-buddy-agent/1.10.10/byte-buddy-agent-1.10.10.jar"); put( "org.apiguardian.api", "https://repo.maven.apache.org/maven2/org/apiguardian/apiguardian-api/1.1.0/apiguardian-api-1.1.0.jar"); put( "org.assertj.core", "https://repo.maven.apache.org/maven2/org/assertj/assertj-core/3.16.1/assertj-core-3.16.1.jar"); put( "org.hamcrest", "https://repo.maven.apache.org/maven2/org/hamcrest/hamcrest/2.2/hamcrest-2.2.jar"); put( "org.junit.jupiter", "https://repo.maven.apache.org/maven2/org/junit/jupiter/junit-jupiter/5.7.0-M1/junit-jupiter-5.7.0-M1.jar"); put( "org.junit.jupiter.api", "https://repo.maven.apache.org/maven2/org/junit/jupiter/junit-jupiter-api/5.7.0-M1/junit-jupiter-api-5.7.0-M1.jar"); put( "org.junit.jupiter.engine", "https://repo.maven.apache.org/maven2/org/junit/jupiter/junit-jupiter-engine/5.7.0-M1/junit-jupiter-engine-5.7.0-M1.jar"); put( "org.junit.jupiter.params", "https://repo.maven.apache.org/maven2/org/junit/jupiter/junit-jupiter-params/5.7.0-M1/junit-jupiter-params-5.7.0-M1.jar"); put( "org.junit.platform.commons", "https://repo.maven.apache.org/maven2/org/junit/platform/junit-platform-commons/1.7.0-M1/junit-platform-commons-1.7.0-M1.jar"); put( "org.junit.platform.console", "https://repo.maven.apache.org/maven2/org/junit/platform/junit-platform-console/1.7.0-M1/junit-platform-console-1.7.0-M1.jar"); put( "org.junit.platform.engine", "https://repo.maven.apache.org/maven2/org/junit/platform/junit-platform-engine/1.7.0-M1/junit-platform-engine-1.7.0-M1.jar"); put( "org.junit.platform.launcher", "https://repo.maven.apache.org/maven2/org/junit/platform/junit-platform-launcher/1.7.0-M1/junit-platform-launcher-1.7.0-M1.jar"); put( "org.junit.platform.reporting", "https://repo.maven.apache.org/maven2/org/junit/platform/junit-platform-reporting/1.7.0-M1/junit-platform-reporting-1.7.0-M1.jar"); put( "org.junit.platform.testkit", "https://repo.maven.apache.org/maven2/org/junit/platform/junit-platform-testkit/1.7.0-M1/junit-platform-testkit-1.7.0-M1.jar"); put( "org.junit.vintage.engine", "https://repo.maven.apache.org/maven2/org/junit/vintage/junit-vintage-engine/5.7.0-M1/junit-vintage-engine-5.7.0-M1.jar"); put( "org.objectweb.asm", "https://repo.maven.apache.org/maven2/org/ow2/asm/asm/8.0.1/asm-8.0.1.jar"); put( "org.objectweb.asm.commons", "https://repo.maven.apache.org/maven2/org/ow2/asm/asm-commons/8.0.1/asm-commons-8.0.1.jar"); put( "org.objectweb.asm.tree", "https://repo.maven.apache.org/maven2/org/ow2/asm/asm-tree/8.0.1/asm-tree-8.0.1.jar"); put( "org.objectweb.asm.tree.analysis", "https://repo.maven.apache.org/maven2/org/ow2/asm/asm-analysis/8.0.1/asm-analysis-8.0.1.jar"); put( "org.objectweb.asm.util", "https://repo.maven.apache.org/maven2/org/ow2/asm/asm-util/8.0.1/asm-util-8.0.1.jar"); put( "org.opentest4j", "https://repo.maven.apache.org/maven2/org/opentest4j/opentest4j/1.2.0/opentest4j-1.2.0.jar"); } } public static class ModulesResolver { private final Path[] paths; private final Set<String> declared; private final Consumer<Set<String>> transporter; private final Set<String> system; public ModulesResolver(Path[] paths, Set<String> declared, Consumer<Set<String>> transporter) { this.paths = paths; this.declared = new TreeSet<>(declared); this.transporter = transporter; this.system = Modules.declared(ModuleFinder.ofSystem()); } public void resolve(Set<String> required) { resolveModules(required); resolveLibraryModules(); } public void resolveModules(Set<String> required) { var missing = missing(required); if (missing.isEmpty()) return; transporter.accept(missing); var unresolved = missing(required); if (unresolved.isEmpty()) return; throw new IllegalStateException("Unresolved modules: " + unresolved); } public void resolveLibraryModules() { do { var missing = missing(Modules.required(ModuleFinder.of(paths))); if (missing.isEmpty()) return; resolveModules(missing); } while (true); } Set<String> missing(Set<String> required) { var missing = new TreeSet<>(required); missing.removeAll(declared); if (required.isEmpty()) return Set.of(); missing.removeAll(system); if (required.isEmpty()) return Set.of(); var library = Modules.declared(ModuleFinder.of(paths)); missing.removeAll(library); return missing; } } public static class Paths { public static boolean isEmpty(Path path) { try { if (Files.isRegularFile(path)) return Files.size(path) == 0L; try (var stream = Files.list(path)) { return stream.findAny().isEmpty(); } } catch (IOException e) { throw new UncheckedIOException(e); } } public static boolean isJavadocCommentAvailable(Path path) { try { return Files.readString(path).contains("/**"); } catch (IOException e) { throw new UncheckedIOException(e); } } public static boolean isModuleInfoJavaFile(Path path) { return Files.isRegularFile(path) && path.getFileName().toString().equals("module-info.java"); } public static List<Path> find(Collection<Path> roots, Predicate<Path> filter) { var files = new TreeSet<Path>(); for (var root : roots) { try (var stream = Files.walk(root)) { stream.filter(filter).forEach(files::add); } catch (Exception e) { throw new Error("Walk directory '" + root + "' failed: " + e, e); } } return List.copyOf(files); } private Paths() {} } public static class Resources { private final HttpClient client; public Resources(HttpClient client) { this.client = client; } public HttpResponse<Void> head(URI uri, int timeout) throws Exception { var nobody = HttpRequest.BodyPublishers.noBody(); var duration = Duration.ofSeconds(timeout); var request = HttpRequest.newBuilder(uri).method("HEAD", nobody).timeout(duration).build(); return client.send(request, BodyHandlers.discarding()); } public Path copy(URI uri, Path file) throws Exception { return copy(uri, file, StandardCopyOption.COPY_ATTRIBUTES); } public Path copy(URI uri, Path file, CopyOption... options) throws Exception { var request = HttpRequest.newBuilder(uri).GET(); if (Files.exists(file) && Files.getFileStore(file).supportsFileAttributeView("user")) { var etagBytes = (byte[]) Files.getAttribute(file, "user:etag"); var etag = StandardCharsets.UTF_8.decode(ByteBuffer.wrap(etagBytes)).toString(); request.setHeader("If-None-Match", etag); } var directory = file.getParent(); if (directory != null) Files.createDirectories(directory); var handler = BodyHandlers.ofFile(file); var response = client.send(request.build(), handler); if (response.statusCode() == 200) { if (Set.of(options).contains(StandardCopyOption.COPY_ATTRIBUTES)) { var etagHeader = response.headers().firstValue("etag"); if (etagHeader.isPresent() && Files.getFileStore(file).supportsFileAttributeView("user")) { var etag = StandardCharsets.UTF_8.encode(etagHeader.get()); Files.setAttribute(file, "user:etag", etag); } var lastModifiedHeader = response.headers().firstValue("last-modified"); if (lastModifiedHeader.isPresent()) { @SuppressWarnings("SpellCheckingInspection") var format = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz", Locale.US); var current = System.currentTimeMillis(); var millis = format.parse(lastModifiedHeader.get()).getTime(); // 0 means "unknown" var fileTime = FileTime.fromMillis(millis == 0 ? current : millis); Files.setLastModifiedTime(file, fileTime); } } return file; } if (response.statusCode() == 304 /*Not Modified*/) return file; Files.deleteIfExists(file); throw new IllegalStateException("Copy " + uri + " failed: response=" + response); } public String read(URI uri) throws Exception { var request = HttpRequest.newBuilder(uri).GET(); return client.send(request.build(), BodyHandlers.ofString()).body(); } } }
Update generated Bach.java
.bach/src/Bach.java
Update generated Bach.java
<ide><path>bach/src/Bach.java <ide> } <ide> public static final class Project { <ide> public static Builder newProject(Path directory) { <del> return new Builder().base(Base.of(directory)).walk(); <add> return ModulesWalker.walk(directory); <ide> } <ide> public static Builder newProject(String title, String version) { <ide> return new Builder().title(title).version(Version.parse(version)); <ide> } <del> static void tuner(Call call, @SuppressWarnings("unused") Call.Context context) { <add> public static void tuner(Call call, @SuppressWarnings("unused") Call.Context context) { <ide> if (call instanceof GenericModuleSourceFilesConsumer) { <ide> var consumer = (GenericModuleSourceFilesConsumer<?>) call; <ide> consumer.setCharacterEncodingUsedBySourceFiles("UTF-8"); <ide> public Builder structure(Structure structure) { <ide> this.structure = structure; <ide> return this; <del> } <del> public Builder walk() { <del> return walk(Project::tuner); <del> } <del> public Builder walk(Call.Tuner tuner) { <del> var moduleInfoFiles = Paths.find(List.of(base.directory()), Paths::isModuleInfoJavaFile); <del> if (moduleInfoFiles.isEmpty()) throw new IllegalStateException("No module found: " + base); <del> return walkUnnamedRealm(moduleInfoFiles, tuner); <del> } <del> public Builder walkUnnamedRealm(List<Path> moduleInfoFiles, Call.Tuner tuner) { <del> var moduleNames = new TreeSet<String>(); <del> var moduleSourcePathPatterns = new TreeSet<String>(); <del> var units = new ArrayList<Unit>(); <del> var javadocCommentFound = false; <del> for (var info : moduleInfoFiles) { <del> javadocCommentFound = javadocCommentFound || Paths.isJavadocCommentAvailable(info); <del> var descriptor = Modules.describe(info); <del> var module = descriptor.name(); <del> moduleNames.add(module); <del> moduleSourcePathPatterns.add(Modules.modulePatternForm(info, descriptor.name())); <del> var classes = base.classes("", module); <del> var modules = base.modules(""); <del> var jar = modules.resolve(module + ".jar"); <del> var context = new Call.Context("", module); <del> var jarCreate = new Jar(); <del> var jarCreateArgs = jarCreate.getAdditionalArguments(); <del> jarCreateArgs.add("--create").add("--file", jar); <del> descriptor.mainClass().ifPresent(main -> jarCreateArgs.add("--main-class", main)); <del> jarCreateArgs.add("-C", classes, "."); <del> tuner.tune(jarCreate, context); <del> var jarDescribe = new Jar(); <del> jarDescribe.getAdditionalArguments().add("--describe-module").add("--file", jar); <del> tuner.tune(jarDescribe, context); <del> var task = <del> Task.sequence( <del> "Create modular JAR file " + jar.getFileName(), <del> new Task.CreateDirectories(jar.getParent()), <del> jarCreate.toTask(), <del> jarDescribe.toTask()); <del> units.add(new Unit(descriptor, List.of(task))); <del> } <del> var context = new Call.Context("", null); <del> var javac = <del> new Javac() <del> .setModules(moduleNames) <del> .setPatternsWhereToFindSourceFiles(moduleSourcePathPatterns) <del> .setDestinationDirectory(base.classes("")); <del> tuner.tune(javac, context); <del> var tasks = new ArrayList<Task>(); <del> if (javadocCommentFound) { <del> var javadoc = <del> new Javadoc() <del> .setDestinationDirectory(base.api()) <del> .setModules(moduleNames) <del> .setPatternsWhereToFindSourceFiles(moduleSourcePathPatterns); <del> tuner.tune(javadoc, context); <del> tasks.add(javadoc.toTask()); <del> } <del> var mainModule = Modules.findMainModule(units.stream().map(Unit::descriptor)); <del> if (mainModule.isPresent()) { <del> var jlink = <del> new Jlink().setModules(moduleNames).setLocationOfTheGeneratedRuntimeImage(base.image()); <del> var launcher = Path.of(mainModule.get().replace('.', '/')).getFileName().toString(); <del> var arguments = jlink.getAdditionalArguments(); <del> arguments.add("--module-path", base.modules("")); <del> arguments.add("--launcher", launcher + '=' + mainModule.get()); <del> tuner.tune(jlink, context); <del> tasks.add( <del> Task.sequence( <del> String.format("Create custom runtime image with '%s' as launcher", launcher), <del> new Task.DeleteDirectories(base.image()), <del> jlink.toTask())); <del> } <del> var realm = new Realm("", units, javac.toTask(), tasks); <del> var directoryName = base.directory().toAbsolutePath().getFileName(); <del> return title("Project " + Optional.ofNullable(directoryName).map(Path::toString).orElse("?")) <del> .structure(new Structure(Library.of(), List.of(realm))); <ide> } <ide> } <ide> } <ide> return missing; <ide> } <ide> } <add> public static class ModulesWalker { <add> public static Project.Builder walk(Path directory) { <add> return walk(Project.Base.of(directory), Project::tuner); <add> } <add> public static Project.Builder walk(Project.Base base, Call.Tuner tuner) { <add> var moduleInfoFiles = Paths.find(List.of(base.directory()), Paths::isModuleInfoJavaFile); <add> if (moduleInfoFiles.isEmpty()) throw new IllegalStateException("No module found: " + base); <add> var walker = new ModulesWalker(base, moduleInfoFiles, tuner); <add> return walker.walkAndCreateUnnamedRealm(); <add> } <add> private final Project.Base base; <add> private final List<Path> moduleInfoFiles; <add> private final Call.Tuner tuner; <add> public ModulesWalker(Project.Base base, List<Path> moduleInfoFiles, Call.Tuner tuner) { <add> this.base = base; <add> this.moduleInfoFiles = moduleInfoFiles; <add> this.tuner = tuner; <add> } <add> public Project.Builder walkAndCreateUnnamedRealm() { <add> var moduleNames = new TreeSet<String>(); <add> var moduleSourcePathPatterns = new TreeSet<String>(); <add> var units = new ArrayList<Project.Unit>(); <add> var javadocCommentFound = false; <add> for (var info : moduleInfoFiles) { <add> javadocCommentFound = javadocCommentFound || Paths.isJavadocCommentAvailable(info); <add> var descriptor = Modules.describe(info); <add> var module = descriptor.name(); <add> moduleNames.add(module); <add> moduleSourcePathPatterns.add(Modules.modulePatternForm(info, descriptor.name())); <add> var classes = base.classes("", module); <add> var modules = base.modules(""); <add> var jar = modules.resolve(module + ".jar"); <add> var context = new Call.Context("", module); <add> var jarCreate = new Jar(); <add> var jarCreateArgs = jarCreate.getAdditionalArguments(); <add> jarCreateArgs.add("--create").add("--file", jar); <add> descriptor.mainClass().ifPresent(main -> jarCreateArgs.add("--main-class", main)); <add> jarCreateArgs.add("-C", classes, "."); <add> tuner.tune(jarCreate, context); <add> var jarDescribe = new Jar(); <add> jarDescribe.getAdditionalArguments().add("--describe-module").add("--file", jar); <add> tuner.tune(jarDescribe, context); <add> var task = <add> Task.sequence( <add> "Create modular JAR file " + jar.getFileName(), <add> new Task.CreateDirectories(jar.getParent()), <add> jarCreate.toTask(), <add> jarDescribe.toTask()); <add> units.add(new Project.Unit(descriptor, List.of(task))); <add> } <add> var context = new Call.Context("", null); <add> var javac = <add> new Javac() <add> .setModules(moduleNames) <add> .setPatternsWhereToFindSourceFiles(moduleSourcePathPatterns) <add> .setDestinationDirectory(base.classes("")); <add> tuner.tune(javac, context); <add> var tasks = new ArrayList<Task>(); <add> if (javadocCommentFound) { <add> var javadoc = <add> new Javadoc() <add> .setDestinationDirectory(base.api()) <add> .setModules(moduleNames) <add> .setPatternsWhereToFindSourceFiles(moduleSourcePathPatterns); <add> tuner.tune(javadoc, context); <add> tasks.add(javadoc.toTask()); <add> } <add> var mainModule = Modules.findMainModule(units.stream().map(Project.Unit::descriptor)); <add> if (mainModule.isPresent()) { <add> var jlink = <add> new Jlink().setModules(moduleNames).setLocationOfTheGeneratedRuntimeImage(base.image()); <add> var launcher = Path.of(mainModule.get().replace('.', '/')).getFileName().toString(); <add> var arguments = jlink.getAdditionalArguments(); <add> arguments.add("--module-path", base.modules("")); <add> arguments.add("--launcher", launcher + '=' + mainModule.get()); <add> tuner.tune(jlink, context); <add> tasks.add( <add> Task.sequence( <add> String.format("Create custom runtime image with '%s' as launcher", launcher), <add> new Task.DeleteDirectories(base.image()), <add> jlink.toTask())); <add> } <add> var realm = new Project.Realm("", units, javac.toTask(), tasks); <add> var directoryName = base.directory().toAbsolutePath().getFileName(); <add> return new Project.Builder() <add> .base(base) <add> .title("Project " + Optional.ofNullable(directoryName).map(Path::toString).orElse("?")) <add> .structure(new Project.Structure(Project.Library.of(), List.of(realm))); <add> } <add> } <ide> public static class Paths { <ide> public static boolean isEmpty(Path path) { <ide> try {
Java
apache-2.0
bdef8e1ae344646dea1acdcdba8796f90a0262a0
0
semonte/intellij-community,tmpgit/intellij-community,FHannes/intellij-community,fitermay/intellij-community,asedunov/intellij-community,da1z/intellij-community,akosyakov/intellij-community,blademainer/intellij-community,Distrotech/intellij-community,samthor/intellij-community,SerCeMan/intellij-community,wreckJ/intellij-community,nicolargo/intellij-community,semonte/intellij-community,clumsy/intellij-community,gnuhub/intellij-community,amith01994/intellij-community,xfournet/intellij-community,da1z/intellij-community,allotria/intellij-community,jagguli/intellij-community,lucafavatella/intellij-community,ThiagoGarciaAlves/intellij-community,caot/intellij-community,diorcety/intellij-community,fengbaicanhe/intellij-community,akosyakov/intellij-community,suncycheng/intellij-community,adedayo/intellij-community,ibinti/intellij-community,ol-loginov/intellij-community,fitermay/intellij-community,ahb0327/intellij-community,samthor/intellij-community,alphafoobar/intellij-community,suncycheng/intellij-community,FHannes/intellij-community,vvv1559/intellij-community,signed/intellij-community,semonte/intellij-community,suncycheng/intellij-community,michaelgallacher/intellij-community,nicolargo/intellij-community,hurricup/intellij-community,blademainer/intellij-community,vvv1559/intellij-community,fengbaicanhe/intellij-community,MichaelNedzelsky/intellij-community,ftomassetti/intellij-community,youdonghai/intellij-community,izonder/intellij-community,wreckJ/intellij-community,idea4bsd/idea4bsd,ThiagoGarciaAlves/intellij-community,Distrotech/intellij-community,tmpgit/intellij-community,MichaelNedzelsky/intellij-community,retomerz/intellij-community,MichaelNedzelsky/intellij-community,xfournet/intellij-community,TangHao1987/intellij-community,FHannes/intellij-community,ivan-fedorov/intellij-community,amith01994/intellij-community,xfournet/intellij-community,caot/intellij-community,vladmm/intellij-community,adedayo/intellij-community,allotria/intellij-community,ibinti/intellij-community,vladmm/intellij-community,ThiagoGarciaAlves/intellij-community,ThiagoGarciaAlves/intellij-community,fitermay/intellij-community,ibinti/intellij-community,kool79/intellij-community,ftomassetti/intellij-community,fnouama/intellij-community,izonder/intellij-community,ryano144/intellij-community,suncycheng/intellij-community,tmpgit/intellij-community,dslomov/intellij-community,akosyakov/intellij-community,xfournet/intellij-community,SerCeMan/intellij-community,MER-GROUP/intellij-community,robovm/robovm-studio,suncycheng/intellij-community,Lekanich/intellij-community,xfournet/intellij-community,apixandru/intellij-community,suncycheng/intellij-community,lucafavatella/intellij-community,akosyakov/intellij-community,TangHao1987/intellij-community,michaelgallacher/intellij-community,allotria/intellij-community,kool79/intellij-community,akosyakov/intellij-community,signed/intellij-community,nicolargo/intellij-community,kdwink/intellij-community,ryano144/intellij-community,idea4bsd/idea4bsd,muntasirsyed/intellij-community,salguarnieri/intellij-community,salguarnieri/intellij-community,kdwink/intellij-community,orekyuu/intellij-community,nicolargo/intellij-community,suncycheng/intellij-community,ibinti/intellij-community,blademainer/intellij-community,Distrotech/intellij-community,ol-loginov/intellij-community,asedunov/intellij-community,blademainer/intellij-community,robovm/robovm-studio,kdwink/intellij-community,MichaelNedzelsky/intellij-community,robovm/robovm-studio,tmpgit/intellij-community,Lekanich/intellij-community,izonder/intellij-community,muntasirsyed/intellij-community,ibinti/intellij-community,blademainer/intellij-community,blademainer/intellij-community,salguarnieri/intellij-community,jagguli/intellij-community,kdwink/intellij-community,MER-GROUP/intellij-community,diorcety/intellij-community,youdonghai/intellij-community,salguarnieri/intellij-community,muntasirsyed/intellij-community,ryano144/intellij-community,TangHao1987/intellij-community,semonte/intellij-community,lucafavatella/intellij-community,ivan-fedorov/intellij-community,fitermay/intellij-community,apixandru/intellij-community,hurricup/intellij-community,semonte/intellij-community,apixandru/intellij-community,adedayo/intellij-community,kdwink/intellij-community,tmpgit/intellij-community,idea4bsd/idea4bsd,ahb0327/intellij-community,MER-GROUP/intellij-community,Lekanich/intellij-community,da1z/intellij-community,supersven/intellij-community,SerCeMan/intellij-community,da1z/intellij-community,mglukhikh/intellij-community,apixandru/intellij-community,Lekanich/intellij-community,blademainer/intellij-community,orekyuu/intellij-community,supersven/intellij-community,orekyuu/intellij-community,supersven/intellij-community,ryano144/intellij-community,MER-GROUP/intellij-community,allotria/intellij-community,youdonghai/intellij-community,alphafoobar/intellij-community,Distrotech/intellij-community,hurricup/intellij-community,clumsy/intellij-community,youdonghai/intellij-community,FHannes/intellij-community,samthor/intellij-community,ol-loginov/intellij-community,ThiagoGarciaAlves/intellij-community,ryano144/intellij-community,ahb0327/intellij-community,asedunov/intellij-community,michaelgallacher/intellij-community,vladmm/intellij-community,hurricup/intellij-community,fitermay/intellij-community,samthor/intellij-community,dslomov/intellij-community,ahb0327/intellij-community,blademainer/intellij-community,SerCeMan/intellij-community,dslomov/intellij-community,vladmm/intellij-community,Distrotech/intellij-community,xfournet/intellij-community,idea4bsd/idea4bsd,tmpgit/intellij-community,retomerz/intellij-community,vvv1559/intellij-community,tmpgit/intellij-community,dslomov/intellij-community,robovm/robovm-studio,MER-GROUP/intellij-community,SerCeMan/intellij-community,dslomov/intellij-community,Lekanich/intellij-community,ol-loginov/intellij-community,ahb0327/intellij-community,MER-GROUP/intellij-community,vladmm/intellij-community,robovm/robovm-studio,TangHao1987/intellij-community,TangHao1987/intellij-community,xfournet/intellij-community,diorcety/intellij-community,asedunov/intellij-community,clumsy/intellij-community,adedayo/intellij-community,adedayo/intellij-community,pwoodworth/intellij-community,youdonghai/intellij-community,semonte/intellij-community,vladmm/intellij-community,idea4bsd/idea4bsd,samthor/intellij-community,da1z/intellij-community,supersven/intellij-community,ivan-fedorov/intellij-community,orekyuu/intellij-community,wreckJ/intellij-community,salguarnieri/intellij-community,petteyg/intellij-community,akosyakov/intellij-community,asedunov/intellij-community,kool79/intellij-community,vvv1559/intellij-community,alphafoobar/intellij-community,michaelgallacher/intellij-community,MichaelNedzelsky/intellij-community,ivan-fedorov/intellij-community,gnuhub/intellij-community,ol-loginov/intellij-community,fnouama/intellij-community,da1z/intellij-community,michaelgallacher/intellij-community,holmes/intellij-community,fengbaicanhe/intellij-community,idea4bsd/idea4bsd,izonder/intellij-community,idea4bsd/idea4bsd,clumsy/intellij-community,allotria/intellij-community,ibinti/intellij-community,vladmm/intellij-community,dslomov/intellij-community,wreckJ/intellij-community,kdwink/intellij-community,caot/intellij-community,semonte/intellij-community,fitermay/intellij-community,fnouama/intellij-community,gnuhub/intellij-community,vvv1559/intellij-community,slisson/intellij-community,ivan-fedorov/intellij-community,ThiagoGarciaAlves/intellij-community,hurricup/intellij-community,SerCeMan/intellij-community,clumsy/intellij-community,apixandru/intellij-community,da1z/intellij-community,kool79/intellij-community,lucafavatella/intellij-community,holmes/intellij-community,retomerz/intellij-community,SerCeMan/intellij-community,TangHao1987/intellij-community,gnuhub/intellij-community,slisson/intellij-community,supersven/intellij-community,kdwink/intellij-community,ol-loginov/intellij-community,apixandru/intellij-community,da1z/intellij-community,fitermay/intellij-community,ol-loginov/intellij-community,lucafavatella/intellij-community,amith01994/intellij-community,nicolargo/intellij-community,diorcety/intellij-community,diorcety/intellij-community,muntasirsyed/intellij-community,alphafoobar/intellij-community,SerCeMan/intellij-community,diorcety/intellij-community,FHannes/intellij-community,ftomassetti/intellij-community,adedayo/intellij-community,ThiagoGarciaAlves/intellij-community,gnuhub/intellij-community,ivan-fedorov/intellij-community,ryano144/intellij-community,gnuhub/intellij-community,fnouama/intellij-community,samthor/intellij-community,kool79/intellij-community,orekyuu/intellij-community,ibinti/intellij-community,caot/intellij-community,ol-loginov/intellij-community,vvv1559/intellij-community,MER-GROUP/intellij-community,robovm/robovm-studio,nicolargo/intellij-community,supersven/intellij-community,robovm/robovm-studio,ftomassetti/intellij-community,clumsy/intellij-community,retomerz/intellij-community,lucafavatella/intellij-community,muntasirsyed/intellij-community,caot/intellij-community,ivan-fedorov/intellij-community,ahb0327/intellij-community,fengbaicanhe/intellij-community,FHannes/intellij-community,asedunov/intellij-community,signed/intellij-community,adedayo/intellij-community,holmes/intellij-community,Lekanich/intellij-community,slisson/intellij-community,ibinti/intellij-community,petteyg/intellij-community,allotria/intellij-community,samthor/intellij-community,mglukhikh/intellij-community,semonte/intellij-community,SerCeMan/intellij-community,samthor/intellij-community,slisson/intellij-community,izonder/intellij-community,hurricup/intellij-community,signed/intellij-community,FHannes/intellij-community,diorcety/intellij-community,TangHao1987/intellij-community,retomerz/intellij-community,tmpgit/intellij-community,wreckJ/intellij-community,amith01994/intellij-community,adedayo/intellij-community,idea4bsd/idea4bsd,retomerz/intellij-community,akosyakov/intellij-community,allotria/intellij-community,semonte/intellij-community,ibinti/intellij-community,amith01994/intellij-community,samthor/intellij-community,vvv1559/intellij-community,wreckJ/intellij-community,petteyg/intellij-community,wreckJ/intellij-community,hurricup/intellij-community,michaelgallacher/intellij-community,izonder/intellij-community,youdonghai/intellij-community,fnouama/intellij-community,caot/intellij-community,fengbaicanhe/intellij-community,gnuhub/intellij-community,holmes/intellij-community,diorcety/intellij-community,suncycheng/intellij-community,jagguli/intellij-community,salguarnieri/intellij-community,clumsy/intellij-community,ThiagoGarciaAlves/intellij-community,akosyakov/intellij-community,youdonghai/intellij-community,kdwink/intellij-community,ol-loginov/intellij-community,ftomassetti/intellij-community,ftomassetti/intellij-community,blademainer/intellij-community,akosyakov/intellij-community,samthor/intellij-community,vvv1559/intellij-community,alphafoobar/intellij-community,slisson/intellij-community,holmes/intellij-community,akosyakov/intellij-community,amith01994/intellij-community,lucafavatella/intellij-community,amith01994/intellij-community,samthor/intellij-community,fengbaicanhe/intellij-community,suncycheng/intellij-community,SerCeMan/intellij-community,caot/intellij-community,ivan-fedorov/intellij-community,allotria/intellij-community,fitermay/intellij-community,semonte/intellij-community,michaelgallacher/intellij-community,jagguli/intellij-community,amith01994/intellij-community,petteyg/intellij-community,mglukhikh/intellij-community,amith01994/intellij-community,orekyuu/intellij-community,fengbaicanhe/intellij-community,caot/intellij-community,mglukhikh/intellij-community,FHannes/intellij-community,samthor/intellij-community,Distrotech/intellij-community,wreckJ/intellij-community,MichaelNedzelsky/intellij-community,michaelgallacher/intellij-community,izonder/intellij-community,nicolargo/intellij-community,gnuhub/intellij-community,amith01994/intellij-community,petteyg/intellij-community,jagguli/intellij-community,ryano144/intellij-community,fitermay/intellij-community,signed/intellij-community,ivan-fedorov/intellij-community,ryano144/intellij-community,apixandru/intellij-community,slisson/intellij-community,MichaelNedzelsky/intellij-community,ivan-fedorov/intellij-community,ryano144/intellij-community,mglukhikh/intellij-community,pwoodworth/intellij-community,ThiagoGarciaAlves/intellij-community,orekyuu/intellij-community,fnouama/intellij-community,kool79/intellij-community,Lekanich/intellij-community,suncycheng/intellij-community,diorcety/intellij-community,nicolargo/intellij-community,apixandru/intellij-community,asedunov/intellij-community,idea4bsd/idea4bsd,ahb0327/intellij-community,MER-GROUP/intellij-community,mglukhikh/intellij-community,caot/intellij-community,Distrotech/intellij-community,dslomov/intellij-community,ThiagoGarciaAlves/intellij-community,asedunov/intellij-community,signed/intellij-community,asedunov/intellij-community,idea4bsd/idea4bsd,akosyakov/intellij-community,fengbaicanhe/intellij-community,FHannes/intellij-community,vvv1559/intellij-community,ryano144/intellij-community,vvv1559/intellij-community,ftomassetti/intellij-community,ftomassetti/intellij-community,kool79/intellij-community,orekyuu/intellij-community,dslomov/intellij-community,signed/intellij-community,pwoodworth/intellij-community,idea4bsd/idea4bsd,youdonghai/intellij-community,SerCeMan/intellij-community,pwoodworth/intellij-community,clumsy/intellij-community,kool79/intellij-community,caot/intellij-community,holmes/intellij-community,orekyuu/intellij-community,izonder/intellij-community,dslomov/intellij-community,kdwink/intellij-community,kdwink/intellij-community,fitermay/intellij-community,alphafoobar/intellij-community,pwoodworth/intellij-community,supersven/intellij-community,hurricup/intellij-community,hurricup/intellij-community,ol-loginov/intellij-community,allotria/intellij-community,petteyg/intellij-community,Distrotech/intellij-community,da1z/intellij-community,apixandru/intellij-community,semonte/intellij-community,fnouama/intellij-community,clumsy/intellij-community,alphafoobar/intellij-community,FHannes/intellij-community,kool79/intellij-community,MER-GROUP/intellij-community,vvv1559/intellij-community,nicolargo/intellij-community,blademainer/intellij-community,asedunov/intellij-community,muntasirsyed/intellij-community,Lekanich/intellij-community,gnuhub/intellij-community,holmes/intellij-community,allotria/intellij-community,ibinti/intellij-community,ahb0327/intellij-community,dslomov/intellij-community,pwoodworth/intellij-community,ibinti/intellij-community,lucafavatella/intellij-community,ThiagoGarciaAlves/intellij-community,gnuhub/intellij-community,pwoodworth/intellij-community,wreckJ/intellij-community,petteyg/intellij-community,robovm/robovm-studio,jagguli/intellij-community,TangHao1987/intellij-community,ftomassetti/intellij-community,izonder/intellij-community,robovm/robovm-studio,TangHao1987/intellij-community,supersven/intellij-community,muntasirsyed/intellij-community,salguarnieri/intellij-community,pwoodworth/intellij-community,slisson/intellij-community,Distrotech/intellij-community,fnouama/intellij-community,tmpgit/intellij-community,clumsy/intellij-community,lucafavatella/intellij-community,holmes/intellij-community,retomerz/intellij-community,signed/intellij-community,nicolargo/intellij-community,MER-GROUP/intellij-community,Distrotech/intellij-community,salguarnieri/intellij-community,apixandru/intellij-community,blademainer/intellij-community,fitermay/intellij-community,mglukhikh/intellij-community,robovm/robovm-studio,izonder/intellij-community,ftomassetti/intellij-community,michaelgallacher/intellij-community,adedayo/intellij-community,orekyuu/intellij-community,caot/intellij-community,Lekanich/intellij-community,salguarnieri/intellij-community,jagguli/intellij-community,kdwink/intellij-community,vvv1559/intellij-community,signed/intellij-community,vvv1559/intellij-community,adedayo/intellij-community,retomerz/intellij-community,clumsy/intellij-community,holmes/intellij-community,amith01994/intellij-community,pwoodworth/intellij-community,MichaelNedzelsky/intellij-community,alphafoobar/intellij-community,MichaelNedzelsky/intellij-community,blademainer/intellij-community,wreckJ/intellij-community,slisson/intellij-community,nicolargo/intellij-community,SerCeMan/intellij-community,ahb0327/intellij-community,hurricup/intellij-community,fnouama/intellij-community,salguarnieri/intellij-community,izonder/intellij-community,FHannes/intellij-community,asedunov/intellij-community,signed/intellij-community,lucafavatella/intellij-community,pwoodworth/intellij-community,ftomassetti/intellij-community,da1z/intellij-community,retomerz/intellij-community,nicolargo/intellij-community,kdwink/intellij-community,hurricup/intellij-community,alphafoobar/intellij-community,mglukhikh/intellij-community,diorcety/intellij-community,ahb0327/intellij-community,suncycheng/intellij-community,allotria/intellij-community,apixandru/intellij-community,michaelgallacher/intellij-community,allotria/intellij-community,lucafavatella/intellij-community,slisson/intellij-community,youdonghai/intellij-community,pwoodworth/intellij-community,jagguli/intellij-community,mglukhikh/intellij-community,kool79/intellij-community,izonder/intellij-community,vladmm/intellij-community,Lekanich/intellij-community,retomerz/intellij-community,da1z/intellij-community,alphafoobar/intellij-community,orekyuu/intellij-community,idea4bsd/idea4bsd,petteyg/intellij-community,supersven/intellij-community,diorcety/intellij-community,Distrotech/intellij-community,MER-GROUP/intellij-community,xfournet/intellij-community,supersven/intellij-community,mglukhikh/intellij-community,pwoodworth/intellij-community,youdonghai/intellij-community,holmes/intellij-community,mglukhikh/intellij-community,vladmm/intellij-community,muntasirsyed/intellij-community,gnuhub/intellij-community,vladmm/intellij-community,fengbaicanhe/intellij-community,retomerz/intellij-community,diorcety/intellij-community,hurricup/intellij-community,kool79/intellij-community,salguarnieri/intellij-community,xfournet/intellij-community,supersven/intellij-community,youdonghai/intellij-community,supersven/intellij-community,signed/intellij-community,ftomassetti/intellij-community,Lekanich/intellij-community,tmpgit/intellij-community,muntasirsyed/intellij-community,holmes/intellij-community,Lekanich/intellij-community,ivan-fedorov/intellij-community,TangHao1987/intellij-community,salguarnieri/intellij-community,petteyg/intellij-community,gnuhub/intellij-community,caot/intellij-community,adedayo/intellij-community,ThiagoGarciaAlves/intellij-community,FHannes/intellij-community,clumsy/intellij-community,vladmm/intellij-community,Distrotech/intellij-community,ahb0327/intellij-community,ibinti/intellij-community,jagguli/intellij-community,idea4bsd/idea4bsd,ahb0327/intellij-community,apixandru/intellij-community,lucafavatella/intellij-community,tmpgit/intellij-community,xfournet/intellij-community,petteyg/intellij-community,adedayo/intellij-community,ryano144/intellij-community,jagguli/intellij-community,ryano144/intellij-community,amith01994/intellij-community,kool79/intellij-community,signed/intellij-community,orekyuu/intellij-community,xfournet/intellij-community,semonte/intellij-community,MER-GROUP/intellij-community,muntasirsyed/intellij-community,youdonghai/intellij-community,FHannes/intellij-community,fitermay/intellij-community,da1z/intellij-community,petteyg/intellij-community,ol-loginov/intellij-community,asedunov/intellij-community,TangHao1987/intellij-community,mglukhikh/intellij-community,ivan-fedorov/intellij-community,petteyg/intellij-community,muntasirsyed/intellij-community,wreckJ/intellij-community,MichaelNedzelsky/intellij-community,asedunov/intellij-community,ol-loginov/intellij-community,da1z/intellij-community,fnouama/intellij-community,akosyakov/intellij-community,apixandru/intellij-community,semonte/intellij-community,wreckJ/intellij-community,fitermay/intellij-community,ibinti/intellij-community,vladmm/intellij-community,signed/intellij-community,michaelgallacher/intellij-community,suncycheng/intellij-community,retomerz/intellij-community,tmpgit/intellij-community,dslomov/intellij-community,TangHao1987/intellij-community,xfournet/intellij-community,slisson/intellij-community,fengbaicanhe/intellij-community,slisson/intellij-community,michaelgallacher/intellij-community,fnouama/intellij-community,lucafavatella/intellij-community,xfournet/intellij-community,slisson/intellij-community,jagguli/intellij-community,MichaelNedzelsky/intellij-community,fnouama/intellij-community,fengbaicanhe/intellij-community,muntasirsyed/intellij-community,robovm/robovm-studio,jagguli/intellij-community,alphafoobar/intellij-community,youdonghai/intellij-community,MichaelNedzelsky/intellij-community,apixandru/intellij-community,dslomov/intellij-community,holmes/intellij-community,allotria/intellij-community,mglukhikh/intellij-community,hurricup/intellij-community,robovm/robovm-studio,alphafoobar/intellij-community,fengbaicanhe/intellij-community,retomerz/intellij-community
package com.intellij.coverage; import com.intellij.openapi.fileTypes.StdFileTypes; import com.intellij.openapi.module.Module; import com.intellij.openapi.module.ModuleManager; import com.intellij.openapi.project.Project; import com.intellij.openapi.roots.*; import com.intellij.openapi.util.Computable; import com.intellij.openapi.vfs.VfsUtil; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.psi.JavaPsiFacade; import com.intellij.psi.PsiClass; import com.intellij.psi.PsiManager; import com.intellij.psi.PsiPackage; import com.intellij.psi.search.GlobalSearchScope; import com.intellij.rt.coverage.data.ClassData; import com.intellij.rt.coverage.data.LineCoverage; import com.intellij.rt.coverage.data.LineData; import com.intellij.rt.coverage.data.ProjectData; import com.intellij.rt.coverage.instrumentation.SourceLineCounter; import com.intellij.util.containers.HashMap; import org.jetbrains.annotations.Nullable; import org.objectweb.asm.ClassReader; import org.objectweb.asm.commons.EmptyVisitor; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Map; /** * @author ven */ public class PackageAnnotator { private final PsiPackage myPackage; private final Project myProject; private final PsiManager myManager; private final CoverageDataManager myCoverageManager; public PackageAnnotator(final PsiPackage aPackage) { myPackage = aPackage; myProject = myPackage.getProject(); myManager = PsiManager.getInstance(myProject); myCoverageManager = CoverageDataManager.getInstance(myProject); } public interface Annotator { void annotateSourceDirectory(VirtualFile virtualFile, PackageCoverageInfo packageCoverageInfo, Module module); void annotateTestDirectory(VirtualFile virtualFile, PackageCoverageInfo packageCoverageInfo, Module module); void annotatePackage(String packageQualifiedName, PackageCoverageInfo packageCoverageInfo); void annotateClass(String classQualifiedName, ClassCoverageInfo classCoverageInfo); } public static class ClassCoverageInfo { public int totalLineCount; public int fullyCoveredLineCount; public int partiallyCoveredLineCount; public int totalMethodCount; public int coveredMethodCount; } public static class PackageCoverageInfo { public int totalClassCount; public int coveredClassCount; public int totalLineCount; public int coveredLineCount; } public static class DirCoverageInfo extends PackageCoverageInfo { public VirtualFile sourceRoot; public DirCoverageInfo(VirtualFile sourceRoot) { this.sourceRoot = sourceRoot; } } //get read lock myself when needed public void annotate(CoverageSuitesBundle suite, Annotator annotator) { final ProjectData data = suite.getCoverageData(); if (data == null) return; final String qualifiedName = myPackage.getQualifiedName(); boolean filtered = false; for (CoverageSuite coverageSuite : suite.getSuites()) { if (((JavaCoverageSuite)coverageSuite).isPackageFiltered(qualifiedName)) { filtered = true; break; } } if (!filtered) return; final Module[] modules = myCoverageManager.doInReadActionIfProjectOpen(new Computable<Module[]>() { public Module[] compute() { return ModuleManager.getInstance(myProject).getModules(); } }); if (modules == null) return; Map<String, PackageCoverageInfo> packageCoverageMap = new HashMap<String, PackageCoverageInfo>(); for (final Module module : modules) { final String rootPackageVMName = qualifiedName.replaceAll("\\.", "/"); final VirtualFile packageRoot = myCoverageManager.doInReadActionIfProjectOpen(new Computable<VirtualFile>() { @Nullable public VirtualFile compute() { final VirtualFile outputPath = CompilerModuleExtension.getInstance(module).getCompilerOutputPath(); if (outputPath != null) { return rootPackageVMName.length() > 0 ? outputPath.findFileByRelativePath(rootPackageVMName) : outputPath; } return null; } }); if (packageRoot != null) { collectCoverageInformation(packageRoot, packageCoverageMap, data, rootPackageVMName, annotator, module, suite.isTrackTestFolders(), false); } if (suite.isTrackTestFolders()) { final VirtualFile testPackageRoot = myCoverageManager.doInReadActionIfProjectOpen(new Computable<VirtualFile>() { @Nullable public VirtualFile compute() { final VirtualFile outputPath = CompilerModuleExtension.getInstance(module).getCompilerOutputPathForTests(); if (outputPath != null) { return rootPackageVMName.length() > 0 ? outputPath.findFileByRelativePath(rootPackageVMName) : outputPath; } return null; } }); if (testPackageRoot != null) { collectCoverageInformation(testPackageRoot, packageCoverageMap, data, rootPackageVMName, annotator, module, suite.isTrackTestFolders(), true); } } } for (Map.Entry<String, PackageCoverageInfo> entry : packageCoverageMap.entrySet()) { final String packageFQName = entry.getKey().replaceAll("/", "."); final PackageCoverageInfo info = entry.getValue(); annotator.annotatePackage(packageFQName, info); } } @Nullable private DirCoverageInfo[] collectCoverageInformation(final VirtualFile packageOutputRoot, final Map<String, PackageCoverageInfo> packageCoverageMap, final ProjectData projectInfo, final String packageVMName, final Annotator annotator, final Module module, final boolean trackTestFolders, final boolean isTestHierarchy) { final List<DirCoverageInfo> dirs = new ArrayList<DirCoverageInfo>(); final ContentEntry[] contentEntries = ModuleRootManager.getInstance(module).getContentEntries(); for (ContentEntry contentEntry : contentEntries) { for (SourceFolder folder : contentEntry.getSourceFolders()) { final VirtualFile file = folder.getFile(); if (file == null) continue; if (folder.isTestSource() && isTestHierarchy || !isTestHierarchy) { final VirtualFile relativeSrcRoot = file.findFileByRelativePath(packageVMName); dirs.add(new DirCoverageInfo(relativeSrcRoot)); } } } final VirtualFile[] children = myCoverageManager.doInReadActionIfProjectOpen(new Computable<VirtualFile[]>() { public VirtualFile[] compute() { return packageOutputRoot.getChildren(); } }); if (children == null) return null; Map<String, ClassCoverageInfo> toplevelClassCoverage = new HashMap<String, ClassCoverageInfo>(); for (VirtualFile child : children) { if (child.isDirectory()) { final String childName = child.getName(); final String childPackageVMName = packageVMName.length() > 0 ? packageVMName + "/" + childName : childName; final DirCoverageInfo[] childCoverageInfo = collectCoverageInformation(child, packageCoverageMap, projectInfo, childPackageVMName, annotator, module, trackTestFolders, isTestHierarchy); if (childCoverageInfo != null) { for (int i = 0; i < childCoverageInfo.length; i++) { DirCoverageInfo coverageInfo = childCoverageInfo[i]; final DirCoverageInfo parentDir = dirs.get(i); parentDir.totalClassCount += coverageInfo.totalClassCount; parentDir.coveredClassCount += coverageInfo.coveredClassCount; parentDir.totalLineCount += coverageInfo.totalLineCount; parentDir.coveredLineCount += coverageInfo.coveredLineCount; } } } else { if (child.getFileType().equals(StdFileTypes.CLASS)) { final String childName = child.getNameWithoutExtension(); final String classFqVMName = packageVMName.length() > 0 ? packageVMName + "/" + childName : childName; final String toplevelClassSrcFQName = getSourceToplevelFQName(classFqVMName); final VirtualFile[] containingFile = new VirtualFile[1]; final Boolean isInSource = myCoverageManager.doInReadActionIfProjectOpen(new Computable<Boolean>() { public Boolean compute() { final PsiClass aClass = JavaPsiFacade.getInstance(myManager.getProject()).findClass(toplevelClassSrcFQName, GlobalSearchScope.moduleScope(module)); if (aClass == null || !aClass.isValid()) return Boolean.FALSE; containingFile[0] = aClass.getContainingFile().getVirtualFile(); assert containingFile[0] != null; final ModuleFileIndex fileIndex = ModuleRootManager.getInstance(module).getFileIndex(); return fileIndex.isInSourceContent(containingFile[0]) && (trackTestFolders || !fileIndex.isInTestSourceContent(containingFile[0])); } }); if (isInSource != null && isInSource.booleanValue()) { for (DirCoverageInfo dirCoverageInfo : dirs) { if (dirCoverageInfo.sourceRoot != null && VfsUtil.isAncestor(dirCoverageInfo.sourceRoot, containingFile[0], false)) { collectClassCoverageInformation(child, dirCoverageInfo, projectInfo, toplevelClassCoverage, classFqVMName.replace("/", "."), toplevelClassSrcFQName); break; } } } } } } for (Map.Entry<String, ClassCoverageInfo> entry : toplevelClassCoverage.entrySet()) { final String toplevelClassName = entry.getKey(); final ClassCoverageInfo coverageInfo = entry.getValue(); annotator.annotateClass(toplevelClassName, coverageInfo); } PackageCoverageInfo packageCoverageInfo = getOrCreateCoverageInfo(packageCoverageMap, packageVMName); for (DirCoverageInfo dir : dirs) { packageCoverageInfo.totalClassCount += dir.totalClassCount; packageCoverageInfo.totalLineCount += dir.totalLineCount; packageCoverageInfo.coveredClassCount += dir.coveredClassCount; packageCoverageInfo.coveredLineCount += dir.coveredLineCount; if (isTestHierarchy) { annotator.annotateTestDirectory(dir.sourceRoot, dir, module); } else { annotator.annotateSourceDirectory(dir.sourceRoot, dir, module); } } return dirs.toArray(new DirCoverageInfo[dirs.size()]); } private static PackageCoverageInfo getOrCreateCoverageInfo(final Map<String, PackageCoverageInfo> packageCoverageMap, final String packageVMName) { PackageCoverageInfo coverageInfo = packageCoverageMap.get(packageVMName); if (coverageInfo == null) { coverageInfo = new PackageCoverageInfo(); packageCoverageMap.put(packageVMName, coverageInfo); } return coverageInfo; } private void collectClassCoverageInformation(final VirtualFile classFile, final PackageCoverageInfo packageCoverageInfo, final ProjectData projectInfo, final Map<String, ClassCoverageInfo> toplevelClassCoverage, final String className, final String toplevelClassSrcFQName) { final ClassCoverageInfo toplevelClassCoverageInfo = new ClassCoverageInfo(); final ClassData classData = projectInfo.getClassData(className); if (classData != null && classData.getLines() != null) { final Object[] lines = classData.getLines(); for (Object l : lines) { if (l instanceof LineData) { final LineData lineData = (LineData)l; if (lineData.getStatus() == LineCoverage.FULL) { toplevelClassCoverageInfo.fullyCoveredLineCount++; } else if (lineData.getStatus() == LineCoverage.PARTIAL) { toplevelClassCoverageInfo.partiallyCoveredLineCount++; } toplevelClassCoverageInfo.totalLineCount++; packageCoverageInfo.totalLineCount++; } } boolean touchedClass = false; for (final Object nameAndSig : classData.getMethodSigs()) { final int covered = classData.getStatus((String)nameAndSig); if (covered != LineCoverage.NONE) { toplevelClassCoverageInfo.coveredMethodCount++; touchedClass = true; } } if (touchedClass) { packageCoverageInfo.coveredClassCount++; } toplevelClassCoverageInfo.totalMethodCount += classData.getMethodSigs().size(); packageCoverageInfo.totalClassCount++; packageCoverageInfo.coveredLineCount += toplevelClassCoverageInfo.fullyCoveredLineCount; packageCoverageInfo.coveredLineCount += toplevelClassCoverageInfo.partiallyCoveredLineCount; } else { collectNonCoveredClassInfo(classFile, toplevelClassCoverageInfo, packageCoverageInfo); } ClassCoverageInfo classCoverageInfo = getOrCreateClassCoverageInfo(toplevelClassCoverage, toplevelClassSrcFQName); classCoverageInfo.totalLineCount += toplevelClassCoverageInfo.totalLineCount; classCoverageInfo.fullyCoveredLineCount += toplevelClassCoverageInfo.fullyCoveredLineCount; classCoverageInfo.partiallyCoveredLineCount += toplevelClassCoverageInfo.partiallyCoveredLineCount; classCoverageInfo.totalMethodCount += toplevelClassCoverageInfo.totalMethodCount; classCoverageInfo.coveredMethodCount += toplevelClassCoverageInfo.coveredMethodCount; } private static ClassCoverageInfo getOrCreateClassCoverageInfo(final Map<String, ClassCoverageInfo> toplevelClassCoverage, final String sourceToplevelFQName) { ClassCoverageInfo toplevelClassCoverageInfo = toplevelClassCoverage.get(sourceToplevelFQName); if (toplevelClassCoverageInfo == null) { toplevelClassCoverageInfo = new ClassCoverageInfo(); toplevelClassCoverage.put(sourceToplevelFQName, toplevelClassCoverageInfo); } return toplevelClassCoverageInfo; } private static String getSourceToplevelFQName(String classFQVMName) { final int index = classFQVMName.indexOf('$'); if (index > 0) classFQVMName = classFQVMName.substring(0, index); if (classFQVMName.startsWith("/")) classFQVMName = classFQVMName.substring(1); return classFQVMName.replaceAll("/", "."); } /* return true if there is executable code in the class */ private boolean collectNonCoveredClassInfo(final VirtualFile classFile, final ClassCoverageInfo classCoverageInfo, final PackageCoverageInfo packageCoverageInfo) { final byte[] content = myCoverageManager.doInReadActionIfProjectOpen(new Computable<byte[]>() { public byte[] compute() { try { return classFile.contentsToByteArray(); } catch (IOException e) { return null; } } }); if (content == null) return false; ClassReader reader = new ClassReader(content, 0, content.length); final CoverageSuitesBundle coverageSuite = CoverageDataManager.getInstance(myProject).getCurrentSuitesBundle(); if (coverageSuite == null) return false; SourceLineCounter counter = new SourceLineCounter(new EmptyVisitor(), null, coverageSuite.isTracingEnabled()); reader.accept(counter, 0); classCoverageInfo.totalLineCount += counter.getNSourceLines(); classCoverageInfo.totalMethodCount += counter.getNMethodsWithCode(); packageCoverageInfo.totalLineCount += counter.getNSourceLines(); if (!counter.isInterface()) { packageCoverageInfo.totalClassCount++; } return counter.getNMethodsWithCode() > 0; } }
plugins/coverage/src/com/intellij/coverage/PackageAnnotator.java
package com.intellij.coverage; import com.intellij.openapi.fileTypes.StdFileTypes; import com.intellij.openapi.module.Module; import com.intellij.openapi.module.ModuleManager; import com.intellij.openapi.project.Project; import com.intellij.openapi.roots.*; import com.intellij.openapi.util.Computable; import com.intellij.openapi.vfs.VfsUtil; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.psi.JavaPsiFacade; import com.intellij.psi.PsiClass; import com.intellij.psi.PsiManager; import com.intellij.psi.PsiPackage; import com.intellij.psi.search.GlobalSearchScope; import com.intellij.rt.coverage.data.ClassData; import com.intellij.rt.coverage.data.LineCoverage; import com.intellij.rt.coverage.data.LineData; import com.intellij.rt.coverage.data.ProjectData; import com.intellij.rt.coverage.instrumentation.SourceLineCounter; import com.intellij.util.containers.HashMap; import org.jetbrains.annotations.Nullable; import org.objectweb.asm.ClassReader; import org.objectweb.asm.commons.EmptyVisitor; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Map; /** * @author ven */ public class PackageAnnotator { private final PsiPackage myPackage; private final Project myProject; private final PsiManager myManager; private final CoverageDataManager myCoverageManager; public PackageAnnotator(final PsiPackage aPackage) { myPackage = aPackage; myProject = myPackage.getProject(); myManager = PsiManager.getInstance(myProject); myCoverageManager = CoverageDataManager.getInstance(myProject); } public interface Annotator { void annotateSourceDirectory(VirtualFile virtualFile, PackageCoverageInfo packageCoverageInfo, Module module); void annotateTestDirectory(VirtualFile virtualFile, PackageCoverageInfo packageCoverageInfo, Module module); void annotatePackage(String packageQualifiedName, PackageCoverageInfo packageCoverageInfo); void annotateClass(String classQualifiedName, ClassCoverageInfo classCoverageInfo); } public static class ClassCoverageInfo { public int totalLineCount; public int fullyCoveredLineCount; public int partiallyCoveredLineCount; public int totalMethodCount; public int coveredMethodCount; } public static class PackageCoverageInfo { public int totalClassCount; public int coveredClassCount; public int totalLineCount; public int coveredLineCount; } public static class DirCoverageInfo extends PackageCoverageInfo { public VirtualFile sourceRoot; public DirCoverageInfo(VirtualFile sourceRoot) { this.sourceRoot = sourceRoot; } } //get read lock myself when needed public void annotate(CoverageSuitesBundle suite, Annotator annotator) { final ProjectData data = suite.getCoverageData(); if (data == null) return; final String qualifiedName = myPackage.getQualifiedName(); boolean filtered = false; for (CoverageSuite coverageSuite : suite.getSuites()) { if (((JavaCoverageSuite)coverageSuite).isPackageFiltered(qualifiedName)) { filtered = true; break; } } if (!filtered) return; final Module[] modules = myCoverageManager.doInReadActionIfProjectOpen(new Computable<Module[]>() { public Module[] compute() { return ModuleManager.getInstance(myProject).getModules(); } }); if (modules == null) return; Map<String, PackageCoverageInfo> packageCoverageMap = new HashMap<String, PackageCoverageInfo>(); for (final Module module : modules) { final String rootPackageVMName = qualifiedName.replaceAll("\\.", "/"); final VirtualFile packageRoot = myCoverageManager.doInReadActionIfProjectOpen(new Computable<VirtualFile>() { @Nullable public VirtualFile compute() { final VirtualFile outputPath = CompilerModuleExtension.getInstance(module).getCompilerOutputPath(); if (outputPath != null) { return rootPackageVMName.length() > 0 ? outputPath.findFileByRelativePath(rootPackageVMName) : outputPath; } return null; } }); if (packageRoot != null) { collectCoverageInformation(packageRoot, packageCoverageMap, data, rootPackageVMName, annotator, module, suite.isTrackTestFolders(), false); } if (suite.isTrackTestFolders()) { final VirtualFile testPackageRoot = myCoverageManager.doInReadActionIfProjectOpen(new Computable<VirtualFile>() { @Nullable public VirtualFile compute() { final VirtualFile outputPath = CompilerModuleExtension.getInstance(module).getCompilerOutputPathForTests(); if (outputPath != null) { return rootPackageVMName.length() > 0 ? outputPath.findFileByRelativePath(rootPackageVMName) : outputPath; } return null; } }); if (testPackageRoot != null) { collectCoverageInformation(testPackageRoot, packageCoverageMap, data, rootPackageVMName, annotator, module, suite.isTrackTestFolders(), true); } } } for (Map.Entry<String, PackageCoverageInfo> entry : packageCoverageMap.entrySet()) { final String packageFQName = entry.getKey().replaceAll("/", "."); final PackageCoverageInfo info = entry.getValue(); annotator.annotatePackage(packageFQName, info); } } @Nullable private DirCoverageInfo[] collectCoverageInformation(final VirtualFile packageOutputRoot, final Map<String, PackageCoverageInfo> packageCoverageMap, final ProjectData projectInfo, final String packageVMName, final Annotator annotator, final Module module, final boolean trackTestFolders, final boolean isTestHierarchy) { final List<DirCoverageInfo> dirs = new ArrayList<DirCoverageInfo>(); final ContentEntry[] contentEntries = ModuleRootManager.getInstance(module).getContentEntries(); for (ContentEntry contentEntry : contentEntries) { for (SourceFolder folder : contentEntry.getSourceFolders()) { final VirtualFile file = folder.getFile(); if (file == null) continue; if (folder.isTestSource() && isTestHierarchy || !isTestHierarchy) { final VirtualFile relativeSrcRoot = file.findFileByRelativePath(packageVMName); dirs.add(new DirCoverageInfo(relativeSrcRoot)); } } } final VirtualFile[] children = myCoverageManager.doInReadActionIfProjectOpen(new Computable<VirtualFile[]>() { public VirtualFile[] compute() { return packageOutputRoot.getChildren(); } }); if (children == null) return null; Map<String, ClassCoverageInfo> toplevelClassCoverage = new HashMap<String, ClassCoverageInfo>(); for (VirtualFile child : children) { if (child.isDirectory()) { final String childName = child.getName(); final String childPackageVMName = packageVMName.length() > 0 ? packageVMName + "/" + childName : childName; final DirCoverageInfo[] childCoverageInfo = collectCoverageInformation(child, packageCoverageMap, projectInfo, childPackageVMName, annotator, module, trackTestFolders, isTestHierarchy); if (childCoverageInfo != null) { for (int i = 0; i < childCoverageInfo.length; i++) { DirCoverageInfo coverageInfo = childCoverageInfo[i]; final DirCoverageInfo parentDir = dirs.get(i); parentDir.totalClassCount += coverageInfo.totalClassCount; parentDir.coveredClassCount += coverageInfo.coveredClassCount; parentDir.totalLineCount += coverageInfo.totalLineCount; parentDir.coveredLineCount += coverageInfo.coveredLineCount; } } } else { if (child.getFileType().equals(StdFileTypes.CLASS)) { final String childName = child.getNameWithoutExtension(); final String classFqVMName = packageVMName.length() > 0 ? packageVMName + "/" + childName : childName; final String toplevelClassSrcFQName = getSourceToplevelFQName(classFqVMName); final VirtualFile[] containingFile = new VirtualFile[1]; final Boolean isInSource = myCoverageManager.doInReadActionIfProjectOpen(new Computable<Boolean>() { public Boolean compute() { final PsiClass aClass = JavaPsiFacade.getInstance(myManager.getProject()).findClass(toplevelClassSrcFQName, GlobalSearchScope.moduleScope(module)); if (aClass == null || !aClass.isValid()) return Boolean.FALSE; containingFile[0] = aClass.getContainingFile().getVirtualFile(); assert containingFile[0] != null; final ModuleFileIndex fileIndex = ModuleRootManager.getInstance(module).getFileIndex(); return fileIndex.isInSourceContent(containingFile[0]) && (trackTestFolders || !fileIndex.isInTestSourceContent(containingFile[0])); } }); if (isInSource != null && isInSource.booleanValue()) { for (DirCoverageInfo dirCoverageInfo : dirs) { if (dirCoverageInfo.sourceRoot != null && VfsUtil.isAncestor(dirCoverageInfo.sourceRoot, containingFile[0], false)) { collectClassCoverageInformation(child, dirCoverageInfo, projectInfo, toplevelClassCoverage, classFqVMName.replace("/", "."), toplevelClassSrcFQName); break; } } } } } } for (Map.Entry<String, ClassCoverageInfo> entry : toplevelClassCoverage.entrySet()) { final String toplevelClassName = entry.getKey(); final ClassCoverageInfo coverageInfo = entry.getValue(); annotator.annotateClass(toplevelClassName, coverageInfo); } PackageCoverageInfo packageCoverageInfo = getOrCreateCoverageInfo(packageCoverageMap, packageVMName); for (DirCoverageInfo dir : dirs) { packageCoverageInfo.totalClassCount += dir.totalClassCount; packageCoverageInfo.totalLineCount += dir.totalLineCount; packageCoverageInfo.coveredClassCount += dir.coveredClassCount; packageCoverageInfo.coveredLineCount += dir.coveredLineCount; if (isTestHierarchy) { annotator.annotateTestDirectory(dir.sourceRoot, dir, module); } else { annotator.annotateSourceDirectory(dir.sourceRoot, dir, module); } } return dirs.toArray(new DirCoverageInfo[dirs.size()]); } private static PackageCoverageInfo getOrCreateCoverageInfo(final Map<String, PackageCoverageInfo> packageCoverageMap, final String packageVMName) { PackageCoverageInfo coverageInfo = packageCoverageMap.get(packageVMName); if (coverageInfo == null) { coverageInfo = new PackageCoverageInfo(); packageCoverageMap.put(packageVMName, coverageInfo); } return coverageInfo; } private void collectClassCoverageInformation(final VirtualFile classFile, final PackageCoverageInfo packageCoverageInfo, final ProjectData projectInfo, final Map<String, ClassCoverageInfo> toplevelClassCoverage, final String className, final String toplevelClassSrcFQName) { final ClassCoverageInfo toplevelClassCoverageInfo = new ClassCoverageInfo(); final ClassData classData = projectInfo.getClassData(SrcFileAnnotator.getFilePath(className)); if (classData != null && classData.getLines() != null) { final Object[] lines = classData.getLines(); for (Object l : lines) { if (l instanceof LineData) { final LineData lineData = (LineData)l; if (lineData.getStatus() == LineCoverage.FULL) { toplevelClassCoverageInfo.fullyCoveredLineCount++; } else if (lineData.getStatus() == LineCoverage.PARTIAL) { toplevelClassCoverageInfo.partiallyCoveredLineCount++; } toplevelClassCoverageInfo.totalLineCount++; packageCoverageInfo.totalLineCount++; } } boolean touchedClass = false; for (final Object nameAndSig : classData.getMethodSigs()) { final int covered = classData.getStatus((String)nameAndSig); if (covered != LineCoverage.NONE) { toplevelClassCoverageInfo.coveredMethodCount++; touchedClass = true; } } if (touchedClass) { packageCoverageInfo.coveredClassCount++; } toplevelClassCoverageInfo.totalMethodCount += classData.getMethodSigs().size(); packageCoverageInfo.totalClassCount++; packageCoverageInfo.coveredLineCount += toplevelClassCoverageInfo.fullyCoveredLineCount; packageCoverageInfo.coveredLineCount += toplevelClassCoverageInfo.partiallyCoveredLineCount; } else { collectNonCoveredClassInfo(classFile, toplevelClassCoverageInfo, packageCoverageInfo); } ClassCoverageInfo classCoverageInfo = getOrCreateClassCoverageInfo(toplevelClassCoverage, toplevelClassSrcFQName); classCoverageInfo.totalLineCount += toplevelClassCoverageInfo.totalLineCount; classCoverageInfo.fullyCoveredLineCount += toplevelClassCoverageInfo.fullyCoveredLineCount; classCoverageInfo.partiallyCoveredLineCount += toplevelClassCoverageInfo.partiallyCoveredLineCount; classCoverageInfo.totalMethodCount += toplevelClassCoverageInfo.totalMethodCount; classCoverageInfo.coveredMethodCount += toplevelClassCoverageInfo.coveredMethodCount; } private static ClassCoverageInfo getOrCreateClassCoverageInfo(final Map<String, ClassCoverageInfo> toplevelClassCoverage, final String sourceToplevelFQName) { ClassCoverageInfo toplevelClassCoverageInfo = toplevelClassCoverage.get(sourceToplevelFQName); if (toplevelClassCoverageInfo == null) { toplevelClassCoverageInfo = new ClassCoverageInfo(); toplevelClassCoverage.put(sourceToplevelFQName, toplevelClassCoverageInfo); } return toplevelClassCoverageInfo; } private static String getSourceToplevelFQName(String classFQVMName) { final int index = classFQVMName.indexOf('$'); if (index > 0) classFQVMName = classFQVMName.substring(0, index); if (classFQVMName.startsWith("/")) classFQVMName = classFQVMName.substring(1); return classFQVMName.replaceAll("/", "."); } /* return true if there is executable code in the class */ private boolean collectNonCoveredClassInfo(final VirtualFile classFile, final ClassCoverageInfo classCoverageInfo, final PackageCoverageInfo packageCoverageInfo) { final byte[] content = myCoverageManager.doInReadActionIfProjectOpen(new Computable<byte[]>() { public byte[] compute() { try { return classFile.contentsToByteArray(); } catch (IOException e) { return null; } } }); if (content == null) return false; ClassReader reader = new ClassReader(content, 0, content.length); final CoverageSuitesBundle coverageSuite = CoverageDataManager.getInstance(myProject).getCurrentSuitesBundle(); if (coverageSuite == null) return false; SourceLineCounter counter = new SourceLineCounter(new EmptyVisitor(), null, coverageSuite.isTracingEnabled()); reader.accept(counter, 0); classCoverageInfo.totalLineCount += counter.getNSourceLines(); classCoverageInfo.totalMethodCount += counter.getNMethodsWithCode(); packageCoverageInfo.totalLineCount += counter.getNSourceLines(); if (!counter.isInterface()) { packageCoverageInfo.totalClassCount++; } return counter.getNMethodsWithCode() > 0; } }
coverage: do not perform magic with classes fqns
plugins/coverage/src/com/intellij/coverage/PackageAnnotator.java
coverage: do not perform magic with classes fqns
<ide><path>lugins/coverage/src/com/intellij/coverage/PackageAnnotator.java <ide> final String toplevelClassSrcFQName) { <ide> final ClassCoverageInfo toplevelClassCoverageInfo = new ClassCoverageInfo(); <ide> <del> final ClassData classData = projectInfo.getClassData(SrcFileAnnotator.getFilePath(className)); <add> final ClassData classData = projectInfo.getClassData(className); <ide> <ide> if (classData != null && classData.getLines() != null) { <ide> final Object[] lines = classData.getLines();
Java
mit
1fe62a2ba2ca33d3b76fed2edfa8b828c205e356
0
cs2103aug2014-t09-4j/main
//@author A0116538A package bakatxt.test; import static java.awt.event.KeyEvent.*; import java.awt.AWTException; import java.awt.Robot; import java.awt.event.InputEvent; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import bakatxt.core.BakaProcessor; import bakatxt.gui.BakaUI; import bakatxt.gui.UIHelper; /** * This class is a helper class to automate test cases for JUnit on the GUI. * */ public class BakaBot extends Robot { // places to store and backup our test files private static final Path TEST_FILE = new File("./mytestfile.txt").toPath(); private static final Path TEST_FILE_SAVE = new File("./mytestfile.txt.bak").toPath(); // commands public static final String ADD = "add "; public static final String DELETE = "delete "; public static final String EDIT = "edit "; public static final String DISPLAY = "display "; public static final int WAIT_SHORT = 25; public static final int WAIT_MEDIUM = 200; public static final int WAIT_LONG = 2000; // some sample strings public static final String SAMPLE_FOX = "the quick brown fox jumps over " + "the lazy dog 1234567890"; public static final String SAMPLE_ZOMBIES = "PAINFUL ZOMBIES QUICKLY WATCH A" + "JINXED GRAVEYARD"; public BakaBot() throws AWTException { super(); } /** * Call this in the @BeforeClass method in your JUnit test. Sets up the files * for testing while retaining the old files. * @throws IOException */ public static void botOneTimeSetUp() throws IOException { saveOldFile(); initializeTestFile(); BakaUI.startGui(new BakaProcessor()); } /** * Call this in the @AfterClass method in your JUnit test. Restores the old * task database file used before the test. * @throws IOException */ public static void botOneTimeTearDown() throws IOException { restoreTestFile(); } /** * Call this in the @Before method in your JUnit test. Starts the GUI and * reinitializes the test files if needed. * @throws IOException */ public static void botSetUp() throws IOException { BakaUI.startGui(new BakaProcessor()); initializeTestFile(); } /** * Call this in the @After method in your JUnit test. Pauses for 2 seconds * between each test to prevent interference between each test. */ public static void botTearDown() { waitAWhile(WAIT_LONG); } /** * moves the cursor to the input box and simulate a keyboard typing the string * s * @param s is the string to be typed */ public void inputThisString(String s) { typeThis(s); waitAWhile(WAIT_SHORT); enter(); } /** * moves the cursor to the BakaTxt input box and clicks it */ public void mouseToInputBox() { mouseMove(UIHelper.WINDOW_LOCATION.x + 60, UIHelper.WINDOW_LOCATION.y + 20); mousePress(InputEvent.BUTTON1_DOWN_MASK); waitAWhile(WAIT_SHORT); mouseRelease(InputEvent.BUTTON1_DOWN_MASK); } /** * Tells the process to wait waitTime milliseconds * @param waitTime is the time in miliseconds to wait */ public static void waitAWhile(final int waitTime) { try{ Thread.sleep(waitTime); } catch (InterruptedException e) { } } /** * Simulates an enter key being pressed */ public void enter() { typeThis("\n"); } /** * Types a string using keyboard inputs * @param toBeTyped is the string to be typed */ public void typeThis(CharSequence toBeTyped) { for (int i = 0; i < toBeTyped.length(); i++) { char character = toBeTyped.charAt(i); typeThisChar(character); waitAWhile(WAIT_SHORT); } } private static void saveOldFile() throws IOException { Files.deleteIfExists(TEST_FILE_SAVE); if(Files.exists(TEST_FILE)) { Files.copy(TEST_FILE, TEST_FILE_SAVE); } } private static void initializeTestFile() throws IOException { Files.deleteIfExists(TEST_FILE); Files.createFile(TEST_FILE); } private static void restoreTestFile() throws IOException { Files.deleteIfExists(TEST_FILE); if(Files.exists(TEST_FILE_SAVE)) { Files.copy(TEST_FILE_SAVE, TEST_FILE); } Files.deleteIfExists(TEST_FILE_SAVE); } /** * types a character, note, only what is on a standard keyboard layout, no unicode * @param character is the character to be typed */ private void typeThisChar(char character) { switch (character) { case 'a' : typingThisChar(VK_A); break; case 'b' : typingThisChar(VK_B); break; case 'c' : typingThisChar(VK_C); break; case 'd' : typingThisChar(VK_D); break; case 'e' : typingThisChar(VK_E); break; case 'f' : typingThisChar(VK_F); break; case 'g' : typingThisChar(VK_G); break; case 'h' : typingThisChar(VK_H); break; case 'i' : typingThisChar(VK_I); break; case 'j' : typingThisChar(VK_J); break; case 'k' : typingThisChar(VK_K); break; case 'l' : typingThisChar(VK_L); break; case 'm' : typingThisChar(VK_M); break; case 'n' : typingThisChar(VK_N); break; case 'o' : typingThisChar(VK_O); break; case 'p' : typingThisChar(VK_P); break; case 'q' : typingThisChar(VK_Q); break; case 'r' : typingThisChar(VK_R); break; case 's' : typingThisChar(VK_S); break; case 't' : typingThisChar(VK_T); break; case 'u' : typingThisChar(VK_U); break; case 'v' : typingThisChar(VK_V); break; case 'w' : typingThisChar(VK_W); break; case 'x' : typingThisChar(VK_X); break; case 'y' : typingThisChar(VK_Y); break; case 'z' : typingThisChar(VK_Z); break; case 'A' : typingThisChar(VK_SHIFT, VK_A); break; case 'B' : typingThisChar(VK_SHIFT, VK_B); break; case 'C' : typingThisChar(VK_SHIFT, VK_C); break; case 'D' : typingThisChar(VK_SHIFT, VK_D); break; case 'E' : typingThisChar(VK_SHIFT, VK_E); break; case 'F' : typingThisChar(VK_SHIFT, VK_F); break; case 'G' : typingThisChar(VK_SHIFT, VK_G); break; case 'H' : typingThisChar(VK_SHIFT, VK_H); break; case 'I' : typingThisChar(VK_SHIFT, VK_I); break; case 'J' : typingThisChar(VK_SHIFT, VK_J); break; case 'K' : typingThisChar(VK_SHIFT, VK_K); break; case 'L' : typingThisChar(VK_SHIFT, VK_L); break; case 'M' : typingThisChar(VK_SHIFT, VK_M); break; case 'N' : typingThisChar(VK_SHIFT, VK_N); break; case 'O' : typingThisChar(VK_SHIFT, VK_O); break; case 'P' : typingThisChar(VK_SHIFT, VK_P); break; case 'Q' : typingThisChar(VK_SHIFT, VK_Q); break; case 'R' : typingThisChar(VK_SHIFT, VK_R); break; case 'S' : typingThisChar(VK_SHIFT, VK_S); break; case 'T' : typingThisChar(VK_SHIFT, VK_T); break; case 'U' : typingThisChar(VK_SHIFT, VK_U); break; case 'V' : typingThisChar(VK_SHIFT, VK_V); break; case 'W' : typingThisChar(VK_SHIFT, VK_W); break; case 'X' : typingThisChar(VK_SHIFT, VK_X); break; case 'Y' : typingThisChar(VK_SHIFT, VK_Y); break; case 'Z' : typingThisChar(VK_SHIFT, VK_Z); break; case '0' : typingThisChar(VK_0); break; case '1' : typingThisChar(VK_1); break; case '2' : typingThisChar(VK_2); break; case '3' : typingThisChar(VK_3); break; case '4' : typingThisChar(VK_4); break; case '5' : typingThisChar(VK_5); break; case '6' : typingThisChar(VK_6); break; case '7' : typingThisChar(VK_7); break; case '8' : typingThisChar(VK_8); break; case '9' : typingThisChar(VK_9); break; case '-' : typingThisChar(VK_MINUS); break; case '@' : typingThisChar(VK_SHIFT, VK_2); break; case '\n' : typingThisChar(VK_ENTER); break; case '/' : typingThisChar(VK_SLASH); break; case ' ' : typingThisChar(VK_SPACE); break; default : throw new IllegalArgumentException("Cannot type: " + character); } } /** * Types the char based on what keypresses are needed to type it * * @param keyCodes is the keyCodes needed to be activated */ private void typingThisChar(int... keyCodes) { for (int i = 0; i < keyCodes.length; i++) { keyPress(keyCodes[i]); } waitAWhile(WAIT_SHORT); for (int i = 0; i < keyCodes.length; i++) { keyRelease(keyCodes[i]); } } }
src/bakatxt/test/BakaBot.java
//@author A0116538A package bakatxt.test; import static java.awt.event.KeyEvent.*; import java.awt.AWTException; import java.awt.Robot; import java.awt.event.InputEvent; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import bakatxt.core.BakaProcessor; import bakatxt.gui.BakaUI; import bakatxt.gui.UIHelper; /** * This class is a helper class to automate test cases for JUnit on the GUI. * */ public class BakaBot extends Robot { // places to store and backup our test files private static final Path TEST_FILE = new File("./mytestfile.txt").toPath(); private static final Path TEST_FILE_SAVE = new File("./mytestfile.txt.bak").toPath(); // commands public static final String ADD = "add "; public static final String DELETE = "delete "; public static final String EDIT = "edit "; public static final String DISPLAY = "display "; public static final int WAIT_SHORT = 25; public static final int WAIT_MEDIUM = 200; public static final int WAIT_LONG = 2000; // some sample strings public static final String SAMPLE_FOX = "the quick brown fox jumps over " + "the lazy dog 1234567890"; public static final String SAMPLE_ZOMBIES = "PAINFUL ZOMBIES QUICKLY WATCH A" + "JINXED GRAVEYARD"; public BakaBot() throws AWTException { super(); } /** * Call this in the @BeforeClass method in your JUnit test. Sets up the files * for testing while retaining the old files. * @throws IOException */ public static void botOneTimeSetUp() throws IOException { saveOldFile(); initializeTestFile(); } /** * Call this in the @AfterClass method in your JUnit test. Restores the old * task database file used before the test. * @throws IOException */ public static void botOneTimeTearDown() throws IOException { restoreTestFile(); } /** * Call this in the @Before method in your JUnit test. Starts the GUI and * reinitializes the test files if needed. * @throws IOException */ public static void botSetUp() throws IOException { BakaUI.startGui(new BakaProcessor()); initializeTestFile(); } /** * Call this in the @After method in your JUnit test. Pauses for 2 seconds * between each test to prevent interference between each test. */ public static void botTearDown() { waitAWhile(WAIT_LONG); } /** * moves the cursor to the input box and simulate a keyboard typing the string * s * @param s is the string to be typed */ public void inputThisString(String s) { typeThis(s); waitAWhile(WAIT_SHORT); enter(); } /** * moves the cursor to the BakaTxt input box and clicks it */ public void mouseToInputBox() { mouseMove(UIHelper.WINDOW_LOCATION.x + 60, UIHelper.WINDOW_LOCATION.y + 20); mousePress(InputEvent.BUTTON1_DOWN_MASK); waitAWhile(WAIT_SHORT); mouseRelease(InputEvent.BUTTON1_DOWN_MASK); } /** * Tells the process to wait waitTime milliseconds * @param waitTime is the time in miliseconds to wait */ public static void waitAWhile(final int waitTime) { try{ Thread.sleep(waitTime); } catch (InterruptedException e) { } } /** * Simulates an enter key being pressed */ public void enter() { typeThis("\n"); } /** * Types a string using keyboard inputs * @param toBeTyped is the string to be typed */ public void typeThis(CharSequence toBeTyped) { for (int i = 0; i < toBeTyped.length(); i++) { char character = toBeTyped.charAt(i); typeThisChar(character); waitAWhile(WAIT_SHORT); } } private static void saveOldFile() throws IOException { Files.deleteIfExists(TEST_FILE_SAVE); if(Files.exists(TEST_FILE)) { Files.copy(TEST_FILE, TEST_FILE_SAVE); } } private static void initializeTestFile() throws IOException { Files.deleteIfExists(TEST_FILE); Files.createFile(TEST_FILE); } private static void restoreTestFile() throws IOException { Files.deleteIfExists(TEST_FILE); if(Files.exists(TEST_FILE_SAVE)) { Files.copy(TEST_FILE_SAVE, TEST_FILE); } Files.deleteIfExists(TEST_FILE_SAVE); } /** * types a character, note, only what is on a standard keyboard layout, no unicode * @param character is the character to be typed */ private void typeThisChar(char character) { switch (character) { case 'a' : typingThisChar(VK_A); break; case 'b' : typingThisChar(VK_B); break; case 'c' : typingThisChar(VK_C); break; case 'd' : typingThisChar(VK_D); break; case 'e' : typingThisChar(VK_E); break; case 'f' : typingThisChar(VK_F); break; case 'g' : typingThisChar(VK_G); break; case 'h' : typingThisChar(VK_H); break; case 'i' : typingThisChar(VK_I); break; case 'j' : typingThisChar(VK_J); break; case 'k' : typingThisChar(VK_K); break; case 'l' : typingThisChar(VK_L); break; case 'm' : typingThisChar(VK_M); break; case 'n' : typingThisChar(VK_N); break; case 'o' : typingThisChar(VK_O); break; case 'p' : typingThisChar(VK_P); break; case 'q' : typingThisChar(VK_Q); break; case 'r' : typingThisChar(VK_R); break; case 's' : typingThisChar(VK_S); break; case 't' : typingThisChar(VK_T); break; case 'u' : typingThisChar(VK_U); break; case 'v' : typingThisChar(VK_V); break; case 'w' : typingThisChar(VK_W); break; case 'x' : typingThisChar(VK_X); break; case 'y' : typingThisChar(VK_Y); break; case 'z' : typingThisChar(VK_Z); break; case 'A' : typingThisChar(VK_SHIFT, VK_A); break; case 'B' : typingThisChar(VK_SHIFT, VK_B); break; case 'C' : typingThisChar(VK_SHIFT, VK_C); break; case 'D' : typingThisChar(VK_SHIFT, VK_D); break; case 'E' : typingThisChar(VK_SHIFT, VK_E); break; case 'F' : typingThisChar(VK_SHIFT, VK_F); break; case 'G' : typingThisChar(VK_SHIFT, VK_G); break; case 'H' : typingThisChar(VK_SHIFT, VK_H); break; case 'I' : typingThisChar(VK_SHIFT, VK_I); break; case 'J' : typingThisChar(VK_SHIFT, VK_J); break; case 'K' : typingThisChar(VK_SHIFT, VK_K); break; case 'L' : typingThisChar(VK_SHIFT, VK_L); break; case 'M' : typingThisChar(VK_SHIFT, VK_M); break; case 'N' : typingThisChar(VK_SHIFT, VK_N); break; case 'O' : typingThisChar(VK_SHIFT, VK_O); break; case 'P' : typingThisChar(VK_SHIFT, VK_P); break; case 'Q' : typingThisChar(VK_SHIFT, VK_Q); break; case 'R' : typingThisChar(VK_SHIFT, VK_R); break; case 'S' : typingThisChar(VK_SHIFT, VK_S); break; case 'T' : typingThisChar(VK_SHIFT, VK_T); break; case 'U' : typingThisChar(VK_SHIFT, VK_U); break; case 'V' : typingThisChar(VK_SHIFT, VK_V); break; case 'W' : typingThisChar(VK_SHIFT, VK_W); break; case 'X' : typingThisChar(VK_SHIFT, VK_X); break; case 'Y' : typingThisChar(VK_SHIFT, VK_Y); break; case 'Z' : typingThisChar(VK_SHIFT, VK_Z); break; case '0' : typingThisChar(VK_0); break; case '1' : typingThisChar(VK_1); break; case '2' : typingThisChar(VK_2); break; case '3' : typingThisChar(VK_3); break; case '4' : typingThisChar(VK_4); break; case '5' : typingThisChar(VK_5); break; case '6' : typingThisChar(VK_6); break; case '7' : typingThisChar(VK_7); break; case '8' : typingThisChar(VK_8); break; case '9' : typingThisChar(VK_9); break; case '-' : typingThisChar(VK_MINUS); break; case '@' : typingThisChar(VK_SHIFT, VK_2); break; case '\n' : typingThisChar(VK_ENTER); break; case '/' : typingThisChar(VK_SLASH); break; case ' ' : typingThisChar(VK_SPACE); break; default : throw new IllegalArgumentException("Cannot type: " + character); } } /** * Types the char based on what keypresses are needed to type it * * @param keyCodes is the keyCodes needed to be activated */ private void typingThisChar(int... keyCodes) { for (int i = 0; i < keyCodes.length; i++) { keyPress(keyCodes[i]); } waitAWhile(WAIT_SHORT); for (int i = 0; i < keyCodes.length; i++) { keyRelease(keyCodes[i]); } } }
Bug Fix: Excessive instances of BakaTxt
src/bakatxt/test/BakaBot.java
Bug Fix: Excessive instances of BakaTxt
<ide><path>rc/bakatxt/test/BakaBot.java <ide> public static void botOneTimeSetUp() throws IOException { <ide> saveOldFile(); <ide> initializeTestFile(); <add> BakaUI.startGui(new BakaProcessor()); <ide> } <ide> <ide> /**